blob: ae9c2f021fb4103c3cd65ab76bbe2809300cb1c8 [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 Topper3428bee2018-06-08 03:24:47 +00002610 case X86::BI__builtin_ia32_vextractf128_pd256:
2611 case X86::BI__builtin_ia32_vextractf128_ps256:
2612 case X86::BI__builtin_ia32_vextractf128_si256:
2613 case X86::BI__builtin_ia32_extract128i256:
Craig Topper5f50f3382018-06-08 21:50:07 +00002614 case X86::BI__builtin_ia32_extractf64x4_mask:
2615 case X86::BI__builtin_ia32_extracti64x4_mask:
2616 case X86::BI__builtin_ia32_extractf32x8_mask:
2617 case X86::BI__builtin_ia32_extracti32x8_mask:
2618 case X86::BI__builtin_ia32_extractf64x2_256_mask:
2619 case X86::BI__builtin_ia32_extracti64x2_256_mask:
2620 case X86::BI__builtin_ia32_extractf32x4_256_mask:
2621 case X86::BI__builtin_ia32_extracti32x4_256_mask:
Craig Topper11899b02018-06-05 21:54:35 +00002622 i = 1; l = 0; u = 1;
2623 break;
Craig Topperf3914b72018-06-06 00:24:55 +00002624 case X86::BI__builtin_ia32_vec_set_v2di:
Craig Topper3428bee2018-06-08 03:24:47 +00002625 case X86::BI__builtin_ia32_vinsertf128_pd256:
2626 case X86::BI__builtin_ia32_vinsertf128_ps256:
2627 case X86::BI__builtin_ia32_vinsertf128_si256:
2628 case X86::BI__builtin_ia32_insert128i256:
2629 case X86::BI__builtin_ia32_insertf32x8:
2630 case X86::BI__builtin_ia32_inserti32x8:
2631 case X86::BI__builtin_ia32_insertf64x4:
2632 case X86::BI__builtin_ia32_inserti64x4:
2633 case X86::BI__builtin_ia32_insertf64x2_256:
2634 case X86::BI__builtin_ia32_inserti64x2_256:
2635 case X86::BI__builtin_ia32_insertf32x4_256:
2636 case X86::BI__builtin_ia32_inserti32x4_256:
Craig Topperf3914b72018-06-06 00:24:55 +00002637 i = 2; l = 0; u = 1;
2638 break;
Craig Topperacf56012018-06-08 00:59:27 +00002639 case X86::BI__builtin_ia32_vpermilpd:
Craig Topper11899b02018-06-05 21:54:35 +00002640 case X86::BI__builtin_ia32_vec_ext_v4hi:
Craig Topperf3914b72018-06-06 00:24:55 +00002641 case X86::BI__builtin_ia32_vec_ext_v4si:
2642 case X86::BI__builtin_ia32_vec_ext_v4sf:
2643 case X86::BI__builtin_ia32_vec_ext_v4di:
Craig Topper5f50f3382018-06-08 21:50:07 +00002644 case X86::BI__builtin_ia32_extractf32x4_mask:
2645 case X86::BI__builtin_ia32_extracti32x4_mask:
2646 case X86::BI__builtin_ia32_extractf64x2_512_mask:
2647 case X86::BI__builtin_ia32_extracti64x2_512_mask:
Craig Topper11899b02018-06-05 21:54:35 +00002648 i = 1; l = 0; u = 3;
2649 break;
Craig Topperf3914b72018-06-06 00:24:55 +00002650 case X86::BI_mm_prefetch:
2651 case X86::BI__builtin_ia32_vec_ext_v8hi:
2652 case X86::BI__builtin_ia32_vec_ext_v8si:
2653 i = 1; l = 0; u = 7;
2654 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00002655 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper7d17d722018-06-08 00:00:21 +00002656 case X86::BI__builtin_ia32_blendpd:
Craig Topper422a1bb2018-06-08 07:18:33 +00002657 case X86::BI__builtin_ia32_shufpd:
Craig Topper11899b02018-06-05 21:54:35 +00002658 case X86::BI__builtin_ia32_vec_set_v4hi:
Craig Topperf3914b72018-06-06 00:24:55 +00002659 case X86::BI__builtin_ia32_vec_set_v4si:
2660 case X86::BI__builtin_ia32_vec_set_v4di:
Craig Topper93921362018-06-07 23:03:08 +00002661 case X86::BI__builtin_ia32_shuf_f32x4_256:
2662 case X86::BI__builtin_ia32_shuf_f64x2_256:
2663 case X86::BI__builtin_ia32_shuf_i32x4_256:
2664 case X86::BI__builtin_ia32_shuf_i64x2_256:
Craig Topper3428bee2018-06-08 03:24:47 +00002665 case X86::BI__builtin_ia32_insertf64x2_512:
2666 case X86::BI__builtin_ia32_inserti64x2_512:
2667 case X86::BI__builtin_ia32_insertf32x4:
2668 case X86::BI__builtin_ia32_inserti32x4:
Craig Topper39c87102016-05-18 03:18:12 +00002669 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002670 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00002671 case X86::BI__builtin_ia32_vpermil2pd:
2672 case X86::BI__builtin_ia32_vpermil2pd256:
2673 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00002674 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00002675 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002676 break;
Craig Topper95b0d732015-01-25 23:30:05 +00002677 case X86::BI__builtin_ia32_cmpb128_mask:
2678 case X86::BI__builtin_ia32_cmpw128_mask:
2679 case X86::BI__builtin_ia32_cmpd128_mask:
2680 case X86::BI__builtin_ia32_cmpq128_mask:
2681 case X86::BI__builtin_ia32_cmpb256_mask:
2682 case X86::BI__builtin_ia32_cmpw256_mask:
2683 case X86::BI__builtin_ia32_cmpd256_mask:
2684 case X86::BI__builtin_ia32_cmpq256_mask:
2685 case X86::BI__builtin_ia32_cmpb512_mask:
2686 case X86::BI__builtin_ia32_cmpw512_mask:
2687 case X86::BI__builtin_ia32_cmpd512_mask:
2688 case X86::BI__builtin_ia32_cmpq512_mask:
2689 case X86::BI__builtin_ia32_ucmpb128_mask:
2690 case X86::BI__builtin_ia32_ucmpw128_mask:
2691 case X86::BI__builtin_ia32_ucmpd128_mask:
2692 case X86::BI__builtin_ia32_ucmpq128_mask:
2693 case X86::BI__builtin_ia32_ucmpb256_mask:
2694 case X86::BI__builtin_ia32_ucmpw256_mask:
2695 case X86::BI__builtin_ia32_ucmpd256_mask:
2696 case X86::BI__builtin_ia32_ucmpq256_mask:
2697 case X86::BI__builtin_ia32_ucmpb512_mask:
2698 case X86::BI__builtin_ia32_ucmpw512_mask:
2699 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00002700 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00002701 case X86::BI__builtin_ia32_vpcomub:
2702 case X86::BI__builtin_ia32_vpcomuw:
2703 case X86::BI__builtin_ia32_vpcomud:
2704 case X86::BI__builtin_ia32_vpcomuq:
2705 case X86::BI__builtin_ia32_vpcomb:
2706 case X86::BI__builtin_ia32_vpcomw:
2707 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00002708 case X86::BI__builtin_ia32_vpcomq:
Craig Topperf3914b72018-06-06 00:24:55 +00002709 case X86::BI__builtin_ia32_vec_set_v8hi:
2710 case X86::BI__builtin_ia32_vec_set_v8si:
Craig Topper39c87102016-05-18 03:18:12 +00002711 i = 2; l = 0; u = 7;
2712 break;
Craig Topperacf56012018-06-08 00:59:27 +00002713 case X86::BI__builtin_ia32_vpermilpd256:
Craig Topper39c87102016-05-18 03:18:12 +00002714 case X86::BI__builtin_ia32_roundps:
2715 case X86::BI__builtin_ia32_roundpd:
2716 case X86::BI__builtin_ia32_roundps256:
2717 case X86::BI__builtin_ia32_roundpd256:
Craig Topperf3914b72018-06-06 00:24:55 +00002718 case X86::BI__builtin_ia32_vec_ext_v16qi:
2719 case X86::BI__builtin_ia32_vec_ext_v16hi:
Craig Topper39c87102016-05-18 03:18:12 +00002720 i = 1; l = 0; u = 15;
2721 break;
Craig Topper7d17d722018-06-08 00:00:21 +00002722 case X86::BI__builtin_ia32_pblendd128:
2723 case X86::BI__builtin_ia32_blendps:
2724 case X86::BI__builtin_ia32_blendpd256:
Craig Topper422a1bb2018-06-08 07:18:33 +00002725 case X86::BI__builtin_ia32_shufpd256:
Craig Topper39c87102016-05-18 03:18:12 +00002726 case X86::BI__builtin_ia32_roundss:
2727 case X86::BI__builtin_ia32_roundsd:
2728 case X86::BI__builtin_ia32_rangepd128_mask:
2729 case X86::BI__builtin_ia32_rangepd256_mask:
2730 case X86::BI__builtin_ia32_rangepd512_mask:
2731 case X86::BI__builtin_ia32_rangeps128_mask:
2732 case X86::BI__builtin_ia32_rangeps256_mask:
2733 case X86::BI__builtin_ia32_rangeps512_mask:
2734 case X86::BI__builtin_ia32_getmantsd_round_mask:
2735 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topperf3914b72018-06-06 00:24:55 +00002736 case X86::BI__builtin_ia32_vec_set_v16qi:
2737 case X86::BI__builtin_ia32_vec_set_v16hi:
Craig Topper39c87102016-05-18 03:18:12 +00002738 i = 2; l = 0; u = 15;
2739 break;
Craig Topperf3914b72018-06-06 00:24:55 +00002740 case X86::BI__builtin_ia32_vec_ext_v32qi:
2741 i = 1; l = 0; u = 31;
2742 break;
Craig Topper39c87102016-05-18 03:18:12 +00002743 case X86::BI__builtin_ia32_cmpps:
2744 case X86::BI__builtin_ia32_cmpss:
2745 case X86::BI__builtin_ia32_cmppd:
2746 case X86::BI__builtin_ia32_cmpsd:
2747 case X86::BI__builtin_ia32_cmpps256:
2748 case X86::BI__builtin_ia32_cmppd256:
2749 case X86::BI__builtin_ia32_cmpps128_mask:
2750 case X86::BI__builtin_ia32_cmppd128_mask:
2751 case X86::BI__builtin_ia32_cmpps256_mask:
2752 case X86::BI__builtin_ia32_cmppd256_mask:
2753 case X86::BI__builtin_ia32_cmpps512_mask:
2754 case X86::BI__builtin_ia32_cmppd512_mask:
2755 case X86::BI__builtin_ia32_cmpsd_mask:
2756 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topperf3914b72018-06-06 00:24:55 +00002757 case X86::BI__builtin_ia32_vec_set_v32qi:
Craig Topper39c87102016-05-18 03:18:12 +00002758 i = 2; l = 0; u = 31;
2759 break;
Craig Topper03f4f042018-06-08 18:00:25 +00002760 case X86::BI__builtin_ia32_permdf256:
2761 case X86::BI__builtin_ia32_permdi256:
2762 case X86::BI__builtin_ia32_permdf512:
2763 case X86::BI__builtin_ia32_permdi512:
Craig Topperacf56012018-06-08 00:59:27 +00002764 case X86::BI__builtin_ia32_vpermilps:
2765 case X86::BI__builtin_ia32_vpermilps256:
2766 case X86::BI__builtin_ia32_vpermilpd512:
2767 case X86::BI__builtin_ia32_vpermilps512:
Craig Topper03de1662018-06-08 06:13:16 +00002768 case X86::BI__builtin_ia32_pshufd:
2769 case X86::BI__builtin_ia32_pshufd256:
2770 case X86::BI__builtin_ia32_pshufd512:
2771 case X86::BI__builtin_ia32_pshufhw:
2772 case X86::BI__builtin_ia32_pshufhw256:
2773 case X86::BI__builtin_ia32_pshufhw512:
2774 case X86::BI__builtin_ia32_pshuflw:
2775 case X86::BI__builtin_ia32_pshuflw256:
2776 case X86::BI__builtin_ia32_pshuflw512:
Craig Topper39c87102016-05-18 03:18:12 +00002777 case X86::BI__builtin_ia32_vcvtps2ph:
Craig Topper23a30222017-11-08 04:54:26 +00002778 case X86::BI__builtin_ia32_vcvtps2ph_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002779 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper23a30222017-11-08 04:54:26 +00002780 case X86::BI__builtin_ia32_vcvtps2ph256_mask:
2781 case X86::BI__builtin_ia32_vcvtps2ph512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002782 case X86::BI__builtin_ia32_rndscaleps_128_mask:
2783 case X86::BI__builtin_ia32_rndscalepd_128_mask:
2784 case X86::BI__builtin_ia32_rndscaleps_256_mask:
2785 case X86::BI__builtin_ia32_rndscalepd_256_mask:
2786 case X86::BI__builtin_ia32_rndscaleps_mask:
2787 case X86::BI__builtin_ia32_rndscalepd_mask:
2788 case X86::BI__builtin_ia32_reducepd128_mask:
2789 case X86::BI__builtin_ia32_reducepd256_mask:
2790 case X86::BI__builtin_ia32_reducepd512_mask:
2791 case X86::BI__builtin_ia32_reduceps128_mask:
2792 case X86::BI__builtin_ia32_reduceps256_mask:
2793 case X86::BI__builtin_ia32_reduceps512_mask:
2794 case X86::BI__builtin_ia32_prold512_mask:
2795 case X86::BI__builtin_ia32_prolq512_mask:
2796 case X86::BI__builtin_ia32_prold128_mask:
2797 case X86::BI__builtin_ia32_prold256_mask:
2798 case X86::BI__builtin_ia32_prolq128_mask:
2799 case X86::BI__builtin_ia32_prolq256_mask:
2800 case X86::BI__builtin_ia32_prord128_mask:
2801 case X86::BI__builtin_ia32_prord256_mask:
2802 case X86::BI__builtin_ia32_prorq128_mask:
2803 case X86::BI__builtin_ia32_prorq256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002804 case X86::BI__builtin_ia32_fpclasspd128_mask:
2805 case X86::BI__builtin_ia32_fpclasspd256_mask:
2806 case X86::BI__builtin_ia32_fpclassps128_mask:
2807 case X86::BI__builtin_ia32_fpclassps256_mask:
2808 case X86::BI__builtin_ia32_fpclassps512_mask:
2809 case X86::BI__builtin_ia32_fpclasspd512_mask:
2810 case X86::BI__builtin_ia32_fpclasssd_mask:
2811 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002812 i = 1; l = 0; u = 255;
2813 break;
Craig Topper9d3962f2018-06-08 18:00:22 +00002814 case X86::BI__builtin_ia32_vperm2f128_pd256:
2815 case X86::BI__builtin_ia32_vperm2f128_ps256:
2816 case X86::BI__builtin_ia32_vperm2f128_si256:
2817 case X86::BI__builtin_ia32_permti256:
Craig Topper7d17d722018-06-08 00:00:21 +00002818 case X86::BI__builtin_ia32_pblendw128:
2819 case X86::BI__builtin_ia32_pblendw256:
2820 case X86::BI__builtin_ia32_blendps256:
2821 case X86::BI__builtin_ia32_pblendd256:
Craig Topper39c87102016-05-18 03:18:12 +00002822 case X86::BI__builtin_ia32_palignr128:
2823 case X86::BI__builtin_ia32_palignr256:
Craig Topper8e3689c2018-05-22 20:48:24 +00002824 case X86::BI__builtin_ia32_palignr512:
Craig Toppere56819e2018-06-07 21:27:41 +00002825 case X86::BI__builtin_ia32_alignq512:
2826 case X86::BI__builtin_ia32_alignd512:
2827 case X86::BI__builtin_ia32_alignd128:
2828 case X86::BI__builtin_ia32_alignd256:
2829 case X86::BI__builtin_ia32_alignq128:
2830 case X86::BI__builtin_ia32_alignq256:
Craig Topper39c87102016-05-18 03:18:12 +00002831 case X86::BI__builtin_ia32_vcomisd:
2832 case X86::BI__builtin_ia32_vcomiss:
Craig Topper93921362018-06-07 23:03:08 +00002833 case X86::BI__builtin_ia32_shuf_f32x4:
2834 case X86::BI__builtin_ia32_shuf_f64x2:
2835 case X86::BI__builtin_ia32_shuf_i32x4:
2836 case X86::BI__builtin_ia32_shuf_i64x2:
Craig Topper422a1bb2018-06-08 07:18:33 +00002837 case X86::BI__builtin_ia32_shufpd512:
2838 case X86::BI__builtin_ia32_shufps:
2839 case X86::BI__builtin_ia32_shufps256:
2840 case X86::BI__builtin_ia32_shufps512:
Craig Topper39c87102016-05-18 03:18:12 +00002841 case X86::BI__builtin_ia32_dbpsadbw128_mask:
2842 case X86::BI__builtin_ia32_dbpsadbw256_mask:
2843 case X86::BI__builtin_ia32_dbpsadbw512_mask:
Craig Topper91926432018-01-11 01:38:02 +00002844 case X86::BI__builtin_ia32_vpshldd128_mask:
2845 case X86::BI__builtin_ia32_vpshldd256_mask:
2846 case X86::BI__builtin_ia32_vpshldd512_mask:
2847 case X86::BI__builtin_ia32_vpshldq128_mask:
2848 case X86::BI__builtin_ia32_vpshldq256_mask:
2849 case X86::BI__builtin_ia32_vpshldq512_mask:
2850 case X86::BI__builtin_ia32_vpshldw128_mask:
2851 case X86::BI__builtin_ia32_vpshldw256_mask:
2852 case X86::BI__builtin_ia32_vpshldw512_mask:
2853 case X86::BI__builtin_ia32_vpshrdd128_mask:
2854 case X86::BI__builtin_ia32_vpshrdd256_mask:
2855 case X86::BI__builtin_ia32_vpshrdd512_mask:
2856 case X86::BI__builtin_ia32_vpshrdq128_mask:
2857 case X86::BI__builtin_ia32_vpshrdq256_mask:
2858 case X86::BI__builtin_ia32_vpshrdq512_mask:
2859 case X86::BI__builtin_ia32_vpshrdw128_mask:
2860 case X86::BI__builtin_ia32_vpshrdw256_mask:
2861 case X86::BI__builtin_ia32_vpshrdw512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002862 i = 2; l = 0; u = 255;
2863 break;
2864 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2865 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2866 case X86::BI__builtin_ia32_fixupimmps512_mask:
2867 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2868 case X86::BI__builtin_ia32_fixupimmsd_mask:
2869 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2870 case X86::BI__builtin_ia32_fixupimmss_mask:
2871 case X86::BI__builtin_ia32_fixupimmss_maskz:
2872 case X86::BI__builtin_ia32_fixupimmpd128_mask:
2873 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2874 case X86::BI__builtin_ia32_fixupimmpd256_mask:
2875 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2876 case X86::BI__builtin_ia32_fixupimmps128_mask:
2877 case X86::BI__builtin_ia32_fixupimmps128_maskz:
2878 case X86::BI__builtin_ia32_fixupimmps256_mask:
2879 case X86::BI__builtin_ia32_fixupimmps256_maskz:
2880 case X86::BI__builtin_ia32_pternlogd512_mask:
2881 case X86::BI__builtin_ia32_pternlogd512_maskz:
2882 case X86::BI__builtin_ia32_pternlogq512_mask:
2883 case X86::BI__builtin_ia32_pternlogq512_maskz:
2884 case X86::BI__builtin_ia32_pternlogd128_mask:
2885 case X86::BI__builtin_ia32_pternlogd128_maskz:
2886 case X86::BI__builtin_ia32_pternlogd256_mask:
2887 case X86::BI__builtin_ia32_pternlogd256_maskz:
2888 case X86::BI__builtin_ia32_pternlogq128_mask:
2889 case X86::BI__builtin_ia32_pternlogq128_maskz:
2890 case X86::BI__builtin_ia32_pternlogq256_mask:
2891 case X86::BI__builtin_ia32_pternlogq256_maskz:
2892 i = 3; l = 0; u = 255;
2893 break;
Craig Topper9625db02017-03-12 22:19:10 +00002894 case X86::BI__builtin_ia32_gatherpfdpd:
2895 case X86::BI__builtin_ia32_gatherpfdps:
2896 case X86::BI__builtin_ia32_gatherpfqpd:
2897 case X86::BI__builtin_ia32_gatherpfqps:
2898 case X86::BI__builtin_ia32_scatterpfdpd:
2899 case X86::BI__builtin_ia32_scatterpfdps:
2900 case X86::BI__builtin_ia32_scatterpfqpd:
2901 case X86::BI__builtin_ia32_scatterpfqps:
Craig Topperf771f79b2017-03-31 17:22:30 +00002902 i = 4; l = 2; u = 3;
Craig Topper9625db02017-03-12 22:19:10 +00002903 break;
Craig Topper39c87102016-05-18 03:18:12 +00002904 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2905 case X86::BI__builtin_ia32_rndscaless_round_mask:
2906 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00002907 break;
Craig Topperd3623152018-06-07 17:28:03 +00002908 case X86::BI__builtin_ia32_pslldqi128:
2909 case X86::BI__builtin_ia32_pslldqi256:
2910 case X86::BI__builtin_ia32_pslldqi512:
2911 case X86::BI__builtin_ia32_psrldqi128:
2912 case X86::BI__builtin_ia32_psrldqi256:
2913 case X86::BI__builtin_ia32_psrldqi512:
2914 i = 1; l = 0; u = 1023;
2915 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002916 }
Craig Topperdd84ec52014-12-27 07:00:08 +00002917 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002918}
2919
Richard Smith55ce3522012-06-25 20:30:08 +00002920/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2921/// parameter with the FormatAttr's correct format_idx and firstDataArg.
2922/// Returns true when the format fits the function and the FormatStringInfo has
2923/// been populated.
2924bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2925 FormatStringInfo *FSI) {
2926 FSI->HasVAListArg = Format->getFirstArg() == 0;
2927 FSI->FormatIdx = Format->getFormatIdx() - 1;
2928 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002929
Richard Smith55ce3522012-06-25 20:30:08 +00002930 // The way the format attribute works in GCC, the implicit this argument
2931 // of member functions is counted. However, it doesn't appear in our own
2932 // lists, so decrement format_idx in that case.
2933 if (IsCXXMember) {
2934 if(FSI->FormatIdx == 0)
2935 return false;
2936 --FSI->FormatIdx;
2937 if (FSI->FirstDataArg != 0)
2938 --FSI->FirstDataArg;
2939 }
2940 return true;
2941}
Mike Stump11289f42009-09-09 15:08:12 +00002942
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002943/// Checks if a the given expression evaluates to null.
2944///
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002945/// Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00002946static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002947 // If the expression has non-null type, it doesn't evaluate to null.
2948 if (auto nullability
2949 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2950 if (*nullability == NullabilityKind::NonNull)
2951 return false;
2952 }
2953
Ted Kremeneka146db32014-01-17 06:24:47 +00002954 // As a special case, transparent unions initialized with zero are
2955 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002956 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00002957 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2958 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002959 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00002960 if (const InitListExpr *ILE =
2961 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002962 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00002963 }
2964
2965 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00002966 return (!Expr->isValueDependent() &&
2967 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2968 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002969}
2970
2971static void CheckNonNullArgument(Sema &S,
2972 const Expr *ArgExpr,
2973 SourceLocation CallSiteLoc) {
2974 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00002975 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2976 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00002977}
2978
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002979bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2980 FormatStringInfo FSI;
2981 if ((GetFormatStringType(Format) == FST_NSString) &&
2982 getFormatStringInfo(Format, false, &FSI)) {
2983 Idx = FSI.FormatIdx;
2984 return true;
2985 }
2986 return false;
2987}
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002988
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002989/// Diagnose use of %s directive in an NSString which is being passed
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002990/// as formatting string to formatting method.
2991static void
2992DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2993 const NamedDecl *FDecl,
2994 Expr **Args,
2995 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002996 unsigned Idx = 0;
2997 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002998 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2999 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00003000 Idx = 2;
3001 Format = true;
3002 }
3003 else
3004 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
3005 if (S.GetFormatNSStringIdx(I, Idx)) {
3006 Format = true;
3007 break;
3008 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00003009 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00003010 if (!Format || NumArgs <= Idx)
3011 return;
3012 const Expr *FormatExpr = Args[Idx];
3013 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
3014 FormatExpr = CSCE->getSubExpr();
3015 const StringLiteral *FormatString;
3016 if (const ObjCStringLiteral *OSL =
3017 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
3018 FormatString = OSL->getString();
3019 else
3020 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
3021 if (!FormatString)
3022 return;
3023 if (S.FormatStringHasSArg(FormatString)) {
3024 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
3025 << "%s" << 1 << 1;
3026 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
3027 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00003028 }
3029}
3030
Douglas Gregorb4866e82015-06-19 18:13:19 +00003031/// Determine whether the given type has a non-null nullability annotation.
3032static bool isNonNullType(ASTContext &ctx, QualType type) {
3033 if (auto nullability = type->getNullability(ctx))
3034 return *nullability == NullabilityKind::NonNull;
3035
3036 return false;
3037}
3038
Ted Kremenek2bc73332014-01-17 06:24:43 +00003039static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00003040 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00003041 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00003042 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00003043 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00003044 assert((FDecl || Proto) && "Need a function declaration or prototype");
3045
Ted Kremenek9aedc152014-01-17 06:24:56 +00003046 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00003047 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00003048 if (FDecl) {
3049 // Handle the nonnull attribute on the function/method declaration itself.
3050 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
3051 if (!NonNull->args_size()) {
3052 // Easy case: all pointer arguments are nonnull.
3053 for (const auto *Arg : Args)
3054 if (S.isValidPointerAttrType(Arg->getType()))
3055 CheckNonNullArgument(S, Arg, CallSiteLoc);
3056 return;
3057 }
Richard Smith588bd9b2014-08-27 04:59:42 +00003058
Joel E. Denny81508102018-03-13 14:51:22 +00003059 for (const ParamIdx &Idx : NonNull->args()) {
3060 unsigned IdxAST = Idx.getASTIndex();
3061 if (IdxAST >= Args.size())
Douglas Gregorb4866e82015-06-19 18:13:19 +00003062 continue;
3063 if (NonNullArgs.empty())
3064 NonNullArgs.resize(Args.size());
Joel E. Denny81508102018-03-13 14:51:22 +00003065 NonNullArgs.set(IdxAST);
Douglas Gregorb4866e82015-06-19 18:13:19 +00003066 }
Richard Smith588bd9b2014-08-27 04:59:42 +00003067 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00003068 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00003069
Douglas Gregorb4866e82015-06-19 18:13:19 +00003070 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
3071 // Handle the nonnull attribute on the parameters of the
3072 // function/method.
3073 ArrayRef<ParmVarDecl*> parms;
3074 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
3075 parms = FD->parameters();
3076 else
3077 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
3078
3079 unsigned ParamIndex = 0;
3080 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
3081 I != E; ++I, ++ParamIndex) {
3082 const ParmVarDecl *PVD = *I;
3083 if (PVD->hasAttr<NonNullAttr>() ||
3084 isNonNullType(S.Context, PVD->getType())) {
3085 if (NonNullArgs.empty())
3086 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00003087
Douglas Gregorb4866e82015-06-19 18:13:19 +00003088 NonNullArgs.set(ParamIndex);
3089 }
3090 }
3091 } else {
3092 // If we have a non-function, non-method declaration but no
3093 // function prototype, try to dig out the function prototype.
3094 if (!Proto) {
3095 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
3096 QualType type = VD->getType().getNonReferenceType();
3097 if (auto pointerType = type->getAs<PointerType>())
3098 type = pointerType->getPointeeType();
3099 else if (auto blockType = type->getAs<BlockPointerType>())
3100 type = blockType->getPointeeType();
3101 // FIXME: data member pointers?
3102
3103 // Dig out the function prototype, if there is one.
3104 Proto = type->getAs<FunctionProtoType>();
3105 }
3106 }
3107
3108 // Fill in non-null argument information from the nullability
3109 // information on the parameter types (if we have them).
3110 if (Proto) {
3111 unsigned Index = 0;
3112 for (auto paramType : Proto->getParamTypes()) {
3113 if (isNonNullType(S.Context, paramType)) {
3114 if (NonNullArgs.empty())
3115 NonNullArgs.resize(Args.size());
3116
3117 NonNullArgs.set(Index);
3118 }
3119
3120 ++Index;
3121 }
3122 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00003123 }
Richard Smith588bd9b2014-08-27 04:59:42 +00003124
Douglas Gregorb4866e82015-06-19 18:13:19 +00003125 // Check for non-null arguments.
3126 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
3127 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00003128 if (NonNullArgs[ArgIndex])
3129 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00003130 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00003131}
3132
Richard Smith55ce3522012-06-25 20:30:08 +00003133/// Handles the checks for format strings, non-POD arguments to vararg
George Burgess IVce6284b2017-01-28 02:19:40 +00003134/// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
3135/// attributes.
Douglas Gregorb4866e82015-06-19 18:13:19 +00003136void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
George Burgess IVce6284b2017-01-28 02:19:40 +00003137 const Expr *ThisArg, ArrayRef<const Expr *> Args,
3138 bool IsMemberFunction, SourceLocation Loc,
3139 SourceRange Range, VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00003140 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00003141 if (CurContext->isDependentContext())
3142 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00003143
Ted Kremenekb8176da2010-09-09 04:33:05 +00003144 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00003145 llvm::SmallBitVector CheckedVarArgs;
3146 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003147 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00003148 // Only create vector if there are format attributes.
3149 CheckedVarArgs.resize(Args.size());
3150
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003151 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00003152 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00003153 }
Richard Smithd7293d72013-08-05 18:49:43 +00003154 }
Richard Smith55ce3522012-06-25 20:30:08 +00003155
3156 // Refuse POD arguments that weren't caught by the format string
3157 // checks above.
Richard Smith836de6b2016-12-19 23:59:34 +00003158 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
3159 if (CallType != VariadicDoesNotApply &&
3160 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00003161 unsigned NumParams = Proto ? Proto->getNumParams()
3162 : FDecl && isa<FunctionDecl>(FDecl)
3163 ? cast<FunctionDecl>(FDecl)->getNumParams()
3164 : FDecl && isa<ObjCMethodDecl>(FDecl)
3165 ? cast<ObjCMethodDecl>(FDecl)->param_size()
3166 : 0;
3167
Alp Toker9cacbab2014-01-20 20:26:09 +00003168 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00003169 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00003170 if (const Expr *Arg = Args[ArgIdx]) {
3171 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
3172 checkVariadicArgument(Arg, CallType);
3173 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00003174 }
Richard Smithd7293d72013-08-05 18:49:43 +00003175 }
Mike Stump11289f42009-09-09 15:08:12 +00003176
Douglas Gregorb4866e82015-06-19 18:13:19 +00003177 if (FDecl || Proto) {
3178 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00003179
Richard Trieu41bc0992013-06-22 00:20:41 +00003180 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00003181 if (FDecl) {
3182 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +00003183 CheckArgumentWithTypeTag(I, Args, Loc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00003184 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00003185 }
George Burgess IVce6284b2017-01-28 02:19:40 +00003186
3187 if (FD)
3188 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
Richard Smith55ce3522012-06-25 20:30:08 +00003189}
3190
3191/// CheckConstructorCall - Check a constructor call for correctness and safety
3192/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003193void Sema::CheckConstructorCall(FunctionDecl *FDecl,
3194 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003195 const FunctionProtoType *Proto,
3196 SourceLocation Loc) {
3197 VariadicCallType CallType =
3198 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
George Burgess IVce6284b2017-01-28 02:19:40 +00003199 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
3200 Loc, SourceRange(), CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00003201}
3202
3203/// CheckFunctionCall - Check a direct function call for various correctness
3204/// and safety properties not strictly enforced by the C type system.
3205bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
3206 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00003207 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
3208 isa<CXXMethodDecl>(FDecl);
3209 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
3210 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00003211 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
3212 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00003213 Expr** Args = TheCall->getArgs();
3214 unsigned NumArgs = TheCall->getNumArgs();
George Burgess IVce6284b2017-01-28 02:19:40 +00003215
3216 Expr *ImplicitThis = nullptr;
Eli Friedmanadf42182012-10-11 00:34:15 +00003217 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00003218 // If this is a call to a member operator, hide the first argument
3219 // from checkCall.
3220 // FIXME: Our choice of AST representation here is less than ideal.
George Burgess IVce6284b2017-01-28 02:19:40 +00003221 ImplicitThis = Args[0];
Eli Friedman726d11c2012-10-11 00:30:58 +00003222 ++Args;
3223 --NumArgs;
George Burgess IVce6284b2017-01-28 02:19:40 +00003224 } else if (IsMemberFunction)
3225 ImplicitThis =
3226 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
3227
3228 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00003229 IsMemberFunction, TheCall->getRParenLoc(),
3230 TheCall->getCallee()->getSourceRange(), CallType);
3231
3232 IdentifierInfo *FnInfo = FDecl->getIdentifier();
3233 // None of the checks below are needed for functions that don't have
3234 // simple names (e.g., C++ conversion functions).
3235 if (!FnInfo)
3236 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003237
Richard Trieua7f30b12016-12-06 01:42:28 +00003238 CheckAbsoluteValueFunction(TheCall, FDecl);
3239 CheckMaxUnsignedZero(TheCall, FDecl);
Richard Trieu67c00712016-12-05 23:41:46 +00003240
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00003241 if (getLangOpts().ObjC1)
3242 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003243
Anna Zaks22122702012-01-17 00:37:07 +00003244 unsigned CMId = FDecl->getMemoryFunctionKind();
3245 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00003246 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00003247
Anna Zaks201d4892012-01-13 21:52:01 +00003248 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00003249 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00003250 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00003251 else if (CMId == Builtin::BIstrncat)
3252 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00003253 else
Anna Zaks22122702012-01-17 00:37:07 +00003254 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003255
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003256 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00003257}
3258
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003259bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00003260 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00003261 VariadicCallType CallType =
3262 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003263
George Burgess IVce6284b2017-01-28 02:19:40 +00003264 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
3265 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
Douglas Gregorb4866e82015-06-19 18:13:19 +00003266 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003267
3268 return false;
3269}
3270
Richard Trieu664c4c62013-06-20 21:03:13 +00003271bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
3272 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00003273 QualType Ty;
3274 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00003275 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00003276 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00003277 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00003278 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003279 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003280
Douglas Gregorb4866e82015-06-19 18:13:19 +00003281 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
3282 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003283 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003284
Richard Trieu664c4c62013-06-20 21:03:13 +00003285 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00003286 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00003287 CallType = VariadicDoesNotApply;
3288 } else if (Ty->isBlockPointerType()) {
3289 CallType = VariadicBlock;
3290 } else { // Ty->isFunctionPointerType()
3291 CallType = VariadicFunction;
3292 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003293
George Burgess IVce6284b2017-01-28 02:19:40 +00003294 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
Douglas Gregorb4866e82015-06-19 18:13:19 +00003295 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
3296 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00003297 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00003298
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003299 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00003300}
3301
Richard Trieu41bc0992013-06-22 00:20:41 +00003302/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
3303/// such as function pointers returned from functions.
3304bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003305 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00003306 TheCall->getCallee());
George Burgess IVce6284b2017-01-28 02:19:40 +00003307 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00003308 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00003309 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00003310 TheCall->getCallee()->getSourceRange(), CallType);
3311
3312 return false;
3313}
3314
Tim Northovere94a34c2014-03-11 10:49:14 +00003315static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00003316 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00003317 return false;
3318
JF Bastiendda2cb12016-04-18 18:01:49 +00003319 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00003320 switch (Op) {
3321 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00003322 case AtomicExpr::AO__opencl_atomic_init:
Tim Northovere94a34c2014-03-11 10:49:14 +00003323 llvm_unreachable("There is no ordering argument for an init");
3324
3325 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00003326 case AtomicExpr::AO__opencl_atomic_load:
Tim Northovere94a34c2014-03-11 10:49:14 +00003327 case AtomicExpr::AO__atomic_load_n:
3328 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00003329 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
3330 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00003331
3332 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00003333 case AtomicExpr::AO__opencl_atomic_store:
Tim Northovere94a34c2014-03-11 10:49:14 +00003334 case AtomicExpr::AO__atomic_store:
3335 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00003336 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
3337 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
3338 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00003339
3340 default:
3341 return true;
3342 }
3343}
3344
Richard Smithfeea8832012-04-12 05:08:17 +00003345ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
3346 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003347 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3348 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003349
Yaxun Liu39195062017-08-04 18:16:31 +00003350 // All the non-OpenCL operations take one of the following forms.
3351 // The OpenCL operations take the __c11 forms with one extra argument for
3352 // synchronization scope.
Richard Smithfeea8832012-04-12 05:08:17 +00003353 enum {
3354 // C __c11_atomic_init(A *, C)
3355 Init,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003356
Richard Smithfeea8832012-04-12 05:08:17 +00003357 // C __c11_atomic_load(A *, int)
3358 Load,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003359
Richard Smithfeea8832012-04-12 05:08:17 +00003360 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00003361 LoadCopy,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003362
Eric Fiselier8d662442016-03-30 23:39:56 +00003363 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00003364 Copy,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003365
Richard Smithfeea8832012-04-12 05:08:17 +00003366 // C __c11_atomic_add(A *, M, int)
3367 Arithmetic,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003368
Richard Smithfeea8832012-04-12 05:08:17 +00003369 // C __atomic_exchange_n(A *, CP, int)
3370 Xchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003371
Richard Smithfeea8832012-04-12 05:08:17 +00003372 // void __atomic_exchange(A *, C *, CP, int)
3373 GNUXchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003374
Richard Smithfeea8832012-04-12 05:08:17 +00003375 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
3376 C11CmpXchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003377
Richard Smithfeea8832012-04-12 05:08:17 +00003378 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
3379 GNUCmpXchg
3380 } Form = Init;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003381
Yaxun Liu39195062017-08-04 18:16:31 +00003382 const unsigned NumForm = GNUCmpXchg + 1;
Eric Fiselier8d662442016-03-30 23:39:56 +00003383 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
3384 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00003385 // where:
3386 // C is an appropriate type,
3387 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
3388 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
3389 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
3390 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003391
Yaxun Liu39195062017-08-04 18:16:31 +00003392 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
3393 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
3394 "need to update code for modified forms");
Gabor Horvath98bd0982015-03-16 09:59:54 +00003395 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
3396 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
3397 AtomicExpr::AO__atomic_load,
3398 "need to update code for modified C11 atomics");
Yaxun Liu39195062017-08-04 18:16:31 +00003399 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
3400 Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
3401 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
3402 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
3403 IsOpenCL;
Richard Smithfeea8832012-04-12 05:08:17 +00003404 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
3405 Op == AtomicExpr::AO__atomic_store_n ||
3406 Op == AtomicExpr::AO__atomic_exchange_n ||
3407 Op == AtomicExpr::AO__atomic_compare_exchange_n;
3408 bool IsAddSub = false;
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00003409 bool IsMinMax = false;
Richard Smithfeea8832012-04-12 05:08:17 +00003410
3411 switch (Op) {
3412 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00003413 case AtomicExpr::AO__opencl_atomic_init:
Richard Smithfeea8832012-04-12 05:08:17 +00003414 Form = Init;
3415 break;
3416
3417 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00003418 case AtomicExpr::AO__opencl_atomic_load:
Richard Smithfeea8832012-04-12 05:08:17 +00003419 case AtomicExpr::AO__atomic_load_n:
3420 Form = Load;
3421 break;
3422
Richard Smithfeea8832012-04-12 05:08:17 +00003423 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00003424 Form = LoadCopy;
3425 break;
3426
3427 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00003428 case AtomicExpr::AO__opencl_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00003429 case AtomicExpr::AO__atomic_store:
3430 case AtomicExpr::AO__atomic_store_n:
3431 Form = Copy;
3432 break;
3433
3434 case AtomicExpr::AO__c11_atomic_fetch_add:
3435 case AtomicExpr::AO__c11_atomic_fetch_sub:
Yaxun Liu39195062017-08-04 18:16:31 +00003436 case AtomicExpr::AO__opencl_atomic_fetch_add:
3437 case AtomicExpr::AO__opencl_atomic_fetch_sub:
3438 case AtomicExpr::AO__opencl_atomic_fetch_min:
3439 case AtomicExpr::AO__opencl_atomic_fetch_max:
Richard Smithfeea8832012-04-12 05:08:17 +00003440 case AtomicExpr::AO__atomic_fetch_add:
3441 case AtomicExpr::AO__atomic_fetch_sub:
3442 case AtomicExpr::AO__atomic_add_fetch:
3443 case AtomicExpr::AO__atomic_sub_fetch:
3444 IsAddSub = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00003445 LLVM_FALLTHROUGH;
Richard Smithfeea8832012-04-12 05:08:17 +00003446 case AtomicExpr::AO__c11_atomic_fetch_and:
3447 case AtomicExpr::AO__c11_atomic_fetch_or:
3448 case AtomicExpr::AO__c11_atomic_fetch_xor:
Yaxun Liu39195062017-08-04 18:16:31 +00003449 case AtomicExpr::AO__opencl_atomic_fetch_and:
3450 case AtomicExpr::AO__opencl_atomic_fetch_or:
3451 case AtomicExpr::AO__opencl_atomic_fetch_xor:
Richard Smithfeea8832012-04-12 05:08:17 +00003452 case AtomicExpr::AO__atomic_fetch_and:
3453 case AtomicExpr::AO__atomic_fetch_or:
3454 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00003455 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00003456 case AtomicExpr::AO__atomic_and_fetch:
3457 case AtomicExpr::AO__atomic_or_fetch:
3458 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00003459 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00003460 Form = Arithmetic;
3461 break;
3462
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00003463 case AtomicExpr::AO__atomic_fetch_min:
3464 case AtomicExpr::AO__atomic_fetch_max:
3465 IsMinMax = true;
3466 Form = Arithmetic;
3467 break;
3468
Richard Smithfeea8832012-04-12 05:08:17 +00003469 case AtomicExpr::AO__c11_atomic_exchange:
Yaxun Liu39195062017-08-04 18:16:31 +00003470 case AtomicExpr::AO__opencl_atomic_exchange:
Richard Smithfeea8832012-04-12 05:08:17 +00003471 case AtomicExpr::AO__atomic_exchange_n:
3472 Form = Xchg;
3473 break;
3474
3475 case AtomicExpr::AO__atomic_exchange:
3476 Form = GNUXchg;
3477 break;
3478
3479 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3480 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
Yaxun Liu39195062017-08-04 18:16:31 +00003481 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
3482 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
Richard Smithfeea8832012-04-12 05:08:17 +00003483 Form = C11CmpXchg;
3484 break;
3485
3486 case AtomicExpr::AO__atomic_compare_exchange:
3487 case AtomicExpr::AO__atomic_compare_exchange_n:
3488 Form = GNUCmpXchg;
3489 break;
3490 }
3491
Yaxun Liu39195062017-08-04 18:16:31 +00003492 unsigned AdjustedNumArgs = NumArgs[Form];
3493 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
3494 ++AdjustedNumArgs;
Richard Smithfeea8832012-04-12 05:08:17 +00003495 // Check we have the right number of arguments.
Yaxun Liu39195062017-08-04 18:16:31 +00003496 if (TheCall->getNumArgs() < AdjustedNumArgs) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003497 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Yaxun Liu39195062017-08-04 18:16:31 +00003498 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003499 << TheCall->getCallee()->getSourceRange();
3500 return ExprError();
Yaxun Liu39195062017-08-04 18:16:31 +00003501 } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
3502 Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003503 diag::err_typecheck_call_too_many_args)
Yaxun Liu39195062017-08-04 18:16:31 +00003504 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003505 << TheCall->getCallee()->getSourceRange();
3506 return ExprError();
3507 }
3508
Richard Smithfeea8832012-04-12 05:08:17 +00003509 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003510 Expr *Ptr = TheCall->getArg(0);
George Burgess IV92b43a42016-07-21 03:28:13 +00003511 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
3512 if (ConvertedPtr.isInvalid())
3513 return ExprError();
3514
3515 Ptr = ConvertedPtr.get();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003516 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
3517 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00003518 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003519 << Ptr->getType() << Ptr->getSourceRange();
3520 return ExprError();
3521 }
3522
Richard Smithfeea8832012-04-12 05:08:17 +00003523 // For a __c11 builtin, this should be a pointer to an _Atomic type.
3524 QualType AtomTy = pointerType->getPointeeType(); // 'A'
3525 QualType ValType = AtomTy; // 'C'
3526 if (IsC11) {
3527 if (!AtomTy->isAtomicType()) {
3528 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
3529 << Ptr->getType() << Ptr->getSourceRange();
3530 return ExprError();
3531 }
Yaxun Liu39195062017-08-04 18:16:31 +00003532 if (AtomTy.isConstQualified() ||
3533 AtomTy.getAddressSpace() == LangAS::opencl_constant) {
Richard Smithe00921a2012-09-15 06:09:58 +00003534 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
Yaxun Liu39195062017-08-04 18:16:31 +00003535 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
3536 << Ptr->getSourceRange();
Richard Smithe00921a2012-09-15 06:09:58 +00003537 return ExprError();
3538 }
Richard Smithfeea8832012-04-12 05:08:17 +00003539 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00003540 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00003541 if (ValType.isConstQualified()) {
3542 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
3543 << Ptr->getType() << Ptr->getSourceRange();
3544 return ExprError();
3545 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003546 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003547
Richard Smithfeea8832012-04-12 05:08:17 +00003548 // For an arithmetic operation, the implied arithmetic must be well-formed.
3549 if (Form == Arithmetic) {
3550 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00003551 if (IsAddSub && !ValType->isIntegerType()
3552 && !ValType->isPointerType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00003553 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3554 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3555 return ExprError();
3556 }
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00003557 if (IsMinMax) {
3558 const BuiltinType *BT = ValType->getAs<BuiltinType>();
3559 if (!BT || (BT->getKind() != BuiltinType::Int &&
3560 BT->getKind() != BuiltinType::UInt)) {
3561 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_int32_or_ptr);
3562 return ExprError();
3563 }
3564 }
3565 if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00003566 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
3567 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3568 return ExprError();
3569 }
David Majnemere85cff82015-01-28 05:48:06 +00003570 if (IsC11 && ValType->isPointerType() &&
3571 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
3572 diag::err_incomplete_type)) {
3573 return ExprError();
3574 }
Richard Smithfeea8832012-04-12 05:08:17 +00003575 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
3576 // For __atomic_*_n operations, the value type must be a scalar integral or
3577 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003578 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00003579 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3580 return ExprError();
3581 }
3582
Eli Friedmanaa769812013-09-11 03:49:34 +00003583 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
3584 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00003585 // For GNU atomics, require a trivially-copyable type. This is not part of
3586 // the GNU atomics specification, but we enforce it for sanity.
3587 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003588 << Ptr->getType() << Ptr->getSourceRange();
3589 return ExprError();
3590 }
3591
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003592 switch (ValType.getObjCLifetime()) {
3593 case Qualifiers::OCL_None:
3594 case Qualifiers::OCL_ExplicitNone:
3595 // okay
3596 break;
3597
3598 case Qualifiers::OCL_Weak:
3599 case Qualifiers::OCL_Strong:
3600 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00003601 // FIXME: Can this happen? By this point, ValType should be known
3602 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003603 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3604 << ValType << Ptr->getSourceRange();
3605 return ExprError();
3606 }
3607
JF Bastien7f0a05a2018-05-25 00:07:09 +00003608 // All atomic operations have an overload which takes a pointer to a volatile
3609 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
3610 // into the result or the other operands. Similarly atomic_load takes a
3611 // pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00003612 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00003613 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003614 QualType ResultType = ValType;
Yaxun Liu39195062017-08-04 18:16:31 +00003615 if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
3616 Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003617 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00003618 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003619 ResultType = Context.BoolTy;
3620
Richard Smithfeea8832012-04-12 05:08:17 +00003621 // The type of a parameter passed 'by value'. In the GNU atomics, such
3622 // arguments are actually passed as pointers.
3623 QualType ByValType = ValType; // 'CP'
JF Bastien7f0a05a2018-05-25 00:07:09 +00003624 bool IsPassedByAddress = false;
3625 if (!IsC11 && !IsN) {
Richard Smithfeea8832012-04-12 05:08:17 +00003626 ByValType = Ptr->getType();
JF Bastien7f0a05a2018-05-25 00:07:09 +00003627 IsPassedByAddress = true;
3628 }
Richard Smithfeea8832012-04-12 05:08:17 +00003629
JF Bastien7f0a05a2018-05-25 00:07:09 +00003630 // The first argument's non-CV pointer type is used to deduce the type of
3631 // subsequent arguments, except for:
3632 // - weak flag (always converted to bool)
3633 // - memory order (always converted to int)
3634 // - scope (always converted to int)
3635 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003636 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00003637 if (i < NumVals[Form] + 1) {
3638 switch (i) {
JF Bastien7f0a05a2018-05-25 00:07:09 +00003639 case 0:
3640 // The first argument is always a pointer. It has a fixed type.
3641 // It is always dereferenced, a nullptr is undefined.
3642 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart());
3643 // Nothing else to do: we already know all we want about this pointer.
3644 continue;
Richard Smithfeea8832012-04-12 05:08:17 +00003645 case 1:
3646 // The second argument is the non-atomic operand. For arithmetic, this
3647 // is always passed by value, and for a compare_exchange it is always
3648 // passed by address. For the rest, GNU uses by-address and C11 uses
3649 // by-value.
3650 assert(Form != Load);
3651 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
3652 Ty = ValType;
JF Bastien7f0a05a2018-05-25 00:07:09 +00003653 else if (Form == Copy || Form == Xchg) {
3654 if (IsPassedByAddress)
3655 // The value pointer is always dereferenced, a nullptr is undefined.
3656 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart());
Richard Smithfeea8832012-04-12 05:08:17 +00003657 Ty = ByValType;
JF Bastien7f0a05a2018-05-25 00:07:09 +00003658 } else if (Form == Arithmetic)
Richard Smithfeea8832012-04-12 05:08:17 +00003659 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003660 else {
3661 Expr *ValArg = TheCall->getArg(i);
JF Bastien7f0a05a2018-05-25 00:07:09 +00003662 // The value pointer is always dereferenced, a nullptr is undefined.
Alex Lorenz67522152016-11-23 16:57:03 +00003663 CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
Alexander Richardson6d989432017-10-15 18:48:14 +00003664 LangAS AS = LangAS::Default;
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003665 // Keep address space of non-atomic pointer type.
3666 if (const PointerType *PtrTy =
3667 ValArg->getType()->getAs<PointerType>()) {
3668 AS = PtrTy->getPointeeType().getAddressSpace();
3669 }
3670 Ty = Context.getPointerType(
3671 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
3672 }
Richard Smithfeea8832012-04-12 05:08:17 +00003673 break;
3674 case 2:
JF Bastien7f0a05a2018-05-25 00:07:09 +00003675 // The third argument to compare_exchange / GNU exchange is the desired
JF Bastien7853d5f2018-05-25 17:36:49 +00003676 // value, either by-value (for the C11 and *_n variant) or as a pointer.
3677 if (IsPassedByAddress)
JF Bastien7f0a05a2018-05-25 00:07:09 +00003678 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart());
Richard Smithfeea8832012-04-12 05:08:17 +00003679 Ty = ByValType;
3680 break;
3681 case 3:
3682 // The fourth argument to GNU compare_exchange is a 'weak' flag.
3683 Ty = Context.BoolTy;
3684 break;
3685 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003686 } else {
Yaxun Liu39195062017-08-04 18:16:31 +00003687 // The order(s) and scope are always converted to int.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003688 Ty = Context.IntTy;
3689 }
Richard Smithfeea8832012-04-12 05:08:17 +00003690
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003691 InitializedEntity Entity =
3692 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00003693 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003694 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3695 if (Arg.isInvalid())
3696 return true;
3697 TheCall->setArg(i, Arg.get());
3698 }
3699
Richard Smithfeea8832012-04-12 05:08:17 +00003700 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003701 SmallVector<Expr*, 5> SubExprs;
3702 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00003703 switch (Form) {
3704 case Init:
3705 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00003706 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003707 break;
3708 case Load:
3709 SubExprs.push_back(TheCall->getArg(1)); // Order
3710 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00003711 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00003712 case Copy:
3713 case Arithmetic:
3714 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003715 SubExprs.push_back(TheCall->getArg(2)); // Order
3716 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003717 break;
3718 case GNUXchg:
3719 // Note, AtomicExpr::getVal2() has a special case for this atomic.
3720 SubExprs.push_back(TheCall->getArg(3)); // Order
3721 SubExprs.push_back(TheCall->getArg(1)); // Val1
3722 SubExprs.push_back(TheCall->getArg(2)); // Val2
3723 break;
3724 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003725 SubExprs.push_back(TheCall->getArg(3)); // Order
3726 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003727 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00003728 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00003729 break;
3730 case GNUCmpXchg:
3731 SubExprs.push_back(TheCall->getArg(4)); // Order
3732 SubExprs.push_back(TheCall->getArg(1)); // Val1
3733 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
3734 SubExprs.push_back(TheCall->getArg(2)); // Val2
3735 SubExprs.push_back(TheCall->getArg(3)); // Weak
3736 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003737 }
Tim Northovere94a34c2014-03-11 10:49:14 +00003738
3739 if (SubExprs.size() >= 2 && Form != Init) {
3740 llvm::APSInt Result(32);
3741 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
3742 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00003743 Diag(SubExprs[1]->getLocStart(),
3744 diag::warn_atomic_op_has_invalid_memory_order)
3745 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00003746 }
3747
Yaxun Liu30d652a2017-08-15 16:02:49 +00003748 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
3749 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
3750 llvm::APSInt Result(32);
3751 if (Scope->isIntegerConstantExpr(Result, Context) &&
3752 !ScopeModel->isValid(Result.getZExtValue())) {
3753 Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope)
3754 << Scope->getSourceRange();
3755 }
3756 SubExprs.push_back(Scope);
3757 }
3758
Fariborz Jahanian615de762013-05-28 17:37:39 +00003759 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
3760 SubExprs, ResultType, Op,
3761 TheCall->getRParenLoc());
3762
3763 if ((Op == AtomicExpr::AO__c11_atomic_load ||
Yaxun Liu39195062017-08-04 18:16:31 +00003764 Op == AtomicExpr::AO__c11_atomic_store ||
3765 Op == AtomicExpr::AO__opencl_atomic_load ||
3766 Op == AtomicExpr::AO__opencl_atomic_store ) &&
Fariborz Jahanian615de762013-05-28 17:37:39 +00003767 Context.AtomicUsesUnsupportedLibcall(AE))
Yaxun Liu39195062017-08-04 18:16:31 +00003768 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib)
3769 << ((Op == AtomicExpr::AO__c11_atomic_load ||
3770 Op == AtomicExpr::AO__opencl_atomic_load)
3771 ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003772
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003773 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003774}
3775
John McCall29ad95b2011-08-27 01:09:30 +00003776/// checkBuiltinArgument - Given a call to a builtin function, perform
3777/// normal type-checking on the given argument, updating the call in
3778/// place. This is useful when a builtin function requires custom
3779/// type-checking for some of its arguments but not necessarily all of
3780/// them.
3781///
3782/// Returns true on error.
3783static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
3784 FunctionDecl *Fn = E->getDirectCallee();
3785 assert(Fn && "builtin call without direct callee!");
3786
3787 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
3788 InitializedEntity Entity =
3789 InitializedEntity::InitializeParameter(S.Context, Param);
3790
3791 ExprResult Arg = E->getArg(0);
3792 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3793 if (Arg.isInvalid())
3794 return true;
3795
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003796 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00003797 return false;
3798}
3799
Chris Lattnerdc046542009-05-08 06:58:22 +00003800/// SemaBuiltinAtomicOverloaded - We have a call to a function like
3801/// __sync_fetch_and_add, which is an overloaded function based on the pointer
3802/// type of its first argument. The main ActOnCallExpr routines have already
3803/// promoted the types of arguments because all of these calls are prototyped as
3804/// void(...).
3805///
3806/// This function goes through and does final semantic checking for these
3807/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00003808ExprResult
3809Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003810 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00003811 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3812 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3813
3814 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003815 if (TheCall->getNumArgs() < 1) {
3816 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3817 << 0 << 1 << TheCall->getNumArgs()
3818 << TheCall->getCallee()->getSourceRange();
3819 return ExprError();
3820 }
Mike Stump11289f42009-09-09 15:08:12 +00003821
Chris Lattnerdc046542009-05-08 06:58:22 +00003822 // Inspect the first argument of the atomic builtin. This should always be
3823 // a pointer type, whose element is an integral scalar or pointer type.
3824 // Because it is a pointer type, we don't have to worry about any implicit
3825 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003826 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00003827 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00003828 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3829 if (FirstArgResult.isInvalid())
3830 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003831 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00003832 TheCall->setArg(0, FirstArg);
3833
John McCall31168b02011-06-15 23:02:42 +00003834 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3835 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003836 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3837 << FirstArg->getType() << FirstArg->getSourceRange();
3838 return ExprError();
3839 }
Mike Stump11289f42009-09-09 15:08:12 +00003840
John McCall31168b02011-06-15 23:02:42 +00003841 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00003842 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003843 !ValType->isBlockPointerType()) {
3844 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3845 << FirstArg->getType() << FirstArg->getSourceRange();
3846 return ExprError();
3847 }
Chris Lattnerdc046542009-05-08 06:58:22 +00003848
Aaron Ballmana383c942018-05-05 17:38:42 +00003849 if (ValType.isConstQualified()) {
3850 Diag(DRE->getLocStart(), diag::err_atomic_builtin_cannot_be_const)
3851 << FirstArg->getType() << FirstArg->getSourceRange();
3852 return ExprError();
3853 }
3854
John McCall31168b02011-06-15 23:02:42 +00003855 switch (ValType.getObjCLifetime()) {
3856 case Qualifiers::OCL_None:
3857 case Qualifiers::OCL_ExplicitNone:
3858 // okay
3859 break;
3860
3861 case Qualifiers::OCL_Weak:
3862 case Qualifiers::OCL_Strong:
3863 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00003864 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00003865 << ValType << FirstArg->getSourceRange();
3866 return ExprError();
3867 }
3868
John McCallb50451a2011-10-05 07:41:44 +00003869 // Strip any qualifiers off ValType.
3870 ValType = ValType.getUnqualifiedType();
3871
Chandler Carruth3973af72010-07-18 20:54:12 +00003872 // The majority of builtins return a value, but a few have special return
3873 // types, so allow them to override appropriately below.
3874 QualType ResultType = ValType;
3875
Chris Lattnerdc046542009-05-08 06:58:22 +00003876 // We need to figure out which concrete builtin this maps onto. For example,
3877 // __sync_fetch_and_add with a 2 byte object turns into
3878 // __sync_fetch_and_add_2.
3879#define BUILTIN_ROW(x) \
3880 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3881 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00003882
Chris Lattnerdc046542009-05-08 06:58:22 +00003883 static const unsigned BuiltinIndices[][5] = {
3884 BUILTIN_ROW(__sync_fetch_and_add),
3885 BUILTIN_ROW(__sync_fetch_and_sub),
3886 BUILTIN_ROW(__sync_fetch_and_or),
3887 BUILTIN_ROW(__sync_fetch_and_and),
3888 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00003889 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00003890
Chris Lattnerdc046542009-05-08 06:58:22 +00003891 BUILTIN_ROW(__sync_add_and_fetch),
3892 BUILTIN_ROW(__sync_sub_and_fetch),
3893 BUILTIN_ROW(__sync_and_and_fetch),
3894 BUILTIN_ROW(__sync_or_and_fetch),
3895 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00003896 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00003897
Chris Lattnerdc046542009-05-08 06:58:22 +00003898 BUILTIN_ROW(__sync_val_compare_and_swap),
3899 BUILTIN_ROW(__sync_bool_compare_and_swap),
3900 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00003901 BUILTIN_ROW(__sync_lock_release),
3902 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00003903 };
Mike Stump11289f42009-09-09 15:08:12 +00003904#undef BUILTIN_ROW
3905
Chris Lattnerdc046542009-05-08 06:58:22 +00003906 // Determine the index of the size.
3907 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00003908 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00003909 case 1: SizeIndex = 0; break;
3910 case 2: SizeIndex = 1; break;
3911 case 4: SizeIndex = 2; break;
3912 case 8: SizeIndex = 3; break;
3913 case 16: SizeIndex = 4; break;
3914 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003915 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3916 << FirstArg->getType() << FirstArg->getSourceRange();
3917 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00003918 }
Mike Stump11289f42009-09-09 15:08:12 +00003919
Chris Lattnerdc046542009-05-08 06:58:22 +00003920 // Each of these builtins has one pointer argument, followed by some number of
3921 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3922 // that we ignore. Find out which row of BuiltinIndices to read from as well
3923 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00003924 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00003925 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00003926 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00003927 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00003928 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00003929 case Builtin::BI__sync_fetch_and_add:
3930 case Builtin::BI__sync_fetch_and_add_1:
3931 case Builtin::BI__sync_fetch_and_add_2:
3932 case Builtin::BI__sync_fetch_and_add_4:
3933 case Builtin::BI__sync_fetch_and_add_8:
3934 case Builtin::BI__sync_fetch_and_add_16:
3935 BuiltinIndex = 0;
3936 break;
3937
3938 case Builtin::BI__sync_fetch_and_sub:
3939 case Builtin::BI__sync_fetch_and_sub_1:
3940 case Builtin::BI__sync_fetch_and_sub_2:
3941 case Builtin::BI__sync_fetch_and_sub_4:
3942 case Builtin::BI__sync_fetch_and_sub_8:
3943 case Builtin::BI__sync_fetch_and_sub_16:
3944 BuiltinIndex = 1;
3945 break;
3946
3947 case Builtin::BI__sync_fetch_and_or:
3948 case Builtin::BI__sync_fetch_and_or_1:
3949 case Builtin::BI__sync_fetch_and_or_2:
3950 case Builtin::BI__sync_fetch_and_or_4:
3951 case Builtin::BI__sync_fetch_and_or_8:
3952 case Builtin::BI__sync_fetch_and_or_16:
3953 BuiltinIndex = 2;
3954 break;
3955
3956 case Builtin::BI__sync_fetch_and_and:
3957 case Builtin::BI__sync_fetch_and_and_1:
3958 case Builtin::BI__sync_fetch_and_and_2:
3959 case Builtin::BI__sync_fetch_and_and_4:
3960 case Builtin::BI__sync_fetch_and_and_8:
3961 case Builtin::BI__sync_fetch_and_and_16:
3962 BuiltinIndex = 3;
3963 break;
Mike Stump11289f42009-09-09 15:08:12 +00003964
Douglas Gregor73722482011-11-28 16:30:08 +00003965 case Builtin::BI__sync_fetch_and_xor:
3966 case Builtin::BI__sync_fetch_and_xor_1:
3967 case Builtin::BI__sync_fetch_and_xor_2:
3968 case Builtin::BI__sync_fetch_and_xor_4:
3969 case Builtin::BI__sync_fetch_and_xor_8:
3970 case Builtin::BI__sync_fetch_and_xor_16:
3971 BuiltinIndex = 4;
3972 break;
3973
Hal Finkeld2208b52014-10-02 20:53:50 +00003974 case Builtin::BI__sync_fetch_and_nand:
3975 case Builtin::BI__sync_fetch_and_nand_1:
3976 case Builtin::BI__sync_fetch_and_nand_2:
3977 case Builtin::BI__sync_fetch_and_nand_4:
3978 case Builtin::BI__sync_fetch_and_nand_8:
3979 case Builtin::BI__sync_fetch_and_nand_16:
3980 BuiltinIndex = 5;
3981 WarnAboutSemanticsChange = true;
3982 break;
3983
Douglas Gregor73722482011-11-28 16:30:08 +00003984 case Builtin::BI__sync_add_and_fetch:
3985 case Builtin::BI__sync_add_and_fetch_1:
3986 case Builtin::BI__sync_add_and_fetch_2:
3987 case Builtin::BI__sync_add_and_fetch_4:
3988 case Builtin::BI__sync_add_and_fetch_8:
3989 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003990 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00003991 break;
3992
3993 case Builtin::BI__sync_sub_and_fetch:
3994 case Builtin::BI__sync_sub_and_fetch_1:
3995 case Builtin::BI__sync_sub_and_fetch_2:
3996 case Builtin::BI__sync_sub_and_fetch_4:
3997 case Builtin::BI__sync_sub_and_fetch_8:
3998 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003999 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00004000 break;
4001
4002 case Builtin::BI__sync_and_and_fetch:
4003 case Builtin::BI__sync_and_and_fetch_1:
4004 case Builtin::BI__sync_and_and_fetch_2:
4005 case Builtin::BI__sync_and_and_fetch_4:
4006 case Builtin::BI__sync_and_and_fetch_8:
4007 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004008 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00004009 break;
4010
4011 case Builtin::BI__sync_or_and_fetch:
4012 case Builtin::BI__sync_or_and_fetch_1:
4013 case Builtin::BI__sync_or_and_fetch_2:
4014 case Builtin::BI__sync_or_and_fetch_4:
4015 case Builtin::BI__sync_or_and_fetch_8:
4016 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004017 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00004018 break;
4019
4020 case Builtin::BI__sync_xor_and_fetch:
4021 case Builtin::BI__sync_xor_and_fetch_1:
4022 case Builtin::BI__sync_xor_and_fetch_2:
4023 case Builtin::BI__sync_xor_and_fetch_4:
4024 case Builtin::BI__sync_xor_and_fetch_8:
4025 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004026 BuiltinIndex = 10;
4027 break;
4028
4029 case Builtin::BI__sync_nand_and_fetch:
4030 case Builtin::BI__sync_nand_and_fetch_1:
4031 case Builtin::BI__sync_nand_and_fetch_2:
4032 case Builtin::BI__sync_nand_and_fetch_4:
4033 case Builtin::BI__sync_nand_and_fetch_8:
4034 case Builtin::BI__sync_nand_and_fetch_16:
4035 BuiltinIndex = 11;
4036 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00004037 break;
Mike Stump11289f42009-09-09 15:08:12 +00004038
Chris Lattnerdc046542009-05-08 06:58:22 +00004039 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00004040 case Builtin::BI__sync_val_compare_and_swap_1:
4041 case Builtin::BI__sync_val_compare_and_swap_2:
4042 case Builtin::BI__sync_val_compare_and_swap_4:
4043 case Builtin::BI__sync_val_compare_and_swap_8:
4044 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004045 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00004046 NumFixed = 2;
4047 break;
Douglas Gregor73722482011-11-28 16:30:08 +00004048
Chris Lattnerdc046542009-05-08 06:58:22 +00004049 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00004050 case Builtin::BI__sync_bool_compare_and_swap_1:
4051 case Builtin::BI__sync_bool_compare_and_swap_2:
4052 case Builtin::BI__sync_bool_compare_and_swap_4:
4053 case Builtin::BI__sync_bool_compare_and_swap_8:
4054 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004055 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00004056 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00004057 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00004058 break;
Douglas Gregor73722482011-11-28 16:30:08 +00004059
JF Bastien7f0a05a2018-05-25 00:07:09 +00004060 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +00004061 case Builtin::BI__sync_lock_test_and_set_1:
4062 case Builtin::BI__sync_lock_test_and_set_2:
4063 case Builtin::BI__sync_lock_test_and_set_4:
4064 case Builtin::BI__sync_lock_test_and_set_8:
4065 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004066 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00004067 break;
4068
Chris Lattnerdc046542009-05-08 06:58:22 +00004069 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00004070 case Builtin::BI__sync_lock_release_1:
4071 case Builtin::BI__sync_lock_release_2:
4072 case Builtin::BI__sync_lock_release_4:
4073 case Builtin::BI__sync_lock_release_8:
4074 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004075 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00004076 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00004077 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00004078 break;
Douglas Gregor73722482011-11-28 16:30:08 +00004079
4080 case Builtin::BI__sync_swap:
4081 case Builtin::BI__sync_swap_1:
4082 case Builtin::BI__sync_swap_2:
4083 case Builtin::BI__sync_swap_4:
4084 case Builtin::BI__sync_swap_8:
4085 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004086 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00004087 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00004088 }
Mike Stump11289f42009-09-09 15:08:12 +00004089
Chris Lattnerdc046542009-05-08 06:58:22 +00004090 // Now that we know how many fixed arguments we expect, first check that we
4091 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004092 if (TheCall->getNumArgs() < 1+NumFixed) {
4093 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
4094 << 0 << 1+NumFixed << TheCall->getNumArgs()
4095 << TheCall->getCallee()->getSourceRange();
4096 return ExprError();
4097 }
Mike Stump11289f42009-09-09 15:08:12 +00004098
Hal Finkeld2208b52014-10-02 20:53:50 +00004099 if (WarnAboutSemanticsChange) {
4100 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
4101 << TheCall->getCallee()->getSourceRange();
4102 }
4103
Chris Lattner5b9241b2009-05-08 15:36:58 +00004104 // Get the decl for the concrete builtin from this, we can tell what the
4105 // concrete integer type we should convert to is.
4106 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Mehdi Amini7186a432016-10-11 19:04:24 +00004107 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00004108 FunctionDecl *NewBuiltinDecl;
4109 if (NewBuiltinID == BuiltinID)
4110 NewBuiltinDecl = FDecl;
4111 else {
4112 // Perform builtin lookup to avoid redeclaring it.
4113 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
4114 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
4115 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
4116 assert(Res.getFoundDecl());
4117 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00004118 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00004119 return ExprError();
4120 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004121
John McCallcf142162010-08-07 06:22:56 +00004122 // The first argument --- the pointer --- has a fixed type; we
4123 // deduce the types of the rest of the arguments accordingly. Walk
4124 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00004125 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00004126 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00004127
Chris Lattnerdc046542009-05-08 06:58:22 +00004128 // GCC does an implicit conversion to the pointer or integer ValType. This
4129 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00004130 // Initialize the argument.
4131 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4132 ValType, /*consume*/ false);
4133 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00004134 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004135 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004136
Chris Lattnerdc046542009-05-08 06:58:22 +00004137 // Okay, we have something that *can* be converted to the right type. Check
4138 // to see if there is a potentially weird extension going on here. This can
4139 // happen when you do an atomic operation on something like an char* and
4140 // pass in 42. The 42 gets converted to char. This is even more strange
4141 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00004142 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004143 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00004144 }
Mike Stump11289f42009-09-09 15:08:12 +00004145
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00004146 ASTContext& Context = this->getASTContext();
4147
4148 // Create a new DeclRefExpr to refer to the new decl.
4149 DeclRefExpr* NewDRE = DeclRefExpr::Create(
4150 Context,
4151 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00004152 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00004153 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00004154 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00004155 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00004156 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00004157 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00004158
Chris Lattnerdc046542009-05-08 06:58:22 +00004159 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00004160 // FIXME: This loses syntactic information.
4161 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
4162 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
4163 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004164 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00004165
Chandler Carruthbc8cab12010-07-18 07:23:17 +00004166 // Change the result type of the call to match the original value type. This
4167 // is arbitrary, but the codegen for these builtins ins design to handle it
4168 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00004169 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004170
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004171 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00004172}
4173
Michael Zolotukhin84df1232015-09-08 23:52:33 +00004174/// SemaBuiltinNontemporalOverloaded - We have a call to
4175/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
4176/// overloaded function based on the pointer type of its last argument.
4177///
4178/// This function goes through and does final semantic checking for these
4179/// builtins.
4180ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
4181 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
4182 DeclRefExpr *DRE =
4183 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4184 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4185 unsigned BuiltinID = FDecl->getBuiltinID();
4186 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
4187 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
4188 "Unexpected nontemporal load/store builtin!");
4189 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
4190 unsigned numArgs = isStore ? 2 : 1;
4191
4192 // Ensure that we have the proper number of arguments.
4193 if (checkArgCount(*this, TheCall, numArgs))
4194 return ExprError();
4195
4196 // Inspect the last argument of the nontemporal builtin. This should always
4197 // be a pointer type, from which we imply the type of the memory access.
4198 // Because it is a pointer type, we don't have to worry about any implicit
4199 // casts here.
4200 Expr *PointerArg = TheCall->getArg(numArgs - 1);
4201 ExprResult PointerArgResult =
4202 DefaultFunctionArrayLvalueConversion(PointerArg);
4203
4204 if (PointerArgResult.isInvalid())
4205 return ExprError();
4206 PointerArg = PointerArgResult.get();
4207 TheCall->setArg(numArgs - 1, PointerArg);
4208
4209 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
4210 if (!pointerType) {
4211 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
4212 << PointerArg->getType() << PointerArg->getSourceRange();
4213 return ExprError();
4214 }
4215
4216 QualType ValType = pointerType->getPointeeType();
4217
4218 // Strip any qualifiers off ValType.
4219 ValType = ValType.getUnqualifiedType();
4220 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4221 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
4222 !ValType->isVectorType()) {
4223 Diag(DRE->getLocStart(),
4224 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
4225 << PointerArg->getType() << PointerArg->getSourceRange();
4226 return ExprError();
4227 }
4228
4229 if (!isStore) {
4230 TheCall->setType(ValType);
4231 return TheCallResult;
4232 }
4233
4234 ExprResult ValArg = TheCall->getArg(0);
4235 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4236 Context, ValType, /*consume*/ false);
4237 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
4238 if (ValArg.isInvalid())
4239 return ExprError();
4240
4241 TheCall->setArg(0, ValArg.get());
4242 TheCall->setType(Context.VoidTy);
4243 return TheCallResult;
4244}
4245
Chris Lattner6436fb62009-02-18 06:01:06 +00004246/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00004247/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00004248/// Note: It might also make sense to do the UTF-16 conversion here (would
4249/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00004250bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00004251 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00004252 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
4253
Douglas Gregorfb65e592011-07-27 05:40:30 +00004254 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00004255 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
4256 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00004257 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00004258 }
Mike Stump11289f42009-09-09 15:08:12 +00004259
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00004260 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004261 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00004262 unsigned NumBytes = String.size();
Justin Lebar90910552016-09-30 00:38:45 +00004263 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
4264 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
4265 llvm::UTF16 *ToPtr = &ToBuf[0];
4266
4267 llvm::ConversionResult Result =
4268 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
4269 ToPtr + NumBytes, llvm::strictConversion);
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00004270 // Check for conversion failure.
Justin Lebar90910552016-09-30 00:38:45 +00004271 if (Result != llvm::conversionOK)
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00004272 Diag(Arg->getLocStart(),
4273 diag::warn_cfstring_truncated) << Arg->getSourceRange();
4274 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00004275 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004276}
4277
Mehdi Amini06d367c2016-10-24 20:39:34 +00004278/// CheckObjCString - Checks that the format string argument to the os_log()
4279/// and os_trace() functions is correct, and converts it to const char *.
4280ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
4281 Arg = Arg->IgnoreParenCasts();
4282 auto *Literal = dyn_cast<StringLiteral>(Arg);
4283 if (!Literal) {
4284 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
4285 Literal = ObjcLiteral->getString();
4286 }
4287 }
4288
4289 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
4290 return ExprError(
4291 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
4292 << Arg->getSourceRange());
4293 }
4294
4295 ExprResult Result(Literal);
4296 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
4297 InitializedEntity Entity =
4298 InitializedEntity::InitializeParameter(Context, ResultTy, false);
4299 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
4300 return Result;
4301}
4302
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004303/// Check that the user is calling the appropriate va_start builtin for the
4304/// target and calling convention.
4305static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
4306 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
4307 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
Martin Storsjo022e7822017-07-17 20:49:45 +00004308 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004309 bool IsWindows = TT.isOSWindows();
Martin Storsjo022e7822017-07-17 20:49:45 +00004310 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
4311 if (IsX64 || IsAArch64) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004312 CallingConv CC = CC_C;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004313 if (const FunctionDecl *FD = S.getCurFunctionDecl())
4314 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
4315 if (IsMSVAStart) {
4316 // Don't allow this in System V ABI functions.
Martin Storsjo022e7822017-07-17 20:49:45 +00004317 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004318 return S.Diag(Fn->getLocStart(),
4319 diag::err_ms_va_start_used_in_sysv_function);
4320 } else {
Martin Storsjo022e7822017-07-17 20:49:45 +00004321 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004322 // On x64 Windows, don't allow this in System V ABI functions.
4323 // (Yes, that means there's no corresponding way to support variadic
4324 // System V ABI functions on Windows.)
4325 if ((IsWindows && CC == CC_X86_64SysV) ||
Martin Storsjo022e7822017-07-17 20:49:45 +00004326 (!IsWindows && CC == CC_Win64))
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004327 return S.Diag(Fn->getLocStart(),
4328 diag::err_va_start_used_in_wrong_abi_function)
4329 << !IsWindows;
4330 }
4331 return false;
4332 }
4333
4334 if (IsMSVAStart)
Martin Storsjo022e7822017-07-17 20:49:45 +00004335 return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004336 return false;
4337}
4338
4339static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
4340 ParmVarDecl **LastParam = nullptr) {
4341 // Determine whether the current function, block, or obj-c method is variadic
4342 // and get its parameter list.
4343 bool IsVariadic = false;
4344 ArrayRef<ParmVarDecl *> Params;
Reid Klecknerf1deb832017-05-04 19:51:05 +00004345 DeclContext *Caller = S.CurContext;
4346 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
4347 IsVariadic = Block->isVariadic();
4348 Params = Block->parameters();
4349 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004350 IsVariadic = FD->isVariadic();
4351 Params = FD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00004352 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004353 IsVariadic = MD->isVariadic();
4354 // FIXME: This isn't correct for methods (results in bogus warning).
4355 Params = MD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00004356 } else if (isa<CapturedDecl>(Caller)) {
4357 // We don't support va_start in a CapturedDecl.
4358 S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
4359 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004360 } else {
Reid Klecknerf1deb832017-05-04 19:51:05 +00004361 // This must be some other declcontext that parses exprs.
4362 S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
4363 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004364 }
4365
4366 if (!IsVariadic) {
Reid Klecknerf1deb832017-05-04 19:51:05 +00004367 S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004368 return true;
4369 }
4370
4371 if (LastParam)
4372 *LastParam = Params.empty() ? nullptr : Params.back();
4373
4374 return false;
4375}
4376
Charles Davisc7d5c942015-09-17 20:55:33 +00004377/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
4378/// for validity. Emit an error and return true on failure; return false
4379/// on success.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004380bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00004381 Expr *Fn = TheCall->getCallee();
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004382
4383 if (checkVAStartABI(*this, BuiltinID, Fn))
4384 return true;
4385
Chris Lattner08464942007-12-28 05:29:59 +00004386 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00004387 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004388 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004389 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4390 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00004391 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004392 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00004393 return true;
4394 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00004395
4396 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00004397 return Diag(TheCall->getLocEnd(),
4398 diag::err_typecheck_call_too_few_args_at_least)
4399 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00004400 }
4401
John McCall29ad95b2011-08-27 01:09:30 +00004402 // Type-check the first argument normally.
4403 if (checkBuiltinArgument(*this, TheCall, 0))
4404 return true;
4405
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004406 // Check that the current function is variadic, and get its last parameter.
4407 ParmVarDecl *LastParam;
4408 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
Chris Lattner43be2e62007-12-19 23:59:04 +00004409 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004410
Chris Lattner43be2e62007-12-19 23:59:04 +00004411 // Verify that the second argument to the builtin is the last argument of the
4412 // current function or method.
4413 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00004414 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00004415
Nico Weber9eea7642013-05-24 23:31:57 +00004416 // These are valid if SecondArgIsLastNamedArgument is false after the next
4417 // block.
4418 QualType Type;
4419 SourceLocation ParamLoc;
Aaron Ballman1de59c52016-04-24 13:30:21 +00004420 bool IsCRegister = false;
Nico Weber9eea7642013-05-24 23:31:57 +00004421
Anders Carlsson6a8350b2008-02-11 04:20:54 +00004422 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
4423 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004424 SecondArgIsLastNamedArgument = PV == LastParam;
Nico Weber9eea7642013-05-24 23:31:57 +00004425
4426 Type = PV->getType();
4427 ParamLoc = PV->getLocation();
Aaron Ballman1de59c52016-04-24 13:30:21 +00004428 IsCRegister =
4429 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
Chris Lattner43be2e62007-12-19 23:59:04 +00004430 }
4431 }
Mike Stump11289f42009-09-09 15:08:12 +00004432
Chris Lattner43be2e62007-12-19 23:59:04 +00004433 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00004434 Diag(TheCall->getArg(1)->getLocStart(),
Aaron Ballman05164812016-04-18 18:10:53 +00004435 diag::warn_second_arg_of_va_start_not_last_named_param);
Aaron Ballman1de59c52016-04-24 13:30:21 +00004436 else if (IsCRegister || Type->isReferenceType() ||
Aaron Ballmana4f597f2016-09-15 18:07:51 +00004437 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
4438 // Promotable integers are UB, but enumerations need a bit of
4439 // extra checking to see what their promotable type actually is.
4440 if (!Type->isPromotableIntegerType())
4441 return false;
4442 if (!Type->isEnumeralType())
4443 return true;
4444 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
4445 return !(ED &&
4446 Context.typesAreCompatible(ED->getPromotionType(), Type));
4447 }()) {
Aaron Ballman1de59c52016-04-24 13:30:21 +00004448 unsigned Reason = 0;
4449 if (Type->isReferenceType()) Reason = 1;
4450 else if (IsCRegister) Reason = 2;
4451 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
Nico Weber9eea7642013-05-24 23:31:57 +00004452 Diag(ParamLoc, diag::note_parameter_type) << Type;
4453 }
4454
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00004455 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00004456 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00004457}
Chris Lattner43be2e62007-12-19 23:59:04 +00004458
Saleem Abdulrasool3450aa72017-09-26 20:12:04 +00004459bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004460 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
4461 // const char *named_addr);
4462
4463 Expr *Func = Call->getCallee();
4464
4465 if (Call->getNumArgs() < 3)
4466 return Diag(Call->getLocEnd(),
4467 diag::err_typecheck_call_too_few_args_at_least)
4468 << 0 /*function call*/ << 3 << Call->getNumArgs();
4469
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004470 // Type-check the first argument normally.
4471 if (checkBuiltinArgument(*this, Call, 0))
4472 return true;
4473
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004474 // Check that the current function is variadic.
4475 if (checkVAStartIsInVariadicFunction(*this, Func))
4476 return true;
4477
Saleem Abdulrasool448e8ad2017-09-26 17:44:10 +00004478 // __va_start on Windows does not validate the parameter qualifiers
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004479
Saleem Abdulrasool448e8ad2017-09-26 17:44:10 +00004480 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
4481 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
4482
4483 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
4484 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
4485
4486 const QualType &ConstCharPtrTy =
4487 Context.getPointerType(Context.CharTy.withConst());
4488 if (!Arg1Ty->isPointerType() ||
4489 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
4490 Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible)
4491 << Arg1->getType() << ConstCharPtrTy
4492 << 1 /* different class */
4493 << 0 /* qualifier difference */
4494 << 3 /* parameter mismatch */
4495 << 2 << Arg1->getType() << ConstCharPtrTy;
4496
4497 const QualType SizeTy = Context.getSizeType();
4498 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
4499 Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible)
4500 << Arg2->getType() << SizeTy
4501 << 1 /* different class */
4502 << 0 /* qualifier difference */
4503 << 3 /* parameter mismatch */
4504 << 3 << Arg2->getType() << SizeTy;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004505
4506 return false;
4507}
4508
Chris Lattner2da14fb2007-12-20 00:26:33 +00004509/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
4510/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00004511bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
4512 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00004513 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00004514 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00004515 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00004516 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004517 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004518 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00004519 << SourceRange(TheCall->getArg(2)->getLocStart(),
4520 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00004521
John Wiegley01296292011-04-08 18:41:53 +00004522 ExprResult OrigArg0 = TheCall->getArg(0);
4523 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00004524
Chris Lattner2da14fb2007-12-20 00:26:33 +00004525 // Do standard promotions between the two arguments, returning their common
4526 // type.
Chris Lattner08464942007-12-28 05:29:59 +00004527 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00004528 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
4529 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00004530
4531 // Make sure any conversions are pushed back into the call; this is
4532 // type safe since unordered compare builtins are declared as "_Bool
4533 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00004534 TheCall->setArg(0, OrigArg0.get());
4535 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00004536
John Wiegley01296292011-04-08 18:41:53 +00004537 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00004538 return false;
4539
Chris Lattner2da14fb2007-12-20 00:26:33 +00004540 // If the common type isn't a real floating type, then the arguments were
4541 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00004542 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00004543 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004544 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00004545 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
4546 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00004547
Chris Lattner2da14fb2007-12-20 00:26:33 +00004548 return false;
4549}
4550
Benjamin Kramer634fc102010-02-15 22:42:31 +00004551/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
4552/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00004553/// to check everything. We expect the last argument to be a floating point
4554/// value.
4555bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
4556 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00004557 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00004558 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00004559 if (TheCall->getNumArgs() > NumArgs)
4560 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004561 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004562 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00004563 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004564 (*(TheCall->arg_end()-1))->getLocEnd());
4565
Benjamin Kramer64aae502010-02-16 10:07:31 +00004566 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00004567
Eli Friedman7e4faac2009-08-31 20:06:00 +00004568 if (OrigArg->isTypeDependent())
4569 return false;
4570
Chris Lattner68784ef2010-05-06 05:50:07 +00004571 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00004572 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00004573 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004574 diag::err_typecheck_call_invalid_unary_fp)
4575 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004576
Neil Hickey88c0fac2016-12-13 16:22:50 +00004577 // If this is an implicit conversion from float -> float or double, remove it.
Chris Lattner68784ef2010-05-06 05:50:07 +00004578 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
Neil Hickey7b5ddab2016-12-14 13:18:48 +00004579 // Only remove standard FloatCasts, leaving other casts inplace
4580 if (Cast->getCastKind() == CK_FloatingCast) {
4581 Expr *CastArg = Cast->getSubExpr();
4582 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
4583 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
4584 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
4585 "promotion from float to either float or double is the only expected cast here");
4586 Cast->setSubExpr(nullptr);
4587 TheCall->setArg(NumArgs-1, CastArg);
4588 }
Chris Lattner68784ef2010-05-06 05:50:07 +00004589 }
4590 }
4591
Eli Friedman7e4faac2009-08-31 20:06:00 +00004592 return false;
4593}
4594
Tony Jiangbbc48e92017-05-24 15:13:32 +00004595// Customized Sema Checking for VSX builtins that have the following signature:
4596// vector [...] builtinName(vector [...], vector [...], const int);
4597// Which takes the same type of vectors (any legal vector type) for the first
4598// two arguments and takes compile time constant for the third argument.
4599// Example builtins are :
4600// vector double vec_xxpermdi(vector double, vector double, int);
4601// vector short vec_xxsldwi(vector short, vector short, int);
4602bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
4603 unsigned ExpectedNumArgs = 3;
4604 if (TheCall->getNumArgs() < ExpectedNumArgs)
4605 return Diag(TheCall->getLocEnd(),
4606 diag::err_typecheck_call_too_few_args_at_least)
4607 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4608 << TheCall->getSourceRange();
4609
4610 if (TheCall->getNumArgs() > ExpectedNumArgs)
4611 return Diag(TheCall->getLocEnd(),
4612 diag::err_typecheck_call_too_many_args_at_most)
4613 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4614 << TheCall->getSourceRange();
4615
4616 // Check the third argument is a compile time constant
4617 llvm::APSInt Value;
4618 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
4619 return Diag(TheCall->getLocStart(),
4620 diag::err_vsx_builtin_nonconstant_argument)
4621 << 3 /* argument index */ << TheCall->getDirectCallee()
4622 << SourceRange(TheCall->getArg(2)->getLocStart(),
4623 TheCall->getArg(2)->getLocEnd());
4624
4625 QualType Arg1Ty = TheCall->getArg(0)->getType();
4626 QualType Arg2Ty = TheCall->getArg(1)->getType();
4627
4628 // Check the type of argument 1 and argument 2 are vectors.
4629 SourceLocation BuiltinLoc = TheCall->getLocStart();
4630 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
4631 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
4632 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
4633 << TheCall->getDirectCallee()
4634 << SourceRange(TheCall->getArg(0)->getLocStart(),
4635 TheCall->getArg(1)->getLocEnd());
4636 }
4637
4638 // Check the first two arguments are the same type.
4639 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
4640 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
4641 << TheCall->getDirectCallee()
4642 << SourceRange(TheCall->getArg(0)->getLocStart(),
4643 TheCall->getArg(1)->getLocEnd());
4644 }
4645
4646 // When default clang type checking is turned off and the customized type
4647 // checking is used, the returning type of the function must be explicitly
4648 // set. Otherwise it is _Bool by default.
4649 TheCall->setType(Arg1Ty);
4650
4651 return false;
4652}
4653
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004654/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
4655// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00004656ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00004657 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004658 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00004659 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00004660 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4661 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004662
Nate Begemana0110022010-06-08 00:16:34 +00004663 // Determine which of the following types of shufflevector we're checking:
4664 // 1) unary, vector mask: (lhs, mask)
Craig Topperb3174a82016-05-18 04:11:25 +00004665 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
Nate Begemana0110022010-06-08 00:16:34 +00004666 QualType resType = TheCall->getArg(0)->getType();
4667 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00004668
Douglas Gregorc25f7662009-05-19 22:10:17 +00004669 if (!TheCall->getArg(0)->isTypeDependent() &&
4670 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00004671 QualType LHSType = TheCall->getArg(0)->getType();
4672 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00004673
Craig Topperbaca3892013-07-29 06:47:04 +00004674 if (!LHSType->isVectorType() || !RHSType->isVectorType())
4675 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004676 diag::err_vec_builtin_non_vector)
4677 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004678 << SourceRange(TheCall->getArg(0)->getLocStart(),
4679 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00004680
Nate Begemana0110022010-06-08 00:16:34 +00004681 numElements = LHSType->getAs<VectorType>()->getNumElements();
4682 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00004683
Nate Begemana0110022010-06-08 00:16:34 +00004684 // Check to see if we have a call with 2 vector arguments, the unary shuffle
4685 // with mask. If so, verify that RHS is an integer vector type with the
4686 // same number of elts as lhs.
4687 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00004688 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00004689 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00004690 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004691 diag::err_vec_builtin_incompatible_vector)
4692 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004693 << SourceRange(TheCall->getArg(1)->getLocStart(),
4694 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00004695 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00004696 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004697 diag::err_vec_builtin_incompatible_vector)
4698 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004699 << SourceRange(TheCall->getArg(0)->getLocStart(),
4700 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00004701 } else if (numElements != numResElements) {
4702 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00004703 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00004704 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00004705 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004706 }
4707
4708 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00004709 if (TheCall->getArg(i)->isTypeDependent() ||
4710 TheCall->getArg(i)->isValueDependent())
4711 continue;
4712
Nate Begemana0110022010-06-08 00:16:34 +00004713 llvm::APSInt Result(32);
4714 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
4715 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004716 diag::err_shufflevector_nonconstant_argument)
4717 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004718
Craig Topper50ad5b72013-08-03 17:40:38 +00004719 // Allow -1 which will be translated to undef in the IR.
4720 if (Result.isSigned() && Result.isAllOnesValue())
4721 continue;
4722
Chris Lattner7ab824e2008-08-10 02:05:13 +00004723 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004724 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004725 diag::err_shufflevector_argument_too_large)
4726 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004727 }
4728
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004729 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004730
Chris Lattner7ab824e2008-08-10 02:05:13 +00004731 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004732 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00004733 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004734 }
4735
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004736 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
4737 TheCall->getCallee()->getLocStart(),
4738 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004739}
Chris Lattner43be2e62007-12-19 23:59:04 +00004740
Hal Finkelc4d7c822013-09-18 03:29:45 +00004741/// SemaConvertVectorExpr - Handle __builtin_convertvector
4742ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
4743 SourceLocation BuiltinLoc,
4744 SourceLocation RParenLoc) {
4745 ExprValueKind VK = VK_RValue;
4746 ExprObjectKind OK = OK_Ordinary;
4747 QualType DstTy = TInfo->getType();
4748 QualType SrcTy = E->getType();
4749
4750 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
4751 return ExprError(Diag(BuiltinLoc,
4752 diag::err_convertvector_non_vector)
4753 << E->getSourceRange());
4754 if (!DstTy->isVectorType() && !DstTy->isDependentType())
4755 return ExprError(Diag(BuiltinLoc,
4756 diag::err_convertvector_non_vector_type));
4757
4758 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
4759 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
4760 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
4761 if (SrcElts != DstElts)
4762 return ExprError(Diag(BuiltinLoc,
4763 diag::err_convertvector_incompatible_vector)
4764 << E->getSourceRange());
4765 }
4766
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004767 return new (Context)
4768 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00004769}
4770
Daniel Dunbarb7257262008-07-21 22:59:13 +00004771/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
4772// This is declared to take (const void*, ...) and can take two
4773// optional constant int args.
4774bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00004775 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004776
Chris Lattner3b054132008-11-19 05:08:23 +00004777 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004778 return Diag(TheCall->getLocEnd(),
4779 diag::err_typecheck_call_too_many_args_at_most)
4780 << 0 /*function call*/ << 3 << NumArgs
4781 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004782
4783 // Argument 0 is checked for us and the remaining arguments must be
4784 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00004785 for (unsigned i = 1; i != NumArgs; ++i)
4786 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004787 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004788
Warren Hunt20e4a5d2014-02-21 23:08:53 +00004789 return false;
4790}
4791
Hal Finkelf0417332014-07-17 14:25:55 +00004792/// SemaBuiltinAssume - Handle __assume (MS Extension).
4793// __assume does not evaluate its arguments, and should warn if its argument
4794// has side effects.
4795bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
4796 Expr *Arg = TheCall->getArg(0);
4797 if (Arg->isInstantiationDependent()) return false;
4798
4799 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00004800 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00004801 << Arg->getSourceRange()
4802 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
4803
4804 return false;
4805}
4806
David Majnemer86b1bfa2016-10-31 18:07:57 +00004807/// Handle __builtin_alloca_with_align. This is declared
David Majnemer51169932016-10-31 05:37:48 +00004808/// as (size_t, size_t) where the second size_t must be a power of 2 greater
4809/// than 8.
4810bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
4811 // The alignment must be a constant integer.
4812 Expr *Arg = TheCall->getArg(1);
4813
4814 // We can't check the value of a dependent argument.
4815 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
David Majnemer86b1bfa2016-10-31 18:07:57 +00004816 if (const auto *UE =
4817 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
4818 if (UE->getKind() == UETT_AlignOf)
4819 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
4820 << Arg->getSourceRange();
4821
David Majnemer51169932016-10-31 05:37:48 +00004822 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
4823
4824 if (!Result.isPowerOf2())
4825 return Diag(TheCall->getLocStart(),
4826 diag::err_alignment_not_power_of_two)
4827 << Arg->getSourceRange();
4828
4829 if (Result < Context.getCharWidth())
4830 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
4831 << (unsigned)Context.getCharWidth()
4832 << Arg->getSourceRange();
4833
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004834 if (Result > std::numeric_limits<int32_t>::max())
David Majnemer51169932016-10-31 05:37:48 +00004835 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004836 << std::numeric_limits<int32_t>::max()
David Majnemer51169932016-10-31 05:37:48 +00004837 << Arg->getSourceRange();
4838 }
4839
4840 return false;
4841}
4842
4843/// Handle __builtin_assume_aligned. This is declared
Hal Finkelbcc06082014-09-07 22:58:14 +00004844/// as (const void*, size_t, ...) and can take one optional constant int arg.
4845bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
4846 unsigned NumArgs = TheCall->getNumArgs();
4847
4848 if (NumArgs > 3)
4849 return Diag(TheCall->getLocEnd(),
4850 diag::err_typecheck_call_too_many_args_at_most)
4851 << 0 /*function call*/ << 3 << NumArgs
4852 << TheCall->getSourceRange();
4853
4854 // The alignment must be a constant integer.
4855 Expr *Arg = TheCall->getArg(1);
4856
4857 // We can't check the value of a dependent argument.
4858 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4859 llvm::APSInt Result;
4860 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4861 return true;
4862
4863 if (!Result.isPowerOf2())
4864 return Diag(TheCall->getLocStart(),
4865 diag::err_alignment_not_power_of_two)
4866 << Arg->getSourceRange();
4867 }
4868
4869 if (NumArgs > 2) {
4870 ExprResult Arg(TheCall->getArg(2));
4871 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4872 Context.getSizeType(), false);
4873 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4874 if (Arg.isInvalid()) return true;
4875 TheCall->setArg(2, Arg.get());
4876 }
Hal Finkelf0417332014-07-17 14:25:55 +00004877
4878 return false;
4879}
4880
Mehdi Amini06d367c2016-10-24 20:39:34 +00004881bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4882 unsigned BuiltinID =
4883 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4884 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4885
4886 unsigned NumArgs = TheCall->getNumArgs();
4887 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4888 if (NumArgs < NumRequiredArgs) {
4889 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4890 << 0 /* function call */ << NumRequiredArgs << NumArgs
4891 << TheCall->getSourceRange();
4892 }
4893 if (NumArgs >= NumRequiredArgs + 0x100) {
4894 return Diag(TheCall->getLocEnd(),
4895 diag::err_typecheck_call_too_many_args_at_most)
4896 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4897 << TheCall->getSourceRange();
4898 }
4899 unsigned i = 0;
4900
4901 // For formatting call, check buffer arg.
4902 if (!IsSizeCall) {
4903 ExprResult Arg(TheCall->getArg(i));
4904 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4905 Context, Context.VoidPtrTy, false);
4906 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4907 if (Arg.isInvalid())
4908 return true;
4909 TheCall->setArg(i, Arg.get());
4910 i++;
4911 }
4912
4913 // Check string literal arg.
4914 unsigned FormatIdx = i;
4915 {
4916 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4917 if (Arg.isInvalid())
4918 return true;
4919 TheCall->setArg(i, Arg.get());
4920 i++;
4921 }
4922
4923 // Make sure variadic args are scalar.
4924 unsigned FirstDataArg = i;
4925 while (i < NumArgs) {
4926 ExprResult Arg = DefaultVariadicArgumentPromotion(
4927 TheCall->getArg(i), VariadicFunction, nullptr);
4928 if (Arg.isInvalid())
4929 return true;
4930 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4931 if (ArgSize.getQuantity() >= 0x100) {
4932 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4933 << i << (int)ArgSize.getQuantity() << 0xff
4934 << TheCall->getSourceRange();
4935 }
4936 TheCall->setArg(i, Arg.get());
4937 i++;
4938 }
4939
4940 // Check formatting specifiers. NOTE: We're only doing this for the non-size
4941 // call to avoid duplicate diagnostics.
4942 if (!IsSizeCall) {
4943 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4944 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4945 bool Success = CheckFormatArguments(
4946 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4947 VariadicFunction, TheCall->getLocStart(), SourceRange(),
4948 CheckedVarArgs);
4949 if (!Success)
4950 return true;
4951 }
4952
4953 if (IsSizeCall) {
4954 TheCall->setType(Context.getSizeType());
4955 } else {
4956 TheCall->setType(Context.VoidPtrTy);
4957 }
4958 return false;
4959}
4960
Eric Christopher8d0c6212010-04-17 02:26:23 +00004961/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4962/// TheCall is a constant expression.
4963bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4964 llvm::APSInt &Result) {
4965 Expr *Arg = TheCall->getArg(ArgNum);
4966 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4967 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4968
4969 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4970
4971 if (!Arg->isIntegerConstantExpr(Result, Context))
4972 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00004973 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00004974
Chris Lattnerd545ad12009-09-23 06:06:36 +00004975 return false;
4976}
4977
Richard Sandiford28940af2014-04-16 08:47:51 +00004978/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4979/// TheCall is a constant expression in the range [Low, High].
4980bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4981 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00004982 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004983
4984 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00004985 Expr *Arg = TheCall->getArg(ArgNum);
4986 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004987 return false;
4988
Eric Christopher8d0c6212010-04-17 02:26:23 +00004989 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00004990 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004991 return true;
4992
Richard Sandiford28940af2014-04-16 08:47:51 +00004993 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00004994 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00004995 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00004996
4997 return false;
4998}
4999
Simon Dardis1f90f2d2016-10-19 17:50:52 +00005000/// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
5001/// TheCall is a constant expression is a multiple of Num..
5002bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
5003 unsigned Num) {
5004 llvm::APSInt Result;
5005
5006 // We can't check the value of a dependent argument.
5007 Expr *Arg = TheCall->getArg(ArgNum);
5008 if (Arg->isTypeDependent() || Arg->isValueDependent())
5009 return false;
5010
5011 // Check constant-ness first.
5012 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
5013 return true;
5014
5015 if (Result.getSExtValue() % Num != 0)
5016 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
5017 << Num << Arg->getSourceRange();
5018
5019 return false;
5020}
5021
Luke Cheeseman59b2d832015-06-15 17:51:01 +00005022/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
5023/// TheCall is an ARM/AArch64 special register string literal.
5024bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
5025 int ArgNum, unsigned ExpectedFieldNum,
5026 bool AllowName) {
5027 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
5028 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
5029 BuiltinID == ARM::BI__builtin_arm_rsr ||
5030 BuiltinID == ARM::BI__builtin_arm_rsrp ||
5031 BuiltinID == ARM::BI__builtin_arm_wsr ||
5032 BuiltinID == ARM::BI__builtin_arm_wsrp;
5033 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
5034 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
5035 BuiltinID == AArch64::BI__builtin_arm_rsr ||
5036 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
5037 BuiltinID == AArch64::BI__builtin_arm_wsr ||
5038 BuiltinID == AArch64::BI__builtin_arm_wsrp;
5039 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
5040
5041 // We can't check the value of a dependent argument.
5042 Expr *Arg = TheCall->getArg(ArgNum);
5043 if (Arg->isTypeDependent() || Arg->isValueDependent())
5044 return false;
5045
5046 // Check if the argument is a string literal.
5047 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
5048 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
5049 << Arg->getSourceRange();
5050
5051 // Check the type of special register given.
5052 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
5053 SmallVector<StringRef, 6> Fields;
5054 Reg.split(Fields, ":");
5055
5056 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
5057 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
5058 << Arg->getSourceRange();
5059
5060 // If the string is the name of a register then we cannot check that it is
5061 // valid here but if the string is of one the forms described in ACLE then we
5062 // can check that the supplied fields are integers and within the valid
5063 // ranges.
5064 if (Fields.size() > 1) {
5065 bool FiveFields = Fields.size() == 5;
5066
5067 bool ValidString = true;
5068 if (IsARMBuiltin) {
5069 ValidString &= Fields[0].startswith_lower("cp") ||
5070 Fields[0].startswith_lower("p");
5071 if (ValidString)
5072 Fields[0] =
5073 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
5074
5075 ValidString &= Fields[2].startswith_lower("c");
5076 if (ValidString)
5077 Fields[2] = Fields[2].drop_front(1);
5078
5079 if (FiveFields) {
5080 ValidString &= Fields[3].startswith_lower("c");
5081 if (ValidString)
5082 Fields[3] = Fields[3].drop_front(1);
5083 }
5084 }
5085
5086 SmallVector<int, 5> Ranges;
5087 if (FiveFields)
Oleg Ranevskyy85d93a82016-11-18 21:00:08 +00005088 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
Luke Cheeseman59b2d832015-06-15 17:51:01 +00005089 else
5090 Ranges.append({15, 7, 15});
5091
5092 for (unsigned i=0; i<Fields.size(); ++i) {
5093 int IntField;
5094 ValidString &= !Fields[i].getAsInteger(10, IntField);
5095 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
5096 }
5097
5098 if (!ValidString)
5099 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
5100 << Arg->getSourceRange();
Luke Cheeseman59b2d832015-06-15 17:51:01 +00005101 } else if (IsAArch64Builtin && Fields.size() == 1) {
5102 // If the register name is one of those that appear in the condition below
5103 // and the special register builtin being used is one of the write builtins,
5104 // then we require that the argument provided for writing to the register
5105 // is an integer constant expression. This is because it will be lowered to
5106 // an MSR (immediate) instruction, so we need to know the immediate at
5107 // compile time.
5108 if (TheCall->getNumArgs() != 2)
5109 return false;
5110
5111 std::string RegLower = Reg.lower();
5112 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
5113 RegLower != "pan" && RegLower != "uao")
5114 return false;
5115
5116 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
5117 }
5118
5119 return false;
5120}
5121
Eli Friedmanc97d0142009-05-03 06:04:26 +00005122/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00005123/// This checks that the target supports __builtin_longjmp and
5124/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00005125bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00005126 if (!Context.getTargetInfo().hasSjLjLowering())
5127 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
5128 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
5129
Eli Friedmaneed8ad22009-05-03 04:46:36 +00005130 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00005131 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00005132
Eric Christopher8d0c6212010-04-17 02:26:23 +00005133 // TODO: This is less than ideal. Overload this to take a value.
5134 if (SemaBuiltinConstantArg(TheCall, 1, Result))
5135 return true;
5136
5137 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00005138 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
5139 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
5140
5141 return false;
5142}
5143
Joerg Sonnenberger27173282015-03-11 23:46:32 +00005144/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
5145/// This checks that the target supports __builtin_setjmp.
5146bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
5147 if (!Context.getTargetInfo().hasSjLjLowering())
5148 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
5149 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
5150 return false;
5151}
5152
Richard Smithd7293d72013-08-05 18:49:43 +00005153namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005154
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005155class UncoveredArgHandler {
5156 enum { Unknown = -1, AllCovered = -2 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005157
5158 signed FirstUncoveredArg = Unknown;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005159 SmallVector<const Expr *, 4> DiagnosticExprs;
5160
5161public:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005162 UncoveredArgHandler() = default;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005163
5164 bool hasUncoveredArg() const {
5165 return (FirstUncoveredArg >= 0);
5166 }
5167
5168 unsigned getUncoveredArg() const {
5169 assert(hasUncoveredArg() && "no uncovered argument");
5170 return FirstUncoveredArg;
5171 }
5172
5173 void setAllCovered() {
5174 // A string has been found with all arguments covered, so clear out
5175 // the diagnostics.
5176 DiagnosticExprs.clear();
5177 FirstUncoveredArg = AllCovered;
5178 }
5179
5180 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
5181 assert(NewFirstUncoveredArg >= 0 && "Outside range");
5182
5183 // Don't update if a previous string covers all arguments.
5184 if (FirstUncoveredArg == AllCovered)
5185 return;
5186
5187 // UncoveredArgHandler tracks the highest uncovered argument index
5188 // and with it all the strings that match this index.
5189 if (NewFirstUncoveredArg == FirstUncoveredArg)
5190 DiagnosticExprs.push_back(StrExpr);
5191 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
5192 DiagnosticExprs.clear();
5193 DiagnosticExprs.push_back(StrExpr);
5194 FirstUncoveredArg = NewFirstUncoveredArg;
5195 }
5196 }
5197
5198 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
5199};
5200
Richard Smithd7293d72013-08-05 18:49:43 +00005201enum StringLiteralCheckType {
5202 SLCT_NotALiteral,
5203 SLCT_UncheckedLiteral,
5204 SLCT_CheckedLiteral
5205};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005206
5207} // namespace
Richard Smithd7293d72013-08-05 18:49:43 +00005208
Stephen Hines648c3692016-09-16 01:07:04 +00005209static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
5210 BinaryOperatorKind BinOpKind,
5211 bool AddendIsRight) {
5212 unsigned BitWidth = Offset.getBitWidth();
5213 unsigned AddendBitWidth = Addend.getBitWidth();
5214 // There might be negative interim results.
5215 if (Addend.isUnsigned()) {
5216 Addend = Addend.zext(++AddendBitWidth);
5217 Addend.setIsSigned(true);
5218 }
5219 // Adjust the bit width of the APSInts.
5220 if (AddendBitWidth > BitWidth) {
5221 Offset = Offset.sext(AddendBitWidth);
5222 BitWidth = AddendBitWidth;
5223 } else if (BitWidth > AddendBitWidth) {
5224 Addend = Addend.sext(BitWidth);
5225 }
5226
5227 bool Ov = false;
5228 llvm::APSInt ResOffset = Offset;
5229 if (BinOpKind == BO_Add)
5230 ResOffset = Offset.sadd_ov(Addend, Ov);
5231 else {
5232 assert(AddendIsRight && BinOpKind == BO_Sub &&
5233 "operator must be add or sub with addend on the right");
5234 ResOffset = Offset.ssub_ov(Addend, Ov);
5235 }
5236
5237 // We add an offset to a pointer here so we should support an offset as big as
5238 // possible.
5239 if (Ov) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005240 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
5241 "index (intermediate) result too big");
Stephen Hinesfec73ad2016-09-16 07:21:24 +00005242 Offset = Offset.sext(2 * BitWidth);
Stephen Hines648c3692016-09-16 01:07:04 +00005243 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
5244 return;
5245 }
5246
5247 Offset = ResOffset;
5248}
5249
5250namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005251
Stephen Hines648c3692016-09-16 01:07:04 +00005252// This is a wrapper class around StringLiteral to support offsetted string
5253// literals as format strings. It takes the offset into account when returning
5254// the string and its length or the source locations to display notes correctly.
5255class FormatStringLiteral {
5256 const StringLiteral *FExpr;
5257 int64_t Offset;
5258
5259 public:
5260 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
5261 : FExpr(fexpr), Offset(Offset) {}
5262
5263 StringRef getString() const {
5264 return FExpr->getString().drop_front(Offset);
5265 }
5266
5267 unsigned getByteLength() const {
5268 return FExpr->getByteLength() - getCharByteWidth() * Offset;
5269 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005270
Stephen Hines648c3692016-09-16 01:07:04 +00005271 unsigned getLength() const { return FExpr->getLength() - Offset; }
5272 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
5273
5274 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
5275
5276 QualType getType() const { return FExpr->getType(); }
5277
5278 bool isAscii() const { return FExpr->isAscii(); }
5279 bool isWide() const { return FExpr->isWide(); }
5280 bool isUTF8() const { return FExpr->isUTF8(); }
5281 bool isUTF16() const { return FExpr->isUTF16(); }
5282 bool isUTF32() const { return FExpr->isUTF32(); }
5283 bool isPascal() const { return FExpr->isPascal(); }
5284
5285 SourceLocation getLocationOfByte(
5286 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
5287 const TargetInfo &Target, unsigned *StartToken = nullptr,
5288 unsigned *StartTokenByteOffset = nullptr) const {
5289 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
5290 StartToken, StartTokenByteOffset);
5291 }
5292
5293 SourceLocation getLocStart() const LLVM_READONLY {
5294 return FExpr->getLocStart().getLocWithOffset(Offset);
5295 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005296
Stephen Hines648c3692016-09-16 01:07:04 +00005297 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
5298};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005299
5300} // namespace
Stephen Hines648c3692016-09-16 01:07:04 +00005301
5302static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005303 const Expr *OrigFormatExpr,
5304 ArrayRef<const Expr *> Args,
5305 bool HasVAListArg, unsigned format_idx,
5306 unsigned firstDataArg,
5307 Sema::FormatStringType Type,
5308 bool inFunctionCall,
5309 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005310 llvm::SmallBitVector &CheckedVarArgs,
5311 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005312
Richard Smith55ce3522012-06-25 20:30:08 +00005313// Determine if an expression is a string literal or constant string.
5314// If this function returns false on the arguments to a function expecting a
5315// format string, we will usually need to emit a warning.
5316// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00005317static StringLiteralCheckType
5318checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
5319 bool HasVAListArg, unsigned format_idx,
5320 unsigned firstDataArg, Sema::FormatStringType Type,
5321 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005322 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00005323 UncoveredArgHandler &UncoveredArg,
5324 llvm::APSInt Offset) {
Ted Kremenek808829352010-09-09 03:51:39 +00005325 tryAgain:
Stephen Hines648c3692016-09-16 01:07:04 +00005326 assert(Offset.isSigned() && "invalid offset");
5327
Douglas Gregorc25f7662009-05-19 22:10:17 +00005328 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00005329 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005330
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005331 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00005332
Richard Smithd7293d72013-08-05 18:49:43 +00005333 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00005334 // Technically -Wformat-nonliteral does not warn about this case.
5335 // The behavior of printf and friends in this case is implementation
5336 // dependent. Ideally if the format string cannot be null then
5337 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00005338 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00005339
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005340 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00005341 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005342 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00005343 // The expression is a literal if both sub-expressions were, and it was
5344 // completely checked only if both sub-expressions were checked.
5345 const AbstractConditionalOperator *C =
5346 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005347
5348 // Determine whether it is necessary to check both sub-expressions, for
5349 // example, because the condition expression is a constant that can be
5350 // evaluated at compile time.
5351 bool CheckLeft = true, CheckRight = true;
5352
5353 bool Cond;
5354 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
5355 if (Cond)
5356 CheckRight = false;
5357 else
5358 CheckLeft = false;
5359 }
5360
Stephen Hines648c3692016-09-16 01:07:04 +00005361 // We need to maintain the offsets for the right and the left hand side
5362 // separately to check if every possible indexed expression is a valid
5363 // string literal. They might have different offsets for different string
5364 // literals in the end.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005365 StringLiteralCheckType Left;
5366 if (!CheckLeft)
5367 Left = SLCT_UncheckedLiteral;
5368 else {
5369 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
5370 HasVAListArg, format_idx, firstDataArg,
5371 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00005372 CheckedVarArgs, UncoveredArg, Offset);
5373 if (Left == SLCT_NotALiteral || !CheckRight) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005374 return Left;
Stephen Hines648c3692016-09-16 01:07:04 +00005375 }
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005376 }
5377
Richard Smith55ce3522012-06-25 20:30:08 +00005378 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00005379 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005380 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005381 Type, CallType, InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00005382 UncoveredArg, Offset);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005383
5384 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005385 }
5386
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005387 case Stmt::ImplicitCastExprClass:
Ted Kremenek808829352010-09-09 03:51:39 +00005388 E = cast<ImplicitCastExpr>(E)->getSubExpr();
5389 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005390
John McCallc07a0c72011-02-17 10:25:35 +00005391 case Stmt::OpaqueValueExprClass:
5392 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
5393 E = src;
5394 goto tryAgain;
5395 }
Richard Smith55ce3522012-06-25 20:30:08 +00005396 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00005397
Ted Kremeneka8890832011-02-24 23:03:04 +00005398 case Stmt::PredefinedExprClass:
5399 // While __func__, etc., are technically not string literals, they
5400 // cannot contain format specifiers and thus are not a security
5401 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00005402 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00005403
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005404 case Stmt::DeclRefExprClass: {
5405 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005406
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005407 // As an exception, do not flag errors for variables binding to
5408 // const string literals.
5409 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
5410 bool isConstant = false;
5411 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005412
Richard Smithd7293d72013-08-05 18:49:43 +00005413 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
5414 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00005415 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00005416 isConstant = T.isConstant(S.Context) &&
5417 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00005418 } else if (T->isObjCObjectPointerType()) {
5419 // In ObjC, there is usually no "const ObjectPointer" type,
5420 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00005421 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005422 }
Mike Stump11289f42009-09-09 15:08:12 +00005423
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005424 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00005425 if (const Expr *Init = VD->getAnyInitializer()) {
5426 // Look through initializers like const char c[] = { "foo" }
5427 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
5428 if (InitList->isStringLiteralInit())
5429 Init = InitList->getInit(0)->IgnoreParenImpCasts();
5430 }
Richard Smithd7293d72013-08-05 18:49:43 +00005431 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005432 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005433 firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00005434 /*InFunctionCall*/ false, CheckedVarArgs,
5435 UncoveredArg, Offset);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00005436 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005437 }
Mike Stump11289f42009-09-09 15:08:12 +00005438
Anders Carlssonb012ca92009-06-28 19:55:58 +00005439 // For vprintf* functions (i.e., HasVAListArg==true), we add a
5440 // special check to see if the format string is a function parameter
5441 // of the function calling the printf function. If the function
5442 // has an attribute indicating it is a printf-like function, then we
5443 // should suppress warnings concerning non-literals being used in a call
5444 // to a vprintf function. For example:
5445 //
5446 // void
5447 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
5448 // va_list ap;
5449 // va_start(ap, fmt);
5450 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
5451 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00005452 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00005453 if (HasVAListArg) {
5454 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
5455 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
5456 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00005457 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00005458 // adjust for implicit parameter
5459 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5460 if (MD->isInstance())
5461 ++PVIndex;
5462 // We also check if the formats are compatible.
5463 // We can't pass a 'scanf' string to a 'printf' function.
5464 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00005465 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00005466 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00005467 }
5468 }
5469 }
5470 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005471 }
Mike Stump11289f42009-09-09 15:08:12 +00005472
Richard Smith55ce3522012-06-25 20:30:08 +00005473 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005474 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005475
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00005476 case Stmt::CallExprClass:
5477 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005478 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00005479 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
5480 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
Joel E. Denny81508102018-03-13 14:51:22 +00005481 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
Richard Smithd7293d72013-08-05 18:49:43 +00005482 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005483 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00005484 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00005485 CheckedVarArgs, UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005486 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5487 unsigned BuiltinID = FD->getBuiltinID();
5488 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
5489 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
5490 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00005491 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005492 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005493 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005494 InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00005495 UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005496 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005497 }
5498 }
Mike Stump11289f42009-09-09 15:08:12 +00005499
Richard Smith55ce3522012-06-25 20:30:08 +00005500 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005501 }
Alex Lorenzd9007142016-10-24 09:42:34 +00005502 case Stmt::ObjCMessageExprClass: {
5503 const auto *ME = cast<ObjCMessageExpr>(E);
5504 if (const auto *ND = ME->getMethodDecl()) {
5505 if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
Joel E. Denny81508102018-03-13 14:51:22 +00005506 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
Alex Lorenzd9007142016-10-24 09:42:34 +00005507 return checkFormatStringExpr(
5508 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
5509 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
5510 }
5511 }
5512
5513 return SLCT_NotALiteral;
5514 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005515 case Stmt::ObjCStringLiteralClass:
5516 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00005517 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005518
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005519 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005520 StrE = ObjCFExpr->getString();
5521 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005522 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005523
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005524 if (StrE) {
Stephen Hines648c3692016-09-16 01:07:04 +00005525 if (Offset.isNegative() || Offset > StrE->getLength()) {
5526 // TODO: It would be better to have an explicit warning for out of
5527 // bounds literals.
5528 return SLCT_NotALiteral;
5529 }
5530 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
5531 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005532 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005533 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00005534 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005535 }
Mike Stump11289f42009-09-09 15:08:12 +00005536
Richard Smith55ce3522012-06-25 20:30:08 +00005537 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005538 }
Stephen Hines648c3692016-09-16 01:07:04 +00005539 case Stmt::BinaryOperatorClass: {
5540 llvm::APSInt LResult;
5541 llvm::APSInt RResult;
5542
5543 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
5544
5545 // A string literal + an int offset is still a string literal.
5546 if (BinOp->isAdditiveOp()) {
5547 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
5548 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
5549
5550 if (LIsInt != RIsInt) {
5551 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
5552
5553 if (LIsInt) {
5554 if (BinOpKind == BO_Add) {
5555 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
5556 E = BinOp->getRHS();
5557 goto tryAgain;
5558 }
5559 } else {
5560 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
5561 E = BinOp->getLHS();
5562 goto tryAgain;
5563 }
5564 }
Stephen Hines648c3692016-09-16 01:07:04 +00005565 }
George Burgess IVd273aab2016-09-22 00:00:26 +00005566
5567 return SLCT_NotALiteral;
Stephen Hines648c3692016-09-16 01:07:04 +00005568 }
5569 case Stmt::UnaryOperatorClass: {
5570 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
5571 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005572 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
Stephen Hines648c3692016-09-16 01:07:04 +00005573 llvm::APSInt IndexResult;
5574 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
5575 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
5576 E = ASE->getBase();
5577 goto tryAgain;
5578 }
5579 }
5580
5581 return SLCT_NotALiteral;
5582 }
Mike Stump11289f42009-09-09 15:08:12 +00005583
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005584 default:
Richard Smith55ce3522012-06-25 20:30:08 +00005585 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005586 }
5587}
5588
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005589Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00005590 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Mehdi Amini06d367c2016-10-24 20:39:34 +00005591 .Case("scanf", FST_Scanf)
5592 .Cases("printf", "printf0", FST_Printf)
5593 .Cases("NSString", "CFString", FST_NSString)
5594 .Case("strftime", FST_Strftime)
5595 .Case("strfmon", FST_Strfmon)
5596 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
5597 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
5598 .Case("os_trace", FST_OSLog)
5599 .Case("os_log", FST_OSLog)
5600 .Default(FST_Unknown);
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005601}
5602
Jordan Rose3e0ec582012-07-19 18:10:23 +00005603/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00005604/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00005605/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005606bool Sema::CheckFormatArguments(const FormatAttr *Format,
5607 ArrayRef<const Expr *> Args,
5608 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005609 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00005610 SourceLocation Loc, SourceRange Range,
5611 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00005612 FormatStringInfo FSI;
5613 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005614 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00005615 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00005616 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00005617 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005618}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00005619
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005620bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005621 bool HasVAListArg, unsigned format_idx,
5622 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005623 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00005624 SourceLocation Loc, SourceRange Range,
5625 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00005626 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005627 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005628 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00005629 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005630 }
Mike Stump11289f42009-09-09 15:08:12 +00005631
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005632 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00005633
Chris Lattnerb87b1b32007-08-10 20:18:51 +00005634 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00005635 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005636 // Dynamically generated format strings are difficult to
5637 // automatically vet at compile time. Requiring that format strings
5638 // are string literals: (1) permits the checking of format strings by
5639 // the compiler and thereby (2) can practically remove the source of
5640 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00005641
Mike Stump11289f42009-09-09 15:08:12 +00005642 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00005643 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00005644 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00005645 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005646 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00005647 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00005648 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
5649 format_idx, firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00005650 /*IsFunctionCall*/ true, CheckedVarArgs,
5651 UncoveredArg,
5652 /*no string offset*/ llvm::APSInt(64, false) = 0);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005653
5654 // Generate a diagnostic where an uncovered argument is detected.
5655 if (UncoveredArg.hasUncoveredArg()) {
5656 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
5657 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
5658 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
5659 }
5660
Richard Smith55ce3522012-06-25 20:30:08 +00005661 if (CT != SLCT_NotALiteral)
5662 // Literal format string found, check done!
5663 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00005664
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00005665 // Strftime is particular as it always uses a single 'time' argument,
5666 // so it is safe to pass a non-literal string.
5667 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00005668 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00005669
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00005670 // Do not emit diag when the string param is a macro expansion and the
5671 // format is either NSString or CFString. This is a hack to prevent
5672 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
5673 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005674 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
5675 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00005676 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00005677
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005678 // If there are no arguments specified, warn with -Wformat-security, otherwise
5679 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005680 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00005681 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
5682 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005683 switch (Type) {
5684 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005685 break;
5686 case FST_Kprintf:
5687 case FST_FreeBSDKPrintf:
5688 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00005689 Diag(FormatLoc, diag::note_format_security_fixit)
5690 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005691 break;
5692 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00005693 Diag(FormatLoc, diag::note_format_security_fixit)
5694 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005695 break;
5696 }
5697 } else {
5698 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005699 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005700 }
Richard Smith55ce3522012-06-25 20:30:08 +00005701 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005702}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005703
Ted Kremenekab278de2010-01-28 23:39:18 +00005704namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005705
Ted Kremenek02087932010-07-16 02:11:22 +00005706class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
5707protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00005708 Sema &S;
Stephen Hines648c3692016-09-16 01:07:04 +00005709 const FormatStringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00005710 const Expr *OrigFormatExpr;
Mehdi Amini06d367c2016-10-24 20:39:34 +00005711 const Sema::FormatStringType FSType;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00005712 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00005713 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00005714 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00005715 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005716 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00005717 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00005718 llvm::SmallBitVector CoveredArgs;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005719 bool usesPositionalArgs = false;
5720 bool atFirstArg = true;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005721 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00005722 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00005723 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005724 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005725
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005726public:
Stephen Hines648c3692016-09-16 01:07:04 +00005727 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005728 const Expr *origFormatExpr,
5729 const Sema::FormatStringType type, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005730 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005731 ArrayRef<const Expr *> Args, unsigned formatIdx,
5732 bool inFunctionCall, Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005733 llvm::SmallBitVector &CheckedVarArgs,
5734 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005735 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
5736 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
5737 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
Mehdi Amini06d367c2016-10-24 20:39:34 +00005738 inFunctionCall(inFunctionCall), CallType(callType),
5739 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00005740 CoveredArgs.resize(numDataArgs);
5741 CoveredArgs.reset();
5742 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005743
Ted Kremenek019d2242010-01-29 01:50:07 +00005744 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005745
Ted Kremenek02087932010-07-16 02:11:22 +00005746 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005747 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005748
Jordan Rose92303592012-09-08 04:00:03 +00005749 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005750 const analyze_format_string::FormatSpecifier &FS,
5751 const analyze_format_string::ConversionSpecifier &CS,
5752 const char *startSpecifier, unsigned specifierLen,
5753 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00005754
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005755 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005756 const analyze_format_string::FormatSpecifier &FS,
5757 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005758
5759 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005760 const analyze_format_string::ConversionSpecifier &CS,
5761 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005762
Craig Toppere14c0f82014-03-12 04:55:44 +00005763 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005764
Craig Toppere14c0f82014-03-12 04:55:44 +00005765 void HandleInvalidPosition(const char *startSpecifier,
5766 unsigned specifierLen,
5767 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005768
Craig Toppere14c0f82014-03-12 04:55:44 +00005769 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005770
Craig Toppere14c0f82014-03-12 04:55:44 +00005771 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005772
Richard Trieu03cf7b72011-10-28 00:41:25 +00005773 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00005774 static void
5775 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
5776 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
5777 bool IsStringLocation, Range StringRange,
5778 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005779
Ted Kremenek02087932010-07-16 02:11:22 +00005780protected:
Ted Kremenekce815422010-07-19 21:25:57 +00005781 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
5782 const char *startSpec,
5783 unsigned specifierLen,
5784 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005785
5786 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
5787 const char *startSpec,
5788 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00005789
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005790 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00005791 CharSourceRange getSpecifierRange(const char *startSpecifier,
5792 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00005793 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005794
Ted Kremenek5739de72010-01-29 01:06:55 +00005795 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005796
5797 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
5798 const analyze_format_string::ConversionSpecifier &CS,
5799 const char *startSpecifier, unsigned specifierLen,
5800 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005801
5802 template <typename Range>
5803 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5804 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00005805 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00005806};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005807
5808} // namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00005809
Ted Kremenek02087932010-07-16 02:11:22 +00005810SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00005811 return OrigFormatExpr->getSourceRange();
5812}
5813
Ted Kremenek02087932010-07-16 02:11:22 +00005814CharSourceRange CheckFormatHandler::
5815getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00005816 SourceLocation Start = getLocationOfByte(startSpecifier);
5817 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
5818
5819 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00005820 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00005821
5822 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005823}
5824
Ted Kremenek02087932010-07-16 02:11:22 +00005825SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines648c3692016-09-16 01:07:04 +00005826 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
5827 S.getLangOpts(), S.Context.getTargetInfo());
Ted Kremenekab278de2010-01-28 23:39:18 +00005828}
5829
Ted Kremenek02087932010-07-16 02:11:22 +00005830void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
5831 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00005832 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
5833 getLocationOfByte(startSpecifier),
5834 /*IsStringLocation*/true,
5835 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00005836}
5837
Jordan Rose92303592012-09-08 04:00:03 +00005838void CheckFormatHandler::HandleInvalidLengthModifier(
5839 const analyze_format_string::FormatSpecifier &FS,
5840 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00005841 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00005842 using namespace analyze_format_string;
5843
5844 const LengthModifier &LM = FS.getLengthModifier();
5845 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5846
5847 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005848 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00005849 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005850 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005851 getLocationOfByte(LM.getStart()),
5852 /*IsStringLocation*/true,
5853 getSpecifierRange(startSpecifier, specifierLen));
5854
5855 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5856 << FixedLM->toString()
5857 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5858
5859 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005860 FixItHint Hint;
5861 if (DiagID == diag::warn_format_nonsensical_length)
5862 Hint = FixItHint::CreateRemoval(LMRange);
5863
5864 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005865 getLocationOfByte(LM.getStart()),
5866 /*IsStringLocation*/true,
5867 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00005868 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00005869 }
5870}
5871
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005872void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00005873 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005874 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005875 using namespace analyze_format_string;
5876
5877 const LengthModifier &LM = FS.getLengthModifier();
5878 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5879
5880 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005881 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00005882 if (FixedLM) {
5883 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5884 << LM.toString() << 0,
5885 getLocationOfByte(LM.getStart()),
5886 /*IsStringLocation*/true,
5887 getSpecifierRange(startSpecifier, specifierLen));
5888
5889 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5890 << FixedLM->toString()
5891 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5892
5893 } else {
5894 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5895 << LM.toString() << 0,
5896 getLocationOfByte(LM.getStart()),
5897 /*IsStringLocation*/true,
5898 getSpecifierRange(startSpecifier, specifierLen));
5899 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005900}
5901
5902void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5903 const analyze_format_string::ConversionSpecifier &CS,
5904 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00005905 using namespace analyze_format_string;
5906
5907 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00005908 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00005909 if (FixedCS) {
5910 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5911 << CS.toString() << /*conversion specifier*/1,
5912 getLocationOfByte(CS.getStart()),
5913 /*IsStringLocation*/true,
5914 getSpecifierRange(startSpecifier, specifierLen));
5915
5916 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5917 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5918 << FixedCS->toString()
5919 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5920 } else {
5921 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5922 << CS.toString() << /*conversion specifier*/1,
5923 getLocationOfByte(CS.getStart()),
5924 /*IsStringLocation*/true,
5925 getSpecifierRange(startSpecifier, specifierLen));
5926 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005927}
5928
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005929void CheckFormatHandler::HandlePosition(const char *startPos,
5930 unsigned posLen) {
5931 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5932 getLocationOfByte(startPos),
5933 /*IsStringLocation*/true,
5934 getSpecifierRange(startPos, posLen));
5935}
5936
Ted Kremenekd1668192010-02-27 01:41:03 +00005937void
Ted Kremenek02087932010-07-16 02:11:22 +00005938CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5939 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005940 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5941 << (unsigned) p,
5942 getLocationOfByte(startPos), /*IsStringLocation*/true,
5943 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005944}
5945
Ted Kremenek02087932010-07-16 02:11:22 +00005946void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00005947 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005948 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5949 getLocationOfByte(startPos),
5950 /*IsStringLocation*/true,
5951 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005952}
5953
Ted Kremenek02087932010-07-16 02:11:22 +00005954void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005955 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005956 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005957 EmitFormatDiagnostic(
5958 S.PDiag(diag::warn_printf_format_string_contains_null_char),
5959 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5960 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005961 }
Ted Kremenek02087932010-07-16 02:11:22 +00005962}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005963
Jordan Rose58bbe422012-07-19 18:10:08 +00005964// Note that this may return NULL if there was an error parsing or building
5965// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00005966const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005967 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00005968}
5969
5970void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005971 // Does the number of data arguments exceed the number of
5972 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00005973 if (!HasVAListArg) {
5974 // Find any arguments that weren't covered.
5975 CoveredArgs.flip();
5976 signed notCoveredArg = CoveredArgs.find_first();
5977 if (notCoveredArg >= 0) {
5978 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005979 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5980 } else {
5981 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00005982 }
5983 }
5984}
5985
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005986void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5987 const Expr *ArgExpr) {
5988 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5989 "Invalid state");
5990
5991 if (!ArgExpr)
5992 return;
5993
5994 SourceLocation Loc = ArgExpr->getLocStart();
5995
5996 if (S.getSourceManager().isInSystemMacro(Loc))
5997 return;
5998
5999 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
6000 for (auto E : DiagnosticExprs)
6001 PDiag << E->getSourceRange();
6002
6003 CheckFormatHandler::EmitFormatDiagnostic(
6004 S, IsFunctionCall, DiagnosticExprs[0],
6005 PDiag, Loc, /*IsStringLocation*/false,
6006 DiagnosticExprs[0]->getSourceRange());
6007}
6008
Ted Kremenekce815422010-07-19 21:25:57 +00006009bool
6010CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
6011 SourceLocation Loc,
6012 const char *startSpec,
6013 unsigned specifierLen,
6014 const char *csStart,
6015 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00006016 bool keepGoing = true;
6017 if (argIndex < NumDataArgs) {
6018 // Consider the argument coverered, even though the specifier doesn't
6019 // make sense.
6020 CoveredArgs.set(argIndex);
6021 }
6022 else {
6023 // If argIndex exceeds the number of data arguments we
6024 // don't issue a warning because that is just a cascade of warnings (and
6025 // they may have intended '%%' anyway). We don't want to continue processing
6026 // the format string after this point, however, as we will like just get
6027 // gibberish when trying to match arguments.
6028 keepGoing = false;
6029 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00006030
6031 StringRef Specifier(csStart, csLen);
6032
6033 // If the specifier in non-printable, it could be the first byte of a UTF-8
6034 // sequence. In that case, print the UTF-8 code point. If not, print the byte
6035 // hex value.
6036 std::string CodePointStr;
6037 if (!llvm::sys::locale::isPrint(*csStart)) {
Justin Lebar90910552016-09-30 00:38:45 +00006038 llvm::UTF32 CodePoint;
6039 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
6040 const llvm::UTF8 *E =
6041 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
6042 llvm::ConversionResult Result =
6043 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00006044
Justin Lebar90910552016-09-30 00:38:45 +00006045 if (Result != llvm::conversionOK) {
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00006046 unsigned char FirstChar = *csStart;
Justin Lebar90910552016-09-30 00:38:45 +00006047 CodePoint = (llvm::UTF32)FirstChar;
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00006048 }
6049
6050 llvm::raw_string_ostream OS(CodePointStr);
6051 if (CodePoint < 256)
6052 OS << "\\x" << llvm::format("%02x", CodePoint);
6053 else if (CodePoint <= 0xFFFF)
6054 OS << "\\u" << llvm::format("%04x", CodePoint);
6055 else
6056 OS << "\\U" << llvm::format("%08x", CodePoint);
6057 OS.flush();
6058 Specifier = CodePointStr;
6059 }
6060
6061 EmitFormatDiagnostic(
6062 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
6063 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
6064
Ted Kremenekce815422010-07-19 21:25:57 +00006065 return keepGoing;
6066}
6067
Richard Trieu03cf7b72011-10-28 00:41:25 +00006068void
6069CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
6070 const char *startSpec,
6071 unsigned specifierLen) {
6072 EmitFormatDiagnostic(
6073 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
6074 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
6075}
6076
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006077bool
6078CheckFormatHandler::CheckNumArgs(
6079 const analyze_format_string::FormatSpecifier &FS,
6080 const analyze_format_string::ConversionSpecifier &CS,
6081 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
6082
6083 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006084 PartialDiagnostic PDiag = FS.usesPositionalArg()
6085 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
6086 << (argIndex+1) << NumDataArgs)
6087 : S.PDiag(diag::warn_printf_insufficient_data_args);
6088 EmitFormatDiagnostic(
6089 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
6090 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006091
6092 // Since more arguments than conversion tokens are given, by extension
6093 // all arguments are covered, so mark this as so.
6094 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006095 return false;
6096 }
6097 return true;
6098}
6099
Richard Trieu03cf7b72011-10-28 00:41:25 +00006100template<typename Range>
6101void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
6102 SourceLocation Loc,
6103 bool IsStringLocation,
6104 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00006105 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00006106 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00006107 Loc, IsStringLocation, StringRange, FixIt);
6108}
6109
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006110/// If the format string is not within the function call, emit a note
Richard Trieu03cf7b72011-10-28 00:41:25 +00006111/// so that the function call and string are in diagnostic messages.
6112///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00006113/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00006114/// call and only one diagnostic message will be produced. Otherwise, an
6115/// extra note will be emitted pointing to location of the format string.
6116///
6117/// \param ArgumentExpr the expression that is passed as the format string
6118/// argument in the function call. Used for getting locations when two
6119/// diagnostics are emitted.
6120///
6121/// \param PDiag the callee should already have provided any strings for the
6122/// diagnostic message. This function only adds locations and fixits
6123/// to diagnostics.
6124///
6125/// \param Loc primary location for diagnostic. If two diagnostics are
6126/// required, one will be at Loc and a new SourceLocation will be created for
6127/// the other one.
6128///
6129/// \param IsStringLocation if true, Loc points to the format string should be
6130/// used for the note. Otherwise, Loc points to the argument list and will
6131/// be used with PDiag.
6132///
6133/// \param StringRange some or all of the string to highlight. This is
6134/// templated so it can accept either a CharSourceRange or a SourceRange.
6135///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00006136/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00006137template <typename Range>
6138void CheckFormatHandler::EmitFormatDiagnostic(
6139 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
6140 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
6141 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00006142 if (InFunctionCall) {
6143 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
6144 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00006145 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00006146 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006147 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
6148 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00006149
6150 const Sema::SemaDiagnosticBuilder &Note =
6151 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
6152 diag::note_format_string_defined);
6153
6154 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00006155 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00006156 }
6157}
6158
Ted Kremenek02087932010-07-16 02:11:22 +00006159//===--- CHECK: Printf format string checking ------------------------------===//
6160
6161namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006162
Ted Kremenek02087932010-07-16 02:11:22 +00006163class CheckPrintfHandler : public CheckFormatHandler {
6164public:
Stephen Hines648c3692016-09-16 01:07:04 +00006165 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006166 const Expr *origFormatExpr,
6167 const Sema::FormatStringType type, unsigned firstDataArg,
6168 unsigned numDataArgs, bool isObjC, const char *beg,
6169 bool hasVAListArg, ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00006170 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00006171 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006172 llvm::SmallBitVector &CheckedVarArgs,
6173 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006174 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6175 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6176 inFunctionCall, CallType, CheckedVarArgs,
6177 UncoveredArg) {}
6178
6179 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
6180
6181 /// Returns true if '%@' specifiers are allowed in the format string.
6182 bool allowsObjCArg() const {
6183 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
6184 FSType == Sema::FST_OSTrace;
6185 }
Jordan Rose3e0ec582012-07-19 18:10:23 +00006186
Ted Kremenek02087932010-07-16 02:11:22 +00006187 bool HandleInvalidPrintfConversionSpecifier(
6188 const analyze_printf::PrintfSpecifier &FS,
6189 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006190 unsigned specifierLen) override;
6191
Ted Kremenek02087932010-07-16 02:11:22 +00006192 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
6193 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006194 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00006195 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6196 const char *StartSpecifier,
6197 unsigned SpecifierLen,
6198 const Expr *E);
6199
Ted Kremenek02087932010-07-16 02:11:22 +00006200 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
6201 const char *startSpecifier, unsigned specifierLen);
6202 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
6203 const analyze_printf::OptionalAmount &Amt,
6204 unsigned type,
6205 const char *startSpecifier, unsigned specifierLen);
6206 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
6207 const analyze_printf::OptionalFlag &flag,
6208 const char *startSpecifier, unsigned specifierLen);
6209 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
6210 const analyze_printf::OptionalFlag &ignoredFlag,
6211 const analyze_printf::OptionalFlag &flag,
6212 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006213 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00006214 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00006215
6216 void HandleEmptyObjCModifierFlag(const char *startFlag,
6217 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00006218
Ted Kremenek2b417712015-07-02 05:39:16 +00006219 void HandleInvalidObjCModifierFlag(const char *startFlag,
6220 unsigned flagLen) override;
6221
6222 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
6223 const char *flagsEnd,
6224 const char *conversionPosition)
6225 override;
6226};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006227
6228} // namespace
Ted Kremenek02087932010-07-16 02:11:22 +00006229
6230bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
6231 const analyze_printf::PrintfSpecifier &FS,
6232 const char *startSpecifier,
6233 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006234 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00006235 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00006236
Ted Kremenekce815422010-07-19 21:25:57 +00006237 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6238 getLocationOfByte(CS.getStart()),
6239 startSpecifier, specifierLen,
6240 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00006241}
6242
Ted Kremenek02087932010-07-16 02:11:22 +00006243bool CheckPrintfHandler::HandleAmount(
6244 const analyze_format_string::OptionalAmount &Amt,
6245 unsigned k, const char *startSpecifier,
6246 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00006247 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00006248 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00006249 unsigned argIndex = Amt.getArgIndex();
6250 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006251 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
6252 << k,
6253 getLocationOfByte(Amt.getStart()),
6254 /*IsStringLocation*/true,
6255 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00006256 // Don't do any more checking. We will just emit
6257 // spurious errors.
6258 return false;
6259 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006260
Ted Kremenek5739de72010-01-29 01:06:55 +00006261 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00006262 // Although not in conformance with C99, we also allow the argument to be
6263 // an 'unsigned int' as that is a reasonably safe case. GCC also
6264 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00006265 CoveredArgs.set(argIndex);
6266 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00006267 if (!Arg)
6268 return false;
6269
Ted Kremenek5739de72010-01-29 01:06:55 +00006270 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006271
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006272 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
6273 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006274
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006275 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006276 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006277 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00006278 << T << Arg->getSourceRange(),
6279 getLocationOfByte(Amt.getStart()),
6280 /*IsStringLocation*/true,
6281 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00006282 // Don't do any more checking. We will just emit
6283 // spurious errors.
6284 return false;
6285 }
6286 }
6287 }
6288 return true;
6289}
Ted Kremenek5739de72010-01-29 01:06:55 +00006290
Tom Careb49ec692010-06-17 19:00:27 +00006291void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00006292 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00006293 const analyze_printf::OptionalAmount &Amt,
6294 unsigned type,
6295 const char *startSpecifier,
6296 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006297 const analyze_printf::PrintfConversionSpecifier &CS =
6298 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00006299
Richard Trieu03cf7b72011-10-28 00:41:25 +00006300 FixItHint fixit =
6301 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
6302 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
6303 Amt.getConstantLength()))
6304 : FixItHint();
6305
6306 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
6307 << type << CS.toString(),
6308 getLocationOfByte(Amt.getStart()),
6309 /*IsStringLocation*/true,
6310 getSpecifierRange(startSpecifier, specifierLen),
6311 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00006312}
6313
Ted Kremenek02087932010-07-16 02:11:22 +00006314void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00006315 const analyze_printf::OptionalFlag &flag,
6316 const char *startSpecifier,
6317 unsigned specifierLen) {
6318 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006319 const analyze_printf::PrintfConversionSpecifier &CS =
6320 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00006321 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
6322 << flag.toString() << CS.toString(),
6323 getLocationOfByte(flag.getPosition()),
6324 /*IsStringLocation*/true,
6325 getSpecifierRange(startSpecifier, specifierLen),
6326 FixItHint::CreateRemoval(
6327 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00006328}
6329
6330void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00006331 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00006332 const analyze_printf::OptionalFlag &ignoredFlag,
6333 const analyze_printf::OptionalFlag &flag,
6334 const char *startSpecifier,
6335 unsigned specifierLen) {
6336 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00006337 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
6338 << ignoredFlag.toString() << flag.toString(),
6339 getLocationOfByte(ignoredFlag.getPosition()),
6340 /*IsStringLocation*/true,
6341 getSpecifierRange(startSpecifier, specifierLen),
6342 FixItHint::CreateRemoval(
6343 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00006344}
6345
Ted Kremenek2b417712015-07-02 05:39:16 +00006346void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
6347 unsigned flagLen) {
6348 // Warn about an empty flag.
6349 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
6350 getLocationOfByte(startFlag),
6351 /*IsStringLocation*/true,
6352 getSpecifierRange(startFlag, flagLen));
6353}
6354
6355void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
6356 unsigned flagLen) {
6357 // Warn about an invalid flag.
6358 auto Range = getSpecifierRange(startFlag, flagLen);
6359 StringRef flag(startFlag, flagLen);
6360 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
6361 getLocationOfByte(startFlag),
6362 /*IsStringLocation*/true,
6363 Range, FixItHint::CreateRemoval(Range));
6364}
6365
6366void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
6367 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
6368 // Warn about using '[...]' without a '@' conversion.
6369 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
6370 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
6371 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
6372 getLocationOfByte(conversionPosition),
6373 /*IsStringLocation*/true,
6374 Range, FixItHint::CreateRemoval(Range));
6375}
6376
Richard Smith55ce3522012-06-25 20:30:08 +00006377// Determines if the specified is a C++ class or struct containing
6378// a member with the specified name and kind (e.g. a CXXMethodDecl named
6379// "c_str()").
6380template<typename MemberKind>
6381static llvm::SmallPtrSet<MemberKind*, 1>
6382CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
6383 const RecordType *RT = Ty->getAs<RecordType>();
6384 llvm::SmallPtrSet<MemberKind*, 1> Results;
6385
6386 if (!RT)
6387 return Results;
6388 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00006389 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00006390 return Results;
6391
Alp Tokerb6cc5922014-05-03 03:45:55 +00006392 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00006393 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00006394 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00006395
6396 // We just need to include all members of the right kind turned up by the
6397 // filter, at this point.
6398 if (S.LookupQualifiedName(R, RT->getDecl()))
6399 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6400 NamedDecl *decl = (*I)->getUnderlyingDecl();
6401 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
6402 Results.insert(FK);
6403 }
6404 return Results;
6405}
6406
Richard Smith2868a732014-02-28 01:36:39 +00006407/// Check if we could call '.c_str()' on an object.
6408///
6409/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
6410/// allow the call, or if it would be ambiguous).
6411bool Sema::hasCStrMethod(const Expr *E) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006412 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
6413
Richard Smith2868a732014-02-28 01:36:39 +00006414 MethodSet Results =
6415 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
6416 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
6417 MI != ME; ++MI)
6418 if ((*MI)->getMinRequiredArguments() == 0)
6419 return true;
6420 return false;
6421}
6422
Richard Smith55ce3522012-06-25 20:30:08 +00006423// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006424// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00006425// Returns true when a c_str() conversion method is found.
6426bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00006427 const analyze_printf::ArgType &AT, const Expr *E) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006428 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
Richard Smith55ce3522012-06-25 20:30:08 +00006429
6430 MethodSet Results =
6431 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
6432
6433 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
6434 MI != ME; ++MI) {
6435 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00006436 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00006437 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00006438 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00006439 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00006440 S.Diag(E->getLocStart(), diag::note_printf_c_str)
6441 << "c_str()"
6442 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
6443 return true;
6444 }
6445 }
6446
6447 return false;
6448}
6449
Ted Kremenekab278de2010-01-28 23:39:18 +00006450bool
Ted Kremenek02087932010-07-16 02:11:22 +00006451CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00006452 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00006453 const char *startSpecifier,
6454 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006455 using namespace analyze_format_string;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006456 using namespace analyze_printf;
6457
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006458 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00006459
Ted Kremenek6cd69422010-07-19 22:01:06 +00006460 if (FS.consumesDataArgument()) {
6461 if (atFirstArg) {
6462 atFirstArg = false;
6463 usesPositionalArgs = FS.usesPositionalArg();
6464 }
6465 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006466 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6467 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00006468 return false;
6469 }
Ted Kremenek5739de72010-01-29 01:06:55 +00006470 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006471
Ted Kremenekd1668192010-02-27 01:41:03 +00006472 // First check if the field width, precision, and conversion specifier
6473 // have matching data arguments.
6474 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
6475 startSpecifier, specifierLen)) {
6476 return false;
6477 }
6478
6479 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
6480 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00006481 return false;
6482 }
6483
Ted Kremenek8d9842d2010-01-29 20:55:36 +00006484 if (!CS.consumesDataArgument()) {
6485 // FIXME: Technically specifying a precision or field width here
6486 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00006487 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00006488 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006489
Ted Kremenek4a49d982010-02-26 19:18:41 +00006490 // Consume the argument.
6491 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00006492 if (argIndex < NumDataArgs) {
6493 // The check to see if the argIndex is valid will come later.
6494 // We set the bit here because we may exit early from this
6495 // function if we encounter some other error.
6496 CoveredArgs.set(argIndex);
6497 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00006498
Dimitry Andric6b5ed342015-02-19 22:32:33 +00006499 // FreeBSD kernel extensions.
6500 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
6501 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
6502 // We need at least two arguments.
6503 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
6504 return false;
6505
6506 // Claim the second argument.
6507 CoveredArgs.set(argIndex + 1);
6508
6509 // Type check the first argument (int for %b, pointer for %D)
6510 const Expr *Ex = getDataArg(argIndex);
6511 const analyze_printf::ArgType &AT =
6512 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
6513 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
6514 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
6515 EmitFormatDiagnostic(
6516 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6517 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
6518 << false << Ex->getSourceRange(),
6519 Ex->getLocStart(), /*IsStringLocation*/false,
6520 getSpecifierRange(startSpecifier, specifierLen));
6521
6522 // Type check the second argument (char * for both %b and %D)
6523 Ex = getDataArg(argIndex + 1);
6524 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
6525 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
6526 EmitFormatDiagnostic(
6527 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6528 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
6529 << false << Ex->getSourceRange(),
6530 Ex->getLocStart(), /*IsStringLocation*/false,
6531 getSpecifierRange(startSpecifier, specifierLen));
6532
6533 return true;
6534 }
6535
Ted Kremenek4a49d982010-02-26 19:18:41 +00006536 // Check for using an Objective-C specific conversion specifier
6537 // in a non-ObjC literal.
Mehdi Amini06d367c2016-10-24 20:39:34 +00006538 if (!allowsObjCArg() && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00006539 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6540 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00006541 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006542
Mehdi Amini06d367c2016-10-24 20:39:34 +00006543 // %P can only be used with os_log.
6544 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
6545 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6546 specifierLen);
6547 }
6548
6549 // %n is not allowed with os_log.
6550 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
6551 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
6552 getLocationOfByte(CS.getStart()),
6553 /*IsStringLocation*/ false,
6554 getSpecifierRange(startSpecifier, specifierLen));
6555
6556 return true;
6557 }
6558
6559 // Only scalars are allowed for os_trace.
6560 if (FSType == Sema::FST_OSTrace &&
6561 (CS.getKind() == ConversionSpecifier::PArg ||
6562 CS.getKind() == ConversionSpecifier::sArg ||
6563 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
6564 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6565 specifierLen);
6566 }
6567
6568 // Check for use of public/private annotation outside of os_log().
6569 if (FSType != Sema::FST_OSLog) {
6570 if (FS.isPublic().isSet()) {
6571 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6572 << "public",
6573 getLocationOfByte(FS.isPublic().getPosition()),
6574 /*IsStringLocation*/ false,
6575 getSpecifierRange(startSpecifier, specifierLen));
6576 }
6577 if (FS.isPrivate().isSet()) {
6578 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6579 << "private",
6580 getLocationOfByte(FS.isPrivate().getPosition()),
6581 /*IsStringLocation*/ false,
6582 getSpecifierRange(startSpecifier, specifierLen));
6583 }
6584 }
6585
Tom Careb49ec692010-06-17 19:00:27 +00006586 // Check for invalid use of field width
6587 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00006588 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00006589 startSpecifier, specifierLen);
6590 }
6591
6592 // Check for invalid use of precision
6593 if (!FS.hasValidPrecision()) {
6594 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
6595 startSpecifier, specifierLen);
6596 }
6597
Mehdi Amini06d367c2016-10-24 20:39:34 +00006598 // Precision is mandatory for %P specifier.
6599 if (CS.getKind() == ConversionSpecifier::PArg &&
6600 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
6601 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
6602 getLocationOfByte(startSpecifier),
6603 /*IsStringLocation*/ false,
6604 getSpecifierRange(startSpecifier, specifierLen));
6605 }
6606
Tom Careb49ec692010-06-17 19:00:27 +00006607 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00006608 if (!FS.hasValidThousandsGroupingPrefix())
6609 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006610 if (!FS.hasValidLeadingZeros())
6611 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
6612 if (!FS.hasValidPlusPrefix())
6613 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00006614 if (!FS.hasValidSpacePrefix())
6615 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006616 if (!FS.hasValidAlternativeForm())
6617 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
6618 if (!FS.hasValidLeftJustified())
6619 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
6620
6621 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00006622 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
6623 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
6624 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006625 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
6626 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
6627 startSpecifier, specifierLen);
6628
6629 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006630 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006631 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6632 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006633 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006634 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006635 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006636 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6637 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00006638
Jordan Rose92303592012-09-08 04:00:03 +00006639 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6640 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6641
Ted Kremenek9fcd8302010-01-29 01:43:31 +00006642 // The remaining checks depend on the data arguments.
6643 if (HasVAListArg)
6644 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006645
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006646 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00006647 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006648
Jordan Rose58bbe422012-07-19 18:10:08 +00006649 const Expr *Arg = getDataArg(argIndex);
6650 if (!Arg)
6651 return true;
6652
6653 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00006654}
6655
Jordan Roseaee34382012-09-05 22:56:26 +00006656static bool requiresParensToAddCast(const Expr *E) {
6657 // FIXME: We should have a general way to reason about operator
6658 // precedence and whether parens are actually needed here.
6659 // Take care of a few common cases where they aren't.
6660 const Expr *Inside = E->IgnoreImpCasts();
6661 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
6662 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
6663
6664 switch (Inside->getStmtClass()) {
6665 case Stmt::ArraySubscriptExprClass:
6666 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006667 case Stmt::CharacterLiteralClass:
6668 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006669 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006670 case Stmt::FloatingLiteralClass:
6671 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006672 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006673 case Stmt::ObjCArrayLiteralClass:
6674 case Stmt::ObjCBoolLiteralExprClass:
6675 case Stmt::ObjCBoxedExprClass:
6676 case Stmt::ObjCDictionaryLiteralClass:
6677 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006678 case Stmt::ObjCIvarRefExprClass:
6679 case Stmt::ObjCMessageExprClass:
6680 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006681 case Stmt::ObjCStringLiteralClass:
6682 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006683 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006684 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006685 case Stmt::UnaryOperatorClass:
6686 return false;
6687 default:
6688 return true;
6689 }
6690}
6691
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006692static std::pair<QualType, StringRef>
6693shouldNotPrintDirectly(const ASTContext &Context,
6694 QualType IntendedTy,
6695 const Expr *E) {
6696 // Use a 'while' to peel off layers of typedefs.
6697 QualType TyTy = IntendedTy;
6698 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
6699 StringRef Name = UserTy->getDecl()->getName();
6700 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Saleem Abdulrasoola01ed932017-10-17 17:39:32 +00006701 .Case("CFIndex", Context.getNSIntegerType())
6702 .Case("NSInteger", Context.getNSIntegerType())
6703 .Case("NSUInteger", Context.getNSUIntegerType())
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006704 .Case("SInt32", Context.IntTy)
6705 .Case("UInt32", Context.UnsignedIntTy)
6706 .Default(QualType());
6707
6708 if (!CastTy.isNull())
6709 return std::make_pair(CastTy, Name);
6710
6711 TyTy = UserTy->desugar();
6712 }
6713
6714 // Strip parens if necessary.
6715 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
6716 return shouldNotPrintDirectly(Context,
6717 PE->getSubExpr()->getType(),
6718 PE->getSubExpr());
6719
6720 // If this is a conditional expression, then its result type is constructed
6721 // via usual arithmetic conversions and thus there might be no necessary
6722 // typedef sugar there. Recurse to operands to check for NSInteger &
6723 // Co. usage condition.
6724 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6725 QualType TrueTy, FalseTy;
6726 StringRef TrueName, FalseName;
6727
6728 std::tie(TrueTy, TrueName) =
6729 shouldNotPrintDirectly(Context,
6730 CO->getTrueExpr()->getType(),
6731 CO->getTrueExpr());
6732 std::tie(FalseTy, FalseName) =
6733 shouldNotPrintDirectly(Context,
6734 CO->getFalseExpr()->getType(),
6735 CO->getFalseExpr());
6736
6737 if (TrueTy == FalseTy)
6738 return std::make_pair(TrueTy, TrueName);
6739 else if (TrueTy.isNull())
6740 return std::make_pair(FalseTy, FalseName);
6741 else if (FalseTy.isNull())
6742 return std::make_pair(TrueTy, TrueName);
6743 }
6744
6745 return std::make_pair(QualType(), StringRef());
6746}
6747
Richard Smith55ce3522012-06-25 20:30:08 +00006748bool
6749CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6750 const char *StartSpecifier,
6751 unsigned SpecifierLen,
6752 const Expr *E) {
6753 using namespace analyze_format_string;
6754 using namespace analyze_printf;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006755
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006756 // Now type check the data expression that matches the
6757 // format specifier.
Mehdi Amini06d367c2016-10-24 20:39:34 +00006758 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
Jordan Rose22b74712012-09-05 22:56:19 +00006759 if (!AT.isValid())
6760 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00006761
Jordan Rose598ec092012-12-05 18:44:40 +00006762 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00006763 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
6764 ExprTy = TET->getUnderlyingExpr()->getType();
6765 }
6766
Seth Cantrellb4802962015-03-04 03:12:10 +00006767 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
6768
6769 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00006770 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006771 }
Jordan Rose98709982012-06-04 22:48:57 +00006772
Jordan Rose22b74712012-09-05 22:56:19 +00006773 // Look through argument promotions for our error message's reported type.
6774 // This includes the integral and floating promotions, but excludes array
6775 // and function pointer decay; seeing that an argument intended to be a
6776 // string has type 'char [6]' is probably more confusing than 'char *'.
6777 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6778 if (ICE->getCastKind() == CK_IntegralCast ||
6779 ICE->getCastKind() == CK_FloatingCast) {
6780 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00006781 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00006782
6783 // Check if we didn't match because of an implicit cast from a 'char'
6784 // or 'short' to an 'int'. This is done because printf is a varargs
6785 // function.
6786 if (ICE->getType() == S.Context.IntTy ||
6787 ICE->getType() == S.Context.UnsignedIntTy) {
6788 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00006789 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00006790 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00006791 }
Jordan Rose98709982012-06-04 22:48:57 +00006792 }
Jordan Rose598ec092012-12-05 18:44:40 +00006793 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
6794 // Special case for 'a', which has type 'int' in C.
6795 // Note, however, that we do /not/ want to treat multibyte constants like
6796 // 'MooV' as characters! This form is deprecated but still exists.
6797 if (ExprTy == S.Context.IntTy)
6798 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6799 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00006800 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006801
Jordan Rosebc53ed12014-05-31 04:12:14 +00006802 // Look through enums to their underlying type.
6803 bool IsEnum = false;
6804 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
6805 ExprTy = EnumTy->getDecl()->getIntegerType();
6806 IsEnum = true;
6807 }
6808
Jordan Rose0e5badd2012-12-05 18:44:49 +00006809 // %C in an Objective-C context prints a unichar, not a wchar_t.
6810 // If the argument is an integer of some kind, believe the %C and suggest
6811 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00006812 QualType IntendedTy = ExprTy;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006813 if (isObjCContext() &&
Jordan Rose0e5badd2012-12-05 18:44:49 +00006814 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
6815 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6816 !ExprTy->isCharType()) {
6817 // 'unichar' is defined as a typedef of unsigned short, but we should
6818 // prefer using the typedef if it is visible.
6819 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00006820
6821 // While we are here, check if the value is an IntegerLiteral that happens
6822 // to be within the valid range.
6823 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
6824 const llvm::APInt &V = IL->getValue();
6825 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6826 return true;
6827 }
6828
Jordan Rose0e5badd2012-12-05 18:44:49 +00006829 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
6830 Sema::LookupOrdinaryName);
6831 if (S.LookupName(Result, S.getCurScope())) {
6832 NamedDecl *ND = Result.getFoundDecl();
6833 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
6834 if (TD->getUnderlyingType() == IntendedTy)
6835 IntendedTy = S.Context.getTypedefType(TD);
6836 }
6837 }
6838 }
6839
6840 // Special-case some of Darwin's platform-independence types by suggesting
6841 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006842 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00006843 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006844 QualType CastTy;
6845 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
6846 if (!CastTy.isNull()) {
6847 IntendedTy = CastTy;
6848 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00006849 }
6850 }
6851
Jordan Rose22b74712012-09-05 22:56:19 +00006852 // We may be able to offer a FixItHint if it is a supported type.
6853 PrintfSpecifier fixedFS = FS;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006854 bool success =
6855 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006856
Jordan Rose22b74712012-09-05 22:56:19 +00006857 if (success) {
6858 // Get the fix string from the fixed format specifier
6859 SmallString<16> buf;
6860 llvm::raw_svector_ostream os(buf);
6861 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006862
Jordan Roseaee34382012-09-05 22:56:26 +00006863 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6864
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006865 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00006866 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6867 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6868 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6869 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00006870 // In this case, the specifier is wrong and should be changed to match
6871 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00006872 EmitFormatDiagnostic(S.PDiag(diag)
6873 << AT.getRepresentativeTypeName(S.Context)
6874 << IntendedTy << IsEnum << E->getSourceRange(),
6875 E->getLocStart(),
6876 /*IsStringLocation*/ false, SpecRange,
6877 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00006878 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00006879 // The canonical type for formatting this value is different from the
6880 // actual type of the expression. (This occurs, for example, with Darwin's
6881 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6882 // should be printed as 'long' for 64-bit compatibility.)
6883 // Rather than emitting a normal format/argument mismatch, we want to
6884 // add a cast to the recommended type (and correct the format string
6885 // if necessary).
6886 SmallString<16> CastBuf;
6887 llvm::raw_svector_ostream CastFix(CastBuf);
6888 CastFix << "(";
6889 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6890 CastFix << ")";
6891
6892 SmallVector<FixItHint,4> Hints;
Alexander Shaposhnikov1788a9b2017-09-22 18:36:06 +00006893 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
Jordan Roseaee34382012-09-05 22:56:26 +00006894 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6895
6896 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6897 // If there's already a cast present, just replace it.
6898 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6899 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6900
6901 } else if (!requiresParensToAddCast(E)) {
6902 // If the expression has high enough precedence,
6903 // just write the C-style cast.
6904 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6905 CastFix.str()));
6906 } else {
6907 // Otherwise, add parens around the expression as well as the cast.
6908 CastFix << "(";
6909 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6910 CastFix.str()));
6911
Alp Tokerb6cc5922014-05-03 03:45:55 +00006912 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00006913 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6914 }
6915
Jordan Rose0e5badd2012-12-05 18:44:49 +00006916 if (ShouldNotPrintDirectly) {
6917 // The expression has a type that should not be printed directly.
6918 // We extract the name from the typedef because we don't want to show
6919 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006920 StringRef Name;
6921 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6922 Name = TypedefTy->getDecl()->getName();
6923 else
6924 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00006925 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00006926 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006927 << E->getSourceRange(),
6928 E->getLocStart(), /*IsStringLocation=*/false,
6929 SpecRange, Hints);
6930 } else {
6931 // In this case, the expression could be printed using a different
6932 // specifier, but we've decided that the specifier is probably correct
6933 // and we should cast instead. Just use the normal warning message.
6934 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00006935 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6936 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006937 << E->getSourceRange(),
6938 E->getLocStart(), /*IsStringLocation*/false,
6939 SpecRange, Hints);
6940 }
Jordan Roseaee34382012-09-05 22:56:26 +00006941 }
Jordan Rose22b74712012-09-05 22:56:19 +00006942 } else {
6943 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6944 SpecifierLen);
6945 // Since the warning for passing non-POD types to variadic functions
6946 // was deferred until now, we emit a warning for non-POD
6947 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00006948 switch (S.isValidVarArgType(ExprTy)) {
6949 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00006950 case Sema::VAK_ValidInCXX11: {
6951 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6952 if (match == analyze_printf::ArgType::NoMatchPedantic) {
6953 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6954 }
Richard Smithd7293d72013-08-05 18:49:43 +00006955
Seth Cantrellb4802962015-03-04 03:12:10 +00006956 EmitFormatDiagnostic(
6957 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6958 << IsEnum << CSR << E->getSourceRange(),
6959 E->getLocStart(), /*IsStringLocation*/ false, CSR);
6960 break;
6961 }
Richard Smithd7293d72013-08-05 18:49:43 +00006962 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00006963 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00006964 EmitFormatDiagnostic(
6965 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006966 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00006967 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00006968 << CallType
6969 << AT.getRepresentativeTypeName(S.Context)
6970 << CSR
6971 << E->getSourceRange(),
6972 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00006973 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00006974 break;
6975
6976 case Sema::VAK_Invalid:
6977 if (ExprTy->isObjCObjectType())
6978 EmitFormatDiagnostic(
6979 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6980 << S.getLangOpts().CPlusPlus11
6981 << ExprTy
6982 << CallType
6983 << AT.getRepresentativeTypeName(S.Context)
6984 << CSR
6985 << E->getSourceRange(),
6986 E->getLocStart(), /*IsStringLocation*/false, CSR);
6987 else
6988 // FIXME: If this is an initializer list, suggest removing the braces
6989 // or inserting a cast to the target type.
6990 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6991 << isa<InitListExpr>(E) << ExprTy << CallType
6992 << AT.getRepresentativeTypeName(S.Context)
6993 << E->getSourceRange();
6994 break;
6995 }
6996
6997 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6998 "format string specifier index out of range");
6999 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00007000 }
7001
Ted Kremenekab278de2010-01-28 23:39:18 +00007002 return true;
7003}
7004
Ted Kremenek02087932010-07-16 02:11:22 +00007005//===--- CHECK: Scanf format string checking ------------------------------===//
7006
7007namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007008
Ted Kremenek02087932010-07-16 02:11:22 +00007009class CheckScanfHandler : public CheckFormatHandler {
7010public:
Stephen Hines648c3692016-09-16 01:07:04 +00007011 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00007012 const Expr *origFormatExpr, Sema::FormatStringType type,
7013 unsigned firstDataArg, unsigned numDataArgs,
7014 const char *beg, bool hasVAListArg,
7015 ArrayRef<const Expr *> Args, unsigned formatIdx,
7016 bool inFunctionCall, Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007017 llvm::SmallBitVector &CheckedVarArgs,
7018 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00007019 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7020 numDataArgs, beg, hasVAListArg, Args, formatIdx,
7021 inFunctionCall, CallType, CheckedVarArgs,
7022 UncoveredArg) {}
7023
Ted Kremenek02087932010-07-16 02:11:22 +00007024 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
7025 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00007026 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00007027
7028 bool HandleInvalidScanfConversionSpecifier(
7029 const analyze_scanf::ScanfSpecifier &FS,
7030 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00007031 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00007032
Craig Toppere14c0f82014-03-12 04:55:44 +00007033 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00007034};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007035
7036} // namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00007037
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00007038void CheckScanfHandler::HandleIncompleteScanList(const char *start,
7039 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007040 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
7041 getLocationOfByte(end), /*IsStringLocation*/true,
7042 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00007043}
7044
Ted Kremenekce815422010-07-19 21:25:57 +00007045bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
7046 const analyze_scanf::ScanfSpecifier &FS,
7047 const char *startSpecifier,
7048 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00007049 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00007050 FS.getConversionSpecifier();
7051
7052 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7053 getLocationOfByte(CS.getStart()),
7054 startSpecifier, specifierLen,
7055 CS.getStart(), CS.getLength());
7056}
7057
Ted Kremenek02087932010-07-16 02:11:22 +00007058bool CheckScanfHandler::HandleScanfSpecifier(
7059 const analyze_scanf::ScanfSpecifier &FS,
7060 const char *startSpecifier,
7061 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00007062 using namespace analyze_scanf;
7063 using namespace analyze_format_string;
7064
Ted Kremenekf03e6d852010-07-20 20:04:27 +00007065 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00007066
Ted Kremenek6cd69422010-07-19 22:01:06 +00007067 // Handle case where '%' and '*' don't consume an argument. These shouldn't
7068 // be used to decide if we are using positional arguments consistently.
7069 if (FS.consumesDataArgument()) {
7070 if (atFirstArg) {
7071 atFirstArg = false;
7072 usesPositionalArgs = FS.usesPositionalArg();
7073 }
7074 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007075 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7076 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00007077 return false;
7078 }
Ted Kremenek02087932010-07-16 02:11:22 +00007079 }
7080
7081 // Check if the field with is non-zero.
7082 const OptionalAmount &Amt = FS.getFieldWidth();
7083 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
7084 if (Amt.getConstantAmount() == 0) {
7085 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
7086 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00007087 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
7088 getLocationOfByte(Amt.getStart()),
7089 /*IsStringLocation*/true, R,
7090 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00007091 }
7092 }
Seth Cantrellb4802962015-03-04 03:12:10 +00007093
Ted Kremenek02087932010-07-16 02:11:22 +00007094 if (!FS.consumesDataArgument()) {
7095 // FIXME: Technically specifying a precision or field width here
7096 // makes no sense. Worth issuing a warning at some point.
7097 return true;
7098 }
Seth Cantrellb4802962015-03-04 03:12:10 +00007099
Ted Kremenek02087932010-07-16 02:11:22 +00007100 // Consume the argument.
7101 unsigned argIndex = FS.getArgIndex();
7102 if (argIndex < NumDataArgs) {
7103 // The check to see if the argIndex is valid will come later.
7104 // We set the bit here because we may exit early from this
7105 // function if we encounter some other error.
7106 CoveredArgs.set(argIndex);
7107 }
Seth Cantrellb4802962015-03-04 03:12:10 +00007108
Ted Kremenek4407ea42010-07-20 20:04:47 +00007109 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00007110 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00007111 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7112 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00007113 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00007114 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00007115 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00007116 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7117 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00007118
Jordan Rose92303592012-09-08 04:00:03 +00007119 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
7120 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
7121
Ted Kremenek02087932010-07-16 02:11:22 +00007122 // The remaining checks depend on the data arguments.
7123 if (HasVAListArg)
7124 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00007125
Ted Kremenek6adb7e32010-07-26 19:45:42 +00007126 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00007127 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00007128
Hans Wennborgb1a5e092011-12-10 13:20:11 +00007129 // Check that the argument type matches the format specifier.
7130 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00007131 if (!Ex)
7132 return true;
7133
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00007134 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00007135
7136 if (!AT.isValid()) {
7137 return true;
7138 }
7139
Seth Cantrellb4802962015-03-04 03:12:10 +00007140 analyze_format_string::ArgType::MatchKind match =
7141 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00007142 if (match == analyze_format_string::ArgType::Match) {
7143 return true;
7144 }
Seth Cantrellb4802962015-03-04 03:12:10 +00007145
Seth Cantrell79340072015-03-04 05:58:08 +00007146 ScanfSpecifier fixedFS = FS;
7147 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
7148 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00007149
Seth Cantrell79340072015-03-04 05:58:08 +00007150 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
7151 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
7152 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
7153 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00007154
Seth Cantrell79340072015-03-04 05:58:08 +00007155 if (success) {
7156 // Get the fix string from the fixed format specifier.
7157 SmallString<128> buf;
7158 llvm::raw_svector_ostream os(buf);
7159 fixedFS.toString(os);
7160
7161 EmitFormatDiagnostic(
7162 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
7163 << Ex->getType() << false << Ex->getSourceRange(),
7164 Ex->getLocStart(),
7165 /*IsStringLocation*/ false,
7166 getSpecifierRange(startSpecifier, specifierLen),
7167 FixItHint::CreateReplacement(
7168 getSpecifierRange(startSpecifier, specifierLen), os.str()));
7169 } else {
7170 EmitFormatDiagnostic(S.PDiag(diag)
7171 << AT.getRepresentativeTypeName(S.Context)
7172 << Ex->getType() << false << Ex->getSourceRange(),
7173 Ex->getLocStart(),
7174 /*IsStringLocation*/ false,
7175 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00007176 }
7177
Ted Kremenek02087932010-07-16 02:11:22 +00007178 return true;
7179}
7180
Stephen Hines648c3692016-09-16 01:07:04 +00007181static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007182 const Expr *OrigFormatExpr,
7183 ArrayRef<const Expr *> Args,
7184 bool HasVAListArg, unsigned format_idx,
7185 unsigned firstDataArg,
7186 Sema::FormatStringType Type,
7187 bool inFunctionCall,
7188 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007189 llvm::SmallBitVector &CheckedVarArgs,
7190 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00007191 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00007192 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007193 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007194 S, inFunctionCall, Args[format_idx],
7195 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00007196 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00007197 return;
7198 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007199
Ted Kremenekab278de2010-01-28 23:39:18 +00007200 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007201 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00007202 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00007203 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007204 const ConstantArrayType *T =
7205 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00007206 assert(T && "String literal not of constant array type!");
7207 size_t TypeSize = T->getSize().getZExtValue();
7208 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00007209 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00007210
7211 // Emit a warning if the string literal is truncated and does not contain an
7212 // embedded null character.
7213 if (TypeSize <= StrRef.size() &&
7214 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
7215 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007216 S, inFunctionCall, Args[format_idx],
7217 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00007218 FExpr->getLocStart(),
7219 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
7220 return;
7221 }
7222
Ted Kremenekab278de2010-01-28 23:39:18 +00007223 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00007224 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007225 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007226 S, inFunctionCall, Args[format_idx],
7227 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00007228 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00007229 return;
7230 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007231
7232 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
Mehdi Amini06d367c2016-10-24 20:39:34 +00007233 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
7234 Type == Sema::FST_OSTrace) {
7235 CheckPrintfHandler H(
7236 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
7237 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
7238 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
7239 CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007240
Hans Wennborg23926bd2011-12-15 10:25:47 +00007241 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007242 S.getLangOpts(),
7243 S.Context.getTargetInfo(),
7244 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00007245 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007246 } else if (Type == Sema::FST_Scanf) {
Mehdi Amini06d367c2016-10-24 20:39:34 +00007247 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
7248 numDataArgs, Str, HasVAListArg, Args, format_idx,
7249 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007250
Hans Wennborg23926bd2011-12-15 10:25:47 +00007251 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007252 S.getLangOpts(),
7253 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00007254 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00007255 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00007256}
7257
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00007258bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
7259 // Str - The format string. NOTE: this is NOT null-terminated!
7260 StringRef StrRef = FExpr->getString();
7261 const char *Str = StrRef.data();
7262 // Account for cases where the string literal is truncated in a declaration.
7263 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
7264 assert(T && "String literal not of constant array type!");
7265 size_t TypeSize = T->getSize().getZExtValue();
7266 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
7267 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
7268 getLangOpts(),
7269 Context.getTargetInfo());
7270}
7271
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007272//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
7273
7274// Returns the related absolute value function that is larger, of 0 if one
7275// does not exist.
7276static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
7277 switch (AbsFunction) {
7278 default:
7279 return 0;
7280
7281 case Builtin::BI__builtin_abs:
7282 return Builtin::BI__builtin_labs;
7283 case Builtin::BI__builtin_labs:
7284 return Builtin::BI__builtin_llabs;
7285 case Builtin::BI__builtin_llabs:
7286 return 0;
7287
7288 case Builtin::BI__builtin_fabsf:
7289 return Builtin::BI__builtin_fabs;
7290 case Builtin::BI__builtin_fabs:
7291 return Builtin::BI__builtin_fabsl;
7292 case Builtin::BI__builtin_fabsl:
7293 return 0;
7294
7295 case Builtin::BI__builtin_cabsf:
7296 return Builtin::BI__builtin_cabs;
7297 case Builtin::BI__builtin_cabs:
7298 return Builtin::BI__builtin_cabsl;
7299 case Builtin::BI__builtin_cabsl:
7300 return 0;
7301
7302 case Builtin::BIabs:
7303 return Builtin::BIlabs;
7304 case Builtin::BIlabs:
7305 return Builtin::BIllabs;
7306 case Builtin::BIllabs:
7307 return 0;
7308
7309 case Builtin::BIfabsf:
7310 return Builtin::BIfabs;
7311 case Builtin::BIfabs:
7312 return Builtin::BIfabsl;
7313 case Builtin::BIfabsl:
7314 return 0;
7315
7316 case Builtin::BIcabsf:
7317 return Builtin::BIcabs;
7318 case Builtin::BIcabs:
7319 return Builtin::BIcabsl;
7320 case Builtin::BIcabsl:
7321 return 0;
7322 }
7323}
7324
7325// Returns the argument type of the absolute value function.
7326static QualType getAbsoluteValueArgumentType(ASTContext &Context,
7327 unsigned AbsType) {
7328 if (AbsType == 0)
7329 return QualType();
7330
7331 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
7332 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
7333 if (Error != ASTContext::GE_None)
7334 return QualType();
7335
7336 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
7337 if (!FT)
7338 return QualType();
7339
7340 if (FT->getNumParams() != 1)
7341 return QualType();
7342
7343 return FT->getParamType(0);
7344}
7345
7346// Returns the best absolute value function, or zero, based on type and
7347// current absolute value function.
7348static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
7349 unsigned AbsFunctionKind) {
7350 unsigned BestKind = 0;
7351 uint64_t ArgSize = Context.getTypeSize(ArgType);
7352 for (unsigned Kind = AbsFunctionKind; Kind != 0;
7353 Kind = getLargerAbsoluteValueFunction(Kind)) {
7354 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
7355 if (Context.getTypeSize(ParamType) >= ArgSize) {
7356 if (BestKind == 0)
7357 BestKind = Kind;
7358 else if (Context.hasSameType(ParamType, ArgType)) {
7359 BestKind = Kind;
7360 break;
7361 }
7362 }
7363 }
7364 return BestKind;
7365}
7366
7367enum AbsoluteValueKind {
7368 AVK_Integer,
7369 AVK_Floating,
7370 AVK_Complex
7371};
7372
7373static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
7374 if (T->isIntegralOrEnumerationType())
7375 return AVK_Integer;
7376 if (T->isRealFloatingType())
7377 return AVK_Floating;
7378 if (T->isAnyComplexType())
7379 return AVK_Complex;
7380
7381 llvm_unreachable("Type not integer, floating, or complex");
7382}
7383
7384// Changes the absolute value function to a different type. Preserves whether
7385// the function is a builtin.
7386static unsigned changeAbsFunction(unsigned AbsKind,
7387 AbsoluteValueKind ValueKind) {
7388 switch (ValueKind) {
7389 case AVK_Integer:
7390 switch (AbsKind) {
7391 default:
7392 return 0;
7393 case Builtin::BI__builtin_fabsf:
7394 case Builtin::BI__builtin_fabs:
7395 case Builtin::BI__builtin_fabsl:
7396 case Builtin::BI__builtin_cabsf:
7397 case Builtin::BI__builtin_cabs:
7398 case Builtin::BI__builtin_cabsl:
7399 return Builtin::BI__builtin_abs;
7400 case Builtin::BIfabsf:
7401 case Builtin::BIfabs:
7402 case Builtin::BIfabsl:
7403 case Builtin::BIcabsf:
7404 case Builtin::BIcabs:
7405 case Builtin::BIcabsl:
7406 return Builtin::BIabs;
7407 }
7408 case AVK_Floating:
7409 switch (AbsKind) {
7410 default:
7411 return 0;
7412 case Builtin::BI__builtin_abs:
7413 case Builtin::BI__builtin_labs:
7414 case Builtin::BI__builtin_llabs:
7415 case Builtin::BI__builtin_cabsf:
7416 case Builtin::BI__builtin_cabs:
7417 case Builtin::BI__builtin_cabsl:
7418 return Builtin::BI__builtin_fabsf;
7419 case Builtin::BIabs:
7420 case Builtin::BIlabs:
7421 case Builtin::BIllabs:
7422 case Builtin::BIcabsf:
7423 case Builtin::BIcabs:
7424 case Builtin::BIcabsl:
7425 return Builtin::BIfabsf;
7426 }
7427 case AVK_Complex:
7428 switch (AbsKind) {
7429 default:
7430 return 0;
7431 case Builtin::BI__builtin_abs:
7432 case Builtin::BI__builtin_labs:
7433 case Builtin::BI__builtin_llabs:
7434 case Builtin::BI__builtin_fabsf:
7435 case Builtin::BI__builtin_fabs:
7436 case Builtin::BI__builtin_fabsl:
7437 return Builtin::BI__builtin_cabsf;
7438 case Builtin::BIabs:
7439 case Builtin::BIlabs:
7440 case Builtin::BIllabs:
7441 case Builtin::BIfabsf:
7442 case Builtin::BIfabs:
7443 case Builtin::BIfabsl:
7444 return Builtin::BIcabsf;
7445 }
7446 }
7447 llvm_unreachable("Unable to convert function");
7448}
7449
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00007450static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007451 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
7452 if (!FnInfo)
7453 return 0;
7454
7455 switch (FDecl->getBuiltinID()) {
7456 default:
7457 return 0;
7458 case Builtin::BI__builtin_abs:
7459 case Builtin::BI__builtin_fabs:
7460 case Builtin::BI__builtin_fabsf:
7461 case Builtin::BI__builtin_fabsl:
7462 case Builtin::BI__builtin_labs:
7463 case Builtin::BI__builtin_llabs:
7464 case Builtin::BI__builtin_cabs:
7465 case Builtin::BI__builtin_cabsf:
7466 case Builtin::BI__builtin_cabsl:
7467 case Builtin::BIabs:
7468 case Builtin::BIlabs:
7469 case Builtin::BIllabs:
7470 case Builtin::BIfabs:
7471 case Builtin::BIfabsf:
7472 case Builtin::BIfabsl:
7473 case Builtin::BIcabs:
7474 case Builtin::BIcabsf:
7475 case Builtin::BIcabsl:
7476 return FDecl->getBuiltinID();
7477 }
7478 llvm_unreachable("Unknown Builtin type");
7479}
7480
7481// If the replacement is valid, emit a note with replacement function.
7482// Additionally, suggest including the proper header if not already included.
7483static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00007484 unsigned AbsKind, QualType ArgType) {
7485 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00007486 const char *HeaderName = nullptr;
Mehdi Amini7186a432016-10-11 19:04:24 +00007487 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00007488 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
7489 FunctionName = "std::abs";
7490 if (ArgType->isIntegralOrEnumerationType()) {
7491 HeaderName = "cstdlib";
7492 } else if (ArgType->isRealFloatingType()) {
7493 HeaderName = "cmath";
7494 } else {
7495 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007496 }
Richard Trieubeffb832014-04-15 23:47:53 +00007497
7498 // Lookup all std::abs
7499 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00007500 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00007501 R.suppressDiagnostics();
7502 S.LookupQualifiedName(R, Std);
7503
7504 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007505 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00007506 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
7507 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
7508 } else {
7509 FDecl = dyn_cast<FunctionDecl>(I);
7510 }
7511 if (!FDecl)
7512 continue;
7513
7514 // Found std::abs(), check that they are the right ones.
7515 if (FDecl->getNumParams() != 1)
7516 continue;
7517
7518 // Check that the parameter type can handle the argument.
7519 QualType ParamType = FDecl->getParamDecl(0)->getType();
7520 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
7521 S.Context.getTypeSize(ArgType) <=
7522 S.Context.getTypeSize(ParamType)) {
7523 // Found a function, don't need the header hint.
7524 EmitHeaderHint = false;
7525 break;
7526 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007527 }
Richard Trieubeffb832014-04-15 23:47:53 +00007528 }
7529 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00007530 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00007531 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
7532
7533 if (HeaderName) {
7534 DeclarationName DN(&S.Context.Idents.get(FunctionName));
7535 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
7536 R.suppressDiagnostics();
7537 S.LookupName(R, S.getCurScope());
7538
7539 if (R.isSingleResult()) {
7540 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
7541 if (FD && FD->getBuiltinID() == AbsKind) {
7542 EmitHeaderHint = false;
7543 } else {
7544 return;
7545 }
7546 } else if (!R.empty()) {
7547 return;
7548 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007549 }
7550 }
7551
7552 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00007553 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007554
Richard Trieubeffb832014-04-15 23:47:53 +00007555 if (!HeaderName)
7556 return;
7557
7558 if (!EmitHeaderHint)
7559 return;
7560
Alp Toker5d96e0a2014-07-11 20:53:51 +00007561 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
7562 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00007563}
7564
Richard Trieua7f30b12016-12-06 01:42:28 +00007565template <std::size_t StrLen>
7566static bool IsStdFunction(const FunctionDecl *FDecl,
7567 const char (&Str)[StrLen]) {
Richard Trieubeffb832014-04-15 23:47:53 +00007568 if (!FDecl)
7569 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00007570 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
Richard Trieubeffb832014-04-15 23:47:53 +00007571 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00007572 if (!FDecl->isInStdNamespace())
Richard Trieubeffb832014-04-15 23:47:53 +00007573 return false;
7574
7575 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007576}
7577
7578// Warn when using the wrong abs() function.
7579void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
Richard Trieua7f30b12016-12-06 01:42:28 +00007580 const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007581 if (Call->getNumArgs() != 1)
7582 return;
7583
7584 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieua7f30b12016-12-06 01:42:28 +00007585 bool IsStdAbs = IsStdFunction(FDecl, "abs");
Richard Trieubeffb832014-04-15 23:47:53 +00007586 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007587 return;
7588
7589 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7590 QualType ParamType = Call->getArg(0)->getType();
7591
Alp Toker5d96e0a2014-07-11 20:53:51 +00007592 // Unsigned types cannot be negative. Suggest removing the absolute value
7593 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007594 if (ArgType->isUnsignedIntegerType()) {
Mehdi Amini7186a432016-10-11 19:04:24 +00007595 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00007596 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007597 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
7598 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00007599 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007600 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
7601 return;
7602 }
7603
David Majnemer7f77eb92015-11-15 03:04:34 +00007604 // Taking the absolute value of a pointer is very suspicious, they probably
7605 // wanted to index into an array, dereference a pointer, call a function, etc.
7606 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
7607 unsigned DiagType = 0;
7608 if (ArgType->isFunctionType())
7609 DiagType = 1;
7610 else if (ArgType->isArrayType())
7611 DiagType = 2;
7612
7613 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
7614 return;
7615 }
7616
Richard Trieubeffb832014-04-15 23:47:53 +00007617 // std::abs has overloads which prevent most of the absolute value problems
7618 // from occurring.
7619 if (IsStdAbs)
7620 return;
7621
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007622 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
7623 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
7624
7625 // The argument and parameter are the same kind. Check if they are the right
7626 // size.
7627 if (ArgValueKind == ParamValueKind) {
7628 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
7629 return;
7630
7631 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
7632 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
7633 << FDecl << ArgType << ParamType;
7634
7635 if (NewAbsKind == 0)
7636 return;
7637
7638 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00007639 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007640 return;
7641 }
7642
7643 // ArgValueKind != ParamValueKind
7644 // The wrong type of absolute value function was used. Attempt to find the
7645 // proper one.
7646 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
7647 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
7648 if (NewAbsKind == 0)
7649 return;
7650
7651 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
7652 << FDecl << ParamValueKind << ArgValueKind;
7653
7654 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00007655 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007656}
7657
Richard Trieu67c00712016-12-05 23:41:46 +00007658//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
Richard Trieua7f30b12016-12-06 01:42:28 +00007659void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
7660 const FunctionDecl *FDecl) {
Richard Trieu67c00712016-12-05 23:41:46 +00007661 if (!Call || !FDecl) return;
7662
7663 // Ignore template specializations and macros.
Richard Smith51ec0cf2017-02-21 01:17:38 +00007664 if (inTemplateInstantiation()) return;
Richard Trieu67c00712016-12-05 23:41:46 +00007665 if (Call->getExprLoc().isMacroID()) return;
7666
7667 // Only care about the one template argument, two function parameter std::max
7668 if (Call->getNumArgs() != 2) return;
Richard Trieua7f30b12016-12-06 01:42:28 +00007669 if (!IsStdFunction(FDecl, "max")) return;
Richard Trieu67c00712016-12-05 23:41:46 +00007670 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
7671 if (!ArgList) return;
7672 if (ArgList->size() != 1) return;
7673
7674 // Check that template type argument is unsigned integer.
7675 const auto& TA = ArgList->get(0);
7676 if (TA.getKind() != TemplateArgument::Type) return;
7677 QualType ArgType = TA.getAsType();
7678 if (!ArgType->isUnsignedIntegerType()) return;
7679
7680 // See if either argument is a literal zero.
7681 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
7682 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
7683 if (!MTE) return false;
7684 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
7685 if (!Num) return false;
7686 if (Num->getValue() != 0) return false;
7687 return true;
7688 };
7689
7690 const Expr *FirstArg = Call->getArg(0);
7691 const Expr *SecondArg = Call->getArg(1);
7692 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
7693 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
7694
7695 // Only warn when exactly one argument is zero.
7696 if (IsFirstArgZero == IsSecondArgZero) return;
7697
7698 SourceRange FirstRange = FirstArg->getSourceRange();
7699 SourceRange SecondRange = SecondArg->getSourceRange();
7700
7701 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
7702
7703 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
7704 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
7705
7706 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
7707 SourceRange RemovalRange;
7708 if (IsFirstArgZero) {
7709 RemovalRange = SourceRange(FirstRange.getBegin(),
7710 SecondRange.getBegin().getLocWithOffset(-1));
7711 } else {
7712 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
7713 SecondRange.getEnd());
7714 }
7715
7716 Diag(Call->getExprLoc(), diag::note_remove_max_call)
7717 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
7718 << FixItHint::CreateRemoval(RemovalRange);
7719}
7720
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007721//===--- CHECK: Standard memory functions ---------------------------------===//
7722
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007723/// Takes the expression passed to the size_t parameter of functions
Nico Weber0e6daef2013-12-26 23:38:39 +00007724/// such as memcmp, strncat, etc and warns if it's a comparison.
7725///
7726/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
7727static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
7728 IdentifierInfo *FnName,
7729 SourceLocation FnLoc,
7730 SourceLocation RParenLoc) {
7731 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
7732 if (!Size)
7733 return false;
7734
Richard Smithc70f1d62017-12-14 15:16:18 +00007735 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
7736 if (!Size->isComparisonOp() && !Size->isLogicalOp())
Nico Weber0e6daef2013-12-26 23:38:39 +00007737 return false;
7738
Nico Weber0e6daef2013-12-26 23:38:39 +00007739 SourceRange SizeRange = Size->getSourceRange();
7740 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
7741 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00007742 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007743 << FnName << FixItHint::CreateInsertion(
7744 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00007745 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00007746 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00007747 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00007748 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
7749 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00007750
7751 return true;
7752}
7753
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007754/// Determine whether the given type is or contains a dynamic class type
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007755/// (e.g., whether it has a vtable).
7756static const CXXRecordDecl *getContainedDynamicClass(QualType T,
7757 bool &IsContained) {
7758 // Look through array types while ignoring qualifiers.
7759 const Type *Ty = T->getBaseElementTypeUnsafe();
7760 IsContained = false;
7761
7762 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
7763 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00007764 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007765 return nullptr;
7766
7767 if (RD->isDynamicClass())
7768 return RD;
7769
7770 // Check all the fields. If any bases were dynamic, the class is dynamic.
7771 // It's impossible for a class to transitively contain itself by value, so
7772 // infinite recursion is impossible.
7773 for (auto *FD : RD->fields()) {
7774 bool SubContained;
7775 if (const CXXRecordDecl *ContainedRD =
7776 getContainedDynamicClass(FD->getType(), SubContained)) {
7777 IsContained = true;
7778 return ContainedRD;
7779 }
7780 }
7781
7782 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00007783}
7784
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007785/// If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007786/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00007787static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00007788 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007789 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007790 if (SizeOf->getKind() == UETT_SizeOf && !SizeOf->isArgumentType())
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007791 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007792
Craig Topperc3ec1492014-05-26 06:22:03 +00007793 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007794}
7795
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007796/// If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00007797static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007798 if (const UnaryExprOrTypeTraitExpr *SizeOf =
7799 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007800 if (SizeOf->getKind() == UETT_SizeOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007801 return SizeOf->getTypeOfArgument();
7802
7803 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00007804}
7805
Akira Hatanaka2be04412018-04-17 19:13:41 +00007806namespace {
7807
7808struct SearchNonTrivialToInitializeField
7809 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
7810 using Super =
7811 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
7812
7813 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
7814
7815 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
7816 SourceLocation SL) {
7817 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
7818 asDerived().visitArray(PDIK, AT, SL);
7819 return;
7820 }
7821
7822 Super::visitWithKind(PDIK, FT, SL);
7823 }
7824
7825 void visitARCStrong(QualType FT, SourceLocation SL) {
7826 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
7827 }
7828 void visitARCWeak(QualType FT, SourceLocation SL) {
7829 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
7830 }
7831 void visitStruct(QualType FT, SourceLocation SL) {
7832 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
7833 visit(FD->getType(), FD->getLocation());
7834 }
7835 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
7836 const ArrayType *AT, SourceLocation SL) {
7837 visit(getContext().getBaseElementType(AT), SL);
7838 }
7839 void visitTrivial(QualType FT, SourceLocation SL) {}
7840
7841 static void diag(QualType RT, const Expr *E, Sema &S) {
7842 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
7843 }
7844
7845 ASTContext &getContext() { return S.getASTContext(); }
7846
7847 const Expr *E;
7848 Sema &S;
7849};
7850
7851struct SearchNonTrivialToCopyField
7852 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
7853 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
7854
7855 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
7856
7857 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
7858 SourceLocation SL) {
7859 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
7860 asDerived().visitArray(PCK, AT, SL);
7861 return;
7862 }
7863
7864 Super::visitWithKind(PCK, FT, SL);
7865 }
7866
7867 void visitARCStrong(QualType FT, SourceLocation SL) {
7868 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
7869 }
7870 void visitARCWeak(QualType FT, SourceLocation SL) {
7871 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
7872 }
7873 void visitStruct(QualType FT, SourceLocation SL) {
7874 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
7875 visit(FD->getType(), FD->getLocation());
7876 }
7877 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
7878 SourceLocation SL) {
7879 visit(getContext().getBaseElementType(AT), SL);
7880 }
7881 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
7882 SourceLocation SL) {}
7883 void visitTrivial(QualType FT, SourceLocation SL) {}
7884 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
7885
7886 static void diag(QualType RT, const Expr *E, Sema &S) {
7887 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
7888 }
7889
7890 ASTContext &getContext() { return S.getASTContext(); }
7891
7892 const Expr *E;
7893 Sema &S;
7894};
7895
7896}
7897
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007898/// Check for dangerous or invalid arguments to memset().
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007899///
Chandler Carruthac687262011-06-03 06:23:57 +00007900/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007901/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
7902/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007903///
7904/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007905void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00007906 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007907 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00007908 assert(BId != 0);
7909
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007910 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00007911 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007912 unsigned ExpectedNumArgs =
7913 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00007914 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007915 return;
7916
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007917 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00007918 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007919 unsigned LenArg =
7920 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00007921 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007922
Nico Weber0e6daef2013-12-26 23:38:39 +00007923 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
7924 Call->getLocStart(), Call->getRParenLoc()))
7925 return;
7926
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007927 // We have special checking when the length is a sizeof expression.
7928 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
7929 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
7930 llvm::FoldingSetNodeID SizeOfArgID;
7931
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00007932 // Although widely used, 'bzero' is not a standard function. Be more strict
7933 // with the argument types before allowing diagnostics and only allow the
7934 // form bzero(ptr, sizeof(...)).
7935 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7936 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
7937 return;
7938
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007939 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7940 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007941 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007942
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007943 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00007944 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007945 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00007946 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00007947
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007948 // Never warn about void type pointers. This can be used to suppress
7949 // false positives.
7950 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007951 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007952
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007953 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
7954 // actually comparing the expressions for equality. Because computing the
7955 // expression IDs can be expensive, we only do this if the diagnostic is
7956 // enabled.
7957 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007958 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
7959 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007960 // We only compute IDs for expressions if the warning is enabled, and
7961 // cache the sizeof arg's ID.
7962 if (SizeOfArgID == llvm::FoldingSetNodeID())
7963 SizeOfArg->Profile(SizeOfArgID, Context, true);
7964 llvm::FoldingSetNodeID DestID;
7965 Dest->Profile(DestID, Context, true);
7966 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00007967 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
7968 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007969 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00007970 StringRef ReadableName = FnName->getName();
7971
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007972 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00007973 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007974 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00007975 if (!PointeeTy->isIncompleteType() &&
7976 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007977 ActionIdx = 2; // If the pointee's size is sizeof(char),
7978 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00007979
7980 // If the function is defined as a builtin macro, do not show macro
7981 // expansion.
7982 SourceLocation SL = SizeOfArg->getExprLoc();
7983 SourceRange DSR = Dest->getSourceRange();
7984 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007985 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00007986
7987 if (SM.isMacroArgExpansion(SL)) {
7988 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7989 SL = SM.getSpellingLoc(SL);
7990 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7991 SM.getSpellingLoc(DSR.getEnd()));
7992 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7993 SM.getSpellingLoc(SSR.getEnd()));
7994 }
7995
Anna Zaksd08d9152012-05-30 23:14:52 +00007996 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007997 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00007998 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00007999 << PointeeTy
8000 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00008001 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00008002 << SSR);
8003 DiagRuntimeBehavior(SL, SizeOfArg,
8004 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
8005 << ActionIdx
8006 << SSR);
8007
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00008008 break;
8009 }
8010 }
8011
8012 // Also check for cases where the sizeof argument is the exact same
8013 // type as the memory argument, and where it points to a user-defined
8014 // record type.
8015 if (SizeOfArgTy != QualType()) {
8016 if (PointeeTy->isRecordType() &&
8017 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
8018 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
8019 PDiag(diag::warn_sizeof_pointer_type_memaccess)
8020 << FnName << SizeOfArgTy << ArgIdx
8021 << PointeeTy << Dest->getSourceRange()
8022 << LenExpr->getSourceRange());
8023 break;
8024 }
Nico Weberc5e73862011-06-14 16:14:58 +00008025 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00008026 } else if (DestTy->isArrayType()) {
8027 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00008028 }
Nico Weberc5e73862011-06-14 16:14:58 +00008029
Nico Weberc44b35e2015-03-21 17:37:46 +00008030 if (PointeeTy == QualType())
8031 continue;
Anna Zaks22122702012-01-17 00:37:07 +00008032
Nico Weberc44b35e2015-03-21 17:37:46 +00008033 // Always complain about dynamic classes.
8034 bool IsContained;
8035 if (const CXXRecordDecl *ContainedRD =
8036 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00008037
Nico Weberc44b35e2015-03-21 17:37:46 +00008038 unsigned OperationType = 0;
8039 // "overwritten" if we're warning about the destination for any call
8040 // but memcmp; otherwise a verb appropriate to the call.
8041 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
8042 if (BId == Builtin::BImemcpy)
8043 OperationType = 1;
8044 else if(BId == Builtin::BImemmove)
8045 OperationType = 2;
8046 else if (BId == Builtin::BImemcmp)
8047 OperationType = 3;
8048 }
8049
John McCall31168b02011-06-15 23:02:42 +00008050 DiagRuntimeBehavior(
8051 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00008052 PDiag(diag::warn_dyn_class_memaccess)
8053 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
8054 << FnName << IsContained << ContainedRD << OperationType
8055 << Call->getCallee()->getSourceRange());
8056 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
8057 BId != Builtin::BImemset)
8058 DiagRuntimeBehavior(
8059 Dest->getExprLoc(), Dest,
8060 PDiag(diag::warn_arc_object_memaccess)
8061 << ArgIdx << FnName << PointeeTy
8062 << Call->getCallee()->getSourceRange());
Akira Hatanaka2be04412018-04-17 19:13:41 +00008063 else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
8064 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
8065 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
8066 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
8067 PDiag(diag::warn_cstruct_memaccess)
8068 << ArgIdx << FnName << PointeeTy << 0);
8069 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
8070 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
8071 RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
8072 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
8073 PDiag(diag::warn_cstruct_memaccess)
8074 << ArgIdx << FnName << PointeeTy << 1);
8075 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
8076 } else {
8077 continue;
8078 }
8079 } else
Nico Weberc44b35e2015-03-21 17:37:46 +00008080 continue;
8081
8082 DiagRuntimeBehavior(
8083 Dest->getExprLoc(), Dest,
8084 PDiag(diag::note_bad_memaccess_silence)
8085 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
8086 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00008087 }
8088}
8089
Ted Kremenek6865f772011-08-18 20:55:45 +00008090// A little helper routine: ignore addition and subtraction of integer literals.
8091// This intentionally does not ignore all integer constant expressions because
8092// we don't want to remove sizeof().
8093static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
8094 Ex = Ex->IgnoreParenCasts();
8095
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008096 while (true) {
Ted Kremenek6865f772011-08-18 20:55:45 +00008097 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
8098 if (!BO || !BO->isAdditiveOp())
8099 break;
8100
8101 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
8102 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
8103
8104 if (isa<IntegerLiteral>(RHS))
8105 Ex = LHS;
8106 else if (isa<IntegerLiteral>(LHS))
8107 Ex = RHS;
8108 else
8109 break;
8110 }
8111
8112 return Ex;
8113}
8114
Anna Zaks13b08572012-08-08 21:42:23 +00008115static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
8116 ASTContext &Context) {
8117 // Only handle constant-sized or VLAs, but not flexible members.
8118 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
8119 // Only issue the FIXIT for arrays of size > 1.
8120 if (CAT->getSize().getSExtValue() <= 1)
8121 return false;
8122 } else if (!Ty->isVariableArrayType()) {
8123 return false;
8124 }
8125 return true;
8126}
8127
Ted Kremenek6865f772011-08-18 20:55:45 +00008128// Warn if the user has made the 'size' argument to strlcpy or strlcat
8129// be the size of the source, instead of the destination.
8130void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
8131 IdentifierInfo *FnName) {
8132
8133 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00008134 unsigned NumArgs = Call->getNumArgs();
8135 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00008136 return;
8137
8138 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
8139 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00008140 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00008141
8142 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
8143 Call->getLocStart(), Call->getRParenLoc()))
8144 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00008145
8146 // Look for 'strlcpy(dst, x, sizeof(x))'
8147 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
8148 CompareWithSrc = Ex;
8149 else {
8150 // Look for 'strlcpy(dst, x, strlen(x))'
8151 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00008152 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
8153 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00008154 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
8155 }
8156 }
8157
8158 if (!CompareWithSrc)
8159 return;
8160
8161 // Determine if the argument to sizeof/strlen is equal to the source
8162 // argument. In principle there's all kinds of things you could do
8163 // here, for instance creating an == expression and evaluating it with
8164 // EvaluateAsBooleanCondition, but this uses a more direct technique:
8165 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
8166 if (!SrcArgDRE)
8167 return;
8168
8169 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
8170 if (!CompareWithSrcDRE ||
8171 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
8172 return;
8173
8174 const Expr *OriginalSizeArg = Call->getArg(2);
8175 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
8176 << OriginalSizeArg->getSourceRange() << FnName;
8177
8178 // Output a FIXIT hint if the destination is an array (rather than a
8179 // pointer to an array). This could be enhanced to handle some
8180 // pointers if we know the actual size, like if DstArg is 'array+2'
8181 // we could say 'sizeof(array)-2'.
8182 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00008183 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00008184 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00008185
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008186 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00008187 llvm::raw_svector_ostream OS(sizeString);
8188 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00008189 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00008190 OS << ")";
8191
8192 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
8193 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
8194 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00008195}
8196
Anna Zaks314cd092012-02-01 19:08:57 +00008197/// Check if two expressions refer to the same declaration.
8198static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
8199 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
8200 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
8201 return D1->getDecl() == D2->getDecl();
8202 return false;
8203}
8204
8205static const Expr *getStrlenExprArg(const Expr *E) {
8206 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8207 const FunctionDecl *FD = CE->getDirectCallee();
8208 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00008209 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00008210 return CE->getArg(0)->IgnoreParenCasts();
8211 }
Craig Topperc3ec1492014-05-26 06:22:03 +00008212 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00008213}
8214
8215// Warn on anti-patterns as the 'size' argument to strncat.
8216// The correct size argument should look like following:
8217// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
8218void Sema::CheckStrncatArguments(const CallExpr *CE,
8219 IdentifierInfo *FnName) {
8220 // Don't crash if the user has the wrong number of arguments.
8221 if (CE->getNumArgs() < 3)
8222 return;
8223 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
8224 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
8225 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
8226
Nico Weber0e6daef2013-12-26 23:38:39 +00008227 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
8228 CE->getRParenLoc()))
8229 return;
8230
Anna Zaks314cd092012-02-01 19:08:57 +00008231 // Identify common expressions, which are wrongly used as the size argument
8232 // to strncat and may lead to buffer overflows.
8233 unsigned PatternType = 0;
8234 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
8235 // - sizeof(dst)
8236 if (referToTheSameDecl(SizeOfArg, DstArg))
8237 PatternType = 1;
8238 // - sizeof(src)
8239 else if (referToTheSameDecl(SizeOfArg, SrcArg))
8240 PatternType = 2;
8241 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
8242 if (BE->getOpcode() == BO_Sub) {
8243 const Expr *L = BE->getLHS()->IgnoreParenCasts();
8244 const Expr *R = BE->getRHS()->IgnoreParenCasts();
8245 // - sizeof(dst) - strlen(dst)
8246 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
8247 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
8248 PatternType = 1;
8249 // - sizeof(src) - (anything)
8250 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
8251 PatternType = 2;
8252 }
8253 }
8254
8255 if (PatternType == 0)
8256 return;
8257
Anna Zaks5069aa32012-02-03 01:27:37 +00008258 // Generate the diagnostic.
8259 SourceLocation SL = LenArg->getLocStart();
8260 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00008261 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00008262
8263 // If the function is defined as a builtin macro, do not show macro expansion.
8264 if (SM.isMacroArgExpansion(SL)) {
8265 SL = SM.getSpellingLoc(SL);
8266 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
8267 SM.getSpellingLoc(SR.getEnd()));
8268 }
8269
Anna Zaks13b08572012-08-08 21:42:23 +00008270 // Check if the destination is an array (rather than a pointer to an array).
8271 QualType DstTy = DstArg->getType();
8272 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
8273 Context);
8274 if (!isKnownSizeArray) {
8275 if (PatternType == 1)
8276 Diag(SL, diag::warn_strncat_wrong_size) << SR;
8277 else
8278 Diag(SL, diag::warn_strncat_src_size) << SR;
8279 return;
8280 }
8281
Anna Zaks314cd092012-02-01 19:08:57 +00008282 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00008283 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00008284 else
Anna Zaks5069aa32012-02-03 01:27:37 +00008285 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00008286
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008287 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00008288 llvm::raw_svector_ostream OS(sizeString);
8289 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00008290 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00008291 OS << ") - ";
8292 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00008293 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00008294 OS << ") - 1";
8295
Anna Zaks5069aa32012-02-03 01:27:37 +00008296 Diag(SL, diag::note_strncat_wrong_size)
8297 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00008298}
8299
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008300//===--- CHECK: Return Address of Stack Variable --------------------------===//
8301
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008302static const Expr *EvalVal(const Expr *E,
8303 SmallVectorImpl<const DeclRefExpr *> &refVars,
8304 const Decl *ParentDecl);
8305static const Expr *EvalAddr(const Expr *E,
8306 SmallVectorImpl<const DeclRefExpr *> &refVars,
8307 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008308
8309/// CheckReturnStackAddr - Check if a return statement returns the address
8310/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008311static void
8312CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
8313 SourceLocation ReturnLoc) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008314 const Expr *stackE = nullptr;
8315 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008316
8317 // Perform checking for returned stack addresses, local blocks,
8318 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00008319 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008320 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008321 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00008322 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008323 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008324 }
8325
Craig Topperc3ec1492014-05-26 06:22:03 +00008326 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008327 return; // Nothing suspicious was found.
8328
Simon Pilgrim750bde62017-03-31 11:00:53 +00008329 // Parameters are initialized in the calling scope, so taking the address
Richard Trieu81b6c562016-08-05 23:24:47 +00008330 // of a parameter reference doesn't need a warning.
8331 for (auto *DRE : refVars)
8332 if (isa<ParmVarDecl>(DRE->getDecl()))
8333 return;
8334
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008335 SourceLocation diagLoc;
8336 SourceRange diagRange;
8337 if (refVars.empty()) {
8338 diagLoc = stackE->getLocStart();
8339 diagRange = stackE->getSourceRange();
8340 } else {
8341 // We followed through a reference variable. 'stackE' contains the
8342 // problematic expression but we will warn at the return statement pointing
8343 // at the reference variable. We will later display the "trail" of
8344 // reference variables using notes.
8345 diagLoc = refVars[0]->getLocStart();
8346 diagRange = refVars[0]->getSourceRange();
8347 }
8348
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008349 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
8350 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00008351 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008352 << DR->getDecl()->getDeclName() << diagRange;
8353 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008354 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008355 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008356 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008357 } else { // local temporary.
Richard Trieu81b6c562016-08-05 23:24:47 +00008358 // If there is an LValue->RValue conversion, then the value of the
8359 // reference type is used, not the reference.
8360 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
8361 if (ICE->getCastKind() == CK_LValueToRValue) {
8362 return;
8363 }
8364 }
Craig Topperda7b27f2015-11-17 05:40:09 +00008365 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
8366 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008367 }
8368
8369 // Display the "trail" of reference variables that we followed until we
8370 // found the problematic expression using notes.
8371 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008372 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008373 // If this var binds to another reference var, show the range of the next
8374 // var, otherwise the var binds to the problematic expression, in which case
8375 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008376 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
8377 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008378 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
8379 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008380 }
8381}
8382
8383/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
8384/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008385/// to a location on the stack, a local block, an address of a label, or a
8386/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008387/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008388/// encounter a subexpression that (1) clearly does not lead to one of the
8389/// above problematic expressions (2) is something we cannot determine leads to
8390/// a problematic expression based on such local checking.
8391///
8392/// Both EvalAddr and EvalVal follow through reference variables to evaluate
8393/// the expression that they point to. Such variables are added to the
8394/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008395///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00008396/// EvalAddr processes expressions that are pointers that are used as
8397/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008398/// At the base case of the recursion is a check for the above problematic
8399/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008400///
8401/// This implementation handles:
8402///
8403/// * pointer-to-pointer casts
8404/// * implicit conversions from array references to pointers
8405/// * taking the address of fields
8406/// * arbitrary interplay between "&" and "*" operators
8407/// * pointer arithmetic from an address of a stack variable
8408/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008409static const Expr *EvalAddr(const Expr *E,
8410 SmallVectorImpl<const DeclRefExpr *> &refVars,
8411 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008412 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00008413 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008414
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008415 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00008416 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00008417 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00008418 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00008419 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00008420
Peter Collingbourne91147592011-04-15 00:35:48 +00008421 E = E->IgnoreParens();
8422
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008423 // Our "symbolic interpreter" is just a dispatch off the currently
8424 // viewed AST node. We then recursively traverse the AST by calling
8425 // EvalAddr and EvalVal appropriately.
8426 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008427 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008428 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008429
Richard Smith40f08eb2014-01-30 22:05:38 +00008430 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00008431 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00008432 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00008433
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008434 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008435 // If this is a reference variable, follow through to the expression that
8436 // it points to.
8437 if (V->hasLocalStorage() &&
8438 V->getType()->isReferenceType() && V->hasInit()) {
8439 // Add the reference variable to the "trail".
8440 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008441 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008442 }
8443
Craig Topperc3ec1492014-05-26 06:22:03 +00008444 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008445 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008446
Chris Lattner934edb22007-12-28 05:31:15 +00008447 case Stmt::UnaryOperatorClass: {
8448 // The only unary operator that make sense to handle here
8449 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008450 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00008451
John McCalle3027922010-08-25 11:45:40 +00008452 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008453 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008454 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008455 }
Mike Stump11289f42009-09-09 15:08:12 +00008456
Chris Lattner934edb22007-12-28 05:31:15 +00008457 case Stmt::BinaryOperatorClass: {
8458 // Handle pointer arithmetic. All other binary operators are not valid
8459 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008460 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00008461 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00008462
John McCalle3027922010-08-25 11:45:40 +00008463 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00008464 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008465
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008466 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00008467
8468 // Determine which argument is the real pointer base. It could be
8469 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008470 if (!Base->getType()->isPointerType())
8471 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00008472
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008473 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008474 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00008475 }
Steve Naroff2752a172008-09-10 19:17:48 +00008476
Chris Lattner934edb22007-12-28 05:31:15 +00008477 // For conditional operators we need to see if either the LHS or RHS are
8478 // valid DeclRefExpr*s. If one of them is valid, we return it.
8479 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008480 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00008481
Chris Lattner934edb22007-12-28 05:31:15 +00008482 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008483 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008484 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008485 // In C++, we can have a throw-expression, which has 'void' type.
8486 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008487 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00008488 return LHS;
8489 }
Chris Lattner934edb22007-12-28 05:31:15 +00008490
Douglas Gregor270b2ef2010-10-21 16:21:08 +00008491 // In C++, we can have a throw-expression, which has 'void' type.
8492 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00008493 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00008494
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008495 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00008496 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008497
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008498 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00008499 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008500 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00008501 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008502
8503 case Stmt::AddrLabelExprClass:
8504 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00008505
John McCall28fc7092011-11-10 05:35:25 +00008506 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008507 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
8508 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00008509
Ted Kremenekc3b4c522008-08-07 00:49:01 +00008510 // For casts, we need to handle conversions from arrays to
8511 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00008512 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00008513 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00008514 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00008515 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00008516 case Stmt::CXXStaticCastExprClass:
8517 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00008518 case Stmt::CXXConstCastExprClass:
8519 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008520 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00008521 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00008522 case CK_LValueToRValue:
8523 case CK_NoOp:
8524 case CK_BaseToDerived:
8525 case CK_DerivedToBase:
8526 case CK_UncheckedDerivedToBase:
8527 case CK_Dynamic:
8528 case CK_CPointerToObjCPointerCast:
8529 case CK_BlockPointerToObjCPointerCast:
8530 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008531 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00008532
8533 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008534 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00008535
Richard Trieudadefde2014-07-02 04:39:38 +00008536 case CK_BitCast:
8537 if (SubExpr->getType()->isAnyPointerType() ||
8538 SubExpr->getType()->isBlockPointerType() ||
8539 SubExpr->getType()->isObjCQualifiedIdType())
8540 return EvalAddr(SubExpr, refVars, ParentDecl);
8541 else
8542 return nullptr;
8543
Eli Friedman8195ad72012-02-23 23:04:32 +00008544 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00008545 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00008546 }
Chris Lattner934edb22007-12-28 05:31:15 +00008547 }
Mike Stump11289f42009-09-09 15:08:12 +00008548
Douglas Gregorfe314812011-06-21 17:03:29 +00008549 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008550 if (const Expr *Result =
8551 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8552 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00008553 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00008554 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008555
Chris Lattner934edb22007-12-28 05:31:15 +00008556 // Everything else: we simply don't reason about them.
8557 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00008558 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00008559 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008560}
Mike Stump11289f42009-09-09 15:08:12 +00008561
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008562/// EvalVal - This function is complements EvalAddr in the mutual recursion.
8563/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008564static const Expr *EvalVal(const Expr *E,
8565 SmallVectorImpl<const DeclRefExpr *> &refVars,
8566 const Decl *ParentDecl) {
8567 do {
8568 // We should only be called for evaluating non-pointer expressions, or
8569 // expressions with a pointer type that are not used as references but
8570 // instead
8571 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00008572
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008573 // Our "symbolic interpreter" is just a dispatch off the currently
8574 // viewed AST node. We then recursively traverse the AST by calling
8575 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00008576
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008577 E = E->IgnoreParens();
8578 switch (E->getStmtClass()) {
8579 case Stmt::ImplicitCastExprClass: {
8580 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
8581 if (IE->getValueKind() == VK_LValue) {
8582 E = IE->getSubExpr();
8583 continue;
8584 }
Craig Topperc3ec1492014-05-26 06:22:03 +00008585 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008586 }
Richard Smith40f08eb2014-01-30 22:05:38 +00008587
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008588 case Stmt::ExprWithCleanupsClass:
8589 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
8590 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008591
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008592 case Stmt::DeclRefExprClass: {
8593 // When we hit a DeclRefExpr we are looking at code that refers to a
8594 // variable's name. If it's not a reference variable we check if it has
8595 // local storage within the function, and if so, return the expression.
8596 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
8597
8598 // If we leave the immediate function, the lifetime isn't about to end.
8599 if (DR->refersToEnclosingVariableOrCapture())
8600 return nullptr;
8601
8602 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
8603 // Check if it refers to itself, e.g. "int& i = i;".
8604 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008605 return DR;
8606
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008607 if (V->hasLocalStorage()) {
8608 if (!V->getType()->isReferenceType())
8609 return DR;
8610
8611 // Reference variable, follow through to the expression that
8612 // it points to.
8613 if (V->hasInit()) {
8614 // Add the reference variable to the "trail".
8615 refVars.push_back(DR);
8616 return EvalVal(V->getInit(), refVars, V);
8617 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008618 }
8619 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008620
8621 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008622 }
Mike Stump11289f42009-09-09 15:08:12 +00008623
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008624 case Stmt::UnaryOperatorClass: {
8625 // The only unary operator that make sense to handle here
8626 // is Deref. All others don't resolve to a "name." This includes
8627 // handling all sorts of rvalues passed to a unary operator.
8628 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00008629
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008630 if (U->getOpcode() == UO_Deref)
8631 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00008632
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008633 return nullptr;
8634 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008635
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008636 case Stmt::ArraySubscriptExprClass: {
8637 // Array subscripts are potential references to data on the stack. We
8638 // retrieve the DeclRefExpr* for the array variable if it indeed
8639 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00008640 const auto *ASE = cast<ArraySubscriptExpr>(E);
8641 if (ASE->isTypeDependent())
8642 return nullptr;
8643 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008644 }
Mike Stump11289f42009-09-09 15:08:12 +00008645
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008646 case Stmt::OMPArraySectionExprClass: {
8647 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
8648 ParentDecl);
8649 }
Mike Stump11289f42009-09-09 15:08:12 +00008650
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008651 case Stmt::ConditionalOperatorClass: {
8652 // For conditional operators we need to see if either the LHS or RHS are
8653 // non-NULL Expr's. If one is non-NULL, we return it.
8654 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00008655
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008656 // Handle the GNU extension for missing LHS.
8657 if (const Expr *LHSExpr = C->getLHS()) {
8658 // In C++, we can have a throw-expression, which has 'void' type.
8659 if (!LHSExpr->getType()->isVoidType())
8660 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
8661 return LHS;
8662 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008663
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008664 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008665 if (C->getRHS()->getType()->isVoidType())
8666 return nullptr;
8667
8668 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008669 }
8670
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008671 // Accesses to members are potential references to data on the stack.
8672 case Stmt::MemberExprClass: {
8673 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00008674
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008675 // Check for indirect access. We only want direct field accesses.
8676 if (M->isArrow())
8677 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008678
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008679 // Check whether the member type is itself a reference, in which case
8680 // we're not going to refer to the member, but to what the member refers
8681 // to.
8682 if (M->getMemberDecl()->getType()->isReferenceType())
8683 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008684
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008685 return EvalVal(M->getBase(), refVars, ParentDecl);
8686 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00008687
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008688 case Stmt::MaterializeTemporaryExprClass:
8689 if (const Expr *Result =
8690 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8691 refVars, ParentDecl))
8692 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008693 return E;
8694
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008695 default:
8696 // Check that we don't return or take the address of a reference to a
8697 // temporary. This is only useful in C++.
8698 if (!E->isTypeDependent() && E->isRValue())
8699 return E;
8700
8701 // Everything else: we simply don't reason about them.
8702 return nullptr;
8703 }
8704 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008705}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008706
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008707void
8708Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
8709 SourceLocation ReturnLoc,
8710 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00008711 const AttrVec *Attrs,
8712 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008713 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
8714
8715 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00008716 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
8717 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00008718 CheckNonNullExpr(*this, RetValExp))
8719 Diag(ReturnLoc, diag::warn_null_ret)
8720 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00008721
8722 // C++11 [basic.stc.dynamic.allocation]p4:
8723 // If an allocation function declared with a non-throwing
8724 // exception-specification fails to allocate storage, it shall return
8725 // a null pointer. Any other allocation function that fails to allocate
8726 // storage shall indicate failure only by throwing an exception [...]
8727 if (FD) {
8728 OverloadedOperatorKind Op = FD->getOverloadedOperator();
8729 if (Op == OO_New || Op == OO_Array_New) {
8730 const FunctionProtoType *Proto
8731 = FD->getType()->castAs<FunctionProtoType>();
Richard Smitheaf11ad2018-05-03 03:58:32 +00008732 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
Artyom Skrobov9f213442014-01-24 11:10:39 +00008733 CheckNonNullExpr(*this, RetValExp))
8734 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
8735 << FD << getLangOpts().CPlusPlus11;
8736 }
8737 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008738}
8739
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008740//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
8741
8742/// Check for comparisons of floating point operands using != and ==.
8743/// Issue a warning if these are no self-comparisons, as they are not likely
8744/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00008745void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00008746 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
8747 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008748
8749 // Special case: check for x == x (which is OK).
8750 // Do not emit warnings for such cases.
8751 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
8752 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
8753 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00008754 return;
Mike Stump11289f42009-09-09 15:08:12 +00008755
Ted Kremenekeda40e22007-11-29 00:59:04 +00008756 // Special case: check for comparisons against literals that can be exactly
8757 // represented by APFloat. In such cases, do not emit a warning. This
8758 // is a heuristic: often comparison against such literals are used to
8759 // detect if a value in a variable has not changed. This clearly can
8760 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00008761 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
8762 if (FLL->isExact())
8763 return;
8764 } else
8765 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
8766 if (FLR->isExact())
8767 return;
Mike Stump11289f42009-09-09 15:08:12 +00008768
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008769 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00008770 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00008771 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00008772 return;
Mike Stump11289f42009-09-09 15:08:12 +00008773
David Blaikie1f4ff152012-07-16 20:47:22 +00008774 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00008775 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00008776 return;
Mike Stump11289f42009-09-09 15:08:12 +00008777
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008778 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00008779 Diag(Loc, diag::warn_floatingpoint_eq)
8780 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008781}
John McCallca01b222010-01-04 23:21:16 +00008782
John McCall70aa5392010-01-06 05:24:50 +00008783//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
8784//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00008785
John McCall70aa5392010-01-06 05:24:50 +00008786namespace {
John McCallca01b222010-01-04 23:21:16 +00008787
John McCall70aa5392010-01-06 05:24:50 +00008788/// Structure recording the 'active' range of an integer-valued
8789/// expression.
8790struct IntRange {
8791 /// The number of bits active in the int.
8792 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00008793
John McCall70aa5392010-01-06 05:24:50 +00008794 /// True if the int is known not to have negative values.
8795 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00008796
John McCall70aa5392010-01-06 05:24:50 +00008797 IntRange(unsigned Width, bool NonNegative)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008798 : Width(Width), NonNegative(NonNegative) {}
John McCallca01b222010-01-04 23:21:16 +00008799
John McCall817d4af2010-11-10 23:38:19 +00008800 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00008801 static IntRange forBoolType() {
8802 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00008803 }
8804
John McCall817d4af2010-11-10 23:38:19 +00008805 /// Returns the range of an opaque value of the given integral type.
8806 static IntRange forValueOfType(ASTContext &C, QualType T) {
8807 return forValueOfCanonicalType(C,
8808 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00008809 }
8810
John McCall817d4af2010-11-10 23:38:19 +00008811 /// Returns the range of an opaque value of a canonical integral type.
8812 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00008813 assert(T->isCanonicalUnqualified());
8814
8815 if (const VectorType *VT = dyn_cast<VectorType>(T))
8816 T = VT->getElementType().getTypePtr();
8817 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8818 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008819 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8820 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00008821
Roman Lebedevca1aaac2017-10-21 16:44:03 +00008822 if (!C.getLangOpts().CPlusPlus) {
8823 // For enum types in C code, use the underlying datatype.
8824 if (const EnumType *ET = dyn_cast<EnumType>(T))
8825 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
8826 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
8827 // For enum types in C++, use the known bit width of the enumerators.
David Majnemer6a426652013-06-07 22:07:20 +00008828 EnumDecl *Enum = ET->getDecl();
Richard Smith371e9e8a2017-12-06 03:00:51 +00008829 // In C++11, enums can have a fixed underlying type. Use this type to
8830 // compute the range.
8831 if (Enum->isFixed()) {
Erich Keane69dbbb02017-09-21 19:58:55 +00008832 return IntRange(C.getIntWidth(QualType(T, 0)),
8833 !ET->isSignedIntegerOrEnumerationType());
Richard Smith371e9e8a2017-12-06 03:00:51 +00008834 }
John McCall18a2c2c2010-11-09 22:22:12 +00008835
David Majnemer6a426652013-06-07 22:07:20 +00008836 unsigned NumPositive = Enum->getNumPositiveBits();
8837 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00008838
David Majnemer6a426652013-06-07 22:07:20 +00008839 if (NumNegative == 0)
8840 return IntRange(NumPositive, true/*NonNegative*/);
8841 else
8842 return IntRange(std::max(NumPositive + 1, NumNegative),
8843 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00008844 }
John McCall70aa5392010-01-06 05:24:50 +00008845
8846 const BuiltinType *BT = cast<BuiltinType>(T);
8847 assert(BT->isInteger());
8848
8849 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8850 }
8851
John McCall817d4af2010-11-10 23:38:19 +00008852 /// Returns the "target" range of a canonical integral type, i.e.
8853 /// the range of values expressible in the type.
8854 ///
8855 /// This matches forValueOfCanonicalType except that enums have the
8856 /// full range of their type, not the range of their enumerators.
8857 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
8858 assert(T->isCanonicalUnqualified());
8859
8860 if (const VectorType *VT = dyn_cast<VectorType>(T))
8861 T = VT->getElementType().getTypePtr();
8862 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8863 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008864 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8865 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008866 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00008867 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008868
8869 const BuiltinType *BT = cast<BuiltinType>(T);
8870 assert(BT->isInteger());
8871
8872 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8873 }
8874
8875 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00008876 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00008877 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00008878 L.NonNegative && R.NonNegative);
8879 }
8880
John McCall817d4af2010-11-10 23:38:19 +00008881 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00008882 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00008883 return IntRange(std::min(L.Width, R.Width),
8884 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00008885 }
8886};
8887
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008888} // namespace
8889
8890static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
8891 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008892 if (value.isSigned() && value.isNegative())
8893 return IntRange(value.getMinSignedBits(), false);
8894
8895 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00008896 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008897
8898 // isNonNegative() just checks the sign bit without considering
8899 // signedness.
8900 return IntRange(value.getActiveBits(), true);
8901}
8902
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008903static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
8904 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008905 if (result.isInt())
8906 return GetValueRange(C, result.getInt(), MaxWidth);
8907
8908 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00008909 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
8910 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
8911 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
8912 R = IntRange::join(R, El);
8913 }
John McCall70aa5392010-01-06 05:24:50 +00008914 return R;
8915 }
8916
8917 if (result.isComplexInt()) {
8918 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
8919 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
8920 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00008921 }
8922
8923 // This can happen with lossless casts to intptr_t of "based" lvalues.
8924 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00008925 // FIXME: The only reason we need to pass the type in here is to get
8926 // the sign right on this one case. It would be nice if APValue
8927 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008928 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00008929 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00008930}
John McCall70aa5392010-01-06 05:24:50 +00008931
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008932static QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008933 QualType Ty = E->getType();
8934 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
8935 Ty = AtomicRHS->getValueType();
8936 return Ty;
8937}
8938
John McCall70aa5392010-01-06 05:24:50 +00008939/// Pseudo-evaluate the given integer expression, estimating the
8940/// range of values it might take.
8941///
8942/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008943static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008944 E = E->IgnoreParens();
8945
8946 // Try a full evaluation first.
8947 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00008948 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00008949 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008950
8951 // I think we only want to look through implicit casts here; if the
8952 // user has an explicit widening cast, we should treat the value as
8953 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008954 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00008955 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00008956 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
8957
Eli Friedmane6d33952013-07-08 20:20:06 +00008958 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00008959
George Burgess IVdf1ed002016-01-13 01:52:39 +00008960 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
8961 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00008962
John McCall70aa5392010-01-06 05:24:50 +00008963 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00008964 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00008965 return OutputTypeRange;
8966
8967 IntRange SubRange
8968 = GetExprRange(C, CE->getSubExpr(),
8969 std::min(MaxWidth, OutputTypeRange.Width));
8970
8971 // Bail out if the subexpr's range is as wide as the cast type.
8972 if (SubRange.Width >= OutputTypeRange.Width)
8973 return OutputTypeRange;
8974
8975 // Otherwise, we take the smaller width, and we're non-negative if
8976 // either the output type or the subexpr is.
8977 return IntRange(SubRange.Width,
8978 SubRange.NonNegative || OutputTypeRange.NonNegative);
8979 }
8980
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008981 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008982 // If we can fold the condition, just take that operand.
8983 bool CondResult;
8984 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
8985 return GetExprRange(C, CondResult ? CO->getTrueExpr()
8986 : CO->getFalseExpr(),
8987 MaxWidth);
8988
8989 // Otherwise, conservatively merge.
8990 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
8991 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
8992 return IntRange::join(L, R);
8993 }
8994
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008995 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008996 switch (BO->getOpcode()) {
Richard Smithc70f1d62017-12-14 15:16:18 +00008997 case BO_Cmp:
8998 llvm_unreachable("builtin <=> should have class type");
John McCall70aa5392010-01-06 05:24:50 +00008999
9000 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00009001 case BO_LAnd:
9002 case BO_LOr:
9003 case BO_LT:
9004 case BO_GT:
9005 case BO_LE:
9006 case BO_GE:
9007 case BO_EQ:
9008 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00009009 return IntRange::forBoolType();
9010
John McCallc3688382011-07-13 06:35:24 +00009011 // The type of the assignments is the type of the LHS, so the RHS
9012 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00009013 case BO_MulAssign:
9014 case BO_DivAssign:
9015 case BO_RemAssign:
9016 case BO_AddAssign:
9017 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00009018 case BO_XorAssign:
9019 case BO_OrAssign:
9020 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00009021 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00009022
John McCallc3688382011-07-13 06:35:24 +00009023 // Simple assignments just pass through the RHS, which will have
9024 // been coerced to the LHS type.
9025 case BO_Assign:
9026 // TODO: bitfields?
9027 return GetExprRange(C, BO->getRHS(), MaxWidth);
9028
John McCall70aa5392010-01-06 05:24:50 +00009029 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00009030 case BO_PtrMemD:
9031 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00009032 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00009033
John McCall2ce81ad2010-01-06 22:07:33 +00009034 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00009035 case BO_And:
9036 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00009037 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
9038 GetExprRange(C, BO->getRHS(), MaxWidth));
9039
John McCall70aa5392010-01-06 05:24:50 +00009040 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00009041 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00009042 // ...except that we want to treat '1 << (blah)' as logically
9043 // positive. It's an important idiom.
9044 if (IntegerLiteral *I
9045 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
9046 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00009047 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00009048 return IntRange(R.Width, /*NonNegative*/ true);
9049 }
9050 }
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00009051 LLVM_FALLTHROUGH;
John McCall1bff9932010-04-07 01:14:35 +00009052
John McCalle3027922010-08-25 11:45:40 +00009053 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00009054 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00009055
John McCall2ce81ad2010-01-06 22:07:33 +00009056 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00009057 case BO_Shr:
9058 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00009059 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
9060
9061 // If the shift amount is a positive constant, drop the width by
9062 // that much.
9063 llvm::APSInt shift;
9064 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
9065 shift.isNonNegative()) {
9066 unsigned zext = shift.getZExtValue();
9067 if (zext >= L.Width)
9068 L.Width = (L.NonNegative ? 0 : 1);
9069 else
9070 L.Width -= zext;
9071 }
9072
9073 return L;
9074 }
9075
9076 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00009077 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00009078 return GetExprRange(C, BO->getRHS(), MaxWidth);
9079
John McCall2ce81ad2010-01-06 22:07:33 +00009080 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00009081 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00009082 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00009083 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00009084 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00009085
John McCall51431812011-07-14 22:39:48 +00009086 // The width of a division result is mostly determined by the size
9087 // of the LHS.
9088 case BO_Div: {
9089 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00009090 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00009091 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
9092
9093 // If the divisor is constant, use that.
9094 llvm::APSInt divisor;
9095 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
9096 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
9097 if (log2 >= L.Width)
9098 L.Width = (L.NonNegative ? 0 : 1);
9099 else
9100 L.Width = std::min(L.Width - log2, MaxWidth);
9101 return L;
9102 }
9103
9104 // Otherwise, just use the LHS's width.
9105 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
9106 return IntRange(L.Width, L.NonNegative && R.NonNegative);
9107 }
9108
9109 // The result of a remainder can't be larger than the result of
9110 // either side.
9111 case BO_Rem: {
9112 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00009113 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00009114 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
9115 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
9116
9117 IntRange meet = IntRange::meet(L, R);
9118 meet.Width = std::min(meet.Width, MaxWidth);
9119 return meet;
9120 }
9121
9122 // The default behavior is okay for these.
9123 case BO_Mul:
9124 case BO_Add:
9125 case BO_Xor:
9126 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00009127 break;
9128 }
9129
John McCall51431812011-07-14 22:39:48 +00009130 // The default case is to treat the operation as if it were closed
9131 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00009132 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
9133 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
9134 return IntRange::join(L, R);
9135 }
9136
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009137 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00009138 switch (UO->getOpcode()) {
9139 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00009140 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00009141 return IntRange::forBoolType();
9142
9143 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00009144 case UO_Deref:
9145 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00009146 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00009147
9148 default:
9149 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
9150 }
9151 }
9152
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009153 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00009154 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
9155
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009156 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00009157 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00009158 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00009159
Eli Friedmane6d33952013-07-08 20:20:06 +00009160 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00009161}
John McCall263a48b2010-01-04 23:31:57 +00009162
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009163static IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00009164 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00009165}
9166
John McCall263a48b2010-01-04 23:31:57 +00009167/// Checks whether the given value, which currently has the given
9168/// source semantics, has the same value when coerced through the
9169/// target semantics.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009170static bool IsSameFloatAfterCast(const llvm::APFloat &value,
9171 const llvm::fltSemantics &Src,
9172 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00009173 llvm::APFloat truncated = value;
9174
9175 bool ignored;
9176 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
9177 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
9178
9179 return truncated.bitwiseIsEqual(value);
9180}
9181
9182/// Checks whether the given value, which currently has the given
9183/// source semantics, has the same value when coerced through the
9184/// target semantics.
9185///
9186/// The value might be a vector of floats (or a complex number).
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009187static bool IsSameFloatAfterCast(const APValue &value,
9188 const llvm::fltSemantics &Src,
9189 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00009190 if (value.isFloat())
9191 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
9192
9193 if (value.isVector()) {
9194 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
9195 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
9196 return false;
9197 return true;
9198 }
9199
9200 assert(value.isComplexFloat());
9201 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
9202 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
9203}
9204
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009205static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009206
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009207static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00009208 // Suppress cases where we are comparing against an enum constant.
9209 if (const DeclRefExpr *DR =
9210 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
9211 if (isa<EnumConstantDecl>(DR->getDecl()))
Roman Lebedev6de129e2017-10-15 20:13:17 +00009212 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +00009213
9214 // Suppress cases where the '0' value is expanded from a macro.
9215 if (E->getLocStart().isMacroID())
Roman Lebedev6de129e2017-10-15 20:13:17 +00009216 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +00009217
Roman Lebedev6de129e2017-10-15 20:13:17 +00009218 return false;
9219}
9220
Richard Smith692f66ab2017-12-06 19:23:19 +00009221static bool isKnownToHaveUnsignedValue(Expr *E) {
9222 return E->getType()->isIntegerType() &&
Roman Lebedev6de129e2017-10-15 20:13:17 +00009223 (!E->getType()->isSignedIntegerType() ||
9224 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
9225}
9226
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009227namespace {
Richard Smitha5370fb2017-12-08 22:57:11 +00009228/// The promoted range of values of a type. In general this has the
9229/// following structure:
9230///
9231/// |-----------| . . . |-----------|
9232/// ^ ^ ^ ^
9233/// Min HoleMin HoleMax Max
9234///
9235/// ... where there is only a hole if a signed type is promoted to unsigned
9236/// (in which case Min and Max are the smallest and largest representable
9237/// values).
9238struct PromotedRange {
9239 // Min, or HoleMax if there is a hole.
9240 llvm::APSInt PromotedMin;
9241 // Max, or HoleMin if there is a hole.
9242 llvm::APSInt PromotedMax;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009243
Richard Smitha5370fb2017-12-08 22:57:11 +00009244 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
9245 if (R.Width == 0)
9246 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
9247 else if (R.Width >= BitWidth && !Unsigned) {
9248 // Promotion made the type *narrower*. This happens when promoting
9249 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
9250 // Treat all values of 'signed int' as being in range for now.
9251 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
9252 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
9253 } else {
9254 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
9255 .extOrTrunc(BitWidth);
9256 PromotedMin.setIsUnsigned(Unsigned);
9257
9258 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
9259 .extOrTrunc(BitWidth);
9260 PromotedMax.setIsUnsigned(Unsigned);
9261 }
9262 }
9263
9264 // Determine whether this range is contiguous (has no hole).
9265 bool isContiguous() const { return PromotedMin <= PromotedMax; }
9266
9267 // Where a constant value is within the range.
9268 enum ComparisonResult {
9269 LT = 0x1,
9270 LE = 0x2,
9271 GT = 0x4,
9272 GE = 0x8,
9273 EQ = 0x10,
9274 NE = 0x20,
9275 InRangeFlag = 0x40,
9276
9277 Less = LE | LT | NE,
9278 Min = LE | InRangeFlag,
9279 InRange = InRangeFlag,
9280 Max = GE | InRangeFlag,
9281 Greater = GE | GT | NE,
9282
9283 OnlyValue = LE | GE | EQ | InRangeFlag,
9284 InHole = NE
9285 };
9286
9287 ComparisonResult compare(const llvm::APSInt &Value) const {
9288 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
9289 Value.isUnsigned() == PromotedMin.isUnsigned());
9290 if (!isContiguous()) {
9291 assert(Value.isUnsigned() && "discontiguous range for signed compare");
9292 if (Value.isMinValue()) return Min;
9293 if (Value.isMaxValue()) return Max;
9294 if (Value >= PromotedMin) return InRange;
9295 if (Value <= PromotedMax) return InRange;
9296 return InHole;
9297 }
9298
9299 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
9300 case -1: return Less;
9301 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
9302 case 1:
9303 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
9304 case -1: return InRange;
9305 case 0: return Max;
9306 case 1: return Greater;
9307 }
9308 }
9309
9310 llvm_unreachable("impossible compare result");
9311 }
9312
Richard Smithc70f1d62017-12-14 15:16:18 +00009313 static llvm::Optional<StringRef>
9314 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
9315 if (Op == BO_Cmp) {
9316 ComparisonResult LTFlag = LT, GTFlag = GT;
9317 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
9318
9319 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
9320 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
9321 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
9322 return llvm::None;
9323 }
9324
Richard Smitha5370fb2017-12-08 22:57:11 +00009325 ComparisonResult TrueFlag, FalseFlag;
9326 if (Op == BO_EQ) {
9327 TrueFlag = EQ;
9328 FalseFlag = NE;
9329 } else if (Op == BO_NE) {
9330 TrueFlag = NE;
9331 FalseFlag = EQ;
9332 } else {
9333 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
9334 TrueFlag = LT;
9335 FalseFlag = GE;
9336 } else {
9337 TrueFlag = GT;
9338 FalseFlag = LE;
9339 }
9340 if (Op == BO_GE || Op == BO_LE)
9341 std::swap(TrueFlag, FalseFlag);
9342 }
9343 if (R & TrueFlag)
Richard Smithc70f1d62017-12-14 15:16:18 +00009344 return StringRef("true");
Richard Smitha5370fb2017-12-08 22:57:11 +00009345 if (R & FalseFlag)
Richard Smithc70f1d62017-12-14 15:16:18 +00009346 return StringRef("false");
Richard Smitha5370fb2017-12-08 22:57:11 +00009347 return llvm::None;
9348 }
Roman Lebedev6de129e2017-10-15 20:13:17 +00009349};
John McCallcc7e5bf2010-05-06 08:58:33 +00009350}
9351
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009352static bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00009353 // Strip off implicit integral promotions.
9354 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00009355 if (ICE->getCastKind() != CK_IntegralCast &&
9356 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00009357 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00009358 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00009359 }
9360
9361 return E->getType()->isEnumeralType();
9362}
9363
Richard Smith692f66ab2017-12-06 19:23:19 +00009364static int classifyConstantValue(Expr *Constant) {
9365 // The values of this enumeration are used in the diagnostics
9366 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
9367 enum ConstantValueKind {
9368 Miscellaneous = 0,
9369 LiteralTrue,
9370 LiteralFalse
9371 };
9372 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
9373 return BL->getValue() ? ConstantValueKind::LiteralTrue
9374 : ConstantValueKind::LiteralFalse;
9375 return ConstantValueKind::Miscellaneous;
9376}
9377
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009378static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
9379 Expr *Constant, Expr *Other,
9380 const llvm::APSInt &Value,
9381 bool RhsConstant) {
Hans Wennborg5bb88e02017-12-08 05:19:12 +00009382 if (S.inTemplateInstantiation())
9383 return false;
9384
Richard Smitha5370fb2017-12-08 22:57:11 +00009385 Expr *OriginalOther = Other;
9386
Hans Wennborg5bb88e02017-12-08 05:19:12 +00009387 Constant = Constant->IgnoreParenImpCasts();
9388 Other = Other->IgnoreParenImpCasts();
9389
Richard Smitha5370fb2017-12-08 22:57:11 +00009390 // Suppress warnings on tautological comparisons between values of the same
9391 // enumeration type. There are only two ways we could warn on this:
9392 // - If the constant is outside the range of representable values of
9393 // the enumeration. In such a case, we should warn about the cast
9394 // to enumeration type, not about the comparison.
9395 // - If the constant is the maximum / minimum in-range value. For an
9396 // enumeratin type, such comparisons can be meaningful and useful.
9397 if (Constant->getType()->isEnumeralType() &&
9398 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
9399 return false;
9400
Hans Wennborg5bb88e02017-12-08 05:19:12 +00009401 // TODO: Investigate using GetExprRange() to get tighter bounds
9402 // on the bit ranges.
9403 QualType OtherT = Other->getType();
9404 if (const auto *AT = OtherT->getAs<AtomicType>())
9405 OtherT = AT->getValueType();
9406 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
9407
9408 // Whether we're treating Other as being a bool because of the form of
9409 // expression despite it having another type (typically 'int' in C).
9410 bool OtherIsBooleanDespiteType =
9411 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
9412 if (OtherIsBooleanDespiteType)
9413 OtherRange = IntRange::forBoolType();
9414
Richard Smitha5370fb2017-12-08 22:57:11 +00009415 // Determine the promoted range of the other type and see if a comparison of
9416 // the constant against that range is tautological.
9417 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
9418 Value.isUnsigned());
9419 auto Cmp = OtherPromotedRange.compare(Value);
9420 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
9421 if (!Result)
9422 return false;
Hans Wennborg5791ce72017-12-08 16:54:08 +00009423
Richard Smitha5370fb2017-12-08 22:57:11 +00009424 // Suppress the diagnostic for an in-range comparison if the constant comes
9425 // from a macro or enumerator. We don't want to diagnose
9426 //
9427 // some_long_value <= INT_MAX
9428 //
9429 // when sizeof(int) == sizeof(long).
9430 bool InRange = Cmp & PromotedRange::InRangeFlag;
9431 if (InRange && IsEnumConstOrFromMacro(S, Constant))
9432 return false;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00009433
9434 // If this is a comparison to an enum constant, include that
9435 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00009436 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00009437 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
9438 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
9439
Richard Smitha5370fb2017-12-08 22:57:11 +00009440 // Should be enough for uint128 (39 decimal digits)
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00009441 SmallString<64> PrettySourceValue;
9442 llvm::raw_svector_ostream OS(PrettySourceValue);
9443 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00009444 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00009445 else
9446 OS << Value;
9447
Richard Smitha5370fb2017-12-08 22:57:11 +00009448 // FIXME: We use a somewhat different formatting for the in-range cases and
9449 // cases involving boolean values for historical reasons. We should pick a
9450 // consistent way of presenting these diagnostics.
9451 if (!InRange || Other->isKnownToHaveBooleanValue()) {
9452 S.DiagRuntimeBehavior(
9453 E->getOperatorLoc(), E,
9454 S.PDiag(!InRange ? diag::warn_out_of_range_compare
9455 : diag::warn_tautological_bool_compare)
9456 << OS.str() << classifyConstantValue(Constant)
9457 << OtherT << OtherIsBooleanDespiteType << *Result
9458 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
9459 } else {
9460 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
9461 ? (HasEnumType(OriginalOther)
9462 ? diag::warn_unsigned_enum_always_true_comparison
9463 : diag::warn_unsigned_always_true_comparison)
9464 : diag::warn_tautological_constant_compare;
Roman Lebedev6de129e2017-10-15 20:13:17 +00009465
Richard Smitha5370fb2017-12-08 22:57:11 +00009466 S.Diag(E->getOperatorLoc(), Diag)
9467 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
9468 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
9469 }
9470
9471 return true;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00009472}
9473
John McCallcc7e5bf2010-05-06 08:58:33 +00009474/// Analyze the operands of the given comparison. Implements the
9475/// fallback case from AnalyzeComparison.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009476static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00009477 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9478 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00009479}
John McCall263a48b2010-01-04 23:31:57 +00009480
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009481/// Implements -Wsign-compare.
John McCallca01b222010-01-04 23:21:16 +00009482///
Richard Trieu82402a02011-09-15 21:56:47 +00009483/// \param E the binary operator to check for warnings
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009484static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009485 // The type the comparison is being performed in.
9486 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00009487
9488 // Only analyze comparison operators where both sides have been converted to
9489 // the same type.
9490 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
9491 return AnalyzeImpConvsInComparison(S, E);
9492
9493 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00009494 if (E->isValueDependent())
9495 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00009496
Roman Lebedev6de129e2017-10-15 20:13:17 +00009497 Expr *LHS = E->getLHS();
9498 Expr *RHS = E->getRHS();
9499
Fariborz Jahanianb1885422012-09-18 17:37:21 +00009500 if (T->isIntegralType(S.Context)) {
9501 llvm::APSInt RHSValue;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00009502 llvm::APSInt LHSValue;
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009503
Roman Lebedev6de129e2017-10-15 20:13:17 +00009504 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
9505 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
Roman Lebedevbd1fc222017-10-12 20:16:51 +00009506
Roman Lebedev6de129e2017-10-15 20:13:17 +00009507 // We don't care about expressions whose result is a constant.
9508 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
9509 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6f405db2017-10-12 22:03:20 +00009510
Roman Lebedev6de129e2017-10-15 20:13:17 +00009511 // We only care about expressions where just one side is literal
9512 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
9513 // Is the constant on the RHS or LHS?
9514 const bool RhsConstant = IsRHSIntegralLiteral;
9515 Expr *Const = RhsConstant ? RHS : LHS;
9516 Expr *Other = RhsConstant ? LHS : RHS;
9517 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
9518
9519 // Check whether an integer constant comparison results in a value
9520 // of 'true' or 'false'.
Roman Lebedev6de129e2017-10-15 20:13:17 +00009521 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
9522 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6de129e2017-10-15 20:13:17 +00009523 }
9524 }
9525
9526 if (!T->hasUnsignedIntegerRepresentation()) {
9527 // We don't do anything special if this isn't an unsigned integral
9528 // comparison: we're only interested in integral comparisons, and
9529 // signed comparisons only happen in cases we don't care to warn about.
Roman Lebedev6f405db2017-10-12 22:03:20 +00009530 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6de129e2017-10-15 20:13:17 +00009531 }
9532
9533 LHS = LHS->IgnoreParenImpCasts();
9534 RHS = RHS->IgnoreParenImpCasts();
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009535
Alex Lorenzb57409f2018-02-07 20:45:39 +00009536 if (!S.getLangOpts().CPlusPlus) {
9537 // Avoid warning about comparison of integers with different signs when
9538 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
9539 // the type of `E`.
9540 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
9541 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
9542 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
9543 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
9544 }
9545
John McCallcc7e5bf2010-05-06 08:58:33 +00009546 // Check to see if one of the (unmodified) operands is of different
9547 // signedness.
9548 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00009549 if (LHS->getType()->hasSignedIntegerRepresentation()) {
9550 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00009551 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00009552 signedOperand = LHS;
9553 unsignedOperand = RHS;
9554 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
9555 signedOperand = RHS;
9556 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00009557 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00009558 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00009559 }
9560
John McCallcc7e5bf2010-05-06 08:58:33 +00009561 // Otherwise, calculate the effective range of the signed operand.
9562 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00009563
John McCallcc7e5bf2010-05-06 08:58:33 +00009564 // Go ahead and analyze implicit conversions in the operands. Note
9565 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00009566 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
9567 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00009568
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009569 // If the signed range is non-negative, -Wsign-compare won't fire.
John McCallcc7e5bf2010-05-06 08:58:33 +00009570 if (signedRange.NonNegative)
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009571 return;
John McCallca01b222010-01-04 23:21:16 +00009572
9573 // For (in)equality comparisons, if the unsigned operand is a
9574 // constant which cannot collide with a overflowed signed operand,
9575 // then reinterpreting the signed operand as unsigned will not
9576 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00009577 if (E->isEqualityOp()) {
9578 unsigned comparisonWidth = S.Context.getIntWidth(T);
9579 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00009580
John McCallcc7e5bf2010-05-06 08:58:33 +00009581 // We should never be unable to prove that the unsigned operand is
9582 // non-negative.
9583 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
9584
9585 if (unsignedRange.Width < comparisonWidth)
9586 return;
9587 }
9588
Douglas Gregorbfb4a212012-05-01 01:53:49 +00009589 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
9590 S.PDiag(diag::warn_mixed_sign_comparison)
9591 << LHS->getType() << RHS->getType()
9592 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00009593}
9594
John McCall1f425642010-11-11 03:21:53 +00009595/// Analyzes an attempt to assign the given value to a bitfield.
9596///
9597/// Returns true if there was something fishy about the attempt.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009598static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
9599 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00009600 assert(Bitfield->isBitField());
9601 if (Bitfield->isInvalidDecl())
9602 return false;
9603
John McCalldeebbcf2010-11-11 05:33:51 +00009604 // White-list bool bitfields.
Reid Klecknerad425622016-11-16 23:40:00 +00009605 QualType BitfieldType = Bitfield->getType();
9606 if (BitfieldType->isBooleanType())
9607 return false;
9608
9609 if (BitfieldType->isEnumeralType()) {
9610 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
9611 // If the underlying enum type was not explicitly specified as an unsigned
9612 // type and the enum contain only positive values, MSVC++ will cause an
9613 // inconsistency by storing this as a signed type.
9614 if (S.getLangOpts().CPlusPlus11 &&
9615 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
9616 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
9617 BitfieldEnumDecl->getNumNegativeBits() == 0) {
9618 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
9619 << BitfieldEnumDecl->getNameAsString();
9620 }
9621 }
9622
John McCalldeebbcf2010-11-11 05:33:51 +00009623 if (Bitfield->getType()->isBooleanType())
9624 return false;
9625
Douglas Gregor789adec2011-02-04 13:09:01 +00009626 // Ignore value- or type-dependent expressions.
9627 if (Bitfield->getBitWidth()->isValueDependent() ||
9628 Bitfield->getBitWidth()->isTypeDependent() ||
9629 Init->isValueDependent() ||
9630 Init->isTypeDependent())
9631 return false;
9632
John McCall1f425642010-11-11 03:21:53 +00009633 Expr *OriginalInit = Init->IgnoreParenImpCasts();
Reid Kleckner329f24d2017-03-14 18:01:02 +00009634 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00009635
Richard Smith5fab0c92011-12-28 19:48:30 +00009636 llvm::APSInt Value;
Reid Kleckner329f24d2017-03-14 18:01:02 +00009637 if (!OriginalInit->EvaluateAsInt(Value, S.Context,
9638 Expr::SE_AllowSideEffects)) {
9639 // The RHS is not constant. If the RHS has an enum type, make sure the
9640 // bitfield is wide enough to hold all the values of the enum without
9641 // truncation.
9642 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
9643 EnumDecl *ED = EnumTy->getDecl();
9644 bool SignedBitfield = BitfieldType->isSignedIntegerType();
9645
9646 // Enum types are implicitly signed on Windows, so check if there are any
9647 // negative enumerators to see if the enum was intended to be signed or
9648 // not.
9649 bool SignedEnum = ED->getNumNegativeBits() > 0;
9650
9651 // Check for surprising sign changes when assigning enum values to a
9652 // bitfield of different signedness. If the bitfield is signed and we
9653 // have exactly the right number of bits to store this unsigned enum,
9654 // suggest changing the enum to an unsigned type. This typically happens
9655 // on Windows where unfixed enums always use an underlying type of 'int'.
9656 unsigned DiagID = 0;
9657 if (SignedEnum && !SignedBitfield) {
9658 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
9659 } else if (SignedBitfield && !SignedEnum &&
9660 ED->getNumPositiveBits() == FieldWidth) {
9661 DiagID = diag::warn_signed_bitfield_enum_conversion;
9662 }
9663
9664 if (DiagID) {
9665 S.Diag(InitLoc, DiagID) << Bitfield << ED;
9666 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
9667 SourceRange TypeRange =
9668 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
9669 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
9670 << SignedEnum << TypeRange;
9671 }
9672
9673 // Compute the required bitwidth. If the enum has negative values, we need
9674 // one more bit than the normal number of positive bits to represent the
9675 // sign bit.
9676 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
9677 ED->getNumNegativeBits())
9678 : ED->getNumPositiveBits();
9679
9680 // Check the bitwidth.
9681 if (BitsNeeded > FieldWidth) {
9682 Expr *WidthExpr = Bitfield->getBitWidth();
9683 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
9684 << Bitfield << ED;
9685 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
9686 << BitsNeeded << ED << WidthExpr->getSourceRange();
9687 }
9688 }
9689
John McCall1f425642010-11-11 03:21:53 +00009690 return false;
Reid Kleckner329f24d2017-03-14 18:01:02 +00009691 }
John McCall1f425642010-11-11 03:21:53 +00009692
John McCall1f425642010-11-11 03:21:53 +00009693 unsigned OriginalWidth = Value.getBitWidth();
John McCall1f425642010-11-11 03:21:53 +00009694
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00009695 if (!Value.isSigned() || Value.isNegative())
Richard Trieu7561ed02016-08-05 02:39:30 +00009696 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00009697 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
9698 OriginalWidth = Value.getMinSignedBits();
Richard Trieu7561ed02016-08-05 02:39:30 +00009699
John McCall1f425642010-11-11 03:21:53 +00009700 if (OriginalWidth <= FieldWidth)
9701 return false;
9702
Eli Friedmanc267a322012-01-26 23:11:39 +00009703 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00009704 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Reid Klecknerad425622016-11-16 23:40:00 +00009705 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00009706
Eli Friedmanc267a322012-01-26 23:11:39 +00009707 // Check whether the stored value is equal to the original value.
9708 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00009709 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00009710 return false;
9711
Eli Friedmanc267a322012-01-26 23:11:39 +00009712 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00009713 // therefore don't strictly fit into a signed bitfield of width 1.
9714 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00009715 return false;
9716
John McCall1f425642010-11-11 03:21:53 +00009717 std::string PrettyValue = Value.toString(10);
9718 std::string PrettyTrunc = TruncatedValue.toString(10);
9719
9720 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
9721 << PrettyValue << PrettyTrunc << OriginalInit->getType()
9722 << Init->getSourceRange();
9723
9724 return true;
9725}
9726
John McCalld2a53122010-11-09 23:24:47 +00009727/// Analyze the given simple or compound assignment for warning-worthy
9728/// operations.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009729static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00009730 // Just recurse on the LHS.
9731 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9732
9733 // We want to recurse on the RHS as normal unless we're assigning to
9734 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00009735 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009736 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00009737 E->getOperatorLoc())) {
9738 // Recurse, ignoring any implicit conversions on the RHS.
9739 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
9740 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00009741 }
9742 }
9743
9744 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9745}
9746
John McCall263a48b2010-01-04 23:31:57 +00009747/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009748static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
9749 SourceLocation CContext, unsigned diag,
9750 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00009751 if (pruneControlFlow) {
9752 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9753 S.PDiag(diag)
9754 << SourceType << T << E->getSourceRange()
9755 << SourceRange(CContext));
9756 return;
9757 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00009758 S.Diag(E->getExprLoc(), diag)
9759 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
9760}
9761
Chandler Carruth7f3654f2011-04-05 06:47:57 +00009762/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009763static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
9764 SourceLocation CContext,
9765 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00009766 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00009767}
9768
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +00009769/// Analyze the given compound assignment for the possible losing of
9770/// floating-point precision.
9771static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
9772 assert(isa<CompoundAssignOperator>(E) &&
9773 "Must be compound assignment operation");
9774 // Recurse on the LHS and RHS in here
9775 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9776 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9777
9778 // Now check the outermost expression
9779 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
9780 const auto *RBT = cast<CompoundAssignOperator>(E)
9781 ->getComputationResultType()
9782 ->getAs<BuiltinType>();
9783
9784 // If both source and target are floating points.
9785 if (ResultBT && ResultBT->isFloatingPoint() && RBT && RBT->isFloatingPoint())
9786 // Builtin FP kinds are ordered by increasing FP rank.
9787 if (ResultBT->getKind() < RBT->getKind())
9788 // We don't want to warn for system macro.
9789 if (!S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
9790 // warn about dropping FP rank.
9791 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(),
9792 E->getOperatorLoc(),
9793 diag::warn_impcast_float_result_precision);
9794}
Richard Trieube234c32016-04-21 21:04:55 +00009795
9796/// Diagnose an implicit cast from a floating point value to an integer value.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009797static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
9798 SourceLocation CContext) {
Richard Trieube234c32016-04-21 21:04:55 +00009799 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
Richard Smith51ec0cf2017-02-21 01:17:38 +00009800 const bool PruneWarnings = S.inTemplateInstantiation();
Richard Trieube234c32016-04-21 21:04:55 +00009801
9802 Expr *InnerE = E->IgnoreParenImpCasts();
9803 // We also want to warn on, e.g., "int i = -1.234"
9804 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
9805 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
9806 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
9807
9808 const bool IsLiteral =
9809 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
9810
9811 llvm::APFloat Value(0.0);
9812 bool IsConstant =
9813 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
9814 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00009815 return DiagnoseImpCast(S, E, T, CContext,
9816 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00009817 }
9818
Chandler Carruth016ef402011-04-10 08:36:24 +00009819 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00009820
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00009821 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
9822 T->hasUnsignedIntegerRepresentation());
Erich Keanea4c48c62018-05-08 21:26:21 +00009823 llvm::APFloat::opStatus Result = Value.convertToInteger(
9824 IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
9825
9826 if (Result == llvm::APFloat::opOK && isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00009827 if (IsLiteral) return;
9828 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
9829 PruneWarnings);
9830 }
9831
Erich Keanea4c48c62018-05-08 21:26:21 +00009832 // Conversion of a floating-point value to a non-bool integer where the
9833 // integral part cannot be represented by the integer type is undefined.
9834 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
9835 return DiagnoseImpCast(
9836 S, E, T, CContext,
9837 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
Richard Trieua2b8fe62018-05-14 23:21:48 +00009838 : diag::warn_impcast_float_to_integer_out_of_range,
9839 PruneWarnings);
Erich Keanea4c48c62018-05-08 21:26:21 +00009840
Richard Trieube234c32016-04-21 21:04:55 +00009841 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00009842 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00009843 // Warn on floating point literal to integer.
9844 DiagID = diag::warn_impcast_literal_float_to_integer;
9845 } else if (IntegerValue == 0) {
9846 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
9847 return DiagnoseImpCast(S, E, T, CContext,
9848 diag::warn_impcast_float_integer, PruneWarnings);
9849 }
9850 // Warn on non-zero to zero conversion.
9851 DiagID = diag::warn_impcast_float_to_integer_zero;
9852 } else {
9853 if (IntegerValue.isUnsigned()) {
9854 if (!IntegerValue.isMaxValue()) {
9855 return DiagnoseImpCast(S, E, T, CContext,
9856 diag::warn_impcast_float_integer, PruneWarnings);
9857 }
9858 } else { // IntegerValue.isSigned()
9859 if (!IntegerValue.isMaxSignedValue() &&
9860 !IntegerValue.isMinSignedValue()) {
9861 return DiagnoseImpCast(S, E, T, CContext,
9862 diag::warn_impcast_float_integer, PruneWarnings);
9863 }
9864 }
9865 // Warn on evaluatable floating point expression to integer conversion.
9866 DiagID = diag::warn_impcast_float_to_integer;
9867 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009868
Eli Friedman07185912013-08-29 23:44:43 +00009869 // FIXME: Force the precision of the source value down so we don't print
9870 // digits which are usually useless (we don't really care here if we
9871 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
9872 // would automatically print the shortest representation, but it's a bit
9873 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00009874 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00009875 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
9876 precision = (precision * 59 + 195) / 196;
9877 Value.toString(PrettySourceValue, precision);
9878
David Blaikie9b88cc02012-05-15 17:18:27 +00009879 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00009880 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00009881 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00009882 else
David Blaikie9b88cc02012-05-15 17:18:27 +00009883 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00009884
Richard Trieube234c32016-04-21 21:04:55 +00009885 if (PruneWarnings) {
9886 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9887 S.PDiag(DiagID)
9888 << E->getType() << T.getUnqualifiedType()
9889 << PrettySourceValue << PrettyTargetValue
9890 << E->getSourceRange() << SourceRange(CContext));
9891 } else {
9892 S.Diag(E->getExprLoc(), DiagID)
9893 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
9894 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
9895 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009896}
9897
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009898static std::string PrettyPrintInRange(const llvm::APSInt &Value,
9899 IntRange Range) {
John McCall18a2c2c2010-11-09 22:22:12 +00009900 if (!Range.Width) return "0";
9901
9902 llvm::APSInt ValueInRange = Value;
9903 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00009904 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00009905 return ValueInRange.toString(10);
9906}
9907
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009908static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009909 if (!isa<ImplicitCastExpr>(Ex))
9910 return false;
9911
9912 Expr *InnerE = Ex->IgnoreParenImpCasts();
9913 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
9914 const Type *Source =
9915 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
9916 if (Target->isDependentType())
9917 return false;
9918
9919 const BuiltinType *FloatCandidateBT =
9920 dyn_cast<BuiltinType>(ToBool ? Source : Target);
9921 const Type *BoolCandidateType = ToBool ? Target : Source;
9922
9923 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
9924 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
9925}
9926
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009927static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
9928 SourceLocation CC) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009929 unsigned NumArgs = TheCall->getNumArgs();
9930 for (unsigned i = 0; i < NumArgs; ++i) {
9931 Expr *CurrA = TheCall->getArg(i);
9932 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
9933 continue;
9934
9935 bool IsSwapped = ((i > 0) &&
9936 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
9937 IsSwapped |= ((i < (NumArgs - 1)) &&
9938 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
9939 if (IsSwapped) {
9940 // Warn on this floating-point to bool conversion.
9941 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
9942 CurrA->getType(), CC,
9943 diag::warn_impcast_floating_point_to_bool);
9944 }
9945 }
9946}
9947
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009948static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
9949 SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00009950 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
9951 E->getExprLoc()))
9952 return;
9953
Richard Trieu09d6b802016-01-08 23:35:06 +00009954 // Don't warn on functions which have return type nullptr_t.
9955 if (isa<CallExpr>(E))
9956 return;
9957
Richard Trieu5b993502014-10-15 03:42:06 +00009958 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
9959 const Expr::NullPointerConstantKind NullKind =
9960 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
9961 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
9962 return;
9963
9964 // Return if target type is a safe conversion.
9965 if (T->isAnyPointerType() || T->isBlockPointerType() ||
9966 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
9967 return;
9968
9969 SourceLocation Loc = E->getSourceRange().getBegin();
9970
Richard Trieu0a5e1662016-02-13 00:58:53 +00009971 // Venture through the macro stacks to get to the source of macro arguments.
9972 // The new location is a better location than the complete location that was
9973 // passed in.
George Karpenkov441e8fd2018-02-09 23:30:07 +00009974 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
9975 CC = S.SourceMgr.getTopMacroCallerLoc(CC);
Richard Trieu0a5e1662016-02-13 00:58:53 +00009976
Richard Trieu5b993502014-10-15 03:42:06 +00009977 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00009978 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
9979 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
9980 Loc, S.SourceMgr, S.getLangOpts());
9981 if (MacroName == "NULL")
Richard Smithb5f81712018-04-30 05:25:48 +00009982 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
Richard Trieu5b993502014-10-15 03:42:06 +00009983 }
9984
9985 // Only warn if the null and context location are in the same macro expansion.
9986 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
9987 return;
9988
9989 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009990 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
Richard Trieu5b993502014-10-15 03:42:06 +00009991 << FixItHint::CreateReplacement(Loc,
9992 S.getFixItZeroLiteralForType(T, Loc));
9993}
9994
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009995static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9996 ObjCArrayLiteral *ArrayLiteral);
9997
9998static void
9999checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
10000 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +000010001
10002/// Check a single element within a collection literal against the
10003/// target element type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010004static void checkObjCCollectionLiteralElement(Sema &S,
10005 QualType TargetElementType,
10006 Expr *Element,
10007 unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +000010008 // Skip a bitcast to 'id' or qualified 'id'.
10009 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
10010 if (ICE->getCastKind() == CK_BitCast &&
10011 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
10012 Element = ICE->getSubExpr();
10013 }
10014
10015 QualType ElementType = Element->getType();
10016 ExprResult ElementResult(Element);
10017 if (ElementType->getAs<ObjCObjectPointerType>() &&
10018 S.CheckSingleAssignmentConstraints(TargetElementType,
10019 ElementResult,
10020 false, false)
10021 != Sema::Compatible) {
10022 S.Diag(Element->getLocStart(),
10023 diag::warn_objc_collection_literal_element)
10024 << ElementType << ElementKind << TargetElementType
10025 << Element->getSourceRange();
10026 }
10027
10028 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
10029 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
10030 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
10031 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
10032}
10033
10034/// Check an Objective-C array literal being converted to the given
10035/// target type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010036static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
10037 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +000010038 if (!S.NSArrayDecl)
10039 return;
10040
10041 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
10042 if (!TargetObjCPtr)
10043 return;
10044
10045 if (TargetObjCPtr->isUnspecialized() ||
10046 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
10047 != S.NSArrayDecl->getCanonicalDecl())
10048 return;
10049
10050 auto TypeArgs = TargetObjCPtr->getTypeArgs();
10051 if (TypeArgs.size() != 1)
10052 return;
10053
10054 QualType TargetElementType = TypeArgs[0];
10055 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
10056 checkObjCCollectionLiteralElement(S, TargetElementType,
10057 ArrayLiteral->getElement(I),
10058 0);
10059 }
10060}
10061
10062/// Check an Objective-C dictionary literal being converted to the given
10063/// target type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010064static void
10065checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
10066 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +000010067 if (!S.NSDictionaryDecl)
10068 return;
10069
10070 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
10071 if (!TargetObjCPtr)
10072 return;
10073
10074 if (TargetObjCPtr->isUnspecialized() ||
10075 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
10076 != S.NSDictionaryDecl->getCanonicalDecl())
10077 return;
10078
10079 auto TypeArgs = TargetObjCPtr->getTypeArgs();
10080 if (TypeArgs.size() != 2)
10081 return;
10082
10083 QualType TargetKeyType = TypeArgs[0];
10084 QualType TargetObjectType = TypeArgs[1];
10085 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
10086 auto Element = DictionaryLiteral->getKeyValueElement(I);
10087 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
10088 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
10089 }
10090}
10091
Richard Trieufc404c72016-02-05 23:02:38 +000010092// Helper function to filter out cases for constant width constant conversion.
10093// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010094static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
10095 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +000010096 // If initializing from a constant, and the constant starts with '0',
10097 // then it is a binary, octal, or hexadecimal. Allow these constants
10098 // to fill all the bits, even if there is a sign change.
10099 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
10100 const char FirstLiteralCharacter =
10101 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
10102 if (FirstLiteralCharacter == '0')
10103 return false;
10104 }
10105
10106 // If the CC location points to a '{', and the type is char, then assume
10107 // assume it is an array initialization.
10108 if (CC.isValid() && T->isCharType()) {
10109 const char FirstContextCharacter =
10110 S.getSourceManager().getCharacterData(CC)[0];
10111 if (FirstContextCharacter == '{')
10112 return false;
10113 }
10114
10115 return true;
10116}
10117
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010118static void
10119CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
10120 bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010121 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +000010122
John McCallcc7e5bf2010-05-06 08:58:33 +000010123 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
10124 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
10125 if (Source == Target) return;
10126 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +000010127
Chandler Carruthc22845a2011-07-26 05:40:03 +000010128 // If the conversion context location is invalid don't complain. We also
10129 // don't want to emit a warning if the issue occurs from the expansion of
10130 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
10131 // delay this check as long as possible. Once we detect we are in that
10132 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010133 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +000010134 return;
10135
Richard Trieu021baa32011-09-23 20:10:00 +000010136 // Diagnose implicit casts to bool.
10137 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
10138 if (isa<StringLiteral>(E))
10139 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +000010140 // and expressions, for instance, assert(0 && "error here"), are
10141 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +000010142 return DiagnoseImpCast(S, E, T, CC,
10143 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +000010144 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
10145 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
10146 // This covers the literal expressions that evaluate to Objective-C
10147 // objects.
10148 return DiagnoseImpCast(S, E, T, CC,
10149 diag::warn_impcast_objective_c_literal_to_bool);
10150 }
Richard Trieu3bb8b562014-02-26 02:36:06 +000010151 if (Source->isPointerType() || Source->canDecayToPointerType()) {
10152 // Warn on pointer to bool conversion that is always true.
10153 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
10154 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +000010155 }
Richard Trieu021baa32011-09-23 20:10:00 +000010156 }
John McCall263a48b2010-01-04 23:31:57 +000010157
Douglas Gregor5054cb02015-07-07 03:58:22 +000010158 // Check implicit casts from Objective-C collection literals to specialized
10159 // collection types, e.g., NSArray<NSString *> *.
10160 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
10161 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
10162 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
10163 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
10164
John McCall263a48b2010-01-04 23:31:57 +000010165 // Strip vector types.
10166 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010167 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010168 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010169 return;
John McCallacf0ee52010-10-08 02:01:28 +000010170 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010171 }
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000010172
Chris Lattneree7286f2011-06-14 04:51:15 +000010173 // If the vector cast is cast between two vectors of the same size, it is
10174 // a bitcast, not a conversion.
10175 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
10176 return;
John McCall263a48b2010-01-04 23:31:57 +000010177
10178 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
10179 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
10180 }
Stephen Canon3ba640d2014-04-03 10:33:25 +000010181 if (auto VecTy = dyn_cast<VectorType>(Target))
10182 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +000010183
10184 // Strip complex types.
10185 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010186 if (!isa<ComplexType>(Target)) {
Tim Northover02416372017-08-08 23:18:05 +000010187 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010188 return;
10189
Tim Northover02416372017-08-08 23:18:05 +000010190 return DiagnoseImpCast(S, E, T, CC,
10191 S.getLangOpts().CPlusPlus
10192 ? diag::err_impcast_complex_scalar
10193 : diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010194 }
John McCall263a48b2010-01-04 23:31:57 +000010195
10196 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
10197 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
10198 }
10199
10200 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
10201 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
10202
10203 // If the source is floating point...
10204 if (SourceBT && SourceBT->isFloatingPoint()) {
10205 // ...and the target is floating point...
10206 if (TargetBT && TargetBT->isFloatingPoint()) {
10207 // ...then warn if we're dropping FP rank.
10208
10209 // Builtin FP kinds are ordered by increasing FP rank.
10210 if (SourceBT->getKind() > TargetBT->getKind()) {
10211 // Don't warn about float constants that are precisely
10212 // representable in the target type.
10213 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +000010214 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +000010215 // Value might be a float, a float vector, or a float complex.
10216 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +000010217 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
10218 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +000010219 return;
10220 }
10221
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010222 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010223 return;
10224
John McCallacf0ee52010-10-08 02:01:28 +000010225 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +000010226 }
10227 // ... or possibly if we're increasing rank, too
10228 else if (TargetBT->getKind() > SourceBT->getKind()) {
10229 if (S.SourceMgr.isInSystemMacro(CC))
10230 return;
10231
10232 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +000010233 }
10234 return;
10235 }
10236
Richard Trieube234c32016-04-21 21:04:55 +000010237 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +000010238 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010239 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010240 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +000010241
Richard Trieube234c32016-04-21 21:04:55 +000010242 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +000010243 }
John McCall263a48b2010-01-04 23:31:57 +000010244
Richard Smith54894fd2015-12-30 01:06:52 +000010245 // Detect the case where a call result is converted from floating-point to
10246 // to bool, and the final argument to the call is converted from bool, to
10247 // discover this typo:
10248 //
10249 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
10250 //
10251 // FIXME: This is an incredibly special case; is there some more general
10252 // way to detect this class of misplaced-parentheses bug?
10253 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010254 // Check last argument of function call to see if it is an
10255 // implicit cast from a type matching the type the result
10256 // is being cast to.
10257 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +000010258 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010259 Expr *LastA = CEx->getArg(NumArgs - 1);
10260 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +000010261 if (isa<ImplicitCastExpr>(LastA) &&
10262 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010263 // Warn on this floating-point to bool conversion
10264 DiagnoseImpCast(S, E, T, CC,
10265 diag::warn_impcast_floating_point_to_bool);
10266 }
10267 }
10268 }
John McCall263a48b2010-01-04 23:31:57 +000010269 return;
10270 }
10271
Richard Trieu5b993502014-10-15 03:42:06 +000010272 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +000010273
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000010274 S.DiscardMisalignedMemberAddress(Target, E);
10275
David Blaikie9366d2b2012-06-19 21:19:06 +000010276 if (!Source->isIntegerType() || !Target->isIntegerType())
10277 return;
10278
David Blaikie7555b6a2012-05-15 16:56:36 +000010279 // TODO: remove this early return once the false positives for constant->bool
10280 // in templates, macros, etc, are reduced or removed.
10281 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
10282 return;
10283
John McCallcc7e5bf2010-05-06 08:58:33 +000010284 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +000010285 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +000010286
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010287 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +000010288 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010289 // TODO: this should happen for bitfield stores, too.
10290 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +000010291 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010292 if (S.SourceMgr.isInSystemMacro(CC))
10293 return;
10294
John McCall18a2c2c2010-11-09 22:22:12 +000010295 std::string PrettySourceValue = Value.toString(10);
10296 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010297
Ted Kremenek33ba9952011-10-22 02:37:33 +000010298 S.DiagRuntimeBehavior(E->getExprLoc(), E,
10299 S.PDiag(diag::warn_impcast_integer_precision_constant)
10300 << PrettySourceValue << PrettyTargetValue
10301 << E->getType() << T << E->getSourceRange()
10302 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +000010303 return;
10304 }
10305
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010306 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
10307 if (S.SourceMgr.isInSystemMacro(CC))
10308 return;
10309
David Blaikie9455da02012-04-12 22:40:54 +000010310 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +000010311 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
10312 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +000010313 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +000010314 }
10315
Richard Trieudcb55572016-01-29 23:51:16 +000010316 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
10317 SourceRange.NonNegative && Source->isSignedIntegerType()) {
10318 // Warn when doing a signed to signed conversion, warn if the positive
10319 // source value is exactly the width of the target type, which will
10320 // cause a negative value to be stored.
10321
10322 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +000010323 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
10324 !S.SourceMgr.isInSystemMacro(CC)) {
10325 if (isSameWidthConstantConversion(S, E, T, CC)) {
10326 std::string PrettySourceValue = Value.toString(10);
10327 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +000010328
Richard Trieufc404c72016-02-05 23:02:38 +000010329 S.DiagRuntimeBehavior(
10330 E->getExprLoc(), E,
10331 S.PDiag(diag::warn_impcast_integer_precision_constant)
10332 << PrettySourceValue << PrettyTargetValue << E->getType() << T
10333 << E->getSourceRange() << clang::SourceRange(CC));
10334 return;
Richard Trieudcb55572016-01-29 23:51:16 +000010335 }
10336 }
Richard Trieufc404c72016-02-05 23:02:38 +000010337
Richard Trieudcb55572016-01-29 23:51:16 +000010338 // Fall through for non-constants to give a sign conversion warning.
10339 }
10340
John McCallcc7e5bf2010-05-06 08:58:33 +000010341 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
10342 (!TargetRange.NonNegative && SourceRange.NonNegative &&
10343 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010344 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010345 return;
10346
John McCallcc7e5bf2010-05-06 08:58:33 +000010347 unsigned DiagID = diag::warn_impcast_integer_sign;
10348
10349 // Traditionally, gcc has warned about this under -Wsign-compare.
10350 // We also want to warn about it in -Wconversion.
10351 // So if -Wconversion is off, use a completely identical diagnostic
10352 // in the sign-compare group.
10353 // The conditional-checking code will
10354 if (ICContext) {
10355 DiagID = diag::warn_impcast_integer_sign_conditional;
10356 *ICContext = true;
10357 }
10358
John McCallacf0ee52010-10-08 02:01:28 +000010359 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +000010360 }
10361
Douglas Gregora78f1932011-02-22 02:45:07 +000010362 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +000010363 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
10364 // type, to give us better diagnostics.
10365 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +000010366 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +000010367 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10368 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
10369 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
10370 SourceType = S.Context.getTypeDeclType(Enum);
10371 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
10372 }
10373 }
10374
Douglas Gregora78f1932011-02-22 02:45:07 +000010375 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
10376 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +000010377 if (SourceEnum->getDecl()->hasNameForLinkage() &&
10378 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010379 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010380 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010381 return;
10382
Douglas Gregor364f7db2011-03-12 00:14:31 +000010383 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +000010384 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010385 }
John McCall263a48b2010-01-04 23:31:57 +000010386}
10387
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010388static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
10389 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +000010390
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010391static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
10392 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010393 E = E->IgnoreParenImpCasts();
10394
10395 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +000010396 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +000010397
John McCallacf0ee52010-10-08 02:01:28 +000010398 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010399 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +000010400 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +000010401}
10402
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010403static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
10404 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +000010405 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +000010406
10407 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +000010408 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
10409 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +000010410
10411 // If -Wconversion would have warned about either of the candidates
10412 // for a signedness conversion to the context type...
10413 if (!Suspicious) return;
10414
10415 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010416 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +000010417 return;
10418
John McCallcc7e5bf2010-05-06 08:58:33 +000010419 // ...then check whether it would have warned about either of the
10420 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +000010421 if (E->getType() == T) return;
10422
10423 Suspicious = false;
10424 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
10425 E->getType(), CC, &Suspicious);
10426 if (!Suspicious)
10427 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +000010428 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +000010429}
10430
Richard Trieu65724892014-11-15 06:37:39 +000010431/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10432/// Input argument E is a logical expression.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010433static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +000010434 if (S.getLangOpts().Bool)
10435 return;
10436 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
10437}
10438
John McCallcc7e5bf2010-05-06 08:58:33 +000010439/// AnalyzeImplicitConversions - Find and report any interesting
10440/// implicit conversions in the given expression. There are a couple
10441/// of competing diagnostics here, -Wconversion and -Wsign-compare.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010442static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
10443 SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +000010444 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +000010445 Expr *E = OrigE->IgnoreParenImpCasts();
10446
Douglas Gregor6e8da6a2011-10-10 17:38:18 +000010447 if (E->isTypeDependent() || E->isValueDependent())
10448 return;
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000010449
John McCallcc7e5bf2010-05-06 08:58:33 +000010450 // For conditional operators, we analyze the arguments as if they
10451 // were being fed directly into the output.
10452 if (isa<ConditionalOperator>(E)) {
10453 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +000010454 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +000010455 return;
10456 }
10457
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010458 // Check implicit argument conversions for function calls.
10459 if (CallExpr *Call = dyn_cast<CallExpr>(E))
10460 CheckImplicitArgumentConversions(S, Call, CC);
10461
John McCallcc7e5bf2010-05-06 08:58:33 +000010462 // Go ahead and check any implicit conversions we might have skipped.
10463 // The non-canonical typecheck is just an optimization;
10464 // CheckImplicitConversion will filter out dead implicit conversions.
10465 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +000010466 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010467
10468 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +000010469
10470 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
10471 // The bound subexpressions in a PseudoObjectExpr are not reachable
10472 // as transitive children.
10473 // FIXME: Use a more uniform representation for this.
10474 for (auto *SE : POE->semantics())
10475 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
10476 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +000010477 }
Richard Smithd7bed4d2015-11-22 02:57:17 +000010478
John McCallcc7e5bf2010-05-06 08:58:33 +000010479 // Skip past explicit casts.
10480 if (isa<ExplicitCastExpr>(E)) {
10481 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +000010482 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010483 }
10484
John McCalld2a53122010-11-09 23:24:47 +000010485 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10486 // Do a somewhat different check with comparison operators.
10487 if (BO->isComparisonOp())
10488 return AnalyzeComparison(S, BO);
10489
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010490 // And with simple assignments.
10491 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +000010492 return AnalyzeAssignment(S, BO);
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000010493 // And with compound assignments.
10494 if (BO->isAssignmentOp())
10495 return AnalyzeCompoundAssignment(S, BO);
John McCalld2a53122010-11-09 23:24:47 +000010496 }
John McCallcc7e5bf2010-05-06 08:58:33 +000010497
10498 // These break the otherwise-useful invariant below. Fortunately,
10499 // we don't really need to recurse into them, because any internal
10500 // expressions should have been analyzed already when they were
10501 // built into statements.
10502 if (isa<StmtExpr>(E)) return;
10503
10504 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +000010505 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +000010506
10507 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +000010508 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +000010509 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +000010510 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +000010511 for (Stmt *SubStmt : E->children()) {
10512 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +000010513 if (!ChildExpr)
10514 continue;
10515
Richard Trieu955231d2014-01-25 01:10:35 +000010516 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +000010517 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +000010518 // Ignore checking string literals that are in logical and operators.
10519 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +000010520 continue;
10521 AnalyzeImplicitConversions(S, ChildExpr, CC);
10522 }
Richard Trieu791b86e2014-11-19 06:08:18 +000010523
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000010524 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +000010525 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
10526 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +000010527 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +000010528
10529 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
10530 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +000010531 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000010532 }
Richard Trieu791b86e2014-11-19 06:08:18 +000010533
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000010534 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
10535 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +000010536 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010537}
10538
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +000010539/// Diagnose integer type and any valid implicit conversion to it.
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000010540static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
10541 // Taking into account implicit conversions,
10542 // allow any integer.
10543 if (!E->getType()->isIntegerType()) {
10544 S.Diag(E->getLocStart(),
10545 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
10546 return true;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010547 }
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000010548 // Potentially emit standard warnings for implicit conversions if enabled
10549 // using -Wconversion.
10550 CheckImplicitConversion(S, E, IntT, E->getLocStart());
10551 return false;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010552}
10553
Richard Trieuc1888e02014-06-28 23:25:37 +000010554// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
10555// Returns true when emitting a warning about taking the address of a reference.
10556static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +000010557 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +000010558 E = E->IgnoreParenImpCasts();
10559
10560 const FunctionDecl *FD = nullptr;
10561
10562 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10563 if (!DRE->getDecl()->getType()->isReferenceType())
10564 return false;
10565 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10566 if (!M->getMemberDecl()->getType()->isReferenceType())
10567 return false;
10568 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +000010569 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +000010570 return false;
10571 FD = Call->getDirectCallee();
10572 } else {
10573 return false;
10574 }
10575
10576 SemaRef.Diag(E->getExprLoc(), PD);
10577
10578 // If possible, point to location of function.
10579 if (FD) {
10580 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
10581 }
10582
10583 return true;
10584}
10585
Richard Trieu4cbff5c2014-08-08 22:41:43 +000010586// Returns true if the SourceLocation is expanded from any macro body.
10587// Returns false if the SourceLocation is invalid, is from not in a macro
10588// expansion, or is from expanded from a top-level macro argument.
10589static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
10590 if (Loc.isInvalid())
10591 return false;
10592
10593 while (Loc.isMacroID()) {
10594 if (SM.isMacroBodyExpansion(Loc))
10595 return true;
10596 Loc = SM.getImmediateMacroCallerLoc(Loc);
10597 }
10598
10599 return false;
10600}
10601
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010602/// Diagnose pointers that are always non-null.
Richard Trieu3bb8b562014-02-26 02:36:06 +000010603/// \param E the expression containing the pointer
10604/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
10605/// compared to a null pointer
10606/// \param IsEqual True when the comparison is equal to a null pointer
10607/// \param Range Extra SourceRange to highlight in the diagnostic
10608void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
10609 Expr::NullPointerConstantKind NullKind,
10610 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +000010611 if (!E)
10612 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010613
10614 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +000010615 if (E->getExprLoc().isMacroID()) {
10616 const SourceManager &SM = getSourceManager();
10617 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
10618 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +000010619 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +000010620 }
Richard Trieu3bb8b562014-02-26 02:36:06 +000010621 E = E->IgnoreImpCasts();
10622
10623 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
10624
Richard Trieuf7432752014-06-06 21:39:26 +000010625 if (isa<CXXThisExpr>(E)) {
10626 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
10627 : diag::warn_this_bool_conversion;
10628 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
10629 return;
10630 }
10631
Richard Trieu3bb8b562014-02-26 02:36:06 +000010632 bool IsAddressOf = false;
10633
10634 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10635 if (UO->getOpcode() != UO_AddrOf)
10636 return;
10637 IsAddressOf = true;
10638 E = UO->getSubExpr();
10639 }
10640
Richard Trieuc1888e02014-06-28 23:25:37 +000010641 if (IsAddressOf) {
10642 unsigned DiagID = IsCompare
10643 ? diag::warn_address_of_reference_null_compare
10644 : diag::warn_address_of_reference_bool_conversion;
10645 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
10646 << IsEqual;
10647 if (CheckForReference(*this, E, PD)) {
10648 return;
10649 }
10650 }
10651
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010652 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
10653 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +000010654 std::string Str;
10655 llvm::raw_string_ostream S(Str);
10656 E->printPretty(S, nullptr, getPrintingPolicy());
10657 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
10658 : diag::warn_cast_nonnull_to_bool;
10659 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
10660 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010661 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +000010662 };
10663
10664 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
10665 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
10666 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010667 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
10668 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000010669 return;
10670 }
10671 }
10672 }
10673
Richard Trieu3bb8b562014-02-26 02:36:06 +000010674 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +000010675 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010676 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
10677 D = R->getDecl();
10678 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10679 D = M->getMemberDecl();
10680 }
10681
10682 // Weak Decls can be null.
10683 if (!D || D->isWeak())
10684 return;
George Burgess IV850269a2015-12-08 22:02:00 +000010685
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010686 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +000010687 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
10688 if (getCurFunction() &&
10689 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010690 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
10691 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000010692 return;
10693 }
10694
10695 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +000010696 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +000010697 assert(ParamIter != FD->param_end());
10698 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
10699
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010700 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
10701 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010702 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +000010703 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010704 }
George Burgess IV850269a2015-12-08 22:02:00 +000010705
Joel E. Denny81508102018-03-13 14:51:22 +000010706 for (const ParamIdx &ArgNo : NonNull->args()) {
10707 if (ArgNo.getASTIndex() == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010708 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010709 return;
10710 }
George Burgess IV850269a2015-12-08 22:02:00 +000010711 }
10712 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010713 }
10714 }
George Burgess IV850269a2015-12-08 22:02:00 +000010715 }
10716
Richard Trieu3bb8b562014-02-26 02:36:06 +000010717 QualType T = D->getType();
10718 const bool IsArray = T->isArrayType();
10719 const bool IsFunction = T->isFunctionType();
10720
Richard Trieuc1888e02014-06-28 23:25:37 +000010721 // Address of function is used to silence the function warning.
10722 if (IsAddressOf && IsFunction) {
10723 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010724 }
10725
10726 // Found nothing.
10727 if (!IsAddressOf && !IsFunction && !IsArray)
10728 return;
10729
10730 // Pretty print the expression for the diagnostic.
10731 std::string Str;
10732 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +000010733 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +000010734
10735 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
10736 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +000010737 enum {
10738 AddressOf,
10739 FunctionPointer,
10740 ArrayPointer
10741 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010742 if (IsAddressOf)
10743 DiagType = AddressOf;
10744 else if (IsFunction)
10745 DiagType = FunctionPointer;
10746 else if (IsArray)
10747 DiagType = ArrayPointer;
10748 else
10749 llvm_unreachable("Could not determine diagnostic.");
10750 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
10751 << Range << IsEqual;
10752
10753 if (!IsFunction)
10754 return;
10755
10756 // Suggest '&' to silence the function warning.
10757 Diag(E->getExprLoc(), diag::note_function_warning_silence)
10758 << FixItHint::CreateInsertion(E->getLocStart(), "&");
10759
10760 // Check to see if '()' fixit should be emitted.
10761 QualType ReturnType;
10762 UnresolvedSet<4> NonTemplateOverloads;
10763 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
10764 if (ReturnType.isNull())
10765 return;
10766
10767 if (IsCompare) {
10768 // There are two cases here. If there is null constant, the only suggest
10769 // for a pointer return type. If the null is 0, then suggest if the return
10770 // type is a pointer or an integer type.
10771 if (!ReturnType->isPointerType()) {
10772 if (NullKind == Expr::NPCK_ZeroExpression ||
10773 NullKind == Expr::NPCK_ZeroLiteral) {
10774 if (!ReturnType->isIntegerType())
10775 return;
10776 } else {
10777 return;
10778 }
10779 }
10780 } else { // !IsCompare
10781 // For function to bool, only suggest if the function pointer has bool
10782 // return type.
10783 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
10784 return;
10785 }
10786 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +000010787 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +000010788}
10789
John McCallcc7e5bf2010-05-06 08:58:33 +000010790/// Diagnoses "dangerous" implicit conversions within the given
10791/// expression (which is a full expression). Implements -Wconversion
10792/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +000010793///
10794/// \param CC the "context" location of the implicit conversion, i.e.
10795/// the most location of the syntactic entity requiring the implicit
10796/// conversion
10797void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010798 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +000010799 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +000010800 return;
10801
10802 // Don't diagnose for value- or type-dependent expressions.
10803 if (E->isTypeDependent() || E->isValueDependent())
10804 return;
10805
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010806 // Check for array bounds violations in cases where the check isn't triggered
10807 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
10808 // ArraySubscriptExpr is on the RHS of a variable initialization.
10809 CheckArrayAccess(E);
10810
John McCallacf0ee52010-10-08 02:01:28 +000010811 // This is not the right CC for (e.g.) a variable initialization.
10812 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010813}
10814
Richard Trieu65724892014-11-15 06:37:39 +000010815/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10816/// Input argument E is a logical expression.
10817void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
10818 ::CheckBoolLikeConversion(*this, E, CC);
10819}
10820
Richard Smith9f7df0c2017-06-26 23:19:32 +000010821/// Diagnose when expression is an integer constant expression and its evaluation
10822/// results in integer overflow
10823void Sema::CheckForIntOverflow (Expr *E) {
10824 // Use a work list to deal with nested struct initializers.
10825 SmallVector<Expr *, 2> Exprs(1, E);
10826
10827 do {
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010828 Expr *OriginalE = Exprs.pop_back_val();
10829 Expr *E = OriginalE->IgnoreParenCasts();
Richard Smith9f7df0c2017-06-26 23:19:32 +000010830
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010831 if (isa<BinaryOperator>(E)) {
10832 E->EvaluateForOverflow(Context);
Richard Smith9f7df0c2017-06-26 23:19:32 +000010833 continue;
10834 }
10835
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010836 if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
Richard Smith9f7df0c2017-06-26 23:19:32 +000010837 Exprs.append(InitList->inits().begin(), InitList->inits().end());
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010838 else if (isa<ObjCBoxedExpr>(OriginalE))
10839 E->EvaluateForOverflow(Context);
10840 else if (auto Call = dyn_cast<CallExpr>(E))
10841 Exprs.append(Call->arg_begin(), Call->arg_end());
10842 else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
10843 Exprs.append(Message->arg_begin(), Message->arg_end());
Richard Smith9f7df0c2017-06-26 23:19:32 +000010844 } while (!Exprs.empty());
10845}
10846
Richard Smithc406cb72013-01-17 01:17:56 +000010847namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010848
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010849/// Visitor for expressions which looks for unsequenced operations on the
Richard Smithc406cb72013-01-17 01:17:56 +000010850/// same object.
10851class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010852 using Base = EvaluatedExprVisitor<SequenceChecker>;
Richard Smithe3dbfe02013-06-30 10:40:20 +000010853
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010854 /// A tree of sequenced regions within an expression. Two regions are
Richard Smithc406cb72013-01-17 01:17:56 +000010855 /// unsequenced if one is an ancestor or a descendent of the other. When we
10856 /// finish processing an expression with sequencing, such as a comma
10857 /// expression, we fold its tree nodes into its parent, since they are
10858 /// unsequenced with respect to nodes we will visit later.
10859 class SequenceTree {
10860 struct Value {
10861 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
10862 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +000010863 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +000010864 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010865 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +000010866
10867 public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010868 /// A region within an expression which may be sequenced with respect
Richard Smithc406cb72013-01-17 01:17:56 +000010869 /// to some other region.
10870 class Seq {
Richard Smithc406cb72013-01-17 01:17:56 +000010871 friend class SequenceTree;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010872
10873 unsigned Index = 0;
10874
10875 explicit Seq(unsigned N) : Index(N) {}
10876
Richard Smithc406cb72013-01-17 01:17:56 +000010877 public:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010878 Seq() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010879 };
10880
10881 SequenceTree() { Values.push_back(Value(0)); }
10882 Seq root() const { return Seq(0); }
10883
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010884 /// Create a new sequence of operations, which is an unsequenced
Richard Smithc406cb72013-01-17 01:17:56 +000010885 /// subset of \p Parent. This sequence of operations is sequenced with
10886 /// respect to other children of \p Parent.
10887 Seq allocate(Seq Parent) {
10888 Values.push_back(Value(Parent.Index));
10889 return Seq(Values.size() - 1);
10890 }
10891
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010892 /// Merge a sequence of operations into its parent.
Richard Smithc406cb72013-01-17 01:17:56 +000010893 void merge(Seq S) {
10894 Values[S.Index].Merged = true;
10895 }
10896
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010897 /// Determine whether two operations are unsequenced. This operation
Richard Smithc406cb72013-01-17 01:17:56 +000010898 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
10899 /// should have been merged into its parent as appropriate.
10900 bool isUnsequenced(Seq Cur, Seq Old) {
10901 unsigned C = representative(Cur.Index);
10902 unsigned Target = representative(Old.Index);
10903 while (C >= Target) {
10904 if (C == Target)
10905 return true;
10906 C = Values[C].Parent;
10907 }
10908 return false;
10909 }
10910
10911 private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010912 /// Pick a representative for a sequence.
Richard Smithc406cb72013-01-17 01:17:56 +000010913 unsigned representative(unsigned K) {
10914 if (Values[K].Merged)
10915 // Perform path compression as we go.
10916 return Values[K].Parent = representative(Values[K].Parent);
10917 return K;
10918 }
10919 };
10920
10921 /// An object for which we can track unsequenced uses.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010922 using Object = NamedDecl *;
Richard Smithc406cb72013-01-17 01:17:56 +000010923
10924 /// Different flavors of object usage which we track. We only track the
10925 /// least-sequenced usage of each kind.
10926 enum UsageKind {
10927 /// A read of an object. Multiple unsequenced reads are OK.
10928 UK_Use,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010929
Richard Smithc406cb72013-01-17 01:17:56 +000010930 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +000010931 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +000010932 UK_ModAsValue,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010933
Richard Smithc406cb72013-01-17 01:17:56 +000010934 /// A modification of an object which is not sequenced before the value
10935 /// computation of the expression, such as n++.
10936 UK_ModAsSideEffect,
10937
10938 UK_Count = UK_ModAsSideEffect + 1
10939 };
10940
10941 struct Usage {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010942 Expr *Use = nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000010943 SequenceTree::Seq Seq;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010944
10945 Usage() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010946 };
10947
10948 struct UsageInfo {
Richard Smithc406cb72013-01-17 01:17:56 +000010949 Usage Uses[UK_Count];
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010950
Richard Smithc406cb72013-01-17 01:17:56 +000010951 /// Have we issued a diagnostic for this variable already?
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010952 bool Diagnosed = false;
10953
10954 UsageInfo() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010955 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010956 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
Richard Smithc406cb72013-01-17 01:17:56 +000010957
10958 Sema &SemaRef;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010959
Richard Smithc406cb72013-01-17 01:17:56 +000010960 /// Sequenced regions within the expression.
10961 SequenceTree Tree;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010962
Richard Smithc406cb72013-01-17 01:17:56 +000010963 /// Declaration modifications and references which we have seen.
10964 UsageInfoMap UsageMap;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010965
Richard Smithc406cb72013-01-17 01:17:56 +000010966 /// The region we are currently within.
10967 SequenceTree::Seq Region;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010968
Richard Smithc406cb72013-01-17 01:17:56 +000010969 /// Filled in with declarations which were modified as a side-effect
10970 /// (that is, post-increment operations).
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010971 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
10972
Richard Smithd33f5202013-01-17 23:18:09 +000010973 /// Expressions to check later. We defer checking these to reduce
10974 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010975 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +000010976
10977 /// RAII object wrapping the visitation of a sequenced subexpression of an
10978 /// expression. At the end of this process, the side-effects of the evaluation
10979 /// become sequenced with respect to the value computation of the result, so
10980 /// we downgrade any UK_ModAsSideEffect within the evaluation to
10981 /// UK_ModAsValue.
10982 struct SequencedSubexpression {
10983 SequencedSubexpression(SequenceChecker &Self)
10984 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
10985 Self.ModAsSideEffect = &ModAsSideEffect;
10986 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010987
Richard Smithc406cb72013-01-17 01:17:56 +000010988 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +000010989 for (auto &M : llvm::reverse(ModAsSideEffect)) {
10990 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +000010991 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +000010992 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
10993 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +000010994 }
10995 Self.ModAsSideEffect = OldModAsSideEffect;
10996 }
10997
10998 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010999 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011000 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +000011001 };
11002
Richard Smith40238f02013-06-20 22:21:56 +000011003 /// RAII object wrapping the visitation of a subexpression which we might
11004 /// choose to evaluate as a constant. If any subexpression is evaluated and
11005 /// found to be non-constant, this allows us to suppress the evaluation of
11006 /// the outer expression.
11007 class EvaluationTracker {
11008 public:
11009 EvaluationTracker(SequenceChecker &Self)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011010 : Self(Self), Prev(Self.EvalTracker) {
Richard Smith40238f02013-06-20 22:21:56 +000011011 Self.EvalTracker = this;
11012 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011013
Richard Smith40238f02013-06-20 22:21:56 +000011014 ~EvaluationTracker() {
11015 Self.EvalTracker = Prev;
11016 if (Prev)
11017 Prev->EvalOK &= EvalOK;
11018 }
11019
11020 bool evaluate(const Expr *E, bool &Result) {
11021 if (!EvalOK || E->isValueDependent())
11022 return false;
11023 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
11024 return EvalOK;
11025 }
11026
11027 private:
11028 SequenceChecker &Self;
11029 EvaluationTracker *Prev;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011030 bool EvalOK = true;
11031 } *EvalTracker = nullptr;
Richard Smith40238f02013-06-20 22:21:56 +000011032
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011033 /// Find the object which is produced by the specified expression,
Richard Smithc406cb72013-01-17 01:17:56 +000011034 /// if any.
11035 Object getObject(Expr *E, bool Mod) const {
11036 E = E->IgnoreParenCasts();
11037 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
11038 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
11039 return getObject(UO->getSubExpr(), Mod);
11040 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11041 if (BO->getOpcode() == BO_Comma)
11042 return getObject(BO->getRHS(), Mod);
11043 if (Mod && BO->isAssignmentOp())
11044 return getObject(BO->getLHS(), Mod);
11045 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
11046 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
11047 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
11048 return ME->getMemberDecl();
11049 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11050 // FIXME: If this is a reference, map through to its value.
11051 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +000011052 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000011053 }
11054
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011055 /// Note that an object was modified or used by an expression.
Richard Smithc406cb72013-01-17 01:17:56 +000011056 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
11057 Usage &U = UI.Uses[UK];
11058 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
11059 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
11060 ModAsSideEffect->push_back(std::make_pair(O, U));
11061 U.Use = Ref;
11062 U.Seq = Region;
11063 }
11064 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011065
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011066 /// Check whether a modification or use conflicts with a prior usage.
Richard Smithc406cb72013-01-17 01:17:56 +000011067 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
11068 bool IsModMod) {
11069 if (UI.Diagnosed)
11070 return;
11071
11072 const Usage &U = UI.Uses[OtherKind];
11073 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
11074 return;
11075
11076 Expr *Mod = U.Use;
11077 Expr *ModOrUse = Ref;
11078 if (OtherKind == UK_Use)
11079 std::swap(Mod, ModOrUse);
11080
11081 SemaRef.Diag(Mod->getExprLoc(),
11082 IsModMod ? diag::warn_unsequenced_mod_mod
11083 : diag::warn_unsequenced_mod_use)
11084 << O << SourceRange(ModOrUse->getExprLoc());
11085 UI.Diagnosed = true;
11086 }
11087
11088 void notePreUse(Object O, Expr *Use) {
11089 UsageInfo &U = UsageMap[O];
11090 // Uses conflict with other modifications.
11091 checkUsage(O, U, Use, UK_ModAsValue, false);
11092 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011093
Richard Smithc406cb72013-01-17 01:17:56 +000011094 void notePostUse(Object O, Expr *Use) {
11095 UsageInfo &U = UsageMap[O];
11096 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
11097 addUsage(U, O, Use, UK_Use);
11098 }
11099
11100 void notePreMod(Object O, Expr *Mod) {
11101 UsageInfo &U = UsageMap[O];
11102 // Modifications conflict with other modifications and with uses.
11103 checkUsage(O, U, Mod, UK_ModAsValue, true);
11104 checkUsage(O, U, Mod, UK_Use, false);
11105 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011106
Richard Smithc406cb72013-01-17 01:17:56 +000011107 void notePostMod(Object O, Expr *Use, UsageKind UK) {
11108 UsageInfo &U = UsageMap[O];
11109 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
11110 addUsage(U, O, Use, UK);
11111 }
11112
11113public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011114 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011115 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
Richard Smithc406cb72013-01-17 01:17:56 +000011116 Visit(E);
11117 }
11118
11119 void VisitStmt(Stmt *S) {
11120 // Skip all statements which aren't expressions for now.
11121 }
11122
11123 void VisitExpr(Expr *E) {
11124 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +000011125 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +000011126 }
11127
11128 void VisitCastExpr(CastExpr *E) {
11129 Object O = Object();
11130 if (E->getCastKind() == CK_LValueToRValue)
11131 O = getObject(E->getSubExpr(), false);
11132
11133 if (O)
11134 notePreUse(O, E);
11135 VisitExpr(E);
11136 if (O)
11137 notePostUse(O, E);
11138 }
11139
11140 void VisitBinComma(BinaryOperator *BO) {
11141 // C++11 [expr.comma]p1:
11142 // Every value computation and side effect associated with the left
11143 // expression is sequenced before every value computation and side
11144 // effect associated with the right expression.
11145 SequenceTree::Seq LHS = Tree.allocate(Region);
11146 SequenceTree::Seq RHS = Tree.allocate(Region);
11147 SequenceTree::Seq OldRegion = Region;
11148
11149 {
11150 SequencedSubexpression SeqLHS(*this);
11151 Region = LHS;
11152 Visit(BO->getLHS());
11153 }
11154
11155 Region = RHS;
11156 Visit(BO->getRHS());
11157
11158 Region = OldRegion;
11159
11160 // Forget that LHS and RHS are sequenced. They are both unsequenced
11161 // with respect to other stuff.
11162 Tree.merge(LHS);
11163 Tree.merge(RHS);
11164 }
11165
11166 void VisitBinAssign(BinaryOperator *BO) {
11167 // The modification is sequenced after the value computation of the LHS
11168 // and RHS, so check it before inspecting the operands and update the
11169 // map afterwards.
11170 Object O = getObject(BO->getLHS(), true);
11171 if (!O)
11172 return VisitExpr(BO);
11173
11174 notePreMod(O, BO);
11175
11176 // C++11 [expr.ass]p7:
11177 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
11178 // only once.
11179 //
11180 // Therefore, for a compound assignment operator, O is considered used
11181 // everywhere except within the evaluation of E1 itself.
11182 if (isa<CompoundAssignOperator>(BO))
11183 notePreUse(O, BO);
11184
11185 Visit(BO->getLHS());
11186
11187 if (isa<CompoundAssignOperator>(BO))
11188 notePostUse(O, BO);
11189
11190 Visit(BO->getRHS());
11191
Richard Smith83e37bee2013-06-26 23:16:51 +000011192 // C++11 [expr.ass]p1:
11193 // the assignment is sequenced [...] before the value computation of the
11194 // assignment expression.
11195 // C11 6.5.16/3 has no such rule.
11196 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
11197 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000011198 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011199
Richard Smithc406cb72013-01-17 01:17:56 +000011200 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
11201 VisitBinAssign(CAO);
11202 }
11203
11204 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
11205 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
11206 void VisitUnaryPreIncDec(UnaryOperator *UO) {
11207 Object O = getObject(UO->getSubExpr(), true);
11208 if (!O)
11209 return VisitExpr(UO);
11210
11211 notePreMod(O, UO);
11212 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +000011213 // C++11 [expr.pre.incr]p1:
11214 // the expression ++x is equivalent to x+=1
11215 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
11216 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000011217 }
11218
11219 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
11220 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
11221 void VisitUnaryPostIncDec(UnaryOperator *UO) {
11222 Object O = getObject(UO->getSubExpr(), true);
11223 if (!O)
11224 return VisitExpr(UO);
11225
11226 notePreMod(O, UO);
11227 Visit(UO->getSubExpr());
11228 notePostMod(O, UO, UK_ModAsSideEffect);
11229 }
11230
11231 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
11232 void VisitBinLOr(BinaryOperator *BO) {
11233 // The side-effects of the LHS of an '&&' are sequenced before the
11234 // value computation of the RHS, and hence before the value computation
11235 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
11236 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +000011237 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000011238 {
11239 SequencedSubexpression Sequenced(*this);
11240 Visit(BO->getLHS());
11241 }
11242
11243 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000011244 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000011245 if (!Result)
11246 Visit(BO->getRHS());
11247 } else {
11248 // Check for unsequenced operations in the RHS, treating it as an
11249 // entirely separate evaluation.
11250 //
11251 // FIXME: If there are operations in the RHS which are unsequenced
11252 // with respect to operations outside the RHS, and those operations
11253 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +000011254 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000011255 }
Richard Smithc406cb72013-01-17 01:17:56 +000011256 }
11257 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +000011258 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000011259 {
11260 SequencedSubexpression Sequenced(*this);
11261 Visit(BO->getLHS());
11262 }
11263
11264 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000011265 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000011266 if (Result)
11267 Visit(BO->getRHS());
11268 } else {
Richard Smithd33f5202013-01-17 23:18:09 +000011269 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000011270 }
Richard Smithc406cb72013-01-17 01:17:56 +000011271 }
11272
11273 // Only visit the condition, unless we can be sure which subexpression will
11274 // be chosen.
11275 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +000011276 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +000011277 {
11278 SequencedSubexpression Sequenced(*this);
11279 Visit(CO->getCond());
11280 }
Richard Smithc406cb72013-01-17 01:17:56 +000011281
11282 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000011283 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +000011284 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000011285 else {
Richard Smithd33f5202013-01-17 23:18:09 +000011286 WorkList.push_back(CO->getTrueExpr());
11287 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000011288 }
Richard Smithc406cb72013-01-17 01:17:56 +000011289 }
11290
Richard Smithe3dbfe02013-06-30 10:40:20 +000011291 void VisitCallExpr(CallExpr *CE) {
11292 // C++11 [intro.execution]p15:
11293 // When calling a function [...], every value computation and side effect
11294 // associated with any argument expression, or with the postfix expression
11295 // designating the called function, is sequenced before execution of every
11296 // expression or statement in the body of the function [and thus before
11297 // the value computation of its result].
11298 SequencedSubexpression Sequenced(*this);
11299 Base::VisitCallExpr(CE);
11300
11301 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
11302 }
11303
Richard Smithc406cb72013-01-17 01:17:56 +000011304 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +000011305 // This is a call, so all subexpressions are sequenced before the result.
11306 SequencedSubexpression Sequenced(*this);
11307
Richard Smithc406cb72013-01-17 01:17:56 +000011308 if (!CCE->isListInitialization())
11309 return VisitExpr(CCE);
11310
11311 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011312 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000011313 SequenceTree::Seq Parent = Region;
11314 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
11315 E = CCE->arg_end();
11316 I != E; ++I) {
11317 Region = Tree.allocate(Parent);
11318 Elts.push_back(Region);
11319 Visit(*I);
11320 }
11321
11322 // Forget that the initializers are sequenced.
11323 Region = Parent;
11324 for (unsigned I = 0; I < Elts.size(); ++I)
11325 Tree.merge(Elts[I]);
11326 }
11327
11328 void VisitInitListExpr(InitListExpr *ILE) {
11329 if (!SemaRef.getLangOpts().CPlusPlus11)
11330 return VisitExpr(ILE);
11331
11332 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011333 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000011334 SequenceTree::Seq Parent = Region;
11335 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
11336 Expr *E = ILE->getInit(I);
11337 if (!E) continue;
11338 Region = Tree.allocate(Parent);
11339 Elts.push_back(Region);
11340 Visit(E);
11341 }
11342
11343 // Forget that the initializers are sequenced.
11344 Region = Parent;
11345 for (unsigned I = 0; I < Elts.size(); ++I)
11346 Tree.merge(Elts[I]);
11347 }
11348};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011349
11350} // namespace
Richard Smithc406cb72013-01-17 01:17:56 +000011351
11352void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011353 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +000011354 WorkList.push_back(E);
11355 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +000011356 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +000011357 SequenceChecker(*this, Item, WorkList);
11358 }
Richard Smithc406cb72013-01-17 01:17:56 +000011359}
11360
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011361void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
11362 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +000011363 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +000011364 if (!E->isInstantiationDependent())
11365 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011366 if (!IsConstexpr && !E->isValueDependent())
Richard Smith9f7df0c2017-06-26 23:19:32 +000011367 CheckForIntOverflow(E);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011368 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +000011369}
11370
John McCall1f425642010-11-11 03:21:53 +000011371void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
11372 FieldDecl *BitField,
11373 Expr *Init) {
11374 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
11375}
11376
David Majnemer61a5bbf2015-04-07 22:08:51 +000011377static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
11378 SourceLocation Loc) {
11379 if (!PType->isVariablyModifiedType())
11380 return;
11381 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
11382 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
11383 return;
11384 }
David Majnemerdf8f73f2015-04-09 19:53:25 +000011385 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
11386 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
11387 return;
11388 }
David Majnemer61a5bbf2015-04-07 22:08:51 +000011389 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
11390 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
11391 return;
11392 }
11393
11394 const ArrayType *AT = S.Context.getAsArrayType(PType);
11395 if (!AT)
11396 return;
11397
11398 if (AT->getSizeModifier() != ArrayType::Star) {
11399 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
11400 return;
11401 }
11402
11403 S.Diag(Loc, diag::err_array_star_in_function_definition);
11404}
11405
Mike Stump0c2ec772010-01-21 03:59:47 +000011406/// CheckParmsForFunctionDef - Check that the parameters of the given
11407/// function are appropriate for the definition of a function. This
11408/// takes care of any checks that cannot be performed on the
11409/// declaration itself, e.g., that the types of each of the function
11410/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +000011411bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +000011412 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +000011413 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +000011414 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +000011415 // C99 6.7.5.3p4: the parameters in a parameter type list in a
11416 // function declarator that is part of a function definition of
11417 // that function shall not have incomplete type.
11418 //
11419 // This is also C++ [dcl.fct]p6.
11420 if (!Param->isInvalidDecl() &&
11421 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011422 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +000011423 Param->setInvalidDecl();
11424 HasInvalidParm = true;
11425 }
11426
11427 // C99 6.9.1p5: If the declarator includes a parameter type list, the
11428 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +000011429 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +000011430 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +000011431 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000011432 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +000011433 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +000011434
11435 // C99 6.7.5.3p12:
11436 // If the function declarator is not part of a definition of that
11437 // function, parameters may have incomplete type and may use the [*]
11438 // notation in their sequences of declarator specifiers to specify
11439 // variable length array types.
11440 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +000011441 // FIXME: This diagnostic should point the '[*]' if source-location
11442 // information is added for it.
11443 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000011444
Akira Hatanaka02914dc2018-02-05 20:23:22 +000011445 // If the parameter is a c++ class type and it has to be destructed in the
11446 // callee function, declare the destructor so that it can be called by the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +000011447 // callee function. Do not perform any direct access check on the dtor here.
Akira Hatanaka02914dc2018-02-05 20:23:22 +000011448 if (!Param->isInvalidDecl()) {
11449 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
11450 if (!ClassDecl->isInvalidDecl() &&
11451 !ClassDecl->hasIrrelevantDestructor() &&
11452 !ClassDecl->isDependentContext() &&
Akira Hatanaka85282972018-05-15 21:00:30 +000011453 ClassDecl->isParamDestroyedInCallee()) {
Akira Hatanaka02914dc2018-02-05 20:23:22 +000011454 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
11455 MarkFunctionReferenced(Param->getLocation(), Destructor);
11456 DiagnoseUseOfDecl(Destructor, Param->getLocation());
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000011457 }
11458 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000011459 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011460
11461 // Parameters with the pass_object_size attribute only need to be marked
11462 // constant at function definitions. Because we lack information about
11463 // whether we're on a declaration or definition when we're instantiating the
11464 // attribute, we need to check for constness here.
11465 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
11466 if (!Param->getType().isConstQualified())
11467 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
11468 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +000011469 }
11470
11471 return HasInvalidParm;
11472}
John McCall2b5c1b22010-08-12 21:44:57 +000011473
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000011474/// A helper function to get the alignment of a Decl referred to by DeclRefExpr
11475/// or MemberExpr.
11476static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
11477 ASTContext &Context) {
11478 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
11479 return Context.getDeclAlign(DRE->getDecl());
11480
11481 if (const auto *ME = dyn_cast<MemberExpr>(E))
11482 return Context.getDeclAlign(ME->getMemberDecl());
11483
11484 return TypeAlign;
11485}
11486
John McCall2b5c1b22010-08-12 21:44:57 +000011487/// CheckCastAlign - Implements -Wcast-align, which warns when a
11488/// pointer cast increases the alignment requirements.
11489void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
11490 // This is actually a lot of work to potentially be doing on every
11491 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011492 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +000011493 return;
11494
11495 // Ignore dependent types.
11496 if (T->isDependentType() || Op->getType()->isDependentType())
11497 return;
11498
11499 // Require that the destination be a pointer type.
11500 const PointerType *DestPtr = T->getAs<PointerType>();
11501 if (!DestPtr) return;
11502
11503 // If the destination has alignment 1, we're done.
11504 QualType DestPointee = DestPtr->getPointeeType();
11505 if (DestPointee->isIncompleteType()) return;
11506 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
11507 if (DestAlign.isOne()) return;
11508
11509 // Require that the source be a pointer type.
11510 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
11511 if (!SrcPtr) return;
11512 QualType SrcPointee = SrcPtr->getPointeeType();
11513
11514 // Whitelist casts from cv void*. We already implicitly
11515 // whitelisted casts to cv void*, since they have alignment 1.
11516 // Also whitelist casts involving incomplete types, which implicitly
11517 // includes 'void'.
11518 if (SrcPointee->isIncompleteType()) return;
11519
11520 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000011521
11522 if (auto *CE = dyn_cast<CastExpr>(Op)) {
11523 if (CE->getCastKind() == CK_ArrayToPointerDecay)
11524 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
11525 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
11526 if (UO->getOpcode() == UO_AddrOf)
11527 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
11528 }
11529
John McCall2b5c1b22010-08-12 21:44:57 +000011530 if (SrcAlign >= DestAlign) return;
11531
11532 Diag(TRange.getBegin(), diag::warn_cast_align)
11533 << Op->getType() << T
11534 << static_cast<unsigned>(SrcAlign.getQuantity())
11535 << static_cast<unsigned>(DestAlign.getQuantity())
11536 << TRange << Op->getSourceRange();
11537}
11538
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011539/// Check whether this array fits the idiom of a size-one tail padded
Chandler Carruth28389f02011-08-05 09:10:50 +000011540/// array member of a struct.
11541///
11542/// We avoid emitting out-of-bounds access warnings for such arrays as they are
11543/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +000011544static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +000011545 const NamedDecl *ND) {
11546 if (Size != 1 || !ND) return false;
11547
11548 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
11549 if (!FD) return false;
11550
11551 // Don't consider sizes resulting from macro expansions or template argument
11552 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +000011553
11554 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000011555 while (TInfo) {
11556 TypeLoc TL = TInfo->getTypeLoc();
11557 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +000011558 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
11559 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000011560 TInfo = TDL->getTypeSourceInfo();
11561 continue;
11562 }
David Blaikie6adc78e2013-02-18 22:06:02 +000011563 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
11564 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +000011565 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
11566 return false;
11567 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +000011568 break;
Sean Callanan06a48a62012-05-04 18:22:53 +000011569 }
Chandler Carruth28389f02011-08-05 09:10:50 +000011570
11571 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +000011572 if (!RD) return false;
11573 if (RD->isUnion()) return false;
11574 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
11575 if (!CRD->isStandardLayout()) return false;
11576 }
Chandler Carruth28389f02011-08-05 09:10:50 +000011577
Benjamin Kramer8c543672011-08-06 03:04:42 +000011578 // See if this is the last field decl in the record.
11579 const Decl *D = FD;
11580 while ((D = D->getNextDeclInContext()))
11581 if (isa<FieldDecl>(D))
11582 return false;
11583 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +000011584}
11585
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011586void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011587 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +000011588 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011589 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011590 if (IndexExpr->isValueDependent())
11591 return;
11592
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000011593 const Type *EffectiveType =
11594 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011595 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011596 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011597 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011598 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +000011599 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +000011600
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011601 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +000011602 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +000011603 return;
Richard Smith13f67182011-12-16 19:31:14 +000011604 if (IndexNegated)
11605 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +000011606
Craig Topperc3ec1492014-05-26 06:22:03 +000011607 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +000011608 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011609 ND = DRE->getDecl();
Chandler Carruth28389f02011-08-05 09:10:50 +000011610 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011611 ND = ME->getMemberDecl();
Chandler Carruth126b1552011-08-05 08:07:29 +000011612
Ted Kremeneke4b316c2011-02-23 23:06:04 +000011613 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011614 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +000011615 if (!size.isStrictlyPositive())
11616 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011617
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000011618 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +000011619 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011620 // Make sure we're comparing apples to apples when comparing index to size
11621 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
11622 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +000011623 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +000011624 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011625 if (ptrarith_typesize != array_typesize) {
11626 // There's a cast to a different size type involved
11627 uint64_t ratio = array_typesize / ptrarith_typesize;
11628 // TODO: Be smarter about handling cases where array_typesize is not a
11629 // multiple of ptrarith_typesize
11630 if (ptrarith_typesize * ratio == array_typesize)
11631 size *= llvm::APInt(size.getBitWidth(), ratio);
11632 }
11633 }
11634
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011635 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011636 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011637 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011638 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011639
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011640 // For array subscripting the index must be less than size, but for pointer
11641 // arithmetic also allow the index (offset) to be equal to size since
11642 // computing the next address after the end of the array is legal and
11643 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011644 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +000011645 return;
11646
11647 // Also don't warn for arrays of size 1 which are members of some
11648 // structure. These are often used to approximate flexible arrays in C89
11649 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011650 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +000011651 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011652
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011653 // Suppress the warning if the subscript expression (as identified by the
11654 // ']' location) and the index expression are both from macro expansions
11655 // within a system header.
11656 if (ASE) {
11657 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
11658 ASE->getRBracketLoc());
11659 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
11660 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
11661 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +000011662 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011663 return;
11664 }
11665 }
11666
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011667 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011668 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011669 DiagID = diag::warn_array_index_exceeds_bounds;
11670
11671 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11672 PDiag(DiagID) << index.toString(10, true)
11673 << size.toString(10, true)
11674 << (unsigned)size.getLimitedValue(~0U)
11675 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011676 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011677 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011678 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011679 DiagID = diag::warn_ptr_arith_precedes_bounds;
11680 if (index.isNegative()) index = -index;
11681 }
11682
11683 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11684 PDiag(DiagID) << index.toString(10, true)
11685 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +000011686 }
Chandler Carruth1af88f12011-02-17 21:10:52 +000011687
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000011688 if (!ND) {
11689 // Try harder to find a NamedDecl to point at in the note.
11690 while (const ArraySubscriptExpr *ASE =
11691 dyn_cast<ArraySubscriptExpr>(BaseExpr))
11692 BaseExpr = ASE->getBase()->IgnoreParenCasts();
11693 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011694 ND = DRE->getDecl();
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000011695 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011696 ND = ME->getMemberDecl();
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000011697 }
11698
Chandler Carruth1af88f12011-02-17 21:10:52 +000011699 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011700 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
11701 PDiag(diag::note_array_index_out_of_bounds)
11702 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +000011703}
11704
Ted Kremenekdf26df72011-03-01 18:41:00 +000011705void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011706 int AllowOnePastEnd = 0;
11707 while (expr) {
11708 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +000011709 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011710 case Stmt::ArraySubscriptExprClass: {
11711 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011712 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011713 AllowOnePastEnd > 0);
Aaron Ballman93c6ba12018-04-24 19:21:04 +000011714 expr = ASE->getBase();
11715 break;
11716 }
11717 case Stmt::MemberExprClass: {
11718 expr = cast<MemberExpr>(expr)->getBase();
11719 break;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011720 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +000011721 case Stmt::OMPArraySectionExprClass: {
11722 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
11723 if (ASE->getLowerBound())
11724 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
11725 /*ASE=*/nullptr, AllowOnePastEnd > 0);
11726 return;
11727 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011728 case Stmt::UnaryOperatorClass: {
11729 // Only unwrap the * and & unary operators
11730 const UnaryOperator *UO = cast<UnaryOperator>(expr);
11731 expr = UO->getSubExpr();
11732 switch (UO->getOpcode()) {
11733 case UO_AddrOf:
11734 AllowOnePastEnd++;
11735 break;
11736 case UO_Deref:
11737 AllowOnePastEnd--;
11738 break;
11739 default:
11740 return;
11741 }
11742 break;
11743 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011744 case Stmt::ConditionalOperatorClass: {
11745 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
11746 if (const Expr *lhs = cond->getLHS())
11747 CheckArrayAccess(lhs);
11748 if (const Expr *rhs = cond->getRHS())
11749 CheckArrayAccess(rhs);
11750 return;
11751 }
Daniel Marjamaki20a209e2017-02-28 14:53:50 +000011752 case Stmt::CXXOperatorCallExprClass: {
11753 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
11754 for (const auto *Arg : OCE->arguments())
11755 CheckArrayAccess(Arg);
11756 return;
11757 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011758 default:
11759 return;
11760 }
Peter Collingbourne91147592011-04-15 00:35:48 +000011761 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011762}
John McCall31168b02011-06-15 23:02:42 +000011763
11764//===--- CHECK: Objective-C retain cycles ----------------------------------//
11765
11766namespace {
John McCall31168b02011-06-15 23:02:42 +000011767
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011768struct RetainCycleOwner {
11769 VarDecl *Variable = nullptr;
11770 SourceRange Range;
11771 SourceLocation Loc;
11772 bool Indirect = false;
11773
11774 RetainCycleOwner() = default;
11775
11776 void setLocsFrom(Expr *e) {
11777 Loc = e->getExprLoc();
11778 Range = e->getSourceRange();
11779 }
11780};
11781
11782} // namespace
John McCall31168b02011-06-15 23:02:42 +000011783
11784/// Consider whether capturing the given variable can possibly lead to
11785/// a retain cycle.
11786static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000011787 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +000011788 // lifetime. In MRR, it's captured strongly if the variable is
11789 // __block and has an appropriate type.
11790 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11791 return false;
11792
11793 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011794 if (ref)
11795 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +000011796 return true;
11797}
11798
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011799static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +000011800 while (true) {
11801 e = e->IgnoreParens();
11802 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
11803 switch (cast->getCastKind()) {
11804 case CK_BitCast:
11805 case CK_LValueBitCast:
11806 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +000011807 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +000011808 e = cast->getSubExpr();
11809 continue;
11810
John McCall31168b02011-06-15 23:02:42 +000011811 default:
11812 return false;
11813 }
11814 }
11815
11816 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
11817 ObjCIvarDecl *ivar = ref->getDecl();
11818 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11819 return false;
11820
11821 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011822 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +000011823 return false;
11824
11825 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
11826 owner.Indirect = true;
11827 return true;
11828 }
11829
11830 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
11831 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
11832 if (!var) return false;
11833 return considerVariable(var, ref, owner);
11834 }
11835
John McCall31168b02011-06-15 23:02:42 +000011836 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
11837 if (member->isArrow()) return false;
11838
11839 // Don't count this as an indirect ownership.
11840 e = member->getBase();
11841 continue;
11842 }
11843
John McCallfe96e0b2011-11-06 09:01:30 +000011844 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
11845 // Only pay attention to pseudo-objects on property references.
11846 ObjCPropertyRefExpr *pre
11847 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
11848 ->IgnoreParens());
11849 if (!pre) return false;
11850 if (pre->isImplicitProperty()) return false;
11851 ObjCPropertyDecl *property = pre->getExplicitProperty();
11852 if (!property->isRetaining() &&
11853 !(property->getPropertyIvarDecl() &&
11854 property->getPropertyIvarDecl()->getType()
11855 .getObjCLifetime() == Qualifiers::OCL_Strong))
11856 return false;
11857
11858 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011859 if (pre->isSuperReceiver()) {
11860 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
11861 if (!owner.Variable)
11862 return false;
11863 owner.Loc = pre->getLocation();
11864 owner.Range = pre->getSourceRange();
11865 return true;
11866 }
John McCallfe96e0b2011-11-06 09:01:30 +000011867 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
11868 ->getSourceExpr());
11869 continue;
11870 }
11871
John McCall31168b02011-06-15 23:02:42 +000011872 // Array ivars?
11873
11874 return false;
11875 }
11876}
11877
11878namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011879
John McCall31168b02011-06-15 23:02:42 +000011880 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011881 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +000011882 VarDecl *Variable;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011883 Expr *Capturer = nullptr;
11884 bool VarWillBeReased = false;
11885
11886 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
11887 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
11888 Context(Context), Variable(variable) {}
John McCall31168b02011-06-15 23:02:42 +000011889
11890 void VisitDeclRefExpr(DeclRefExpr *ref) {
11891 if (ref->getDecl() == Variable && !Capturer)
11892 Capturer = ref;
11893 }
11894
John McCall31168b02011-06-15 23:02:42 +000011895 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
11896 if (Capturer) return;
11897 Visit(ref->getBase());
11898 if (Capturer && ref->isFreeIvar())
11899 Capturer = ref;
11900 }
11901
11902 void VisitBlockExpr(BlockExpr *block) {
11903 // Look inside nested blocks
11904 if (block->getBlockDecl()->capturesVariable(Variable))
11905 Visit(block->getBlockDecl()->getBody());
11906 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +000011907
11908 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
11909 if (Capturer) return;
11910 if (OVE->getSourceExpr())
11911 Visit(OVE->getSourceExpr());
11912 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011913
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011914 void VisitBinaryOperator(BinaryOperator *BinOp) {
11915 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
11916 return;
11917 Expr *LHS = BinOp->getLHS();
11918 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
11919 if (DRE->getDecl() != Variable)
11920 return;
11921 if (Expr *RHS = BinOp->getRHS()) {
11922 RHS = RHS->IgnoreParenCasts();
11923 llvm::APSInt Value;
11924 VarWillBeReased =
11925 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
11926 }
11927 }
11928 }
John McCall31168b02011-06-15 23:02:42 +000011929 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011930
11931} // namespace
John McCall31168b02011-06-15 23:02:42 +000011932
11933/// Check whether the given argument is a block which captures a
11934/// variable.
11935static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
11936 assert(owner.Variable && owner.Loc.isValid());
11937
11938 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000011939
11940 // Look through [^{...} copy] and Block_copy(^{...}).
11941 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
11942 Selector Cmd = ME->getSelector();
11943 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
11944 e = ME->getInstanceReceiver();
11945 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000011946 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000011947 e = e->IgnoreParenCasts();
11948 }
11949 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
11950 if (CE->getNumArgs() == 1) {
11951 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000011952 if (Fn) {
11953 const IdentifierInfo *FnI = Fn->getIdentifier();
11954 if (FnI && FnI->isStr("_Block_copy")) {
11955 e = CE->getArg(0)->IgnoreParenCasts();
11956 }
11957 }
Jordan Rose67e887c2012-09-17 17:54:30 +000011958 }
11959 }
11960
John McCall31168b02011-06-15 23:02:42 +000011961 BlockExpr *block = dyn_cast<BlockExpr>(e);
11962 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000011963 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000011964
11965 FindCaptureVisitor visitor(S.Context, owner.Variable);
11966 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011967 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000011968}
11969
11970static void diagnoseRetainCycle(Sema &S, Expr *capturer,
11971 RetainCycleOwner &owner) {
11972 assert(capturer);
11973 assert(owner.Variable && owner.Loc.isValid());
11974
11975 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
11976 << owner.Variable << capturer->getSourceRange();
11977 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
11978 << owner.Indirect << owner.Range;
11979}
11980
11981/// Check for a keyword selector that starts with the word 'add' or
11982/// 'set'.
11983static bool isSetterLikeSelector(Selector sel) {
11984 if (sel.isUnarySelector()) return false;
11985
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011986 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000011987 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011988 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000011989 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011990 else if (str.startswith("add")) {
11991 // Specially whitelist 'addOperationWithBlock:'.
11992 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
11993 return false;
11994 str = str.substr(3);
11995 }
John McCall31168b02011-06-15 23:02:42 +000011996 else
11997 return false;
11998
11999 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000012000 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000012001}
12002
Benjamin Kramer3a743452015-03-09 15:03:32 +000012003static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
12004 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000012005 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
12006 Message->getReceiverInterface(),
12007 NSAPI::ClassId_NSMutableArray);
12008 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012009 return None;
12010 }
12011
12012 Selector Sel = Message->getSelector();
12013
12014 Optional<NSAPI::NSArrayMethodKind> MKOpt =
12015 S.NSAPIObj->getNSArrayMethodKind(Sel);
12016 if (!MKOpt) {
12017 return None;
12018 }
12019
12020 NSAPI::NSArrayMethodKind MK = *MKOpt;
12021
12022 switch (MK) {
12023 case NSAPI::NSMutableArr_addObject:
12024 case NSAPI::NSMutableArr_insertObjectAtIndex:
12025 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
12026 return 0;
12027 case NSAPI::NSMutableArr_replaceObjectAtIndex:
12028 return 1;
12029
12030 default:
12031 return None;
12032 }
12033
12034 return None;
12035}
12036
12037static
12038Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
12039 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000012040 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
12041 Message->getReceiverInterface(),
12042 NSAPI::ClassId_NSMutableDictionary);
12043 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012044 return None;
12045 }
12046
12047 Selector Sel = Message->getSelector();
12048
12049 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
12050 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
12051 if (!MKOpt) {
12052 return None;
12053 }
12054
12055 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
12056
12057 switch (MK) {
12058 case NSAPI::NSMutableDict_setObjectForKey:
12059 case NSAPI::NSMutableDict_setValueForKey:
12060 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
12061 return 0;
12062
12063 default:
12064 return None;
12065 }
12066
12067 return None;
12068}
12069
12070static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000012071 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
12072 Message->getReceiverInterface(),
12073 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000012074
Alex Denisov5dfac812015-08-06 04:51:14 +000012075 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
12076 Message->getReceiverInterface(),
12077 NSAPI::ClassId_NSMutableOrderedSet);
12078 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012079 return None;
12080 }
12081
12082 Selector Sel = Message->getSelector();
12083
12084 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
12085 if (!MKOpt) {
12086 return None;
12087 }
12088
12089 NSAPI::NSSetMethodKind MK = *MKOpt;
12090
12091 switch (MK) {
12092 case NSAPI::NSMutableSet_addObject:
12093 case NSAPI::NSOrderedSet_setObjectAtIndex:
12094 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
12095 case NSAPI::NSOrderedSet_insertObjectAtIndex:
12096 return 0;
12097 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
12098 return 1;
12099 }
12100
12101 return None;
12102}
12103
12104void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
12105 if (!Message->isInstanceMessage()) {
12106 return;
12107 }
12108
12109 Optional<int> ArgOpt;
12110
12111 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
12112 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
12113 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
12114 return;
12115 }
12116
12117 int ArgIndex = *ArgOpt;
12118
Alex Denisove1d882c2015-03-04 17:55:52 +000012119 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
12120 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
12121 Arg = OE->getSourceExpr()->IgnoreImpCasts();
12122 }
12123
Alex Denisov5dfac812015-08-06 04:51:14 +000012124 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012125 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000012126 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012127 Diag(Message->getSourceRange().getBegin(),
12128 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000012129 << ArgRE->getDecl() << StringRef("'super'");
Alex Denisove1d882c2015-03-04 17:55:52 +000012130 }
12131 }
Alex Denisov5dfac812015-08-06 04:51:14 +000012132 } else {
12133 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
12134
12135 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
12136 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
12137 }
12138
12139 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
12140 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
12141 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
12142 ValueDecl *Decl = ReceiverRE->getDecl();
12143 Diag(Message->getSourceRange().getBegin(),
12144 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000012145 << Decl << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012146 if (!ArgRE->isObjCSelfExpr()) {
12147 Diag(Decl->getLocation(),
12148 diag::note_objc_circular_container_declared_here)
Richard Trieub4025802018-03-28 04:16:13 +000012149 << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012150 }
12151 }
12152 }
12153 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
12154 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
12155 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
12156 ObjCIvarDecl *Decl = IvarRE->getDecl();
12157 Diag(Message->getSourceRange().getBegin(),
12158 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000012159 << Decl << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012160 Diag(Decl->getLocation(),
12161 diag::note_objc_circular_container_declared_here)
Richard Trieub4025802018-03-28 04:16:13 +000012162 << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012163 }
Alex Denisove1d882c2015-03-04 17:55:52 +000012164 }
12165 }
12166 }
Alex Denisove1d882c2015-03-04 17:55:52 +000012167}
12168
John McCall31168b02011-06-15 23:02:42 +000012169/// Check a message send to see if it's likely to cause a retain cycle.
12170void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
12171 // Only check instance methods whose selector looks like a setter.
12172 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
12173 return;
12174
12175 // Try to find a variable that the receiver is strongly owned by.
12176 RetainCycleOwner owner;
12177 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000012178 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000012179 return;
12180 } else {
12181 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
12182 owner.Variable = getCurMethodDecl()->getSelfDecl();
12183 owner.Loc = msg->getSuperLoc();
12184 owner.Range = msg->getSuperLoc();
12185 }
12186
12187 // Check whether the receiver is captured by any of the arguments.
Alex Lorenz42a97a92017-11-17 20:44:25 +000012188 const ObjCMethodDecl *MD = msg->getMethodDecl();
12189 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
12190 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
12191 // noescape blocks should not be retained by the method.
12192 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
12193 continue;
John McCall31168b02011-06-15 23:02:42 +000012194 return diagnoseRetainCycle(*this, capturer, owner);
Alex Lorenz42a97a92017-11-17 20:44:25 +000012195 }
12196 }
John McCall31168b02011-06-15 23:02:42 +000012197}
12198
12199/// Check a property assign to see if it's likely to cause a retain cycle.
12200void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
12201 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000012202 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000012203 return;
12204
12205 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
12206 diagnoseRetainCycle(*this, capturer, owner);
12207}
12208
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000012209void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
12210 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000012211 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000012212 return;
12213
12214 // Because we don't have an expression for the variable, we have to set the
12215 // location explicitly here.
12216 Owner.Loc = Var->getLocation();
12217 Owner.Range = Var->getSourceRange();
12218
12219 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
12220 diagnoseRetainCycle(*this, Capturer, Owner);
12221}
12222
Ted Kremenek9304da92012-12-21 08:04:28 +000012223static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
12224 Expr *RHS, bool isProperty) {
12225 // Check if RHS is an Objective-C object literal, which also can get
12226 // immediately zapped in a weak reference. Note that we explicitly
12227 // allow ObjCStringLiterals, since those are designed to never really die.
12228 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000012229
Ted Kremenek64873352012-12-21 22:46:35 +000012230 // This enum needs to match with the 'select' in
12231 // warn_objc_arc_literal_assign (off-by-1).
12232 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
12233 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
12234 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000012235
12236 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000012237 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000012238 << (isProperty ? 0 : 1)
12239 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000012240
12241 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000012242}
12243
Ted Kremenekc1f014a2012-12-21 19:45:30 +000012244static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
12245 Qualifiers::ObjCLifetime LT,
12246 Expr *RHS, bool isProperty) {
12247 // Strip off any implicit cast added to get to the one ARC-specific.
12248 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
12249 if (cast->getCastKind() == CK_ARCConsumeObject) {
12250 S.Diag(Loc, diag::warn_arc_retained_assign)
12251 << (LT == Qualifiers::OCL_ExplicitNone)
12252 << (isProperty ? 0 : 1)
12253 << RHS->getSourceRange();
12254 return true;
12255 }
12256 RHS = cast->getSubExpr();
12257 }
12258
12259 if (LT == Qualifiers::OCL_Weak &&
12260 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
12261 return true;
12262
12263 return false;
12264}
12265
Ted Kremenekb36234d2012-12-21 08:04:20 +000012266bool Sema::checkUnsafeAssigns(SourceLocation Loc,
12267 QualType LHS, Expr *RHS) {
12268 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
12269
12270 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
12271 return false;
12272
12273 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
12274 return true;
12275
12276 return false;
12277}
12278
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012279void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
12280 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012281 QualType LHSType;
12282 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000012283 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012284 ObjCPropertyRefExpr *PRE
12285 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
12286 if (PRE && !PRE->isImplicitProperty()) {
12287 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
12288 if (PD)
12289 LHSType = PD->getType();
12290 }
12291
12292 if (LHSType.isNull())
12293 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000012294
12295 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
12296
12297 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000012298 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000012299 getCurFunction()->markSafeWeakUse(LHS);
12300 }
12301
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012302 if (checkUnsafeAssigns(Loc, LHSType, RHS))
12303 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000012304
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012305 // FIXME. Check for other life times.
12306 if (LT != Qualifiers::OCL_None)
12307 return;
12308
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012309 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012310 if (PRE->isImplicitProperty())
12311 return;
12312 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
12313 if (!PD)
12314 return;
12315
Bill Wendling44426052012-12-20 19:22:21 +000012316 unsigned Attributes = PD->getPropertyAttributes();
12317 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012318 // when 'assign' attribute was not explicitly specified
12319 // by user, ignore it and rely on property type itself
12320 // for lifetime info.
12321 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
12322 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
12323 LHSType->isObjCRetainableType())
12324 return;
12325
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012326 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000012327 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012328 Diag(Loc, diag::warn_arc_retained_property_assign)
12329 << RHS->getSourceRange();
12330 return;
12331 }
12332 RHS = cast->getSubExpr();
12333 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012334 }
Bill Wendling44426052012-12-20 19:22:21 +000012335 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000012336 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
12337 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000012338 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012339 }
12340}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012341
12342//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
12343
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012344static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
12345 SourceLocation StmtLoc,
12346 const NullStmt *Body) {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012347 // Do not warn if the body is a macro that expands to nothing, e.g:
12348 //
12349 // #define CALL(x)
12350 // if (condition)
12351 // CALL(0);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012352 if (Body->hasLeadingEmptyMacro())
12353 return false;
12354
12355 // Get line numbers of statement and body.
12356 bool StmtLineInvalid;
Hans Wennborg95419752017-11-20 17:38:16 +000012357 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012358 &StmtLineInvalid);
12359 if (StmtLineInvalid)
12360 return false;
12361
12362 bool BodyLineInvalid;
12363 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
12364 &BodyLineInvalid);
12365 if (BodyLineInvalid)
12366 return false;
12367
12368 // Warn if null statement and body are on the same line.
12369 if (StmtLine != BodyLine)
12370 return false;
12371
12372 return true;
12373}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012374
12375void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
12376 const Stmt *Body,
12377 unsigned DiagID) {
12378 // Since this is a syntactic check, don't emit diagnostic for template
12379 // instantiations, this just adds noise.
12380 if (CurrentInstantiationScope)
12381 return;
12382
12383 // The body should be a null statement.
12384 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
12385 if (!NBody)
12386 return;
12387
12388 // Do the usual checks.
12389 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
12390 return;
12391
12392 Diag(NBody->getSemiLoc(), DiagID);
12393 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
12394}
12395
12396void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
12397 const Stmt *PossibleBody) {
12398 assert(!CurrentInstantiationScope); // Ensured by caller
12399
12400 SourceLocation StmtLoc;
12401 const Stmt *Body;
12402 unsigned DiagID;
12403 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
12404 StmtLoc = FS->getRParenLoc();
12405 Body = FS->getBody();
12406 DiagID = diag::warn_empty_for_body;
12407 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
12408 StmtLoc = WS->getCond()->getSourceRange().getEnd();
12409 Body = WS->getBody();
12410 DiagID = diag::warn_empty_while_body;
12411 } else
12412 return; // Neither `for' nor `while'.
12413
12414 // The body should be a null statement.
12415 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
12416 if (!NBody)
12417 return;
12418
12419 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000012420 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012421 return;
12422
12423 // Do the usual checks.
12424 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
12425 return;
12426
12427 // `for(...);' and `while(...);' are popular idioms, so in order to keep
12428 // noise level low, emit diagnostics only if for/while is followed by a
12429 // CompoundStmt, e.g.:
12430 // for (int i = 0; i < n; i++);
12431 // {
12432 // a(i);
12433 // }
12434 // or if for/while is followed by a statement with more indentation
12435 // than for/while itself:
12436 // for (int i = 0; i < n; i++);
12437 // a(i);
12438 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
12439 if (!ProbableTypo) {
12440 bool BodyColInvalid;
12441 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
12442 PossibleBody->getLocStart(),
12443 &BodyColInvalid);
12444 if (BodyColInvalid)
12445 return;
12446
12447 bool StmtColInvalid;
12448 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
12449 S->getLocStart(),
12450 &StmtColInvalid);
12451 if (StmtColInvalid)
12452 return;
12453
12454 if (BodyCol > StmtCol)
12455 ProbableTypo = true;
12456 }
12457
12458 if (ProbableTypo) {
12459 Diag(NBody->getSemiLoc(), DiagID);
12460 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
12461 }
12462}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012463
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012464//===--- CHECK: Warn on self move with std::move. -------------------------===//
12465
12466/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
12467void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
12468 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012469 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
12470 return;
12471
Richard Smith51ec0cf2017-02-21 01:17:38 +000012472 if (inTemplateInstantiation())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012473 return;
12474
12475 // Strip parens and casts away.
12476 LHSExpr = LHSExpr->IgnoreParenImpCasts();
12477 RHSExpr = RHSExpr->IgnoreParenImpCasts();
12478
12479 // Check for a call expression
12480 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
12481 if (!CE || CE->getNumArgs() != 1)
12482 return;
12483
12484 // Check for a call to std::move
Nico Weberb688d132017-09-28 16:16:39 +000012485 if (!CE->isCallToStdMove())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012486 return;
12487
12488 // Get argument from std::move
12489 RHSExpr = CE->getArg(0);
12490
12491 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
12492 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
12493
12494 // Two DeclRefExpr's, check that the decls are the same.
12495 if (LHSDeclRef && RHSDeclRef) {
12496 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
12497 return;
12498 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
12499 RHSDeclRef->getDecl()->getCanonicalDecl())
12500 return;
12501
12502 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12503 << LHSExpr->getSourceRange()
12504 << RHSExpr->getSourceRange();
12505 return;
12506 }
12507
12508 // Member variables require a different approach to check for self moves.
12509 // MemberExpr's are the same if every nested MemberExpr refers to the same
12510 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
12511 // the base Expr's are CXXThisExpr's.
12512 const Expr *LHSBase = LHSExpr;
12513 const Expr *RHSBase = RHSExpr;
12514 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
12515 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
12516 if (!LHSME || !RHSME)
12517 return;
12518
12519 while (LHSME && RHSME) {
12520 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
12521 RHSME->getMemberDecl()->getCanonicalDecl())
12522 return;
12523
12524 LHSBase = LHSME->getBase();
12525 RHSBase = RHSME->getBase();
12526 LHSME = dyn_cast<MemberExpr>(LHSBase);
12527 RHSME = dyn_cast<MemberExpr>(RHSBase);
12528 }
12529
12530 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
12531 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
12532 if (LHSDeclRef && RHSDeclRef) {
12533 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
12534 return;
12535 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
12536 RHSDeclRef->getDecl()->getCanonicalDecl())
12537 return;
12538
12539 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12540 << LHSExpr->getSourceRange()
12541 << RHSExpr->getSourceRange();
12542 return;
12543 }
12544
12545 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
12546 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12547 << LHSExpr->getSourceRange()
12548 << RHSExpr->getSourceRange();
12549}
12550
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012551//===--- Layout compatibility ----------------------------------------------//
12552
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012553static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012554
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012555/// Check if two enumeration types are layout-compatible.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012556static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012557 // C++11 [dcl.enum] p8:
12558 // Two enumeration types are layout-compatible if they have the same
12559 // underlying type.
12560 return ED1->isComplete() && ED2->isComplete() &&
12561 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
12562}
12563
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012564/// Check if two fields are layout-compatible.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012565static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
12566 FieldDecl *Field2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012567 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
12568 return false;
12569
12570 if (Field1->isBitField() != Field2->isBitField())
12571 return false;
12572
12573 if (Field1->isBitField()) {
12574 // Make sure that the bit-fields are the same length.
12575 unsigned Bits1 = Field1->getBitWidthValue(C);
12576 unsigned Bits2 = Field2->getBitWidthValue(C);
12577
12578 if (Bits1 != Bits2)
12579 return false;
12580 }
12581
12582 return true;
12583}
12584
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012585/// Check if two standard-layout structs are layout-compatible.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012586/// (C++11 [class.mem] p17)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012587static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
12588 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012589 // If both records are C++ classes, check that base classes match.
12590 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
12591 // If one of records is a CXXRecordDecl we are in C++ mode,
12592 // thus the other one is a CXXRecordDecl, too.
12593 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
12594 // Check number of base classes.
12595 if (D1CXX->getNumBases() != D2CXX->getNumBases())
12596 return false;
12597
12598 // Check the base classes.
12599 for (CXXRecordDecl::base_class_const_iterator
12600 Base1 = D1CXX->bases_begin(),
12601 BaseEnd1 = D1CXX->bases_end(),
12602 Base2 = D2CXX->bases_begin();
12603 Base1 != BaseEnd1;
12604 ++Base1, ++Base2) {
12605 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
12606 return false;
12607 }
12608 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
12609 // If only RD2 is a C++ class, it should have zero base classes.
12610 if (D2CXX->getNumBases() > 0)
12611 return false;
12612 }
12613
12614 // Check the fields.
12615 RecordDecl::field_iterator Field2 = RD2->field_begin(),
12616 Field2End = RD2->field_end(),
12617 Field1 = RD1->field_begin(),
12618 Field1End = RD1->field_end();
12619 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
12620 if (!isLayoutCompatible(C, *Field1, *Field2))
12621 return false;
12622 }
12623 if (Field1 != Field1End || Field2 != Field2End)
12624 return false;
12625
12626 return true;
12627}
12628
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012629/// Check if two standard-layout unions are layout-compatible.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012630/// (C++11 [class.mem] p18)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012631static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
12632 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012633 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012634 for (auto *Field2 : RD2->fields())
12635 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012636
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012637 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012638 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
12639 I = UnmatchedFields.begin(),
12640 E = UnmatchedFields.end();
12641
12642 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012643 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012644 bool Result = UnmatchedFields.erase(*I);
12645 (void) Result;
12646 assert(Result);
12647 break;
12648 }
12649 }
12650 if (I == E)
12651 return false;
12652 }
12653
12654 return UnmatchedFields.empty();
12655}
12656
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012657static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
12658 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012659 if (RD1->isUnion() != RD2->isUnion())
12660 return false;
12661
12662 if (RD1->isUnion())
12663 return isLayoutCompatibleUnion(C, RD1, RD2);
12664 else
12665 return isLayoutCompatibleStruct(C, RD1, RD2);
12666}
12667
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012668/// Check if two types are layout-compatible in C++11 sense.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012669static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012670 if (T1.isNull() || T2.isNull())
12671 return false;
12672
12673 // C++11 [basic.types] p11:
12674 // If two types T1 and T2 are the same type, then T1 and T2 are
12675 // layout-compatible types.
12676 if (C.hasSameType(T1, T2))
12677 return true;
12678
12679 T1 = T1.getCanonicalType().getUnqualifiedType();
12680 T2 = T2.getCanonicalType().getUnqualifiedType();
12681
12682 const Type::TypeClass TC1 = T1->getTypeClass();
12683 const Type::TypeClass TC2 = T2->getTypeClass();
12684
12685 if (TC1 != TC2)
12686 return false;
12687
12688 if (TC1 == Type::Enum) {
12689 return isLayoutCompatible(C,
12690 cast<EnumType>(T1)->getDecl(),
12691 cast<EnumType>(T2)->getDecl());
12692 } else if (TC1 == Type::Record) {
12693 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
12694 return false;
12695
12696 return isLayoutCompatible(C,
12697 cast<RecordType>(T1)->getDecl(),
12698 cast<RecordType>(T2)->getDecl());
12699 }
12700
12701 return false;
12702}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012703
12704//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
12705
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012706/// Given a type tag expression find the type tag itself.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012707///
12708/// \param TypeExpr Type tag expression, as it appears in user's code.
12709///
12710/// \param VD Declaration of an identifier that appears in a type tag.
12711///
12712/// \param MagicValue Type tag magic value.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012713static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
12714 const ValueDecl **VD, uint64_t *MagicValue) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012715 while(true) {
12716 if (!TypeExpr)
12717 return false;
12718
12719 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
12720
12721 switch (TypeExpr->getStmtClass()) {
12722 case Stmt::UnaryOperatorClass: {
12723 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
12724 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
12725 TypeExpr = UO->getSubExpr();
12726 continue;
12727 }
12728 return false;
12729 }
12730
12731 case Stmt::DeclRefExprClass: {
12732 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
12733 *VD = DRE->getDecl();
12734 return true;
12735 }
12736
12737 case Stmt::IntegerLiteralClass: {
12738 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
12739 llvm::APInt MagicValueAPInt = IL->getValue();
12740 if (MagicValueAPInt.getActiveBits() <= 64) {
12741 *MagicValue = MagicValueAPInt.getZExtValue();
12742 return true;
12743 } else
12744 return false;
12745 }
12746
12747 case Stmt::BinaryConditionalOperatorClass:
12748 case Stmt::ConditionalOperatorClass: {
12749 const AbstractConditionalOperator *ACO =
12750 cast<AbstractConditionalOperator>(TypeExpr);
12751 bool Result;
12752 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
12753 if (Result)
12754 TypeExpr = ACO->getTrueExpr();
12755 else
12756 TypeExpr = ACO->getFalseExpr();
12757 continue;
12758 }
12759 return false;
12760 }
12761
12762 case Stmt::BinaryOperatorClass: {
12763 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
12764 if (BO->getOpcode() == BO_Comma) {
12765 TypeExpr = BO->getRHS();
12766 continue;
12767 }
12768 return false;
12769 }
12770
12771 default:
12772 return false;
12773 }
12774 }
12775}
12776
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012777/// Retrieve the C type corresponding to type tag TypeExpr.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012778///
12779/// \param TypeExpr Expression that specifies a type tag.
12780///
12781/// \param MagicValues Registered magic values.
12782///
12783/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
12784/// kind.
12785///
12786/// \param TypeInfo Information about the corresponding C type.
12787///
12788/// \returns true if the corresponding C type was found.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012789static bool GetMatchingCType(
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012790 const IdentifierInfo *ArgumentKind,
12791 const Expr *TypeExpr, const ASTContext &Ctx,
12792 const llvm::DenseMap<Sema::TypeTagMagicValue,
12793 Sema::TypeTagData> *MagicValues,
12794 bool &FoundWrongKind,
12795 Sema::TypeTagData &TypeInfo) {
12796 FoundWrongKind = false;
12797
12798 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000012799 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012800
12801 uint64_t MagicValue;
12802
12803 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
12804 return false;
12805
12806 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000012807 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012808 if (I->getArgumentKind() != ArgumentKind) {
12809 FoundWrongKind = true;
12810 return false;
12811 }
12812 TypeInfo.Type = I->getMatchingCType();
12813 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
12814 TypeInfo.MustBeNull = I->getMustBeNull();
12815 return true;
12816 }
12817 return false;
12818 }
12819
12820 if (!MagicValues)
12821 return false;
12822
12823 llvm::DenseMap<Sema::TypeTagMagicValue,
12824 Sema::TypeTagData>::const_iterator I =
12825 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
12826 if (I == MagicValues->end())
12827 return false;
12828
12829 TypeInfo = I->second;
12830 return true;
12831}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012832
12833void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
12834 uint64_t MagicValue, QualType Type,
12835 bool LayoutCompatible,
12836 bool MustBeNull) {
12837 if (!TypeTagForDatatypeMagicValues)
12838 TypeTagForDatatypeMagicValues.reset(
12839 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
12840
12841 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
12842 (*TypeTagForDatatypeMagicValues)[Magic] =
12843 TypeTagData(Type, LayoutCompatible, MustBeNull);
12844}
12845
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012846static bool IsSameCharType(QualType T1, QualType T2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012847 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
12848 if (!BT1)
12849 return false;
12850
12851 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
12852 if (!BT2)
12853 return false;
12854
12855 BuiltinType::Kind T1Kind = BT1->getKind();
12856 BuiltinType::Kind T2Kind = BT2->getKind();
12857
12858 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
12859 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
12860 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
12861 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
12862}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012863
12864void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012865 const ArrayRef<const Expr *> ExprArgs,
12866 SourceLocation CallSiteLoc) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012867 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
12868 bool IsPointerAttr = Attr->getIsPointer();
12869
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012870 // Retrieve the argument representing the 'type_tag'.
Joel E. Denny81508102018-03-13 14:51:22 +000012871 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
12872 if (TypeTagIdxAST >= ExprArgs.size()) {
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012873 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
Joel E. Denny81508102018-03-13 14:51:22 +000012874 << 0 << Attr->getTypeTagIdx().getSourceIndex();
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012875 return;
12876 }
Joel E. Denny81508102018-03-13 14:51:22 +000012877 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012878 bool FoundWrongKind;
12879 TypeTagData TypeInfo;
12880 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
12881 TypeTagForDatatypeMagicValues.get(),
12882 FoundWrongKind, TypeInfo)) {
12883 if (FoundWrongKind)
12884 Diag(TypeTagExpr->getExprLoc(),
12885 diag::warn_type_tag_for_datatype_wrong_kind)
12886 << TypeTagExpr->getSourceRange();
12887 return;
12888 }
12889
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012890 // Retrieve the argument representing the 'arg_idx'.
Joel E. Denny81508102018-03-13 14:51:22 +000012891 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
12892 if (ArgumentIdxAST >= ExprArgs.size()) {
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012893 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
Joel E. Denny81508102018-03-13 14:51:22 +000012894 << 1 << Attr->getArgumentIdx().getSourceIndex();
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012895 return;
12896 }
Joel E. Denny81508102018-03-13 14:51:22 +000012897 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012898 if (IsPointerAttr) {
12899 // Skip implicit cast of pointer to `void *' (as a function argument).
12900 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000012901 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000012902 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012903 ArgumentExpr = ICE->getSubExpr();
12904 }
12905 QualType ArgumentType = ArgumentExpr->getType();
12906
12907 // Passing a `void*' pointer shouldn't trigger a warning.
12908 if (IsPointerAttr && ArgumentType->isVoidPointerType())
12909 return;
12910
12911 if (TypeInfo.MustBeNull) {
12912 // Type tag with matching void type requires a null pointer.
12913 if (!ArgumentExpr->isNullPointerConstant(Context,
12914 Expr::NPC_ValueDependentIsNotNull)) {
12915 Diag(ArgumentExpr->getExprLoc(),
12916 diag::warn_type_safety_null_pointer_required)
12917 << ArgumentKind->getName()
12918 << ArgumentExpr->getSourceRange()
12919 << TypeTagExpr->getSourceRange();
12920 }
12921 return;
12922 }
12923
12924 QualType RequiredType = TypeInfo.Type;
12925 if (IsPointerAttr)
12926 RequiredType = Context.getPointerType(RequiredType);
12927
12928 bool mismatch = false;
12929 if (!TypeInfo.LayoutCompatible) {
12930 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
12931
12932 // C++11 [basic.fundamental] p1:
12933 // Plain char, signed char, and unsigned char are three distinct types.
12934 //
12935 // But we treat plain `char' as equivalent to `signed char' or `unsigned
12936 // char' depending on the current char signedness mode.
12937 if (mismatch)
12938 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
12939 RequiredType->getPointeeType())) ||
12940 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
12941 mismatch = false;
12942 } else
12943 if (IsPointerAttr)
12944 mismatch = !isLayoutCompatible(Context,
12945 ArgumentType->getPointeeType(),
12946 RequiredType->getPointeeType());
12947 else
12948 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
12949
12950 if (mismatch)
12951 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000012952 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012953 << TypeInfo.LayoutCompatible << RequiredType
12954 << ArgumentExpr->getSourceRange()
12955 << TypeTagExpr->getSourceRange();
12956}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012957
12958void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
12959 CharUnits Alignment) {
12960 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
12961}
12962
12963void Sema::DiagnoseMisalignedMembers() {
12964 for (MisalignedMember &m : MisalignedMembers) {
Alex Lorenz014181e2016-10-05 09:27:48 +000012965 const NamedDecl *ND = m.RD;
12966 if (ND->getName().empty()) {
12967 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
12968 ND = TD;
12969 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012970 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
Alex Lorenz014181e2016-10-05 09:27:48 +000012971 << m.MD << ND << m.E->getSourceRange();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012972 }
12973 MisalignedMembers.clear();
12974}
12975
12976void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012977 E = E->IgnoreParens();
12978 if (!T->isPointerType() && !T->isIntegerType())
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012979 return;
12980 if (isa<UnaryOperator>(E) &&
12981 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
12982 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12983 if (isa<MemberExpr>(Op)) {
12984 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
12985 MisalignedMember(Op));
12986 if (MA != MisalignedMembers.end() &&
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012987 (T->isIntegerType() ||
Roger Ferrer Ibanezd80d6c52017-12-07 09:23:50 +000012988 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
12989 Context.getTypeAlignInChars(
12990 T->getPointeeType()) <= MA->Alignment))))
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012991 MisalignedMembers.erase(MA);
12992 }
12993 }
12994}
12995
12996void Sema::RefersToMemberWithReducedAlignment(
12997 Expr *E,
Benjamin Kramera8c3e672016-12-12 14:41:19 +000012998 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
12999 Action) {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013000 const auto *ME = dyn_cast<MemberExpr>(E);
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013001 if (!ME)
13002 return;
13003
Roger Ferrer Ibanez9f963472017-03-13 13:18:21 +000013004 // No need to check expressions with an __unaligned-qualified type.
13005 if (E->getType().getQualifiers().hasUnaligned())
13006 return;
13007
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013008 // For a chain of MemberExpr like "a.b.c.d" this list
13009 // will keep FieldDecl's like [d, c, b].
13010 SmallVector<FieldDecl *, 4> ReverseMemberChain;
13011 const MemberExpr *TopME = nullptr;
13012 bool AnyIsPacked = false;
13013 do {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013014 QualType BaseType = ME->getBase()->getType();
13015 if (ME->isArrow())
13016 BaseType = BaseType->getPointeeType();
13017 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
Olivier Goffart67049f02017-07-07 09:38:59 +000013018 if (RD->isInvalidDecl())
13019 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013020
13021 ValueDecl *MD = ME->getMemberDecl();
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013022 auto *FD = dyn_cast<FieldDecl>(MD);
13023 // We do not care about non-data members.
13024 if (!FD || FD->isInvalidDecl())
13025 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013026
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013027 AnyIsPacked =
13028 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
13029 ReverseMemberChain.push_back(FD);
13030
13031 TopME = ME;
13032 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
13033 } while (ME);
13034 assert(TopME && "We did not compute a topmost MemberExpr!");
13035
13036 // Not the scope of this diagnostic.
13037 if (!AnyIsPacked)
13038 return;
13039
13040 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
13041 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
13042 // TODO: The innermost base of the member expression may be too complicated.
13043 // For now, just disregard these cases. This is left for future
13044 // improvement.
13045 if (!DRE && !isa<CXXThisExpr>(TopBase))
13046 return;
13047
13048 // Alignment expected by the whole expression.
13049 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
13050
13051 // No need to do anything else with this case.
13052 if (ExpectedAlignment.isOne())
13053 return;
13054
13055 // Synthesize offset of the whole access.
13056 CharUnits Offset;
13057 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
13058 I++) {
13059 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
13060 }
13061
13062 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
13063 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
13064 ReverseMemberChain.back()->getParent()->getTypeForDecl());
13065
13066 // The base expression of the innermost MemberExpr may give
13067 // stronger guarantees than the class containing the member.
13068 if (DRE && !TopME->isArrow()) {
13069 const ValueDecl *VD = DRE->getDecl();
13070 if (!VD->getType()->isReferenceType())
13071 CompleteObjectAlignment =
13072 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
13073 }
13074
13075 // Check if the synthesized offset fulfills the alignment.
13076 if (Offset % ExpectedAlignment != 0 ||
13077 // It may fulfill the offset it but the effective alignment may still be
13078 // lower than the expected expression alignment.
13079 CompleteObjectAlignment < ExpectedAlignment) {
13080 // If this happens, we want to determine a sensible culprit of this.
13081 // Intuitively, watching the chain of member expressions from right to
13082 // left, we start with the required alignment (as required by the field
13083 // type) but some packed attribute in that chain has reduced the alignment.
13084 // It may happen that another packed structure increases it again. But if
13085 // we are here such increase has not been enough. So pointing the first
13086 // FieldDecl that either is packed or else its RecordDecl is,
13087 // seems reasonable.
13088 FieldDecl *FD = nullptr;
13089 CharUnits Alignment;
13090 for (FieldDecl *FDI : ReverseMemberChain) {
13091 if (FDI->hasAttr<PackedAttr>() ||
13092 FDI->getParent()->hasAttr<PackedAttr>()) {
13093 FD = FDI;
13094 Alignment = std::min(
13095 Context.getTypeAlignInChars(FD->getType()),
13096 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
13097 break;
13098 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013099 }
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013100 assert(FD && "We did not find a packed FieldDecl!");
13101 Action(E, FD->getParent(), FD, Alignment);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013102 }
13103}
13104
13105void Sema::CheckAddressOfPackedMember(Expr *rhs) {
13106 using namespace std::placeholders;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013107
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013108 RefersToMemberWithReducedAlignment(
13109 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
13110 _2, _3, _4));
13111}