blob: fdf7e2b70f39cfaec0213b97f8a82756fcf7493f [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"
31#include "clang/AST/OperationKinds.h"
32#include "clang/AST/Stmt.h"
33#include "clang/AST/TemplateBase.h"
34#include "clang/AST/Type.h"
35#include "clang/AST/TypeLoc.h"
36#include "clang/AST/UnresolvedSet.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000037#include "clang/Analysis/Analyses/FormatString.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000038#include "clang/Basic/AddressSpaces.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000039#include "clang/Basic/CharInfo.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000040#include "clang/Basic/Diagnostic.h"
41#include "clang/Basic/IdentifierTable.h"
42#include "clang/Basic/LLVM.h"
43#include "clang/Basic/LangOptions.h"
44#include "clang/Basic/OpenCLOptions.h"
45#include "clang/Basic/OperatorKinds.h"
46#include "clang/Basic/PartialDiagnostic.h"
47#include "clang/Basic/SourceLocation.h"
48#include "clang/Basic/SourceManager.h"
49#include "clang/Basic/Specifiers.h"
Yaxun Liu39195062017-08-04 18:16:31 +000050#include "clang/Basic/SyncScope.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000051#include "clang/Basic/TargetBuiltins.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000052#include "clang/Basic/TargetCXXABI.h"
Nate Begeman4904e322010-06-08 02:47:44 +000053#include "clang/Basic/TargetInfo.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000054#include "clang/Basic/TypeTraits.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000055#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
Chandler Carruth3a022472012-12-04 09:13:33 +000056#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000057#include "clang/Sema/Lookup.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000058#include "clang/Sema/Ownership.h"
59#include "clang/Sema/Scope.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000060#include "clang/Sema/ScopeInfo.h"
61#include "clang/Sema/Sema.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000062#include "clang/Sema/SemaInternal.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000063#include "llvm/ADT/APFloat.h"
64#include "llvm/ADT/APInt.h"
65#include "llvm/ADT/APSInt.h"
66#include "llvm/ADT/ArrayRef.h"
67#include "llvm/ADT/DenseMap.h"
68#include "llvm/ADT/FoldingSet.h"
69#include "llvm/ADT/None.h"
70#include "llvm/ADT/Optional.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000071#include "llvm/ADT/STLExtras.h"
Richard Smithd7293d72013-08-05 18:49:43 +000072#include "llvm/ADT/SmallBitVector.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000073#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000074#include "llvm/ADT/SmallString.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000075#include "llvm/ADT/SmallVector.h"
76#include "llvm/ADT/StringRef.h"
77#include "llvm/ADT/StringSwitch.h"
78#include "llvm/ADT/Triple.h"
79#include "llvm/Support/AtomicOrdering.h"
80#include "llvm/Support/Casting.h"
81#include "llvm/Support/Compiler.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000082#include "llvm/Support/ConvertUTF.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000083#include "llvm/Support/ErrorHandling.h"
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +000084#include "llvm/Support/Format.h"
85#include "llvm/Support/Locale.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000086#include "llvm/Support/MathExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000087#include "llvm/Support/raw_ostream.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000088#include <algorithm>
89#include <cassert>
90#include <cstddef>
91#include <cstdint>
92#include <functional>
93#include <limits>
94#include <string>
95#include <tuple>
96#include <utility>
Eugene Zelenko1ced5092016-02-12 22:53:10 +000097
Chris Lattnerb87b1b32007-08-10 20:18:51 +000098using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000099using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +0000100
Chris Lattnera26fb342009-02-18 17:49:48 +0000101SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
102 unsigned ByteNo) const {
Alp Tokerb6cc5922014-05-03 03:45:55 +0000103 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
104 Context.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +0000105}
106
John McCallbebede42011-02-26 05:39:39 +0000107/// Checks that a call expression's argument count is the desired number.
108/// This is useful when doing custom type-checking. Returns true on error.
109static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
110 unsigned argCount = call->getNumArgs();
111 if (argCount == desiredArgCount) return false;
112
113 if (argCount < desiredArgCount)
114 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
115 << 0 /*function call*/ << desiredArgCount << argCount
116 << call->getSourceRange();
117
118 // Highlight all the excess arguments.
119 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
120 call->getArg(argCount - 1)->getLocEnd());
Nico Weberade321e2018-04-10 18:53:28 +0000121
John McCallbebede42011-02-26 05:39:39 +0000122 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
123 << 0 /*function call*/ << desiredArgCount << argCount
124 << call->getArg(1)->getSourceRange();
125}
126
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000127/// Check that the first argument to __builtin_annotation is an integer
128/// and the second argument is a non-wide string literal.
129static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
130 if (checkArgCount(S, TheCall, 2))
131 return true;
132
133 // First argument should be an integer.
134 Expr *ValArg = TheCall->getArg(0);
135 QualType Ty = ValArg->getType();
136 if (!Ty->isIntegerType()) {
137 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
138 << ValArg->getSourceRange();
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000139 return true;
140 }
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000141
142 // Second argument should be a constant string.
143 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
144 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
145 if (!Literal || !Literal->isAscii()) {
146 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
147 << StrArg->getSourceRange();
148 return true;
149 }
150
151 TheCall->setType(Ty);
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000152 return false;
153}
154
Reid Kleckner30701ed2017-09-05 20:27:35 +0000155static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
156 // We need at least one argument.
157 if (TheCall->getNumArgs() < 1) {
158 S.Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
159 << 0 << 1 << TheCall->getNumArgs()
160 << TheCall->getCallee()->getSourceRange();
161 return true;
162 }
163
164 // All arguments should be wide string literals.
165 for (Expr *Arg : TheCall->arguments()) {
166 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
167 if (!Literal || !Literal->isWide()) {
168 S.Diag(Arg->getLocStart(), diag::err_msvc_annotation_wide_str)
169 << Arg->getSourceRange();
170 return true;
171 }
172 }
173
174 return false;
175}
176
Richard Smith6cbd65d2013-07-11 02:27:57 +0000177/// Check that the argument to __builtin_addressof is a glvalue, and set the
178/// result type to the corresponding pointer type.
179static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
180 if (checkArgCount(S, TheCall, 1))
181 return true;
182
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000183 ExprResult Arg(TheCall->getArg(0));
Richard Smith6cbd65d2013-07-11 02:27:57 +0000184 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
185 if (ResultType.isNull())
186 return true;
187
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000188 TheCall->setArg(0, Arg.get());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000189 TheCall->setType(ResultType);
190 return false;
191}
192
John McCall03107a42015-10-29 20:48:01 +0000193static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
194 if (checkArgCount(S, TheCall, 3))
195 return true;
196
197 // First two arguments should be integers.
198 for (unsigned I = 0; I < 2; ++I) {
199 Expr *Arg = TheCall->getArg(I);
200 QualType Ty = Arg->getType();
201 if (!Ty->isIntegerType()) {
202 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
203 << Ty << Arg->getSourceRange();
204 return true;
205 }
206 }
207
208 // Third argument should be a pointer to a non-const integer.
209 // IRGen correctly handles volatile, restrict, and address spaces, and
210 // the other qualifiers aren't possible.
211 {
212 Expr *Arg = TheCall->getArg(2);
213 QualType Ty = Arg->getType();
214 const auto *PtrTy = Ty->getAs<PointerType>();
215 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
216 !PtrTy->getPointeeType().isConstQualified())) {
217 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
218 << Ty << Arg->getSourceRange();
219 return true;
220 }
221 }
222
223 return false;
224}
225
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000226static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
Nico Weberade321e2018-04-10 18:53:28 +0000227 CallExpr *TheCall, unsigned SizeIdx,
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000228 unsigned DstSizeIdx) {
229 if (TheCall->getNumArgs() <= SizeIdx ||
230 TheCall->getNumArgs() <= DstSizeIdx)
231 return;
232
233 const Expr *SizeArg = TheCall->getArg(SizeIdx);
234 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
235
236 llvm::APSInt Size, DstSize;
237
238 // find out if both sizes are known at compile time
239 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
240 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
241 return;
242
243 if (Size.ule(DstSize))
244 return;
245
246 // confirmed overflow so generate the diagnostic.
247 IdentifierInfo *FnName = FDecl->getIdentifier();
248 SourceLocation SL = TheCall->getLocStart();
249 SourceRange SR = TheCall->getSourceRange();
250
251 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
252}
253
Peter Collingbournef7706832014-12-12 23:41:25 +0000254static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
255 if (checkArgCount(S, BuiltinCall, 2))
256 return true;
257
258 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
259 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
260 Expr *Call = BuiltinCall->getArg(0);
261 Expr *Chain = BuiltinCall->getArg(1);
262
263 if (Call->getStmtClass() != Stmt::CallExprClass) {
264 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
265 << Call->getSourceRange();
266 return true;
267 }
268
269 auto CE = cast<CallExpr>(Call);
270 if (CE->getCallee()->getType()->isBlockPointerType()) {
271 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
272 << Call->getSourceRange();
273 return true;
274 }
275
276 const Decl *TargetDecl = CE->getCalleeDecl();
277 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
278 if (FD->getBuiltinID()) {
279 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
280 << Call->getSourceRange();
281 return true;
282 }
283
284 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
285 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
286 << Call->getSourceRange();
287 return true;
288 }
289
290 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
291 if (ChainResult.isInvalid())
292 return true;
293 if (!ChainResult.get()->getType()->isPointerType()) {
294 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
295 << Chain->getSourceRange();
296 return true;
297 }
298
David Majnemerced8bdf2015-02-25 17:36:15 +0000299 QualType ReturnTy = CE->getCallReturnType(S.Context);
Peter Collingbournef7706832014-12-12 23:41:25 +0000300 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
301 QualType BuiltinTy = S.Context.getFunctionType(
302 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
303 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
304
305 Builtin =
306 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
307
308 BuiltinCall->setType(CE->getType());
309 BuiltinCall->setValueKind(CE->getValueKind());
310 BuiltinCall->setObjectKind(CE->getObjectKind());
311 BuiltinCall->setCallee(Builtin);
312 BuiltinCall->setArg(1, ChainResult.get());
313
314 return false;
315}
316
Reid Kleckner1d59f992015-01-22 01:36:17 +0000317static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
318 Scope::ScopeFlags NeededScopeFlags,
319 unsigned DiagID) {
320 // Scopes aren't available during instantiation. Fortunately, builtin
321 // functions cannot be template args so they cannot be formed through template
322 // instantiation. Therefore checking once during the parse is sufficient.
Richard Smith51ec0cf2017-02-21 01:17:38 +0000323 if (SemaRef.inTemplateInstantiation())
Reid Kleckner1d59f992015-01-22 01:36:17 +0000324 return false;
325
326 Scope *S = SemaRef.getCurScope();
327 while (S && !S->isSEHExceptScope())
328 S = S->getParent();
329 if (!S || !(S->getFlags() & NeededScopeFlags)) {
330 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
331 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
332 << DRE->getDecl()->getIdentifier();
333 return true;
334 }
335
336 return false;
337}
338
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000339static inline bool isBlockPointer(Expr *Arg) {
340 return Arg->getType()->isBlockPointerType();
341}
342
343/// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
344/// void*, which is a requirement of device side enqueue.
345static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
346 const BlockPointerType *BPT =
347 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
348 ArrayRef<QualType> Params =
349 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
350 unsigned ArgCounter = 0;
351 bool IllegalParams = false;
352 // Iterate through the block parameters until either one is found that is not
353 // a local void*, or the block is valid.
354 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
355 I != E; ++I, ++ArgCounter) {
356 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
357 (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
358 LangAS::opencl_local) {
359 // Get the location of the error. If a block literal has been passed
360 // (BlockExpr) then we can point straight to the offending argument,
361 // else we just point to the variable reference.
362 SourceLocation ErrorLoc;
363 if (isa<BlockExpr>(BlockArg)) {
364 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
365 ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
366 } else if (isa<DeclRefExpr>(BlockArg)) {
367 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
368 }
369 S.Diag(ErrorLoc,
370 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
371 IllegalParams = true;
372 }
373 }
374
375 return IllegalParams;
376}
377
Joey Gouly84ae3362017-07-31 15:15:59 +0000378static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
379 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
380 S.Diag(Call->getLocStart(), diag::err_opencl_requires_extension)
381 << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
382 return true;
383 }
384 return false;
385}
386
Joey Goulyfa76b492017-08-01 13:27:09 +0000387static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
388 if (checkArgCount(S, TheCall, 2))
389 return true;
390
391 if (checkOpenCLSubgroupExt(S, TheCall))
392 return true;
393
394 // First argument is an ndrange_t type.
395 Expr *NDRangeArg = TheCall->getArg(0);
Yaxun Liub7318e02017-10-13 03:37:48 +0000396 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
Joey Goulyfa76b492017-08-01 13:27:09 +0000397 S.Diag(NDRangeArg->getLocStart(),
398 diag::err_opencl_builtin_expected_type)
399 << TheCall->getDirectCallee() << "'ndrange_t'";
400 return true;
401 }
402
403 Expr *BlockArg = TheCall->getArg(1);
404 if (!isBlockPointer(BlockArg)) {
405 S.Diag(BlockArg->getLocStart(),
406 diag::err_opencl_builtin_expected_type)
407 << TheCall->getDirectCallee() << "block";
408 return true;
409 }
410 return checkOpenCLBlockArgs(S, BlockArg);
411}
412
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000413/// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
414/// get_kernel_work_group_size
415/// and get_kernel_preferred_work_group_size_multiple builtin functions.
416static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
417 if (checkArgCount(S, TheCall, 1))
418 return true;
419
420 Expr *BlockArg = TheCall->getArg(0);
421 if (!isBlockPointer(BlockArg)) {
422 S.Diag(BlockArg->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000423 diag::err_opencl_builtin_expected_type)
424 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000425 return true;
426 }
427 return checkOpenCLBlockArgs(S, BlockArg);
428}
429
Simon Pilgrim2c518802017-03-30 14:13:19 +0000430/// Diagnose integer type and any valid implicit conversion to it.
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000431static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
432 const QualType &IntType);
433
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000434static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000435 unsigned Start, unsigned End) {
436 bool IllegalParams = false;
437 for (unsigned I = Start; I <= End; ++I)
438 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
439 S.Context.getSizeType());
440 return IllegalParams;
441}
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000442
443/// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
444/// 'local void*' parameter of passed block.
445static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
446 Expr *BlockArg,
447 unsigned NumNonVarArgs) {
448 const BlockPointerType *BPT =
449 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
450 unsigned NumBlockParams =
451 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
452 unsigned TotalNumArgs = TheCall->getNumArgs();
453
454 // For each argument passed to the block, a corresponding uint needs to
455 // be passed to describe the size of the local memory.
456 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
457 S.Diag(TheCall->getLocStart(),
458 diag::err_opencl_enqueue_kernel_local_size_args);
459 return true;
460 }
461
462 // Check that the sizes of the local memory are specified by integers.
463 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
464 TotalNumArgs - 1);
465}
466
467/// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
468/// overload formats specified in Table 6.13.17.1.
469/// int enqueue_kernel(queue_t queue,
470/// kernel_enqueue_flags_t flags,
471/// const ndrange_t ndrange,
472/// void (^block)(void))
473/// int enqueue_kernel(queue_t queue,
474/// kernel_enqueue_flags_t flags,
475/// const ndrange_t ndrange,
476/// uint num_events_in_wait_list,
477/// clk_event_t *event_wait_list,
478/// clk_event_t *event_ret,
479/// void (^block)(void))
480/// int enqueue_kernel(queue_t queue,
481/// kernel_enqueue_flags_t flags,
482/// const ndrange_t ndrange,
483/// void (^block)(local void*, ...),
484/// uint size0, ...)
485/// int enqueue_kernel(queue_t queue,
486/// kernel_enqueue_flags_t flags,
487/// const ndrange_t ndrange,
488/// uint num_events_in_wait_list,
489/// clk_event_t *event_wait_list,
490/// clk_event_t *event_ret,
491/// void (^block)(local void*, ...),
492/// uint size0, ...)
493static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
494 unsigned NumArgs = TheCall->getNumArgs();
495
496 if (NumArgs < 4) {
497 S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
498 return true;
499 }
500
501 Expr *Arg0 = TheCall->getArg(0);
502 Expr *Arg1 = TheCall->getArg(1);
503 Expr *Arg2 = TheCall->getArg(2);
504 Expr *Arg3 = TheCall->getArg(3);
505
506 // First argument always needs to be a queue_t type.
507 if (!Arg0->getType()->isQueueT()) {
508 S.Diag(TheCall->getArg(0)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000509 diag::err_opencl_builtin_expected_type)
510 << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000511 return true;
512 }
513
514 // Second argument always needs to be a kernel_enqueue_flags_t enum value.
515 if (!Arg1->getType()->isIntegerType()) {
516 S.Diag(TheCall->getArg(1)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000517 diag::err_opencl_builtin_expected_type)
518 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000519 return true;
520 }
521
522 // Third argument is always an ndrange_t type.
Anastasia Stulovab42f3c02017-04-21 15:13:24 +0000523 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000524 S.Diag(TheCall->getArg(2)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000525 diag::err_opencl_builtin_expected_type)
526 << TheCall->getDirectCallee() << "'ndrange_t'";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000527 return true;
528 }
529
530 // With four arguments, there is only one form that the function could be
531 // called in: no events and no variable arguments.
532 if (NumArgs == 4) {
533 // check that the last argument is the right block type.
534 if (!isBlockPointer(Arg3)) {
Joey Gouly6b03d952017-07-04 11:50:23 +0000535 S.Diag(Arg3->getLocStart(), diag::err_opencl_builtin_expected_type)
536 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000537 return true;
538 }
539 // we have a block type, check the prototype
540 const BlockPointerType *BPT =
541 cast<BlockPointerType>(Arg3->getType().getCanonicalType());
542 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
543 S.Diag(Arg3->getLocStart(),
544 diag::err_opencl_enqueue_kernel_blocks_no_args);
545 return true;
546 }
547 return false;
548 }
549 // we can have block + varargs.
550 if (isBlockPointer(Arg3))
551 return (checkOpenCLBlockArgs(S, Arg3) ||
552 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
553 // last two cases with either exactly 7 args or 7 args and varargs.
554 if (NumArgs >= 7) {
555 // check common block argument.
556 Expr *Arg6 = TheCall->getArg(6);
557 if (!isBlockPointer(Arg6)) {
Joey Gouly6b03d952017-07-04 11:50:23 +0000558 S.Diag(Arg6->getLocStart(), diag::err_opencl_builtin_expected_type)
559 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000560 return true;
561 }
562 if (checkOpenCLBlockArgs(S, Arg6))
563 return true;
564
565 // Forth argument has to be any integer type.
566 if (!Arg3->getType()->isIntegerType()) {
567 S.Diag(TheCall->getArg(3)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000568 diag::err_opencl_builtin_expected_type)
569 << TheCall->getDirectCallee() << "integer";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000570 return true;
571 }
572 // check remaining common arguments.
573 Expr *Arg4 = TheCall->getArg(4);
574 Expr *Arg5 = TheCall->getArg(5);
575
Anastasia Stulova2b461202016-11-14 15:34:01 +0000576 // Fifth argument is always passed as a pointer to clk_event_t.
577 if (!Arg4->isNullPointerConstant(S.Context,
578 Expr::NPC_ValueDependentIsNotNull) &&
579 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000580 S.Diag(TheCall->getArg(4)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000581 diag::err_opencl_builtin_expected_type)
582 << TheCall->getDirectCallee()
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000583 << S.Context.getPointerType(S.Context.OCLClkEventTy);
584 return true;
585 }
586
Anastasia Stulova2b461202016-11-14 15:34:01 +0000587 // Sixth argument is always passed as a pointer to clk_event_t.
588 if (!Arg5->isNullPointerConstant(S.Context,
589 Expr::NPC_ValueDependentIsNotNull) &&
590 !(Arg5->getType()->isPointerType() &&
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000591 Arg5->getType()->getPointeeType()->isClkEventT())) {
592 S.Diag(TheCall->getArg(5)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000593 diag::err_opencl_builtin_expected_type)
594 << TheCall->getDirectCallee()
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000595 << S.Context.getPointerType(S.Context.OCLClkEventTy);
596 return true;
597 }
598
599 if (NumArgs == 7)
600 return false;
601
602 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
603 }
604
605 // None of the specific case has been detected, give generic error
606 S.Diag(TheCall->getLocStart(),
607 diag::err_opencl_enqueue_kernel_incorrect_args);
608 return true;
609}
610
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000611/// Returns OpenCL access qual.
Xiuli Pan11e13f62016-02-26 03:13:03 +0000612static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
Xiuli Pan11e13f62016-02-26 03:13:03 +0000613 return D->getAttr<OpenCLAccessAttr>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000614}
615
616/// Returns true if pipe element type is different from the pointer.
617static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
618 const Expr *Arg0 = Call->getArg(0);
619 // First argument type should always be pipe.
620 if (!Arg0->getType()->isPipeType()) {
621 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000622 << Call->getDirectCallee() << Arg0->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000623 return true;
624 }
Xiuli Pan11e13f62016-02-26 03:13:03 +0000625 OpenCLAccessAttr *AccessQual =
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000626 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
627 // Validates the access qualifier is compatible with the call.
628 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
629 // read_only and write_only, and assumed to be read_only if no qualifier is
630 // specified.
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000631 switch (Call->getDirectCallee()->getBuiltinID()) {
632 case Builtin::BIread_pipe:
633 case Builtin::BIreserve_read_pipe:
634 case Builtin::BIcommit_read_pipe:
635 case Builtin::BIwork_group_reserve_read_pipe:
636 case Builtin::BIsub_group_reserve_read_pipe:
637 case Builtin::BIwork_group_commit_read_pipe:
638 case Builtin::BIsub_group_commit_read_pipe:
639 if (!(!AccessQual || AccessQual->isReadOnly())) {
640 S.Diag(Arg0->getLocStart(),
641 diag::err_opencl_builtin_pipe_invalid_access_modifier)
642 << "read_only" << Arg0->getSourceRange();
643 return true;
644 }
645 break;
646 case Builtin::BIwrite_pipe:
647 case Builtin::BIreserve_write_pipe:
648 case Builtin::BIcommit_write_pipe:
649 case Builtin::BIwork_group_reserve_write_pipe:
650 case Builtin::BIsub_group_reserve_write_pipe:
651 case Builtin::BIwork_group_commit_write_pipe:
652 case Builtin::BIsub_group_commit_write_pipe:
653 if (!(AccessQual && AccessQual->isWriteOnly())) {
654 S.Diag(Arg0->getLocStart(),
655 diag::err_opencl_builtin_pipe_invalid_access_modifier)
656 << "write_only" << Arg0->getSourceRange();
657 return true;
658 }
659 break;
660 default:
661 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000662 }
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000663 return false;
664}
665
666/// Returns true if pipe element type is different from the pointer.
667static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
668 const Expr *Arg0 = Call->getArg(0);
669 const Expr *ArgIdx = Call->getArg(Idx);
670 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000671 const QualType EltTy = PipeTy->getElementType();
672 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000673 // The Idx argument should be a pointer and the type of the pointer and
674 // the type of pipe element should also be the same.
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000675 if (!ArgTy ||
676 !S.Context.hasSameType(
677 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000678 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000679 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000680 << ArgIdx->getType() << ArgIdx->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000681 return true;
682 }
683 return false;
684}
685
686// \brief Performs semantic analysis for the read/write_pipe call.
687// \param S Reference to the semantic analyzer.
688// \param Call A pointer to the builtin call.
689// \return True if a semantic error has been found, false otherwise.
690static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000691 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
692 // functions have two forms.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000693 switch (Call->getNumArgs()) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +0000694 case 2:
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000695 if (checkOpenCLPipeArg(S, Call))
696 return true;
697 // The call with 2 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000698 // read/write_pipe(pipe T, T*).
699 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000700 if (checkOpenCLPipePacketType(S, Call, 1))
701 return true;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +0000702 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000703
704 case 4: {
705 if (checkOpenCLPipeArg(S, Call))
706 return true;
707 // The call with 4 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000708 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
709 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000710 if (!Call->getArg(1)->getType()->isReserveIDT()) {
711 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000712 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000713 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000714 return true;
715 }
716
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000717 // Check the index.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000718 const Expr *Arg2 = Call->getArg(2);
719 if (!Arg2->getType()->isIntegerType() &&
720 !Arg2->getType()->isUnsignedIntegerType()) {
721 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000722 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000723 << Arg2->getType() << Arg2->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000724 return true;
725 }
726
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000727 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000728 if (checkOpenCLPipePacketType(S, Call, 3))
729 return true;
730 } break;
731 default:
732 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000733 << Call->getDirectCallee() << Call->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000734 return true;
735 }
736
737 return false;
738}
739
740// \brief Performs a semantic analysis on the {work_group_/sub_group_
741// /_}reserve_{read/write}_pipe
742// \param S Reference to the semantic analyzer.
743// \param Call The call to the builtin function to be analyzed.
744// \return True if a semantic error was found, false otherwise.
745static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
746 if (checkArgCount(S, Call, 2))
747 return true;
748
749 if (checkOpenCLPipeArg(S, Call))
750 return true;
751
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000752 // Check the reserve size.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000753 if (!Call->getArg(1)->getType()->isIntegerType() &&
754 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
755 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000756 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000757 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000758 return true;
759 }
760
Joey Gouly922ca232017-08-09 14:52:47 +0000761 // Since return type of reserve_read/write_pipe built-in function is
762 // reserve_id_t, which is not defined in the builtin def file , we used int
763 // as return type and need to override the return type of these functions.
764 Call->setType(S.Context.OCLReserveIDTy);
765
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000766 return false;
767}
768
769// \brief Performs a semantic analysis on {work_group_/sub_group_
770// /_}commit_{read/write}_pipe
771// \param S Reference to the semantic analyzer.
772// \param Call The call to the builtin function to be analyzed.
773// \return True if a semantic error was found, false otherwise.
774static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
775 if (checkArgCount(S, Call, 2))
776 return true;
777
778 if (checkOpenCLPipeArg(S, Call))
779 return true;
780
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000781 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000782 if (!Call->getArg(1)->getType()->isReserveIDT()) {
783 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000784 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000785 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000786 return true;
787 }
788
789 return false;
790}
791
792// \brief Performs a semantic analysis on the call to built-in Pipe
793// Query Functions.
794// \param S Reference to the semantic analyzer.
795// \param Call The call to the builtin function to be analyzed.
796// \return True if a semantic error was found, false otherwise.
797static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
798 if (checkArgCount(S, Call, 1))
799 return true;
800
801 if (!Call->getArg(0)->getType()->isPipeType()) {
802 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000803 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000804 return true;
805 }
806
807 return false;
808}
Eugene Zelenko11a7ef82017-11-15 22:00:04 +0000809
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +0000810// \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
Yaxun Liuf7449a12016-05-20 19:54:38 +0000811// \brief Performs semantic analysis for the to_global/local/private call.
812// \param S Reference to the semantic analyzer.
813// \param BuiltinID ID of the builtin function.
814// \param Call A pointer to the builtin call.
815// \return True if a semantic error has been found, false otherwise.
816static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
817 CallExpr *Call) {
Yaxun Liuf7449a12016-05-20 19:54:38 +0000818 if (Call->getNumArgs() != 1) {
819 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
820 << Call->getDirectCallee() << Call->getSourceRange();
821 return true;
822 }
823
824 auto RT = Call->getArg(0)->getType();
825 if (!RT->isPointerType() || RT->getPointeeType()
826 .getAddressSpace() == LangAS::opencl_constant) {
827 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
828 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
829 return true;
830 }
831
832 RT = RT->getPointeeType();
833 auto Qual = RT.getQualifiers();
834 switch (BuiltinID) {
835 case Builtin::BIto_global:
836 Qual.setAddressSpace(LangAS::opencl_global);
837 break;
838 case Builtin::BIto_local:
839 Qual.setAddressSpace(LangAS::opencl_local);
840 break;
Yaxun Liub7318e02017-10-13 03:37:48 +0000841 case Builtin::BIto_private:
842 Qual.setAddressSpace(LangAS::opencl_private);
843 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +0000844 default:
Yaxun Liub7318e02017-10-13 03:37:48 +0000845 llvm_unreachable("Invalid builtin function");
Yaxun Liuf7449a12016-05-20 19:54:38 +0000846 }
847 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
848 RT.getUnqualifiedType(), Qual)));
849
850 return false;
851}
852
John McCalldadc5752010-08-24 06:29:42 +0000853ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000854Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
855 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000856 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000857
Chris Lattner3be167f2010-10-01 23:23:24 +0000858 // Find out if any arguments are required to be integer constant expressions.
859 unsigned ICEArguments = 0;
860 ASTContext::GetBuiltinTypeError Error;
861 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
862 if (Error != ASTContext::GE_None)
863 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
864
865 // If any arguments are required to be ICE's, check and diagnose.
866 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
867 // Skip arguments not required to be ICE's.
868 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
869
870 llvm::APSInt Result;
871 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
872 return true;
873 ICEArguments &= ~(1 << ArgNo);
874 }
875
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000876 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000877 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000878 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000879 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000880 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000881 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000882 break;
Martin Storsjo022e7822017-07-17 20:49:45 +0000883 case Builtin::BI__builtin_ms_va_start:
Ted Kremeneka174c522008-07-09 17:58:53 +0000884 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000885 case Builtin::BI__builtin_va_start:
Reid Kleckner2b0fa122017-05-02 20:10:03 +0000886 if (SemaBuiltinVAStart(BuiltinID, TheCall))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000887 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000888 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000889 case Builtin::BI__va_start: {
890 switch (Context.getTargetInfo().getTriple().getArch()) {
891 case llvm::Triple::arm:
892 case llvm::Triple::thumb:
Saleem Abdulrasool3450aa72017-09-26 20:12:04 +0000893 if (SemaBuiltinVAStartARMMicrosoft(TheCall))
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000894 return ExprError();
895 break;
896 default:
Reid Kleckner2b0fa122017-05-02 20:10:03 +0000897 if (SemaBuiltinVAStart(BuiltinID, TheCall))
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000898 return ExprError();
899 break;
900 }
901 break;
902 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000903 case Builtin::BI__builtin_isgreater:
904 case Builtin::BI__builtin_isgreaterequal:
905 case Builtin::BI__builtin_isless:
906 case Builtin::BI__builtin_islessequal:
907 case Builtin::BI__builtin_islessgreater:
908 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000909 if (SemaBuiltinUnorderedCompare(TheCall))
910 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000911 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000912 case Builtin::BI__builtin_fpclassify:
913 if (SemaBuiltinFPClassification(TheCall, 6))
914 return ExprError();
915 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000916 case Builtin::BI__builtin_isfinite:
917 case Builtin::BI__builtin_isinf:
918 case Builtin::BI__builtin_isinf_sign:
919 case Builtin::BI__builtin_isnan:
920 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000921 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000922 return ExprError();
923 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000924 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000925 return SemaBuiltinShuffleVector(TheCall);
926 // TheCall will be freed by the smart pointer here, but that's fine, since
927 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000928 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000929 if (SemaBuiltinPrefetch(TheCall))
930 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000931 break;
David Majnemer51169932016-10-31 05:37:48 +0000932 case Builtin::BI__builtin_alloca_with_align:
933 if (SemaBuiltinAllocaWithAlign(TheCall))
934 return ExprError();
935 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000936 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000937 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000938 if (SemaBuiltinAssume(TheCall))
939 return ExprError();
940 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000941 case Builtin::BI__builtin_assume_aligned:
942 if (SemaBuiltinAssumeAligned(TheCall))
943 return ExprError();
944 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000945 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000946 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000947 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000948 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000949 case Builtin::BI__builtin_longjmp:
950 if (SemaBuiltinLongjmp(TheCall))
951 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000952 break;
Joerg Sonnenberger27173282015-03-11 23:46:32 +0000953 case Builtin::BI__builtin_setjmp:
954 if (SemaBuiltinSetjmp(TheCall))
955 return ExprError();
956 break;
David Majnemerc403a1c2015-03-20 17:03:35 +0000957 case Builtin::BI_setjmp:
958 case Builtin::BI_setjmpex:
959 if (checkArgCount(*this, TheCall, 1))
960 return true;
961 break;
John McCallbebede42011-02-26 05:39:39 +0000962 case Builtin::BI__builtin_classify_type:
963 if (checkArgCount(*this, TheCall, 1)) return true;
964 TheCall->setType(Context.IntTy);
965 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000966 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000967 if (checkArgCount(*this, TheCall, 1)) return true;
968 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000969 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000970 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000971 case Builtin::BI__sync_fetch_and_add_1:
972 case Builtin::BI__sync_fetch_and_add_2:
973 case Builtin::BI__sync_fetch_and_add_4:
974 case Builtin::BI__sync_fetch_and_add_8:
975 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000976 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000977 case Builtin::BI__sync_fetch_and_sub_1:
978 case Builtin::BI__sync_fetch_and_sub_2:
979 case Builtin::BI__sync_fetch_and_sub_4:
980 case Builtin::BI__sync_fetch_and_sub_8:
981 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000982 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000983 case Builtin::BI__sync_fetch_and_or_1:
984 case Builtin::BI__sync_fetch_and_or_2:
985 case Builtin::BI__sync_fetch_and_or_4:
986 case Builtin::BI__sync_fetch_and_or_8:
987 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000988 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000989 case Builtin::BI__sync_fetch_and_and_1:
990 case Builtin::BI__sync_fetch_and_and_2:
991 case Builtin::BI__sync_fetch_and_and_4:
992 case Builtin::BI__sync_fetch_and_and_8:
993 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000994 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000995 case Builtin::BI__sync_fetch_and_xor_1:
996 case Builtin::BI__sync_fetch_and_xor_2:
997 case Builtin::BI__sync_fetch_and_xor_4:
998 case Builtin::BI__sync_fetch_and_xor_8:
999 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001000 case Builtin::BI__sync_fetch_and_nand:
1001 case Builtin::BI__sync_fetch_and_nand_1:
1002 case Builtin::BI__sync_fetch_and_nand_2:
1003 case Builtin::BI__sync_fetch_and_nand_4:
1004 case Builtin::BI__sync_fetch_and_nand_8:
1005 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001006 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001007 case Builtin::BI__sync_add_and_fetch_1:
1008 case Builtin::BI__sync_add_and_fetch_2:
1009 case Builtin::BI__sync_add_and_fetch_4:
1010 case Builtin::BI__sync_add_and_fetch_8:
1011 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001012 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001013 case Builtin::BI__sync_sub_and_fetch_1:
1014 case Builtin::BI__sync_sub_and_fetch_2:
1015 case Builtin::BI__sync_sub_and_fetch_4:
1016 case Builtin::BI__sync_sub_and_fetch_8:
1017 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001018 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001019 case Builtin::BI__sync_and_and_fetch_1:
1020 case Builtin::BI__sync_and_and_fetch_2:
1021 case Builtin::BI__sync_and_and_fetch_4:
1022 case Builtin::BI__sync_and_and_fetch_8:
1023 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001024 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001025 case Builtin::BI__sync_or_and_fetch_1:
1026 case Builtin::BI__sync_or_and_fetch_2:
1027 case Builtin::BI__sync_or_and_fetch_4:
1028 case Builtin::BI__sync_or_and_fetch_8:
1029 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001030 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001031 case Builtin::BI__sync_xor_and_fetch_1:
1032 case Builtin::BI__sync_xor_and_fetch_2:
1033 case Builtin::BI__sync_xor_and_fetch_4:
1034 case Builtin::BI__sync_xor_and_fetch_8:
1035 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001036 case Builtin::BI__sync_nand_and_fetch:
1037 case Builtin::BI__sync_nand_and_fetch_1:
1038 case Builtin::BI__sync_nand_and_fetch_2:
1039 case Builtin::BI__sync_nand_and_fetch_4:
1040 case Builtin::BI__sync_nand_and_fetch_8:
1041 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001042 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001043 case Builtin::BI__sync_val_compare_and_swap_1:
1044 case Builtin::BI__sync_val_compare_and_swap_2:
1045 case Builtin::BI__sync_val_compare_and_swap_4:
1046 case Builtin::BI__sync_val_compare_and_swap_8:
1047 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001048 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001049 case Builtin::BI__sync_bool_compare_and_swap_1:
1050 case Builtin::BI__sync_bool_compare_and_swap_2:
1051 case Builtin::BI__sync_bool_compare_and_swap_4:
1052 case Builtin::BI__sync_bool_compare_and_swap_8:
1053 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001054 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +00001055 case Builtin::BI__sync_lock_test_and_set_1:
1056 case Builtin::BI__sync_lock_test_and_set_2:
1057 case Builtin::BI__sync_lock_test_and_set_4:
1058 case Builtin::BI__sync_lock_test_and_set_8:
1059 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001060 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001061 case Builtin::BI__sync_lock_release_1:
1062 case Builtin::BI__sync_lock_release_2:
1063 case Builtin::BI__sync_lock_release_4:
1064 case Builtin::BI__sync_lock_release_8:
1065 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001066 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001067 case Builtin::BI__sync_swap_1:
1068 case Builtin::BI__sync_swap_2:
1069 case Builtin::BI__sync_swap_4:
1070 case Builtin::BI__sync_swap_8:
1071 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001072 return SemaBuiltinAtomicOverloaded(TheCallResult);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001073 case Builtin::BI__builtin_nontemporal_load:
1074 case Builtin::BI__builtin_nontemporal_store:
1075 return SemaBuiltinNontemporalOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +00001076#define BUILTIN(ID, TYPE, ATTRS)
1077#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1078 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001079 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +00001080#include "clang/Basic/Builtins.def"
Reid Kleckner30701ed2017-09-05 20:27:35 +00001081 case Builtin::BI__annotation:
1082 if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1083 return ExprError();
1084 break;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001085 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +00001086 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001087 return ExprError();
1088 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +00001089 case Builtin::BI__builtin_addressof:
1090 if (SemaBuiltinAddressof(*this, TheCall))
1091 return ExprError();
1092 break;
John McCall03107a42015-10-29 20:48:01 +00001093 case Builtin::BI__builtin_add_overflow:
1094 case Builtin::BI__builtin_sub_overflow:
1095 case Builtin::BI__builtin_mul_overflow:
Craig Toppera86e70d2015-11-07 06:16:14 +00001096 if (SemaBuiltinOverflow(*this, TheCall))
1097 return ExprError();
1098 break;
Richard Smith760520b2014-06-03 23:27:44 +00001099 case Builtin::BI__builtin_operator_new:
Eric Fiselierfa752f22018-03-21 19:19:48 +00001100 case Builtin::BI__builtin_operator_delete: {
1101 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1102 ExprResult Res =
1103 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1104 if (Res.isInvalid())
1105 CorrectDelayedTyposInExpr(TheCallResult.get());
1106 return Res;
1107 }
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001108 // check secure string manipulation functions where overflows
1109 // are detectable at compile time
1110 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001111 case Builtin::BI__builtin___memmove_chk:
1112 case Builtin::BI__builtin___memset_chk:
1113 case Builtin::BI__builtin___strlcat_chk:
1114 case Builtin::BI__builtin___strlcpy_chk:
1115 case Builtin::BI__builtin___strncat_chk:
1116 case Builtin::BI__builtin___strncpy_chk:
1117 case Builtin::BI__builtin___stpncpy_chk:
1118 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
1119 break;
Steven Wu566c14e2014-09-24 04:37:33 +00001120 case Builtin::BI__builtin___memccpy_chk:
1121 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
1122 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001123 case Builtin::BI__builtin___snprintf_chk:
1124 case Builtin::BI__builtin___vsnprintf_chk:
1125 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
1126 break;
Peter Collingbournef7706832014-12-12 23:41:25 +00001127 case Builtin::BI__builtin_call_with_static_chain:
1128 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1129 return ExprError();
1130 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001131 case Builtin::BI__exception_code:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001132 case Builtin::BI_exception_code:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001133 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1134 diag::err_seh___except_block))
1135 return ExprError();
1136 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001137 case Builtin::BI__exception_info:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001138 case Builtin::BI_exception_info:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001139 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1140 diag::err_seh___except_filter))
1141 return ExprError();
1142 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +00001143 case Builtin::BI__GetExceptionInfo:
1144 if (checkArgCount(*this, TheCall, 1))
1145 return ExprError();
1146
1147 if (CheckCXXThrowOperand(
1148 TheCall->getLocStart(),
1149 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1150 TheCall))
1151 return ExprError();
1152
1153 TheCall->setType(Context.VoidPtrTy);
1154 break;
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +00001155 // OpenCL v2.0, s6.13.16 - Pipe functions
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001156 case Builtin::BIread_pipe:
1157 case Builtin::BIwrite_pipe:
1158 // Since those two functions are declared with var args, we need a semantic
1159 // check for the argument.
1160 if (SemaBuiltinRWPipe(*this, TheCall))
1161 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001162 TheCall->setType(Context.IntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001163 break;
1164 case Builtin::BIreserve_read_pipe:
1165 case Builtin::BIreserve_write_pipe:
1166 case Builtin::BIwork_group_reserve_read_pipe:
1167 case Builtin::BIwork_group_reserve_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001168 if (SemaBuiltinReserveRWPipe(*this, TheCall))
1169 return ExprError();
Joey Gouly84ae3362017-07-31 15:15:59 +00001170 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001171 case Builtin::BIsub_group_reserve_read_pipe:
1172 case Builtin::BIsub_group_reserve_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001173 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1174 SemaBuiltinReserveRWPipe(*this, TheCall))
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001175 return ExprError();
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001176 break;
1177 case Builtin::BIcommit_read_pipe:
1178 case Builtin::BIcommit_write_pipe:
1179 case Builtin::BIwork_group_commit_read_pipe:
1180 case Builtin::BIwork_group_commit_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001181 if (SemaBuiltinCommitRWPipe(*this, TheCall))
1182 return ExprError();
1183 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001184 case Builtin::BIsub_group_commit_read_pipe:
1185 case Builtin::BIsub_group_commit_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001186 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1187 SemaBuiltinCommitRWPipe(*this, TheCall))
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001188 return ExprError();
1189 break;
1190 case Builtin::BIget_pipe_num_packets:
1191 case Builtin::BIget_pipe_max_packets:
1192 if (SemaBuiltinPipePackets(*this, TheCall))
1193 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001194 TheCall->setType(Context.UnsignedIntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001195 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +00001196 case Builtin::BIto_global:
1197 case Builtin::BIto_local:
1198 case Builtin::BIto_private:
1199 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1200 return ExprError();
1201 break;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001202 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1203 case Builtin::BIenqueue_kernel:
1204 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1205 return ExprError();
1206 break;
1207 case Builtin::BIget_kernel_work_group_size:
1208 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1209 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1210 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001211 break;
Joey Goulyfa76b492017-08-01 13:27:09 +00001212 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1213 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1214 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1215 return ExprError();
1216 break;
Mehdi Amini06d367c2016-10-24 20:39:34 +00001217 case Builtin::BI__builtin_os_log_format:
1218 case Builtin::BI__builtin_os_log_format_buffer_size:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00001219 if (SemaBuiltinOSLogFormat(TheCall))
Mehdi Amini06d367c2016-10-24 20:39:34 +00001220 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001221 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001222 }
Richard Smith760520b2014-06-03 23:27:44 +00001223
Nate Begeman4904e322010-06-08 02:47:44 +00001224 // Since the target specific builtins for each arch overlap, only check those
1225 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +00001226 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001227 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +00001228 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001229 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001230 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001231 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001232 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1233 return ExprError();
1234 break;
Tim Northover25e8a672014-05-24 12:51:25 +00001235 case llvm::Triple::aarch64:
1236 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +00001237 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +00001238 return ExprError();
1239 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001240 case llvm::Triple::mips:
1241 case llvm::Triple::mipsel:
1242 case llvm::Triple::mips64:
1243 case llvm::Triple::mips64el:
1244 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1245 return ExprError();
1246 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001247 case llvm::Triple::systemz:
1248 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1249 return ExprError();
1250 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001251 case llvm::Triple::x86:
1252 case llvm::Triple::x86_64:
1253 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1254 return ExprError();
1255 break;
Kit Bartone50adcb2015-03-30 19:40:59 +00001256 case llvm::Triple::ppc:
1257 case llvm::Triple::ppc64:
1258 case llvm::Triple::ppc64le:
1259 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1260 return ExprError();
1261 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001262 default:
1263 break;
1264 }
1265 }
1266
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001267 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +00001268}
1269
Nate Begeman91e1fea2010-06-14 05:21:25 +00001270// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +00001271static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +00001272 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +00001273 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +00001274 switch (Type.getEltType()) {
1275 case NeonTypeFlags::Int8:
1276 case NeonTypeFlags::Poly8:
1277 return shift ? 7 : (8 << IsQuad) - 1;
1278 case NeonTypeFlags::Int16:
1279 case NeonTypeFlags::Poly16:
1280 return shift ? 15 : (4 << IsQuad) - 1;
1281 case NeonTypeFlags::Int32:
1282 return shift ? 31 : (2 << IsQuad) - 1;
1283 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +00001284 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +00001285 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001286 case NeonTypeFlags::Poly128:
1287 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +00001288 case NeonTypeFlags::Float16:
1289 assert(!shift && "cannot shift float types!");
1290 return (4 << IsQuad) - 1;
1291 case NeonTypeFlags::Float32:
1292 assert(!shift && "cannot shift float types!");
1293 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001294 case NeonTypeFlags::Float64:
1295 assert(!shift && "cannot shift float types!");
1296 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +00001297 }
David Blaikie8a40f702012-01-17 06:56:22 +00001298 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +00001299}
1300
Bob Wilsone4d77232011-11-08 05:04:11 +00001301/// getNeonEltType - Return the QualType corresponding to the elements of
1302/// the vector type specified by the NeonTypeFlags. This is used to check
1303/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +00001304static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +00001305 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +00001306 switch (Flags.getEltType()) {
1307 case NeonTypeFlags::Int8:
1308 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1309 case NeonTypeFlags::Int16:
1310 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1311 case NeonTypeFlags::Int32:
1312 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1313 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +00001314 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +00001315 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1316 else
1317 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1318 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001319 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +00001320 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001321 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +00001322 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +00001323 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +00001324 if (IsInt64Long)
1325 return Context.UnsignedLongTy;
1326 else
1327 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001328 case NeonTypeFlags::Poly128:
1329 break;
Bob Wilsone4d77232011-11-08 05:04:11 +00001330 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +00001331 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001332 case NeonTypeFlags::Float32:
1333 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +00001334 case NeonTypeFlags::Float64:
1335 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001336 }
David Blaikie8a40f702012-01-17 06:56:22 +00001337 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +00001338}
1339
Tim Northover12670412014-02-19 10:37:05 +00001340bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +00001341 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +00001342 uint64_t mask = 0;
1343 unsigned TV = 0;
1344 int PtrArgNum = -1;
1345 bool HasConstPtr = false;
1346 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +00001347#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001348#include "clang/Basic/arm_neon.inc"
Abderrazek Zaafranice8746d2018-01-19 23:11:18 +00001349#include "clang/Basic/arm_fp16.inc"
Tim Northover12670412014-02-19 10:37:05 +00001350#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001351 }
1352
1353 // For NEON intrinsics which are overloaded on vector element type, validate
1354 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +00001355 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001356 if (mask) {
1357 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1358 return true;
1359
1360 TV = Result.getLimitedValue(64);
1361 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1362 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +00001363 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +00001364 }
1365
1366 if (PtrArgNum >= 0) {
1367 // Check that pointer arguments have the specified type.
1368 Expr *Arg = TheCall->getArg(PtrArgNum);
1369 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1370 Arg = ICE->getSubExpr();
1371 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1372 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +00001373
Tim Northovera2ee4332014-03-29 15:09:45 +00001374 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Joerg Sonnenberger47006c52017-01-09 11:40:41 +00001375 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1376 Arch == llvm::Triple::aarch64_be;
Tim Northovera2ee4332014-03-29 15:09:45 +00001377 bool IsInt64Long =
1378 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1379 QualType EltTy =
1380 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +00001381 if (HasConstPtr)
1382 EltTy = EltTy.withConst();
1383 QualType LHSTy = Context.getPointerType(EltTy);
1384 AssignConvertType ConvTy;
1385 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1386 if (RHS.isInvalid())
1387 return true;
1388 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1389 RHS.get(), AA_Assigning))
1390 return true;
1391 }
1392
1393 // For NEON intrinsics which take an immediate value as part of the
1394 // instruction, range check them here.
1395 unsigned i = 0, l = 0, u = 0;
1396 switch (BuiltinID) {
1397 default:
1398 return false;
Tim Northover12670412014-02-19 10:37:05 +00001399#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001400#include "clang/Basic/arm_neon.inc"
Abderrazek Zaafranice8746d2018-01-19 23:11:18 +00001401#include "clang/Basic/arm_fp16.inc"
Tim Northover12670412014-02-19 10:37:05 +00001402#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001403 }
Tim Northover2fe823a2013-08-01 09:23:19 +00001404
Richard Sandiford28940af2014-04-16 08:47:51 +00001405 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +00001406}
1407
Tim Northovera2ee4332014-03-29 15:09:45 +00001408bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1409 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +00001410 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001411 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +00001412 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001413 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +00001414 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001415 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1416 BuiltinID == AArch64::BI__builtin_arm_strex ||
1417 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +00001418 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +00001419 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001420 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1421 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1422 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +00001423
1424 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1425
1426 // Ensure that we have the proper number of arguments.
1427 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1428 return true;
1429
1430 // Inspect the pointer argument of the atomic builtin. This should always be
1431 // a pointer type, whose element is an integral scalar or pointer type.
1432 // Because it is a pointer type, we don't have to worry about any implicit
1433 // casts here.
1434 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1435 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1436 if (PointerArgRes.isInvalid())
1437 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001438 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001439
1440 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1441 if (!pointerType) {
1442 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1443 << PointerArg->getType() << PointerArg->getSourceRange();
1444 return true;
1445 }
1446
1447 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1448 // task is to insert the appropriate casts into the AST. First work out just
1449 // what the appropriate type is.
1450 QualType ValType = pointerType->getPointeeType();
1451 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1452 if (IsLdrex)
1453 AddrType.addConst();
1454
1455 // Issue a warning if the cast is dodgy.
1456 CastKind CastNeeded = CK_NoOp;
1457 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1458 CastNeeded = CK_BitCast;
1459 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1460 << PointerArg->getType()
1461 << Context.getPointerType(AddrType)
1462 << AA_Passing << PointerArg->getSourceRange();
1463 }
1464
1465 // Finally, do the cast and replace the argument with the corrected version.
1466 AddrType = Context.getPointerType(AddrType);
1467 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1468 if (PointerArgRes.isInvalid())
1469 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001470 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001471
1472 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1473
1474 // In general, we allow ints, floats and pointers to be loaded and stored.
1475 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1476 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1477 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1478 << PointerArg->getType() << PointerArg->getSourceRange();
1479 return true;
1480 }
1481
1482 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001483 if (Context.getTypeSize(ValType) > MaxWidth) {
1484 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +00001485 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1486 << PointerArg->getType() << PointerArg->getSourceRange();
1487 return true;
1488 }
1489
1490 switch (ValType.getObjCLifetime()) {
1491 case Qualifiers::OCL_None:
1492 case Qualifiers::OCL_ExplicitNone:
1493 // okay
1494 break;
1495
1496 case Qualifiers::OCL_Weak:
1497 case Qualifiers::OCL_Strong:
1498 case Qualifiers::OCL_Autoreleasing:
1499 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1500 << ValType << PointerArg->getSourceRange();
1501 return true;
1502 }
1503
Tim Northover6aacd492013-07-16 09:47:53 +00001504 if (IsLdrex) {
1505 TheCall->setType(ValType);
1506 return false;
1507 }
1508
1509 // Initialize the argument to be stored.
1510 ExprResult ValArg = TheCall->getArg(0);
1511 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1512 Context, ValType, /*consume*/ false);
1513 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1514 if (ValArg.isInvalid())
1515 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001516 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001517
1518 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1519 // but the custom checker bypasses all default analysis.
1520 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001521 return false;
1522}
1523
Nate Begeman4904e322010-06-08 02:47:44 +00001524bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover6aacd492013-07-16 09:47:53 +00001525 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001526 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1527 BuiltinID == ARM::BI__builtin_arm_strex ||
1528 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001529 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001530 }
1531
Yi Kong26d104a2014-08-13 19:18:14 +00001532 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1533 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1534 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1535 }
1536
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001537 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1538 BuiltinID == ARM::BI__builtin_arm_wsr64)
1539 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1540
1541 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1542 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1543 BuiltinID == ARM::BI__builtin_arm_wsr ||
1544 BuiltinID == ARM::BI__builtin_arm_wsrp)
1545 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1546
Tim Northover12670412014-02-19 10:37:05 +00001547 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1548 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001549
Yi Kong4efadfb2014-07-03 16:01:25 +00001550 // For intrinsics which take an immediate value as part of the instruction,
1551 // range check them here.
Sjoerd Meijer293da702017-12-07 09:54:39 +00001552 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begemand773fe62010-06-13 04:47:52 +00001553 switch (BuiltinID) {
1554 default: return false;
Sjoerd Meijer293da702017-12-07 09:54:39 +00001555 case ARM::BI__builtin_arm_ssat:
1556 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
1557 case ARM::BI__builtin_arm_usat:
1558 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
1559 case ARM::BI__builtin_arm_ssat16:
1560 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
1561 case ARM::BI__builtin_arm_usat16:
1562 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
Nate Begemanf568b072010-08-03 21:32:34 +00001563 case ARM::BI__builtin_arm_vcvtr_f:
Sjoerd Meijer293da702017-12-07 09:54:39 +00001564 case ARM::BI__builtin_arm_vcvtr_d:
1565 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
Weiming Zhao87bb4922013-11-12 21:42:50 +00001566 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001567 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001568 case ARM::BI__builtin_arm_isb:
Sjoerd Meijer293da702017-12-07 09:54:39 +00001569 case ARM::BI__builtin_arm_dbg:
1570 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
Richard Sandiford28940af2014-04-16 08:47:51 +00001571 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001572}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001573
Tim Northover573cbee2014-05-24 12:52:07 +00001574bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001575 CallExpr *TheCall) {
Tim Northover573cbee2014-05-24 12:52:07 +00001576 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001577 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1578 BuiltinID == AArch64::BI__builtin_arm_strex ||
1579 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001580 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1581 }
1582
Yi Konga5548432014-08-13 19:18:20 +00001583 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1584 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1585 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1586 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1587 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1588 }
1589
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001590 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1591 BuiltinID == AArch64::BI__builtin_arm_wsr64)
Tim Northover54e50002016-04-13 17:08:55 +00001592 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001593
1594 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1595 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1596 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1597 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1598 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1599
Tim Northovera2ee4332014-03-29 15:09:45 +00001600 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1601 return true;
1602
Yi Kong19a29ac2014-07-17 10:52:06 +00001603 // For intrinsics which take an immediate value as part of the instruction,
1604 // range check them here.
1605 unsigned i = 0, l = 0, u = 0;
1606 switch (BuiltinID) {
1607 default: return false;
1608 case AArch64::BI__builtin_arm_dmb:
1609 case AArch64::BI__builtin_arm_dsb:
1610 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1611 }
1612
Yi Kong19a29ac2014-07-17 10:52:06 +00001613 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001614}
1615
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001616// CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1617// intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1618// ordering for DSP is unspecified. MSA is ordered by the data format used
1619// by the underlying instruction i.e., df/m, df/n and then by size.
1620//
1621// FIXME: The size tests here should instead be tablegen'd along with the
1622// definitions from include/clang/Basic/BuiltinsMips.def.
1623// FIXME: GCC is strict on signedness for some of these intrinsics, we should
1624// be too.
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001625bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001626 unsigned i = 0, l = 0, u = 0, m = 0;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001627 switch (BuiltinID) {
1628 default: return false;
1629 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1630 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00001631 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1632 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1633 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1634 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1635 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001636 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1637 // df/m field.
1638 // These intrinsics take an unsigned 3 bit immediate.
1639 case Mips::BI__builtin_msa_bclri_b:
1640 case Mips::BI__builtin_msa_bnegi_b:
1641 case Mips::BI__builtin_msa_bseti_b:
1642 case Mips::BI__builtin_msa_sat_s_b:
1643 case Mips::BI__builtin_msa_sat_u_b:
1644 case Mips::BI__builtin_msa_slli_b:
1645 case Mips::BI__builtin_msa_srai_b:
1646 case Mips::BI__builtin_msa_srari_b:
1647 case Mips::BI__builtin_msa_srli_b:
1648 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1649 case Mips::BI__builtin_msa_binsli_b:
1650 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1651 // These intrinsics take an unsigned 4 bit immediate.
1652 case Mips::BI__builtin_msa_bclri_h:
1653 case Mips::BI__builtin_msa_bnegi_h:
1654 case Mips::BI__builtin_msa_bseti_h:
1655 case Mips::BI__builtin_msa_sat_s_h:
1656 case Mips::BI__builtin_msa_sat_u_h:
1657 case Mips::BI__builtin_msa_slli_h:
1658 case Mips::BI__builtin_msa_srai_h:
1659 case Mips::BI__builtin_msa_srari_h:
1660 case Mips::BI__builtin_msa_srli_h:
1661 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1662 case Mips::BI__builtin_msa_binsli_h:
1663 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00001664 // These intrinsics take an unsigned 5 bit immediate.
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001665 // The first block of intrinsics actually have an unsigned 5 bit field,
1666 // not a df/n field.
1667 case Mips::BI__builtin_msa_clei_u_b:
1668 case Mips::BI__builtin_msa_clei_u_h:
1669 case Mips::BI__builtin_msa_clei_u_w:
1670 case Mips::BI__builtin_msa_clei_u_d:
1671 case Mips::BI__builtin_msa_clti_u_b:
1672 case Mips::BI__builtin_msa_clti_u_h:
1673 case Mips::BI__builtin_msa_clti_u_w:
1674 case Mips::BI__builtin_msa_clti_u_d:
1675 case Mips::BI__builtin_msa_maxi_u_b:
1676 case Mips::BI__builtin_msa_maxi_u_h:
1677 case Mips::BI__builtin_msa_maxi_u_w:
1678 case Mips::BI__builtin_msa_maxi_u_d:
1679 case Mips::BI__builtin_msa_mini_u_b:
1680 case Mips::BI__builtin_msa_mini_u_h:
1681 case Mips::BI__builtin_msa_mini_u_w:
1682 case Mips::BI__builtin_msa_mini_u_d:
1683 case Mips::BI__builtin_msa_addvi_b:
1684 case Mips::BI__builtin_msa_addvi_h:
1685 case Mips::BI__builtin_msa_addvi_w:
1686 case Mips::BI__builtin_msa_addvi_d:
1687 case Mips::BI__builtin_msa_bclri_w:
1688 case Mips::BI__builtin_msa_bnegi_w:
1689 case Mips::BI__builtin_msa_bseti_w:
1690 case Mips::BI__builtin_msa_sat_s_w:
1691 case Mips::BI__builtin_msa_sat_u_w:
1692 case Mips::BI__builtin_msa_slli_w:
1693 case Mips::BI__builtin_msa_srai_w:
1694 case Mips::BI__builtin_msa_srari_w:
1695 case Mips::BI__builtin_msa_srli_w:
1696 case Mips::BI__builtin_msa_srlri_w:
1697 case Mips::BI__builtin_msa_subvi_b:
1698 case Mips::BI__builtin_msa_subvi_h:
1699 case Mips::BI__builtin_msa_subvi_w:
1700 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1701 case Mips::BI__builtin_msa_binsli_w:
1702 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1703 // These intrinsics take an unsigned 6 bit immediate.
1704 case Mips::BI__builtin_msa_bclri_d:
1705 case Mips::BI__builtin_msa_bnegi_d:
1706 case Mips::BI__builtin_msa_bseti_d:
1707 case Mips::BI__builtin_msa_sat_s_d:
1708 case Mips::BI__builtin_msa_sat_u_d:
1709 case Mips::BI__builtin_msa_slli_d:
1710 case Mips::BI__builtin_msa_srai_d:
1711 case Mips::BI__builtin_msa_srari_d:
1712 case Mips::BI__builtin_msa_srli_d:
1713 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1714 case Mips::BI__builtin_msa_binsli_d:
1715 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1716 // These intrinsics take a signed 5 bit immediate.
1717 case Mips::BI__builtin_msa_ceqi_b:
1718 case Mips::BI__builtin_msa_ceqi_h:
1719 case Mips::BI__builtin_msa_ceqi_w:
1720 case Mips::BI__builtin_msa_ceqi_d:
1721 case Mips::BI__builtin_msa_clti_s_b:
1722 case Mips::BI__builtin_msa_clti_s_h:
1723 case Mips::BI__builtin_msa_clti_s_w:
1724 case Mips::BI__builtin_msa_clti_s_d:
1725 case Mips::BI__builtin_msa_clei_s_b:
1726 case Mips::BI__builtin_msa_clei_s_h:
1727 case Mips::BI__builtin_msa_clei_s_w:
1728 case Mips::BI__builtin_msa_clei_s_d:
1729 case Mips::BI__builtin_msa_maxi_s_b:
1730 case Mips::BI__builtin_msa_maxi_s_h:
1731 case Mips::BI__builtin_msa_maxi_s_w:
1732 case Mips::BI__builtin_msa_maxi_s_d:
1733 case Mips::BI__builtin_msa_mini_s_b:
1734 case Mips::BI__builtin_msa_mini_s_h:
1735 case Mips::BI__builtin_msa_mini_s_w:
1736 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
1737 // These intrinsics take an unsigned 8 bit immediate.
1738 case Mips::BI__builtin_msa_andi_b:
1739 case Mips::BI__builtin_msa_nori_b:
1740 case Mips::BI__builtin_msa_ori_b:
1741 case Mips::BI__builtin_msa_shf_b:
1742 case Mips::BI__builtin_msa_shf_h:
1743 case Mips::BI__builtin_msa_shf_w:
1744 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
1745 case Mips::BI__builtin_msa_bseli_b:
1746 case Mips::BI__builtin_msa_bmnzi_b:
1747 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
1748 // df/n format
1749 // These intrinsics take an unsigned 4 bit immediate.
1750 case Mips::BI__builtin_msa_copy_s_b:
1751 case Mips::BI__builtin_msa_copy_u_b:
1752 case Mips::BI__builtin_msa_insve_b:
1753 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001754 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
1755 // These intrinsics take an unsigned 3 bit immediate.
1756 case Mips::BI__builtin_msa_copy_s_h:
1757 case Mips::BI__builtin_msa_copy_u_h:
1758 case Mips::BI__builtin_msa_insve_h:
1759 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001760 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1761 // These intrinsics take an unsigned 2 bit immediate.
1762 case Mips::BI__builtin_msa_copy_s_w:
1763 case Mips::BI__builtin_msa_copy_u_w:
1764 case Mips::BI__builtin_msa_insve_w:
1765 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001766 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1767 // These intrinsics take an unsigned 1 bit immediate.
1768 case Mips::BI__builtin_msa_copy_s_d:
1769 case Mips::BI__builtin_msa_copy_u_d:
1770 case Mips::BI__builtin_msa_insve_d:
1771 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001772 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1773 // Memory offsets and immediate loads.
1774 // These intrinsics take a signed 10 bit immediate.
Petar Jovanovic9b8b9e82017-03-31 16:16:43 +00001775 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001776 case Mips::BI__builtin_msa_ldi_h:
1777 case Mips::BI__builtin_msa_ldi_w:
1778 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1779 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1780 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1781 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1782 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1783 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1784 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1785 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1786 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001787 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001788
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001789 if (!m)
1790 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1791
1792 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1793 SemaBuiltinConstantArgMultiple(TheCall, i, m);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001794}
1795
Kit Bartone50adcb2015-03-30 19:40:59 +00001796bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1797 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00001798 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1799 BuiltinID == PPC::BI__builtin_divdeu ||
1800 BuiltinID == PPC::BI__builtin_bpermd;
1801 bool IsTarget64Bit = Context.getTargetInfo()
1802 .getTypeWidth(Context
1803 .getTargetInfo()
1804 .getIntPtrType()) == 64;
1805 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1806 BuiltinID == PPC::BI__builtin_divweu ||
1807 BuiltinID == PPC::BI__builtin_divde ||
1808 BuiltinID == PPC::BI__builtin_divdeu;
1809
1810 if (Is64BitBltin && !IsTarget64Bit)
1811 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1812 << TheCall->getSourceRange();
1813
1814 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1815 (BuiltinID == PPC::BI__builtin_bpermd &&
1816 !Context.getTargetInfo().hasFeature("bpermd")))
1817 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1818 << TheCall->getSourceRange();
1819
Kit Bartone50adcb2015-03-30 19:40:59 +00001820 switch (BuiltinID) {
1821 default: return false;
1822 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1823 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1824 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1825 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1826 case PPC::BI__builtin_tbegin:
1827 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1828 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1829 case PPC::BI__builtin_tabortwc:
1830 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1831 case PPC::BI__builtin_tabortwci:
1832 case PPC::BI__builtin_tabortdci:
1833 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1834 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
Tony Jiangbbc48e92017-05-24 15:13:32 +00001835 case PPC::BI__builtin_vsx_xxpermdi:
Tony Jiang9aa2c032017-05-24 15:54:13 +00001836 case PPC::BI__builtin_vsx_xxsldwi:
Tony Jiangbbc48e92017-05-24 15:13:32 +00001837 return SemaBuiltinVSX(TheCall);
Kit Bartone50adcb2015-03-30 19:40:59 +00001838 }
1839 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1840}
1841
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001842bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1843 CallExpr *TheCall) {
1844 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1845 Expr *Arg = TheCall->getArg(0);
1846 llvm::APSInt AbortCode(32);
1847 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1848 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1849 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1850 << Arg->getSourceRange();
1851 }
1852
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001853 // For intrinsics which take an immediate value as part of the instruction,
1854 // range check them here.
1855 unsigned i = 0, l = 0, u = 0;
1856 switch (BuiltinID) {
1857 default: return false;
1858 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1859 case SystemZ::BI__builtin_s390_verimb:
1860 case SystemZ::BI__builtin_s390_verimh:
1861 case SystemZ::BI__builtin_s390_verimf:
1862 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1863 case SystemZ::BI__builtin_s390_vfaeb:
1864 case SystemZ::BI__builtin_s390_vfaeh:
1865 case SystemZ::BI__builtin_s390_vfaef:
1866 case SystemZ::BI__builtin_s390_vfaebs:
1867 case SystemZ::BI__builtin_s390_vfaehs:
1868 case SystemZ::BI__builtin_s390_vfaefs:
1869 case SystemZ::BI__builtin_s390_vfaezb:
1870 case SystemZ::BI__builtin_s390_vfaezh:
1871 case SystemZ::BI__builtin_s390_vfaezf:
1872 case SystemZ::BI__builtin_s390_vfaezbs:
1873 case SystemZ::BI__builtin_s390_vfaezhs:
1874 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00001875 case SystemZ::BI__builtin_s390_vfisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001876 case SystemZ::BI__builtin_s390_vfidb:
1877 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1878 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00001879 case SystemZ::BI__builtin_s390_vftcisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001880 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1881 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1882 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1883 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1884 case SystemZ::BI__builtin_s390_vstrcb:
1885 case SystemZ::BI__builtin_s390_vstrch:
1886 case SystemZ::BI__builtin_s390_vstrcf:
1887 case SystemZ::BI__builtin_s390_vstrczb:
1888 case SystemZ::BI__builtin_s390_vstrczh:
1889 case SystemZ::BI__builtin_s390_vstrczf:
1890 case SystemZ::BI__builtin_s390_vstrcbs:
1891 case SystemZ::BI__builtin_s390_vstrchs:
1892 case SystemZ::BI__builtin_s390_vstrcfs:
1893 case SystemZ::BI__builtin_s390_vstrczbs:
1894 case SystemZ::BI__builtin_s390_vstrczhs:
1895 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00001896 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
1897 case SystemZ::BI__builtin_s390_vfminsb:
1898 case SystemZ::BI__builtin_s390_vfmaxsb:
1899 case SystemZ::BI__builtin_s390_vfmindb:
1900 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001901 }
1902 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001903}
1904
Craig Topper5ba2c502015-11-07 08:08:31 +00001905/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1906/// This checks that the target supports __builtin_cpu_supports and
1907/// that the string argument is constant and valid.
1908static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1909 Expr *Arg = TheCall->getArg(0);
1910
1911 // Check if the argument is a string literal.
1912 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1913 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1914 << Arg->getSourceRange();
1915
1916 // Check the contents of the string.
1917 StringRef Feature =
1918 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1919 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1920 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1921 << Arg->getSourceRange();
1922 return false;
1923}
1924
Craig Topper699ae0c2017-08-10 20:28:30 +00001925/// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
1926/// This checks that the target supports __builtin_cpu_is and
1927/// that the string argument is constant and valid.
1928static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
1929 Expr *Arg = TheCall->getArg(0);
1930
1931 // Check if the argument is a string literal.
1932 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1933 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1934 << Arg->getSourceRange();
1935
1936 // Check the contents of the string.
1937 StringRef Feature =
1938 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1939 if (!S.Context.getTargetInfo().validateCpuIs(Feature))
1940 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is)
1941 << Arg->getSourceRange();
1942 return false;
1943}
1944
Craig Toppera7e253e2016-09-23 04:48:31 +00001945// Check if the rounding mode is legal.
1946bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
1947 // Indicates if this instruction has rounding control or just SAE.
1948 bool HasRC = false;
1949
1950 unsigned ArgNum = 0;
1951 switch (BuiltinID) {
1952 default:
1953 return false;
1954 case X86::BI__builtin_ia32_vcvttsd2si32:
1955 case X86::BI__builtin_ia32_vcvttsd2si64:
1956 case X86::BI__builtin_ia32_vcvttsd2usi32:
1957 case X86::BI__builtin_ia32_vcvttsd2usi64:
1958 case X86::BI__builtin_ia32_vcvttss2si32:
1959 case X86::BI__builtin_ia32_vcvttss2si64:
1960 case X86::BI__builtin_ia32_vcvttss2usi32:
1961 case X86::BI__builtin_ia32_vcvttss2usi64:
1962 ArgNum = 1;
1963 break;
1964 case X86::BI__builtin_ia32_cvtps2pd512_mask:
1965 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1966 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1967 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1968 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1969 case X86::BI__builtin_ia32_cvttps2dq512_mask:
1970 case X86::BI__builtin_ia32_cvttps2qq512_mask:
1971 case X86::BI__builtin_ia32_cvttps2udq512_mask:
1972 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1973 case X86::BI__builtin_ia32_exp2pd_mask:
1974 case X86::BI__builtin_ia32_exp2ps_mask:
1975 case X86::BI__builtin_ia32_getexppd512_mask:
1976 case X86::BI__builtin_ia32_getexpps512_mask:
1977 case X86::BI__builtin_ia32_rcp28pd_mask:
1978 case X86::BI__builtin_ia32_rcp28ps_mask:
1979 case X86::BI__builtin_ia32_rsqrt28pd_mask:
1980 case X86::BI__builtin_ia32_rsqrt28ps_mask:
1981 case X86::BI__builtin_ia32_vcomisd:
1982 case X86::BI__builtin_ia32_vcomiss:
1983 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1984 ArgNum = 3;
1985 break;
1986 case X86::BI__builtin_ia32_cmppd512_mask:
1987 case X86::BI__builtin_ia32_cmpps512_mask:
1988 case X86::BI__builtin_ia32_cmpsd_mask:
1989 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001990 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00001991 case X86::BI__builtin_ia32_getexpsd128_round_mask:
1992 case X86::BI__builtin_ia32_getexpss128_round_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001993 case X86::BI__builtin_ia32_maxpd512_mask:
1994 case X86::BI__builtin_ia32_maxps512_mask:
1995 case X86::BI__builtin_ia32_maxsd_round_mask:
1996 case X86::BI__builtin_ia32_maxss_round_mask:
1997 case X86::BI__builtin_ia32_minpd512_mask:
1998 case X86::BI__builtin_ia32_minps512_mask:
1999 case X86::BI__builtin_ia32_minsd_round_mask:
2000 case X86::BI__builtin_ia32_minss_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00002001 case X86::BI__builtin_ia32_rcp28sd_round_mask:
2002 case X86::BI__builtin_ia32_rcp28ss_round_mask:
2003 case X86::BI__builtin_ia32_reducepd512_mask:
2004 case X86::BI__builtin_ia32_reduceps512_mask:
2005 case X86::BI__builtin_ia32_rndscalepd_mask:
2006 case X86::BI__builtin_ia32_rndscaleps_mask:
2007 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
2008 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
2009 ArgNum = 4;
2010 break;
2011 case X86::BI__builtin_ia32_fixupimmpd512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002012 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002013 case X86::BI__builtin_ia32_fixupimmps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002014 case X86::BI__builtin_ia32_fixupimmps512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002015 case X86::BI__builtin_ia32_fixupimmsd_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002016 case X86::BI__builtin_ia32_fixupimmsd_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002017 case X86::BI__builtin_ia32_fixupimmss_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002018 case X86::BI__builtin_ia32_fixupimmss_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002019 case X86::BI__builtin_ia32_rangepd512_mask:
2020 case X86::BI__builtin_ia32_rangeps512_mask:
2021 case X86::BI__builtin_ia32_rangesd128_round_mask:
2022 case X86::BI__builtin_ia32_rangess128_round_mask:
2023 case X86::BI__builtin_ia32_reducesd_mask:
2024 case X86::BI__builtin_ia32_reducess_mask:
2025 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2026 case X86::BI__builtin_ia32_rndscaless_round_mask:
2027 ArgNum = 5;
2028 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00002029 case X86::BI__builtin_ia32_vcvtsd2si64:
2030 case X86::BI__builtin_ia32_vcvtsd2si32:
2031 case X86::BI__builtin_ia32_vcvtsd2usi32:
2032 case X86::BI__builtin_ia32_vcvtsd2usi64:
2033 case X86::BI__builtin_ia32_vcvtss2si32:
2034 case X86::BI__builtin_ia32_vcvtss2si64:
2035 case X86::BI__builtin_ia32_vcvtss2usi32:
2036 case X86::BI__builtin_ia32_vcvtss2usi64:
2037 ArgNum = 1;
2038 HasRC = true;
2039 break;
Craig Topper8e066312016-11-07 07:01:09 +00002040 case X86::BI__builtin_ia32_cvtsi2sd64:
2041 case X86::BI__builtin_ia32_cvtsi2ss32:
2042 case X86::BI__builtin_ia32_cvtsi2ss64:
Craig Topper7609f1c2016-10-01 21:03:50 +00002043 case X86::BI__builtin_ia32_cvtusi2sd64:
2044 case X86::BI__builtin_ia32_cvtusi2ss32:
2045 case X86::BI__builtin_ia32_cvtusi2ss64:
2046 ArgNum = 2;
2047 HasRC = true;
2048 break;
2049 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
2050 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
2051 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
2052 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
2053 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
2054 case X86::BI__builtin_ia32_cvtps2qq512_mask:
2055 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
2056 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
2057 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
2058 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
2059 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002060 case X86::BI__builtin_ia32_sqrtpd512_mask:
2061 case X86::BI__builtin_ia32_sqrtps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002062 ArgNum = 3;
2063 HasRC = true;
2064 break;
2065 case X86::BI__builtin_ia32_addpd512_mask:
2066 case X86::BI__builtin_ia32_addps512_mask:
2067 case X86::BI__builtin_ia32_divpd512_mask:
2068 case X86::BI__builtin_ia32_divps512_mask:
2069 case X86::BI__builtin_ia32_mulpd512_mask:
2070 case X86::BI__builtin_ia32_mulps512_mask:
2071 case X86::BI__builtin_ia32_subpd512_mask:
2072 case X86::BI__builtin_ia32_subps512_mask:
2073 case X86::BI__builtin_ia32_addss_round_mask:
2074 case X86::BI__builtin_ia32_addsd_round_mask:
2075 case X86::BI__builtin_ia32_divss_round_mask:
2076 case X86::BI__builtin_ia32_divsd_round_mask:
2077 case X86::BI__builtin_ia32_mulss_round_mask:
2078 case X86::BI__builtin_ia32_mulsd_round_mask:
2079 case X86::BI__builtin_ia32_subss_round_mask:
2080 case X86::BI__builtin_ia32_subsd_round_mask:
2081 case X86::BI__builtin_ia32_scalefpd512_mask:
2082 case X86::BI__builtin_ia32_scalefps512_mask:
2083 case X86::BI__builtin_ia32_scalefsd_round_mask:
2084 case X86::BI__builtin_ia32_scalefss_round_mask:
2085 case X86::BI__builtin_ia32_getmantpd512_mask:
2086 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002087 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
2088 case X86::BI__builtin_ia32_sqrtsd_round_mask:
2089 case X86::BI__builtin_ia32_sqrtss_round_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002090 case X86::BI__builtin_ia32_vfmaddpd512_mask:
2091 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
2092 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
2093 case X86::BI__builtin_ia32_vfmaddps512_mask:
2094 case X86::BI__builtin_ia32_vfmaddps512_mask3:
2095 case X86::BI__builtin_ia32_vfmaddps512_maskz:
2096 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
2097 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
2098 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
2099 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
2100 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
2101 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
2102 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
2103 case X86::BI__builtin_ia32_vfmsubps512_mask3:
2104 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
2105 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
2106 case X86::BI__builtin_ia32_vfnmaddpd512_mask:
2107 case X86::BI__builtin_ia32_vfnmaddps512_mask:
2108 case X86::BI__builtin_ia32_vfnmsubpd512_mask:
2109 case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
2110 case X86::BI__builtin_ia32_vfnmsubps512_mask:
2111 case X86::BI__builtin_ia32_vfnmsubps512_mask3:
2112 case X86::BI__builtin_ia32_vfmaddsd3_mask:
2113 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
2114 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
2115 case X86::BI__builtin_ia32_vfmaddss3_mask:
2116 case X86::BI__builtin_ia32_vfmaddss3_maskz:
2117 case X86::BI__builtin_ia32_vfmaddss3_mask3:
2118 ArgNum = 4;
2119 HasRC = true;
2120 break;
2121 case X86::BI__builtin_ia32_getmantsd_round_mask:
2122 case X86::BI__builtin_ia32_getmantss_round_mask:
2123 ArgNum = 5;
2124 HasRC = true;
2125 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00002126 }
2127
2128 llvm::APSInt Result;
2129
2130 // We can't check the value of a dependent argument.
2131 Expr *Arg = TheCall->getArg(ArgNum);
2132 if (Arg->isTypeDependent() || Arg->isValueDependent())
2133 return false;
2134
2135 // Check constant-ness first.
2136 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2137 return true;
2138
2139 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
2140 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
2141 // combined with ROUND_NO_EXC.
2142 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
2143 Result == 8/*ROUND_NO_EXC*/ ||
2144 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
2145 return false;
2146
2147 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
2148 << Arg->getSourceRange();
2149}
2150
Craig Topperdf5beb22017-03-13 17:16:50 +00002151// Check if the gather/scatter scale is legal.
2152bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
2153 CallExpr *TheCall) {
2154 unsigned ArgNum = 0;
2155 switch (BuiltinID) {
2156 default:
2157 return false;
2158 case X86::BI__builtin_ia32_gatherpfdpd:
2159 case X86::BI__builtin_ia32_gatherpfdps:
2160 case X86::BI__builtin_ia32_gatherpfqpd:
2161 case X86::BI__builtin_ia32_gatherpfqps:
2162 case X86::BI__builtin_ia32_scatterpfdpd:
2163 case X86::BI__builtin_ia32_scatterpfdps:
2164 case X86::BI__builtin_ia32_scatterpfqpd:
2165 case X86::BI__builtin_ia32_scatterpfqps:
2166 ArgNum = 3;
2167 break;
2168 case X86::BI__builtin_ia32_gatherd_pd:
2169 case X86::BI__builtin_ia32_gatherd_pd256:
2170 case X86::BI__builtin_ia32_gatherq_pd:
2171 case X86::BI__builtin_ia32_gatherq_pd256:
2172 case X86::BI__builtin_ia32_gatherd_ps:
2173 case X86::BI__builtin_ia32_gatherd_ps256:
2174 case X86::BI__builtin_ia32_gatherq_ps:
2175 case X86::BI__builtin_ia32_gatherq_ps256:
2176 case X86::BI__builtin_ia32_gatherd_q:
2177 case X86::BI__builtin_ia32_gatherd_q256:
2178 case X86::BI__builtin_ia32_gatherq_q:
2179 case X86::BI__builtin_ia32_gatherq_q256:
2180 case X86::BI__builtin_ia32_gatherd_d:
2181 case X86::BI__builtin_ia32_gatherd_d256:
2182 case X86::BI__builtin_ia32_gatherq_d:
2183 case X86::BI__builtin_ia32_gatherq_d256:
2184 case X86::BI__builtin_ia32_gather3div2df:
2185 case X86::BI__builtin_ia32_gather3div2di:
2186 case X86::BI__builtin_ia32_gather3div4df:
2187 case X86::BI__builtin_ia32_gather3div4di:
2188 case X86::BI__builtin_ia32_gather3div4sf:
2189 case X86::BI__builtin_ia32_gather3div4si:
2190 case X86::BI__builtin_ia32_gather3div8sf:
2191 case X86::BI__builtin_ia32_gather3div8si:
2192 case X86::BI__builtin_ia32_gather3siv2df:
2193 case X86::BI__builtin_ia32_gather3siv2di:
2194 case X86::BI__builtin_ia32_gather3siv4df:
2195 case X86::BI__builtin_ia32_gather3siv4di:
2196 case X86::BI__builtin_ia32_gather3siv4sf:
2197 case X86::BI__builtin_ia32_gather3siv4si:
2198 case X86::BI__builtin_ia32_gather3siv8sf:
2199 case X86::BI__builtin_ia32_gather3siv8si:
2200 case X86::BI__builtin_ia32_gathersiv8df:
2201 case X86::BI__builtin_ia32_gathersiv16sf:
2202 case X86::BI__builtin_ia32_gatherdiv8df:
2203 case X86::BI__builtin_ia32_gatherdiv16sf:
2204 case X86::BI__builtin_ia32_gathersiv8di:
2205 case X86::BI__builtin_ia32_gathersiv16si:
2206 case X86::BI__builtin_ia32_gatherdiv8di:
2207 case X86::BI__builtin_ia32_gatherdiv16si:
2208 case X86::BI__builtin_ia32_scatterdiv2df:
2209 case X86::BI__builtin_ia32_scatterdiv2di:
2210 case X86::BI__builtin_ia32_scatterdiv4df:
2211 case X86::BI__builtin_ia32_scatterdiv4di:
2212 case X86::BI__builtin_ia32_scatterdiv4sf:
2213 case X86::BI__builtin_ia32_scatterdiv4si:
2214 case X86::BI__builtin_ia32_scatterdiv8sf:
2215 case X86::BI__builtin_ia32_scatterdiv8si:
2216 case X86::BI__builtin_ia32_scattersiv2df:
2217 case X86::BI__builtin_ia32_scattersiv2di:
2218 case X86::BI__builtin_ia32_scattersiv4df:
2219 case X86::BI__builtin_ia32_scattersiv4di:
2220 case X86::BI__builtin_ia32_scattersiv4sf:
2221 case X86::BI__builtin_ia32_scattersiv4si:
2222 case X86::BI__builtin_ia32_scattersiv8sf:
2223 case X86::BI__builtin_ia32_scattersiv8si:
2224 case X86::BI__builtin_ia32_scattersiv8df:
2225 case X86::BI__builtin_ia32_scattersiv16sf:
2226 case X86::BI__builtin_ia32_scatterdiv8df:
2227 case X86::BI__builtin_ia32_scatterdiv16sf:
2228 case X86::BI__builtin_ia32_scattersiv8di:
2229 case X86::BI__builtin_ia32_scattersiv16si:
2230 case X86::BI__builtin_ia32_scatterdiv8di:
2231 case X86::BI__builtin_ia32_scatterdiv16si:
2232 ArgNum = 4;
2233 break;
2234 }
2235
2236 llvm::APSInt Result;
2237
2238 // We can't check the value of a dependent argument.
2239 Expr *Arg = TheCall->getArg(ArgNum);
2240 if (Arg->isTypeDependent() || Arg->isValueDependent())
2241 return false;
2242
2243 // Check constant-ness first.
2244 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2245 return true;
2246
2247 if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
2248 return false;
2249
2250 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
2251 << Arg->getSourceRange();
2252}
2253
Craig Topperf0ddc892016-09-23 04:48:27 +00002254bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2255 if (BuiltinID == X86::BI__builtin_cpu_supports)
2256 return SemaBuiltinCpuSupports(*this, TheCall);
2257
Craig Topper699ae0c2017-08-10 20:28:30 +00002258 if (BuiltinID == X86::BI__builtin_cpu_is)
2259 return SemaBuiltinCpuIs(*this, TheCall);
2260
Craig Toppera7e253e2016-09-23 04:48:31 +00002261 // If the intrinsic has rounding or SAE make sure its valid.
2262 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2263 return true;
2264
Craig Topperdf5beb22017-03-13 17:16:50 +00002265 // If the intrinsic has a gather/scatter scale immediate make sure its valid.
2266 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
2267 return true;
2268
Craig Topperf0ddc892016-09-23 04:48:27 +00002269 // For intrinsics which take an immediate value as part of the instruction,
2270 // range check them here.
2271 int i = 0, l = 0, u = 0;
2272 switch (BuiltinID) {
2273 default:
2274 return false;
Richard Trieucc3949d2016-02-18 22:34:54 +00002275 case X86::BI_mm_prefetch:
Craig Topper170de4b2017-12-21 23:50:22 +00002276 i = 1; l = 0; u = 7;
Craig Topper39c87102016-05-18 03:18:12 +00002277 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00002278 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper39c87102016-05-18 03:18:12 +00002279 case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2280 case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2281 case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2282 case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002283 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002284 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00002285 case X86::BI__builtin_ia32_vpermil2pd:
2286 case X86::BI__builtin_ia32_vpermil2pd256:
2287 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00002288 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00002289 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002290 break;
Craig Topper95b0d732015-01-25 23:30:05 +00002291 case X86::BI__builtin_ia32_cmpb128_mask:
2292 case X86::BI__builtin_ia32_cmpw128_mask:
2293 case X86::BI__builtin_ia32_cmpd128_mask:
2294 case X86::BI__builtin_ia32_cmpq128_mask:
2295 case X86::BI__builtin_ia32_cmpb256_mask:
2296 case X86::BI__builtin_ia32_cmpw256_mask:
2297 case X86::BI__builtin_ia32_cmpd256_mask:
2298 case X86::BI__builtin_ia32_cmpq256_mask:
2299 case X86::BI__builtin_ia32_cmpb512_mask:
2300 case X86::BI__builtin_ia32_cmpw512_mask:
2301 case X86::BI__builtin_ia32_cmpd512_mask:
2302 case X86::BI__builtin_ia32_cmpq512_mask:
2303 case X86::BI__builtin_ia32_ucmpb128_mask:
2304 case X86::BI__builtin_ia32_ucmpw128_mask:
2305 case X86::BI__builtin_ia32_ucmpd128_mask:
2306 case X86::BI__builtin_ia32_ucmpq128_mask:
2307 case X86::BI__builtin_ia32_ucmpb256_mask:
2308 case X86::BI__builtin_ia32_ucmpw256_mask:
2309 case X86::BI__builtin_ia32_ucmpd256_mask:
2310 case X86::BI__builtin_ia32_ucmpq256_mask:
2311 case X86::BI__builtin_ia32_ucmpb512_mask:
2312 case X86::BI__builtin_ia32_ucmpw512_mask:
2313 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00002314 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00002315 case X86::BI__builtin_ia32_vpcomub:
2316 case X86::BI__builtin_ia32_vpcomuw:
2317 case X86::BI__builtin_ia32_vpcomud:
2318 case X86::BI__builtin_ia32_vpcomuq:
2319 case X86::BI__builtin_ia32_vpcomb:
2320 case X86::BI__builtin_ia32_vpcomw:
2321 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00002322 case X86::BI__builtin_ia32_vpcomq:
Craig Topper39c87102016-05-18 03:18:12 +00002323 i = 2; l = 0; u = 7;
2324 break;
2325 case X86::BI__builtin_ia32_roundps:
2326 case X86::BI__builtin_ia32_roundpd:
2327 case X86::BI__builtin_ia32_roundps256:
2328 case X86::BI__builtin_ia32_roundpd256:
Craig Topper39c87102016-05-18 03:18:12 +00002329 i = 1; l = 0; u = 15;
2330 break;
2331 case X86::BI__builtin_ia32_roundss:
2332 case X86::BI__builtin_ia32_roundsd:
2333 case X86::BI__builtin_ia32_rangepd128_mask:
2334 case X86::BI__builtin_ia32_rangepd256_mask:
2335 case X86::BI__builtin_ia32_rangepd512_mask:
2336 case X86::BI__builtin_ia32_rangeps128_mask:
2337 case X86::BI__builtin_ia32_rangeps256_mask:
2338 case X86::BI__builtin_ia32_rangeps512_mask:
2339 case X86::BI__builtin_ia32_getmantsd_round_mask:
2340 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002341 i = 2; l = 0; u = 15;
2342 break;
2343 case X86::BI__builtin_ia32_cmpps:
2344 case X86::BI__builtin_ia32_cmpss:
2345 case X86::BI__builtin_ia32_cmppd:
2346 case X86::BI__builtin_ia32_cmpsd:
2347 case X86::BI__builtin_ia32_cmpps256:
2348 case X86::BI__builtin_ia32_cmppd256:
2349 case X86::BI__builtin_ia32_cmpps128_mask:
2350 case X86::BI__builtin_ia32_cmppd128_mask:
2351 case X86::BI__builtin_ia32_cmpps256_mask:
2352 case X86::BI__builtin_ia32_cmppd256_mask:
2353 case X86::BI__builtin_ia32_cmpps512_mask:
2354 case X86::BI__builtin_ia32_cmppd512_mask:
2355 case X86::BI__builtin_ia32_cmpsd_mask:
2356 case X86::BI__builtin_ia32_cmpss_mask:
2357 i = 2; l = 0; u = 31;
2358 break;
Craig Topper39c87102016-05-18 03:18:12 +00002359 case X86::BI__builtin_ia32_vcvtps2ph:
Craig Topper23a30222017-11-08 04:54:26 +00002360 case X86::BI__builtin_ia32_vcvtps2ph_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002361 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper23a30222017-11-08 04:54:26 +00002362 case X86::BI__builtin_ia32_vcvtps2ph256_mask:
2363 case X86::BI__builtin_ia32_vcvtps2ph512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002364 case X86::BI__builtin_ia32_rndscaleps_128_mask:
2365 case X86::BI__builtin_ia32_rndscalepd_128_mask:
2366 case X86::BI__builtin_ia32_rndscaleps_256_mask:
2367 case X86::BI__builtin_ia32_rndscalepd_256_mask:
2368 case X86::BI__builtin_ia32_rndscaleps_mask:
2369 case X86::BI__builtin_ia32_rndscalepd_mask:
2370 case X86::BI__builtin_ia32_reducepd128_mask:
2371 case X86::BI__builtin_ia32_reducepd256_mask:
2372 case X86::BI__builtin_ia32_reducepd512_mask:
2373 case X86::BI__builtin_ia32_reduceps128_mask:
2374 case X86::BI__builtin_ia32_reduceps256_mask:
2375 case X86::BI__builtin_ia32_reduceps512_mask:
2376 case X86::BI__builtin_ia32_prold512_mask:
2377 case X86::BI__builtin_ia32_prolq512_mask:
2378 case X86::BI__builtin_ia32_prold128_mask:
2379 case X86::BI__builtin_ia32_prold256_mask:
2380 case X86::BI__builtin_ia32_prolq128_mask:
2381 case X86::BI__builtin_ia32_prolq256_mask:
2382 case X86::BI__builtin_ia32_prord128_mask:
2383 case X86::BI__builtin_ia32_prord256_mask:
2384 case X86::BI__builtin_ia32_prorq128_mask:
2385 case X86::BI__builtin_ia32_prorq256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002386 case X86::BI__builtin_ia32_fpclasspd128_mask:
2387 case X86::BI__builtin_ia32_fpclasspd256_mask:
2388 case X86::BI__builtin_ia32_fpclassps128_mask:
2389 case X86::BI__builtin_ia32_fpclassps256_mask:
2390 case X86::BI__builtin_ia32_fpclassps512_mask:
2391 case X86::BI__builtin_ia32_fpclasspd512_mask:
2392 case X86::BI__builtin_ia32_fpclasssd_mask:
2393 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002394 i = 1; l = 0; u = 255;
2395 break;
Craig Topper39c87102016-05-18 03:18:12 +00002396 case X86::BI__builtin_ia32_palignr128:
2397 case X86::BI__builtin_ia32_palignr256:
Craig Topper39c87102016-05-18 03:18:12 +00002398 case X86::BI__builtin_ia32_palignr512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002399 case X86::BI__builtin_ia32_vcomisd:
2400 case X86::BI__builtin_ia32_vcomiss:
2401 case X86::BI__builtin_ia32_shuf_f32x4_mask:
2402 case X86::BI__builtin_ia32_shuf_f64x2_mask:
2403 case X86::BI__builtin_ia32_shuf_i32x4_mask:
2404 case X86::BI__builtin_ia32_shuf_i64x2_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002405 case X86::BI__builtin_ia32_dbpsadbw128_mask:
2406 case X86::BI__builtin_ia32_dbpsadbw256_mask:
2407 case X86::BI__builtin_ia32_dbpsadbw512_mask:
Craig Topper91926432018-01-11 01:38:02 +00002408 case X86::BI__builtin_ia32_vpshldd128_mask:
2409 case X86::BI__builtin_ia32_vpshldd256_mask:
2410 case X86::BI__builtin_ia32_vpshldd512_mask:
2411 case X86::BI__builtin_ia32_vpshldq128_mask:
2412 case X86::BI__builtin_ia32_vpshldq256_mask:
2413 case X86::BI__builtin_ia32_vpshldq512_mask:
2414 case X86::BI__builtin_ia32_vpshldw128_mask:
2415 case X86::BI__builtin_ia32_vpshldw256_mask:
2416 case X86::BI__builtin_ia32_vpshldw512_mask:
2417 case X86::BI__builtin_ia32_vpshrdd128_mask:
2418 case X86::BI__builtin_ia32_vpshrdd256_mask:
2419 case X86::BI__builtin_ia32_vpshrdd512_mask:
2420 case X86::BI__builtin_ia32_vpshrdq128_mask:
2421 case X86::BI__builtin_ia32_vpshrdq256_mask:
2422 case X86::BI__builtin_ia32_vpshrdq512_mask:
2423 case X86::BI__builtin_ia32_vpshrdw128_mask:
2424 case X86::BI__builtin_ia32_vpshrdw256_mask:
2425 case X86::BI__builtin_ia32_vpshrdw512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002426 i = 2; l = 0; u = 255;
2427 break;
2428 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2429 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2430 case X86::BI__builtin_ia32_fixupimmps512_mask:
2431 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2432 case X86::BI__builtin_ia32_fixupimmsd_mask:
2433 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2434 case X86::BI__builtin_ia32_fixupimmss_mask:
2435 case X86::BI__builtin_ia32_fixupimmss_maskz:
2436 case X86::BI__builtin_ia32_fixupimmpd128_mask:
2437 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2438 case X86::BI__builtin_ia32_fixupimmpd256_mask:
2439 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2440 case X86::BI__builtin_ia32_fixupimmps128_mask:
2441 case X86::BI__builtin_ia32_fixupimmps128_maskz:
2442 case X86::BI__builtin_ia32_fixupimmps256_mask:
2443 case X86::BI__builtin_ia32_fixupimmps256_maskz:
2444 case X86::BI__builtin_ia32_pternlogd512_mask:
2445 case X86::BI__builtin_ia32_pternlogd512_maskz:
2446 case X86::BI__builtin_ia32_pternlogq512_mask:
2447 case X86::BI__builtin_ia32_pternlogq512_maskz:
2448 case X86::BI__builtin_ia32_pternlogd128_mask:
2449 case X86::BI__builtin_ia32_pternlogd128_maskz:
2450 case X86::BI__builtin_ia32_pternlogd256_mask:
2451 case X86::BI__builtin_ia32_pternlogd256_maskz:
2452 case X86::BI__builtin_ia32_pternlogq128_mask:
2453 case X86::BI__builtin_ia32_pternlogq128_maskz:
2454 case X86::BI__builtin_ia32_pternlogq256_mask:
2455 case X86::BI__builtin_ia32_pternlogq256_maskz:
2456 i = 3; l = 0; u = 255;
2457 break;
Craig Topper9625db02017-03-12 22:19:10 +00002458 case X86::BI__builtin_ia32_gatherpfdpd:
2459 case X86::BI__builtin_ia32_gatherpfdps:
2460 case X86::BI__builtin_ia32_gatherpfqpd:
2461 case X86::BI__builtin_ia32_gatherpfqps:
2462 case X86::BI__builtin_ia32_scatterpfdpd:
2463 case X86::BI__builtin_ia32_scatterpfdps:
2464 case X86::BI__builtin_ia32_scatterpfqpd:
2465 case X86::BI__builtin_ia32_scatterpfqps:
Craig Topperf771f79b2017-03-31 17:22:30 +00002466 i = 4; l = 2; u = 3;
Craig Topper9625db02017-03-12 22:19:10 +00002467 break;
Craig Topper39c87102016-05-18 03:18:12 +00002468 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2469 case X86::BI__builtin_ia32_rndscaless_round_mask:
2470 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00002471 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002472 }
Craig Topperdd84ec52014-12-27 07:00:08 +00002473 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002474}
2475
Richard Smith55ce3522012-06-25 20:30:08 +00002476/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2477/// parameter with the FormatAttr's correct format_idx and firstDataArg.
2478/// Returns true when the format fits the function and the FormatStringInfo has
2479/// been populated.
2480bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2481 FormatStringInfo *FSI) {
2482 FSI->HasVAListArg = Format->getFirstArg() == 0;
2483 FSI->FormatIdx = Format->getFormatIdx() - 1;
2484 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002485
Richard Smith55ce3522012-06-25 20:30:08 +00002486 // The way the format attribute works in GCC, the implicit this argument
2487 // of member functions is counted. However, it doesn't appear in our own
2488 // lists, so decrement format_idx in that case.
2489 if (IsCXXMember) {
2490 if(FSI->FormatIdx == 0)
2491 return false;
2492 --FSI->FormatIdx;
2493 if (FSI->FirstDataArg != 0)
2494 --FSI->FirstDataArg;
2495 }
2496 return true;
2497}
Mike Stump11289f42009-09-09 15:08:12 +00002498
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002499/// Checks if a the given expression evaluates to null.
2500///
2501/// \brief Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00002502static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002503 // If the expression has non-null type, it doesn't evaluate to null.
2504 if (auto nullability
2505 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2506 if (*nullability == NullabilityKind::NonNull)
2507 return false;
2508 }
2509
Ted Kremeneka146db32014-01-17 06:24:47 +00002510 // As a special case, transparent unions initialized with zero are
2511 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002512 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00002513 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2514 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002515 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00002516 if (const InitListExpr *ILE =
2517 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002518 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00002519 }
2520
2521 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00002522 return (!Expr->isValueDependent() &&
2523 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2524 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002525}
2526
2527static void CheckNonNullArgument(Sema &S,
2528 const Expr *ArgExpr,
2529 SourceLocation CallSiteLoc) {
2530 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00002531 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2532 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00002533}
2534
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002535bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2536 FormatStringInfo FSI;
2537 if ((GetFormatStringType(Format) == FST_NSString) &&
2538 getFormatStringInfo(Format, false, &FSI)) {
2539 Idx = FSI.FormatIdx;
2540 return true;
2541 }
2542 return false;
2543}
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002544
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002545/// \brief Diagnose use of %s directive in an NSString which is being passed
2546/// as formatting string to formatting method.
2547static void
2548DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2549 const NamedDecl *FDecl,
2550 Expr **Args,
2551 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002552 unsigned Idx = 0;
2553 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002554 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2555 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002556 Idx = 2;
2557 Format = true;
2558 }
2559 else
2560 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2561 if (S.GetFormatNSStringIdx(I, Idx)) {
2562 Format = true;
2563 break;
2564 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002565 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002566 if (!Format || NumArgs <= Idx)
2567 return;
2568 const Expr *FormatExpr = Args[Idx];
2569 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2570 FormatExpr = CSCE->getSubExpr();
2571 const StringLiteral *FormatString;
2572 if (const ObjCStringLiteral *OSL =
2573 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2574 FormatString = OSL->getString();
2575 else
2576 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2577 if (!FormatString)
2578 return;
2579 if (S.FormatStringHasSArg(FormatString)) {
2580 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2581 << "%s" << 1 << 1;
2582 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2583 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002584 }
2585}
2586
Douglas Gregorb4866e82015-06-19 18:13:19 +00002587/// Determine whether the given type has a non-null nullability annotation.
2588static bool isNonNullType(ASTContext &ctx, QualType type) {
2589 if (auto nullability = type->getNullability(ctx))
2590 return *nullability == NullabilityKind::NonNull;
2591
2592 return false;
2593}
2594
Ted Kremenek2bc73332014-01-17 06:24:43 +00002595static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00002596 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002597 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00002598 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00002599 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002600 assert((FDecl || Proto) && "Need a function declaration or prototype");
2601
Ted Kremenek9aedc152014-01-17 06:24:56 +00002602 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00002603 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00002604 if (FDecl) {
2605 // Handle the nonnull attribute on the function/method declaration itself.
2606 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2607 if (!NonNull->args_size()) {
2608 // Easy case: all pointer arguments are nonnull.
2609 for (const auto *Arg : Args)
2610 if (S.isValidPointerAttrType(Arg->getType()))
2611 CheckNonNullArgument(S, Arg, CallSiteLoc);
2612 return;
2613 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002614
Joel E. Denny81508102018-03-13 14:51:22 +00002615 for (const ParamIdx &Idx : NonNull->args()) {
2616 unsigned IdxAST = Idx.getASTIndex();
2617 if (IdxAST >= Args.size())
Douglas Gregorb4866e82015-06-19 18:13:19 +00002618 continue;
2619 if (NonNullArgs.empty())
2620 NonNullArgs.resize(Args.size());
Joel E. Denny81508102018-03-13 14:51:22 +00002621 NonNullArgs.set(IdxAST);
Douglas Gregorb4866e82015-06-19 18:13:19 +00002622 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002623 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002624 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002625
Douglas Gregorb4866e82015-06-19 18:13:19 +00002626 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2627 // Handle the nonnull attribute on the parameters of the
2628 // function/method.
2629 ArrayRef<ParmVarDecl*> parms;
2630 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2631 parms = FD->parameters();
2632 else
2633 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2634
2635 unsigned ParamIndex = 0;
2636 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2637 I != E; ++I, ++ParamIndex) {
2638 const ParmVarDecl *PVD = *I;
2639 if (PVD->hasAttr<NonNullAttr>() ||
2640 isNonNullType(S.Context, PVD->getType())) {
2641 if (NonNullArgs.empty())
2642 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00002643
Douglas Gregorb4866e82015-06-19 18:13:19 +00002644 NonNullArgs.set(ParamIndex);
2645 }
2646 }
2647 } else {
2648 // If we have a non-function, non-method declaration but no
2649 // function prototype, try to dig out the function prototype.
2650 if (!Proto) {
2651 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2652 QualType type = VD->getType().getNonReferenceType();
2653 if (auto pointerType = type->getAs<PointerType>())
2654 type = pointerType->getPointeeType();
2655 else if (auto blockType = type->getAs<BlockPointerType>())
2656 type = blockType->getPointeeType();
2657 // FIXME: data member pointers?
2658
2659 // Dig out the function prototype, if there is one.
2660 Proto = type->getAs<FunctionProtoType>();
2661 }
2662 }
2663
2664 // Fill in non-null argument information from the nullability
2665 // information on the parameter types (if we have them).
2666 if (Proto) {
2667 unsigned Index = 0;
2668 for (auto paramType : Proto->getParamTypes()) {
2669 if (isNonNullType(S.Context, paramType)) {
2670 if (NonNullArgs.empty())
2671 NonNullArgs.resize(Args.size());
2672
2673 NonNullArgs.set(Index);
2674 }
2675
2676 ++Index;
2677 }
2678 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002679 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002680
Douglas Gregorb4866e82015-06-19 18:13:19 +00002681 // Check for non-null arguments.
2682 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2683 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00002684 if (NonNullArgs[ArgIndex])
2685 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00002686 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002687}
2688
Richard Smith55ce3522012-06-25 20:30:08 +00002689/// Handles the checks for format strings, non-POD arguments to vararg
George Burgess IVce6284b2017-01-28 02:19:40 +00002690/// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
2691/// attributes.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002692void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
George Burgess IVce6284b2017-01-28 02:19:40 +00002693 const Expr *ThisArg, ArrayRef<const Expr *> Args,
2694 bool IsMemberFunction, SourceLocation Loc,
2695 SourceRange Range, VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00002696 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00002697 if (CurContext->isDependentContext())
2698 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00002699
Ted Kremenekb8176da2010-09-09 04:33:05 +00002700 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00002701 llvm::SmallBitVector CheckedVarArgs;
2702 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002703 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002704 // Only create vector if there are format attributes.
2705 CheckedVarArgs.resize(Args.size());
2706
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002707 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00002708 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002709 }
Richard Smithd7293d72013-08-05 18:49:43 +00002710 }
Richard Smith55ce3522012-06-25 20:30:08 +00002711
2712 // Refuse POD arguments that weren't caught by the format string
2713 // checks above.
Richard Smith836de6b2016-12-19 23:59:34 +00002714 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
2715 if (CallType != VariadicDoesNotApply &&
2716 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002717 unsigned NumParams = Proto ? Proto->getNumParams()
2718 : FDecl && isa<FunctionDecl>(FDecl)
2719 ? cast<FunctionDecl>(FDecl)->getNumParams()
2720 : FDecl && isa<ObjCMethodDecl>(FDecl)
2721 ? cast<ObjCMethodDecl>(FDecl)->param_size()
2722 : 0;
2723
Alp Toker9cacbab2014-01-20 20:26:09 +00002724 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002725 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00002726 if (const Expr *Arg = Args[ArgIdx]) {
2727 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2728 checkVariadicArgument(Arg, CallType);
2729 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002730 }
Richard Smithd7293d72013-08-05 18:49:43 +00002731 }
Mike Stump11289f42009-09-09 15:08:12 +00002732
Douglas Gregorb4866e82015-06-19 18:13:19 +00002733 if (FDecl || Proto) {
2734 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002735
Richard Trieu41bc0992013-06-22 00:20:41 +00002736 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002737 if (FDecl) {
2738 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +00002739 CheckArgumentWithTypeTag(I, Args, Loc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00002740 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002741 }
George Burgess IVce6284b2017-01-28 02:19:40 +00002742
2743 if (FD)
2744 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
Richard Smith55ce3522012-06-25 20:30:08 +00002745}
2746
2747/// CheckConstructorCall - Check a constructor call for correctness and safety
2748/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002749void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2750 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002751 const FunctionProtoType *Proto,
2752 SourceLocation Loc) {
2753 VariadicCallType CallType =
2754 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
George Burgess IVce6284b2017-01-28 02:19:40 +00002755 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
2756 Loc, SourceRange(), CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00002757}
2758
2759/// CheckFunctionCall - Check a direct function call for various correctness
2760/// and safety properties not strictly enforced by the C type system.
2761bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2762 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002763 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2764 isa<CXXMethodDecl>(FDecl);
2765 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2766 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00002767 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2768 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00002769 Expr** Args = TheCall->getArgs();
2770 unsigned NumArgs = TheCall->getNumArgs();
George Burgess IVce6284b2017-01-28 02:19:40 +00002771
2772 Expr *ImplicitThis = nullptr;
Eli Friedmanadf42182012-10-11 00:34:15 +00002773 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002774 // If this is a call to a member operator, hide the first argument
2775 // from checkCall.
2776 // FIXME: Our choice of AST representation here is less than ideal.
George Burgess IVce6284b2017-01-28 02:19:40 +00002777 ImplicitThis = Args[0];
Eli Friedman726d11c2012-10-11 00:30:58 +00002778 ++Args;
2779 --NumArgs;
George Burgess IVce6284b2017-01-28 02:19:40 +00002780 } else if (IsMemberFunction)
2781 ImplicitThis =
2782 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
2783
2784 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00002785 IsMemberFunction, TheCall->getRParenLoc(),
2786 TheCall->getCallee()->getSourceRange(), CallType);
2787
2788 IdentifierInfo *FnInfo = FDecl->getIdentifier();
2789 // None of the checks below are needed for functions that don't have
2790 // simple names (e.g., C++ conversion functions).
2791 if (!FnInfo)
2792 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002793
Richard Trieua7f30b12016-12-06 01:42:28 +00002794 CheckAbsoluteValueFunction(TheCall, FDecl);
2795 CheckMaxUnsignedZero(TheCall, FDecl);
Richard Trieu67c00712016-12-05 23:41:46 +00002796
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002797 if (getLangOpts().ObjC1)
2798 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00002799
Anna Zaks22122702012-01-17 00:37:07 +00002800 unsigned CMId = FDecl->getMemoryFunctionKind();
2801 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00002802 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00002803
Anna Zaks201d4892012-01-13 21:52:01 +00002804 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00002805 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00002806 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00002807 else if (CMId == Builtin::BIstrncat)
2808 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00002809 else
Anna Zaks22122702012-01-17 00:37:07 +00002810 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002811
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002812 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00002813}
2814
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002815bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00002816 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00002817 VariadicCallType CallType =
2818 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002819
George Burgess IVce6284b2017-01-28 02:19:40 +00002820 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
2821 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002822 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002823
2824 return false;
2825}
2826
Richard Trieu664c4c62013-06-20 21:03:13 +00002827bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2828 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00002829 QualType Ty;
2830 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002831 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002832 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002833 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002834 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002835 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002836
Douglas Gregorb4866e82015-06-19 18:13:19 +00002837 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2838 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002839 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002840
Richard Trieu664c4c62013-06-20 21:03:13 +00002841 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00002842 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00002843 CallType = VariadicDoesNotApply;
2844 } else if (Ty->isBlockPointerType()) {
2845 CallType = VariadicBlock;
2846 } else { // Ty->isFunctionPointerType()
2847 CallType = VariadicFunction;
2848 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002849
George Burgess IVce6284b2017-01-28 02:19:40 +00002850 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002851 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2852 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00002853 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00002854
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002855 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00002856}
2857
Richard Trieu41bc0992013-06-22 00:20:41 +00002858/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2859/// such as function pointers returned from functions.
2860bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002861 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00002862 TheCall->getCallee());
George Burgess IVce6284b2017-01-28 02:19:40 +00002863 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00002864 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002865 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00002866 TheCall->getCallee()->getSourceRange(), CallType);
2867
2868 return false;
2869}
2870
Tim Northovere94a34c2014-03-11 10:49:14 +00002871static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00002872 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00002873 return false;
2874
JF Bastiendda2cb12016-04-18 18:01:49 +00002875 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00002876 switch (Op) {
2877 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00002878 case AtomicExpr::AO__opencl_atomic_init:
Tim Northovere94a34c2014-03-11 10:49:14 +00002879 llvm_unreachable("There is no ordering argument for an init");
2880
2881 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00002882 case AtomicExpr::AO__opencl_atomic_load:
Tim Northovere94a34c2014-03-11 10:49:14 +00002883 case AtomicExpr::AO__atomic_load_n:
2884 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00002885 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2886 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002887
2888 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00002889 case AtomicExpr::AO__opencl_atomic_store:
Tim Northovere94a34c2014-03-11 10:49:14 +00002890 case AtomicExpr::AO__atomic_store:
2891 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00002892 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2893 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2894 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002895
2896 default:
2897 return true;
2898 }
2899}
2900
Richard Smithfeea8832012-04-12 05:08:17 +00002901ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2902 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002903 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2904 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002905
Yaxun Liu39195062017-08-04 18:16:31 +00002906 // All the non-OpenCL operations take one of the following forms.
2907 // The OpenCL operations take the __c11 forms with one extra argument for
2908 // synchronization scope.
Richard Smithfeea8832012-04-12 05:08:17 +00002909 enum {
2910 // C __c11_atomic_init(A *, C)
2911 Init,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002912
Richard Smithfeea8832012-04-12 05:08:17 +00002913 // C __c11_atomic_load(A *, int)
2914 Load,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002915
Richard Smithfeea8832012-04-12 05:08:17 +00002916 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00002917 LoadCopy,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002918
Eric Fiselier8d662442016-03-30 23:39:56 +00002919 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00002920 Copy,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002921
Richard Smithfeea8832012-04-12 05:08:17 +00002922 // C __c11_atomic_add(A *, M, int)
2923 Arithmetic,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002924
Richard Smithfeea8832012-04-12 05:08:17 +00002925 // C __atomic_exchange_n(A *, CP, int)
2926 Xchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002927
Richard Smithfeea8832012-04-12 05:08:17 +00002928 // void __atomic_exchange(A *, C *, CP, int)
2929 GNUXchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002930
Richard Smithfeea8832012-04-12 05:08:17 +00002931 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2932 C11CmpXchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002933
Richard Smithfeea8832012-04-12 05:08:17 +00002934 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2935 GNUCmpXchg
2936 } Form = Init;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002937
Yaxun Liu39195062017-08-04 18:16:31 +00002938 const unsigned NumForm = GNUCmpXchg + 1;
Eric Fiselier8d662442016-03-30 23:39:56 +00002939 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2940 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00002941 // where:
2942 // C is an appropriate type,
2943 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2944 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2945 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2946 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002947
Yaxun Liu39195062017-08-04 18:16:31 +00002948 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
2949 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
2950 "need to update code for modified forms");
Gabor Horvath98bd0982015-03-16 09:59:54 +00002951 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2952 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2953 AtomicExpr::AO__atomic_load,
2954 "need to update code for modified C11 atomics");
Yaxun Liu39195062017-08-04 18:16:31 +00002955 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
2956 Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
2957 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
2958 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
2959 IsOpenCL;
Richard Smithfeea8832012-04-12 05:08:17 +00002960 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2961 Op == AtomicExpr::AO__atomic_store_n ||
2962 Op == AtomicExpr::AO__atomic_exchange_n ||
2963 Op == AtomicExpr::AO__atomic_compare_exchange_n;
2964 bool IsAddSub = false;
2965
2966 switch (Op) {
2967 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00002968 case AtomicExpr::AO__opencl_atomic_init:
Richard Smithfeea8832012-04-12 05:08:17 +00002969 Form = Init;
2970 break;
2971
2972 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00002973 case AtomicExpr::AO__opencl_atomic_load:
Richard Smithfeea8832012-04-12 05:08:17 +00002974 case AtomicExpr::AO__atomic_load_n:
2975 Form = Load;
2976 break;
2977
Richard Smithfeea8832012-04-12 05:08:17 +00002978 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00002979 Form = LoadCopy;
2980 break;
2981
2982 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00002983 case AtomicExpr::AO__opencl_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00002984 case AtomicExpr::AO__atomic_store:
2985 case AtomicExpr::AO__atomic_store_n:
2986 Form = Copy;
2987 break;
2988
2989 case AtomicExpr::AO__c11_atomic_fetch_add:
2990 case AtomicExpr::AO__c11_atomic_fetch_sub:
Yaxun Liu39195062017-08-04 18:16:31 +00002991 case AtomicExpr::AO__opencl_atomic_fetch_add:
2992 case AtomicExpr::AO__opencl_atomic_fetch_sub:
2993 case AtomicExpr::AO__opencl_atomic_fetch_min:
2994 case AtomicExpr::AO__opencl_atomic_fetch_max:
Richard Smithfeea8832012-04-12 05:08:17 +00002995 case AtomicExpr::AO__atomic_fetch_add:
2996 case AtomicExpr::AO__atomic_fetch_sub:
2997 case AtomicExpr::AO__atomic_add_fetch:
2998 case AtomicExpr::AO__atomic_sub_fetch:
2999 IsAddSub = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00003000 LLVM_FALLTHROUGH;
Richard Smithfeea8832012-04-12 05:08:17 +00003001 case AtomicExpr::AO__c11_atomic_fetch_and:
3002 case AtomicExpr::AO__c11_atomic_fetch_or:
3003 case AtomicExpr::AO__c11_atomic_fetch_xor:
Yaxun Liu39195062017-08-04 18:16:31 +00003004 case AtomicExpr::AO__opencl_atomic_fetch_and:
3005 case AtomicExpr::AO__opencl_atomic_fetch_or:
3006 case AtomicExpr::AO__opencl_atomic_fetch_xor:
Richard Smithfeea8832012-04-12 05:08:17 +00003007 case AtomicExpr::AO__atomic_fetch_and:
3008 case AtomicExpr::AO__atomic_fetch_or:
3009 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00003010 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00003011 case AtomicExpr::AO__atomic_and_fetch:
3012 case AtomicExpr::AO__atomic_or_fetch:
3013 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00003014 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00003015 Form = Arithmetic;
3016 break;
3017
3018 case AtomicExpr::AO__c11_atomic_exchange:
Yaxun Liu39195062017-08-04 18:16:31 +00003019 case AtomicExpr::AO__opencl_atomic_exchange:
Richard Smithfeea8832012-04-12 05:08:17 +00003020 case AtomicExpr::AO__atomic_exchange_n:
3021 Form = Xchg;
3022 break;
3023
3024 case AtomicExpr::AO__atomic_exchange:
3025 Form = GNUXchg;
3026 break;
3027
3028 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3029 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
Yaxun Liu39195062017-08-04 18:16:31 +00003030 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
3031 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
Richard Smithfeea8832012-04-12 05:08:17 +00003032 Form = C11CmpXchg;
3033 break;
3034
3035 case AtomicExpr::AO__atomic_compare_exchange:
3036 case AtomicExpr::AO__atomic_compare_exchange_n:
3037 Form = GNUCmpXchg;
3038 break;
3039 }
3040
Yaxun Liu39195062017-08-04 18:16:31 +00003041 unsigned AdjustedNumArgs = NumArgs[Form];
3042 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
3043 ++AdjustedNumArgs;
Richard Smithfeea8832012-04-12 05:08:17 +00003044 // Check we have the right number of arguments.
Yaxun Liu39195062017-08-04 18:16:31 +00003045 if (TheCall->getNumArgs() < AdjustedNumArgs) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003046 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Yaxun Liu39195062017-08-04 18:16:31 +00003047 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003048 << TheCall->getCallee()->getSourceRange();
3049 return ExprError();
Yaxun Liu39195062017-08-04 18:16:31 +00003050 } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
3051 Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003052 diag::err_typecheck_call_too_many_args)
Yaxun Liu39195062017-08-04 18:16:31 +00003053 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003054 << TheCall->getCallee()->getSourceRange();
3055 return ExprError();
3056 }
3057
Richard Smithfeea8832012-04-12 05:08:17 +00003058 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003059 Expr *Ptr = TheCall->getArg(0);
George Burgess IV92b43a42016-07-21 03:28:13 +00003060 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
3061 if (ConvertedPtr.isInvalid())
3062 return ExprError();
3063
3064 Ptr = ConvertedPtr.get();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003065 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
3066 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00003067 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003068 << Ptr->getType() << Ptr->getSourceRange();
3069 return ExprError();
3070 }
3071
Richard Smithfeea8832012-04-12 05:08:17 +00003072 // For a __c11 builtin, this should be a pointer to an _Atomic type.
3073 QualType AtomTy = pointerType->getPointeeType(); // 'A'
3074 QualType ValType = AtomTy; // 'C'
3075 if (IsC11) {
3076 if (!AtomTy->isAtomicType()) {
3077 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
3078 << Ptr->getType() << Ptr->getSourceRange();
3079 return ExprError();
3080 }
Yaxun Liu39195062017-08-04 18:16:31 +00003081 if (AtomTy.isConstQualified() ||
3082 AtomTy.getAddressSpace() == LangAS::opencl_constant) {
Richard Smithe00921a2012-09-15 06:09:58 +00003083 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
Yaxun Liu39195062017-08-04 18:16:31 +00003084 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
3085 << Ptr->getSourceRange();
Richard Smithe00921a2012-09-15 06:09:58 +00003086 return ExprError();
3087 }
Richard Smithfeea8832012-04-12 05:08:17 +00003088 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00003089 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00003090 if (ValType.isConstQualified()) {
3091 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
3092 << Ptr->getType() << Ptr->getSourceRange();
3093 return ExprError();
3094 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003095 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003096
Richard Smithfeea8832012-04-12 05:08:17 +00003097 // For an arithmetic operation, the implied arithmetic must be well-formed.
3098 if (Form == Arithmetic) {
3099 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
3100 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
3101 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3102 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3103 return ExprError();
3104 }
3105 if (!IsAddSub && !ValType->isIntegerType()) {
3106 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
3107 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3108 return ExprError();
3109 }
David Majnemere85cff82015-01-28 05:48:06 +00003110 if (IsC11 && ValType->isPointerType() &&
3111 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
3112 diag::err_incomplete_type)) {
3113 return ExprError();
3114 }
Richard Smithfeea8832012-04-12 05:08:17 +00003115 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
3116 // For __atomic_*_n operations, the value type must be a scalar integral or
3117 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003118 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00003119 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3120 return ExprError();
3121 }
3122
Eli Friedmanaa769812013-09-11 03:49:34 +00003123 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
3124 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00003125 // For GNU atomics, require a trivially-copyable type. This is not part of
3126 // the GNU atomics specification, but we enforce it for sanity.
3127 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003128 << Ptr->getType() << Ptr->getSourceRange();
3129 return ExprError();
3130 }
3131
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003132 switch (ValType.getObjCLifetime()) {
3133 case Qualifiers::OCL_None:
3134 case Qualifiers::OCL_ExplicitNone:
3135 // okay
3136 break;
3137
3138 case Qualifiers::OCL_Weak:
3139 case Qualifiers::OCL_Strong:
3140 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00003141 // FIXME: Can this happen? By this point, ValType should be known
3142 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003143 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3144 << ValType << Ptr->getSourceRange();
3145 return ExprError();
3146 }
3147
David Majnemerc6eb6502015-06-03 00:26:35 +00003148 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
3149 // volatile-ness of the pointee-type inject itself into the result or the
Eric Fiselier8d662442016-03-30 23:39:56 +00003150 // other operands. Similarly atomic_load can take a pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00003151 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00003152 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003153 QualType ResultType = ValType;
Yaxun Liu39195062017-08-04 18:16:31 +00003154 if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
3155 Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003156 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00003157 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003158 ResultType = Context.BoolTy;
3159
Richard Smithfeea8832012-04-12 05:08:17 +00003160 // The type of a parameter passed 'by value'. In the GNU atomics, such
3161 // arguments are actually passed as pointers.
3162 QualType ByValType = ValType; // 'CP'
3163 if (!IsC11 && !IsN)
3164 ByValType = Ptr->getType();
3165
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003166 // The first argument --- the pointer --- has a fixed type; we
3167 // deduce the types of the rest of the arguments accordingly. Walk
3168 // the remaining arguments, converting them to the deduced value type.
Yaxun Liu39195062017-08-04 18:16:31 +00003169 for (unsigned i = 1; i != TheCall->getNumArgs(); ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003170 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00003171 if (i < NumVals[Form] + 1) {
3172 switch (i) {
3173 case 1:
3174 // The second argument is the non-atomic operand. For arithmetic, this
3175 // is always passed by value, and for a compare_exchange it is always
3176 // passed by address. For the rest, GNU uses by-address and C11 uses
3177 // by-value.
3178 assert(Form != Load);
3179 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
3180 Ty = ValType;
3181 else if (Form == Copy || Form == Xchg)
3182 Ty = ByValType;
3183 else if (Form == Arithmetic)
3184 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003185 else {
3186 Expr *ValArg = TheCall->getArg(i);
Alex Lorenz67522152016-11-23 16:57:03 +00003187 // Treat this argument as _Nonnull as we want to show a warning if
3188 // NULL is passed into it.
3189 CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
Alexander Richardson6d989432017-10-15 18:48:14 +00003190 LangAS AS = LangAS::Default;
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003191 // Keep address space of non-atomic pointer type.
3192 if (const PointerType *PtrTy =
3193 ValArg->getType()->getAs<PointerType>()) {
3194 AS = PtrTy->getPointeeType().getAddressSpace();
3195 }
3196 Ty = Context.getPointerType(
3197 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
3198 }
Richard Smithfeea8832012-04-12 05:08:17 +00003199 break;
3200 case 2:
3201 // The third argument to compare_exchange / GNU exchange is a
3202 // (pointer to a) desired value.
3203 Ty = ByValType;
3204 break;
3205 case 3:
3206 // The fourth argument to GNU compare_exchange is a 'weak' flag.
3207 Ty = Context.BoolTy;
3208 break;
3209 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003210 } else {
Yaxun Liu39195062017-08-04 18:16:31 +00003211 // The order(s) and scope are always converted to int.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003212 Ty = Context.IntTy;
3213 }
Richard Smithfeea8832012-04-12 05:08:17 +00003214
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003215 InitializedEntity Entity =
3216 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00003217 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003218 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3219 if (Arg.isInvalid())
3220 return true;
3221 TheCall->setArg(i, Arg.get());
3222 }
3223
Richard Smithfeea8832012-04-12 05:08:17 +00003224 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003225 SmallVector<Expr*, 5> SubExprs;
3226 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00003227 switch (Form) {
3228 case Init:
3229 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00003230 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003231 break;
3232 case Load:
3233 SubExprs.push_back(TheCall->getArg(1)); // Order
3234 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00003235 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00003236 case Copy:
3237 case Arithmetic:
3238 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003239 SubExprs.push_back(TheCall->getArg(2)); // Order
3240 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003241 break;
3242 case GNUXchg:
3243 // Note, AtomicExpr::getVal2() has a special case for this atomic.
3244 SubExprs.push_back(TheCall->getArg(3)); // Order
3245 SubExprs.push_back(TheCall->getArg(1)); // Val1
3246 SubExprs.push_back(TheCall->getArg(2)); // Val2
3247 break;
3248 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003249 SubExprs.push_back(TheCall->getArg(3)); // Order
3250 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003251 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00003252 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00003253 break;
3254 case GNUCmpXchg:
3255 SubExprs.push_back(TheCall->getArg(4)); // Order
3256 SubExprs.push_back(TheCall->getArg(1)); // Val1
3257 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
3258 SubExprs.push_back(TheCall->getArg(2)); // Val2
3259 SubExprs.push_back(TheCall->getArg(3)); // Weak
3260 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003261 }
Tim Northovere94a34c2014-03-11 10:49:14 +00003262
3263 if (SubExprs.size() >= 2 && Form != Init) {
3264 llvm::APSInt Result(32);
3265 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
3266 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00003267 Diag(SubExprs[1]->getLocStart(),
3268 diag::warn_atomic_op_has_invalid_memory_order)
3269 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00003270 }
3271
Yaxun Liu30d652a2017-08-15 16:02:49 +00003272 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
3273 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
3274 llvm::APSInt Result(32);
3275 if (Scope->isIntegerConstantExpr(Result, Context) &&
3276 !ScopeModel->isValid(Result.getZExtValue())) {
3277 Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope)
3278 << Scope->getSourceRange();
3279 }
3280 SubExprs.push_back(Scope);
3281 }
3282
Fariborz Jahanian615de762013-05-28 17:37:39 +00003283 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
3284 SubExprs, ResultType, Op,
3285 TheCall->getRParenLoc());
3286
3287 if ((Op == AtomicExpr::AO__c11_atomic_load ||
Yaxun Liu39195062017-08-04 18:16:31 +00003288 Op == AtomicExpr::AO__c11_atomic_store ||
3289 Op == AtomicExpr::AO__opencl_atomic_load ||
3290 Op == AtomicExpr::AO__opencl_atomic_store ) &&
Fariborz Jahanian615de762013-05-28 17:37:39 +00003291 Context.AtomicUsesUnsupportedLibcall(AE))
Yaxun Liu39195062017-08-04 18:16:31 +00003292 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib)
3293 << ((Op == AtomicExpr::AO__c11_atomic_load ||
3294 Op == AtomicExpr::AO__opencl_atomic_load)
3295 ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003296
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003297 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003298}
3299
John McCall29ad95b2011-08-27 01:09:30 +00003300/// checkBuiltinArgument - Given a call to a builtin function, perform
3301/// normal type-checking on the given argument, updating the call in
3302/// place. This is useful when a builtin function requires custom
3303/// type-checking for some of its arguments but not necessarily all of
3304/// them.
3305///
3306/// Returns true on error.
3307static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
3308 FunctionDecl *Fn = E->getDirectCallee();
3309 assert(Fn && "builtin call without direct callee!");
3310
3311 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
3312 InitializedEntity Entity =
3313 InitializedEntity::InitializeParameter(S.Context, Param);
3314
3315 ExprResult Arg = E->getArg(0);
3316 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3317 if (Arg.isInvalid())
3318 return true;
3319
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003320 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00003321 return false;
3322}
3323
Chris Lattnerdc046542009-05-08 06:58:22 +00003324/// SemaBuiltinAtomicOverloaded - We have a call to a function like
3325/// __sync_fetch_and_add, which is an overloaded function based on the pointer
3326/// type of its first argument. The main ActOnCallExpr routines have already
3327/// promoted the types of arguments because all of these calls are prototyped as
3328/// void(...).
3329///
3330/// This function goes through and does final semantic checking for these
3331/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00003332ExprResult
3333Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003334 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00003335 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3336 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3337
3338 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003339 if (TheCall->getNumArgs() < 1) {
3340 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3341 << 0 << 1 << TheCall->getNumArgs()
3342 << TheCall->getCallee()->getSourceRange();
3343 return ExprError();
3344 }
Mike Stump11289f42009-09-09 15:08:12 +00003345
Chris Lattnerdc046542009-05-08 06:58:22 +00003346 // Inspect the first argument of the atomic builtin. This should always be
3347 // a pointer type, whose element is an integral scalar or pointer type.
3348 // Because it is a pointer type, we don't have to worry about any implicit
3349 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003350 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00003351 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00003352 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3353 if (FirstArgResult.isInvalid())
3354 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003355 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00003356 TheCall->setArg(0, FirstArg);
3357
John McCall31168b02011-06-15 23:02:42 +00003358 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3359 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003360 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3361 << FirstArg->getType() << FirstArg->getSourceRange();
3362 return ExprError();
3363 }
Mike Stump11289f42009-09-09 15:08:12 +00003364
John McCall31168b02011-06-15 23:02:42 +00003365 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00003366 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003367 !ValType->isBlockPointerType()) {
3368 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3369 << FirstArg->getType() << FirstArg->getSourceRange();
3370 return ExprError();
3371 }
Chris Lattnerdc046542009-05-08 06:58:22 +00003372
John McCall31168b02011-06-15 23:02:42 +00003373 switch (ValType.getObjCLifetime()) {
3374 case Qualifiers::OCL_None:
3375 case Qualifiers::OCL_ExplicitNone:
3376 // okay
3377 break;
3378
3379 case Qualifiers::OCL_Weak:
3380 case Qualifiers::OCL_Strong:
3381 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00003382 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00003383 << ValType << FirstArg->getSourceRange();
3384 return ExprError();
3385 }
3386
John McCallb50451a2011-10-05 07:41:44 +00003387 // Strip any qualifiers off ValType.
3388 ValType = ValType.getUnqualifiedType();
3389
Chandler Carruth3973af72010-07-18 20:54:12 +00003390 // The majority of builtins return a value, but a few have special return
3391 // types, so allow them to override appropriately below.
3392 QualType ResultType = ValType;
3393
Chris Lattnerdc046542009-05-08 06:58:22 +00003394 // We need to figure out which concrete builtin this maps onto. For example,
3395 // __sync_fetch_and_add with a 2 byte object turns into
3396 // __sync_fetch_and_add_2.
3397#define BUILTIN_ROW(x) \
3398 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3399 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00003400
Chris Lattnerdc046542009-05-08 06:58:22 +00003401 static const unsigned BuiltinIndices[][5] = {
3402 BUILTIN_ROW(__sync_fetch_and_add),
3403 BUILTIN_ROW(__sync_fetch_and_sub),
3404 BUILTIN_ROW(__sync_fetch_and_or),
3405 BUILTIN_ROW(__sync_fetch_and_and),
3406 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00003407 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00003408
Chris Lattnerdc046542009-05-08 06:58:22 +00003409 BUILTIN_ROW(__sync_add_and_fetch),
3410 BUILTIN_ROW(__sync_sub_and_fetch),
3411 BUILTIN_ROW(__sync_and_and_fetch),
3412 BUILTIN_ROW(__sync_or_and_fetch),
3413 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00003414 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00003415
Chris Lattnerdc046542009-05-08 06:58:22 +00003416 BUILTIN_ROW(__sync_val_compare_and_swap),
3417 BUILTIN_ROW(__sync_bool_compare_and_swap),
3418 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00003419 BUILTIN_ROW(__sync_lock_release),
3420 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00003421 };
Mike Stump11289f42009-09-09 15:08:12 +00003422#undef BUILTIN_ROW
3423
Chris Lattnerdc046542009-05-08 06:58:22 +00003424 // Determine the index of the size.
3425 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00003426 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00003427 case 1: SizeIndex = 0; break;
3428 case 2: SizeIndex = 1; break;
3429 case 4: SizeIndex = 2; break;
3430 case 8: SizeIndex = 3; break;
3431 case 16: SizeIndex = 4; break;
3432 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003433 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3434 << FirstArg->getType() << FirstArg->getSourceRange();
3435 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00003436 }
Mike Stump11289f42009-09-09 15:08:12 +00003437
Chris Lattnerdc046542009-05-08 06:58:22 +00003438 // Each of these builtins has one pointer argument, followed by some number of
3439 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3440 // that we ignore. Find out which row of BuiltinIndices to read from as well
3441 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00003442 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00003443 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00003444 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00003445 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00003446 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00003447 case Builtin::BI__sync_fetch_and_add:
3448 case Builtin::BI__sync_fetch_and_add_1:
3449 case Builtin::BI__sync_fetch_and_add_2:
3450 case Builtin::BI__sync_fetch_and_add_4:
3451 case Builtin::BI__sync_fetch_and_add_8:
3452 case Builtin::BI__sync_fetch_and_add_16:
3453 BuiltinIndex = 0;
3454 break;
3455
3456 case Builtin::BI__sync_fetch_and_sub:
3457 case Builtin::BI__sync_fetch_and_sub_1:
3458 case Builtin::BI__sync_fetch_and_sub_2:
3459 case Builtin::BI__sync_fetch_and_sub_4:
3460 case Builtin::BI__sync_fetch_and_sub_8:
3461 case Builtin::BI__sync_fetch_and_sub_16:
3462 BuiltinIndex = 1;
3463 break;
3464
3465 case Builtin::BI__sync_fetch_and_or:
3466 case Builtin::BI__sync_fetch_and_or_1:
3467 case Builtin::BI__sync_fetch_and_or_2:
3468 case Builtin::BI__sync_fetch_and_or_4:
3469 case Builtin::BI__sync_fetch_and_or_8:
3470 case Builtin::BI__sync_fetch_and_or_16:
3471 BuiltinIndex = 2;
3472 break;
3473
3474 case Builtin::BI__sync_fetch_and_and:
3475 case Builtin::BI__sync_fetch_and_and_1:
3476 case Builtin::BI__sync_fetch_and_and_2:
3477 case Builtin::BI__sync_fetch_and_and_4:
3478 case Builtin::BI__sync_fetch_and_and_8:
3479 case Builtin::BI__sync_fetch_and_and_16:
3480 BuiltinIndex = 3;
3481 break;
Mike Stump11289f42009-09-09 15:08:12 +00003482
Douglas Gregor73722482011-11-28 16:30:08 +00003483 case Builtin::BI__sync_fetch_and_xor:
3484 case Builtin::BI__sync_fetch_and_xor_1:
3485 case Builtin::BI__sync_fetch_and_xor_2:
3486 case Builtin::BI__sync_fetch_and_xor_4:
3487 case Builtin::BI__sync_fetch_and_xor_8:
3488 case Builtin::BI__sync_fetch_and_xor_16:
3489 BuiltinIndex = 4;
3490 break;
3491
Hal Finkeld2208b52014-10-02 20:53:50 +00003492 case Builtin::BI__sync_fetch_and_nand:
3493 case Builtin::BI__sync_fetch_and_nand_1:
3494 case Builtin::BI__sync_fetch_and_nand_2:
3495 case Builtin::BI__sync_fetch_and_nand_4:
3496 case Builtin::BI__sync_fetch_and_nand_8:
3497 case Builtin::BI__sync_fetch_and_nand_16:
3498 BuiltinIndex = 5;
3499 WarnAboutSemanticsChange = true;
3500 break;
3501
Douglas Gregor73722482011-11-28 16:30:08 +00003502 case Builtin::BI__sync_add_and_fetch:
3503 case Builtin::BI__sync_add_and_fetch_1:
3504 case Builtin::BI__sync_add_and_fetch_2:
3505 case Builtin::BI__sync_add_and_fetch_4:
3506 case Builtin::BI__sync_add_and_fetch_8:
3507 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003508 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00003509 break;
3510
3511 case Builtin::BI__sync_sub_and_fetch:
3512 case Builtin::BI__sync_sub_and_fetch_1:
3513 case Builtin::BI__sync_sub_and_fetch_2:
3514 case Builtin::BI__sync_sub_and_fetch_4:
3515 case Builtin::BI__sync_sub_and_fetch_8:
3516 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003517 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00003518 break;
3519
3520 case Builtin::BI__sync_and_and_fetch:
3521 case Builtin::BI__sync_and_and_fetch_1:
3522 case Builtin::BI__sync_and_and_fetch_2:
3523 case Builtin::BI__sync_and_and_fetch_4:
3524 case Builtin::BI__sync_and_and_fetch_8:
3525 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003526 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00003527 break;
3528
3529 case Builtin::BI__sync_or_and_fetch:
3530 case Builtin::BI__sync_or_and_fetch_1:
3531 case Builtin::BI__sync_or_and_fetch_2:
3532 case Builtin::BI__sync_or_and_fetch_4:
3533 case Builtin::BI__sync_or_and_fetch_8:
3534 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003535 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00003536 break;
3537
3538 case Builtin::BI__sync_xor_and_fetch:
3539 case Builtin::BI__sync_xor_and_fetch_1:
3540 case Builtin::BI__sync_xor_and_fetch_2:
3541 case Builtin::BI__sync_xor_and_fetch_4:
3542 case Builtin::BI__sync_xor_and_fetch_8:
3543 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003544 BuiltinIndex = 10;
3545 break;
3546
3547 case Builtin::BI__sync_nand_and_fetch:
3548 case Builtin::BI__sync_nand_and_fetch_1:
3549 case Builtin::BI__sync_nand_and_fetch_2:
3550 case Builtin::BI__sync_nand_and_fetch_4:
3551 case Builtin::BI__sync_nand_and_fetch_8:
3552 case Builtin::BI__sync_nand_and_fetch_16:
3553 BuiltinIndex = 11;
3554 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00003555 break;
Mike Stump11289f42009-09-09 15:08:12 +00003556
Chris Lattnerdc046542009-05-08 06:58:22 +00003557 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003558 case Builtin::BI__sync_val_compare_and_swap_1:
3559 case Builtin::BI__sync_val_compare_and_swap_2:
3560 case Builtin::BI__sync_val_compare_and_swap_4:
3561 case Builtin::BI__sync_val_compare_and_swap_8:
3562 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003563 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00003564 NumFixed = 2;
3565 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003566
Chris Lattnerdc046542009-05-08 06:58:22 +00003567 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003568 case Builtin::BI__sync_bool_compare_and_swap_1:
3569 case Builtin::BI__sync_bool_compare_and_swap_2:
3570 case Builtin::BI__sync_bool_compare_and_swap_4:
3571 case Builtin::BI__sync_bool_compare_and_swap_8:
3572 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003573 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00003574 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00003575 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003576 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003577
3578 case Builtin::BI__sync_lock_test_and_set:
3579 case Builtin::BI__sync_lock_test_and_set_1:
3580 case Builtin::BI__sync_lock_test_and_set_2:
3581 case Builtin::BI__sync_lock_test_and_set_4:
3582 case Builtin::BI__sync_lock_test_and_set_8:
3583 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003584 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00003585 break;
3586
Chris Lattnerdc046542009-05-08 06:58:22 +00003587 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00003588 case Builtin::BI__sync_lock_release_1:
3589 case Builtin::BI__sync_lock_release_2:
3590 case Builtin::BI__sync_lock_release_4:
3591 case Builtin::BI__sync_lock_release_8:
3592 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003593 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00003594 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00003595 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003596 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003597
3598 case Builtin::BI__sync_swap:
3599 case Builtin::BI__sync_swap_1:
3600 case Builtin::BI__sync_swap_2:
3601 case Builtin::BI__sync_swap_4:
3602 case Builtin::BI__sync_swap_8:
3603 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003604 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00003605 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00003606 }
Mike Stump11289f42009-09-09 15:08:12 +00003607
Chris Lattnerdc046542009-05-08 06:58:22 +00003608 // Now that we know how many fixed arguments we expect, first check that we
3609 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003610 if (TheCall->getNumArgs() < 1+NumFixed) {
3611 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3612 << 0 << 1+NumFixed << TheCall->getNumArgs()
3613 << TheCall->getCallee()->getSourceRange();
3614 return ExprError();
3615 }
Mike Stump11289f42009-09-09 15:08:12 +00003616
Hal Finkeld2208b52014-10-02 20:53:50 +00003617 if (WarnAboutSemanticsChange) {
3618 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3619 << TheCall->getCallee()->getSourceRange();
3620 }
3621
Chris Lattner5b9241b2009-05-08 15:36:58 +00003622 // Get the decl for the concrete builtin from this, we can tell what the
3623 // concrete integer type we should convert to is.
3624 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Mehdi Amini7186a432016-10-11 19:04:24 +00003625 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003626 FunctionDecl *NewBuiltinDecl;
3627 if (NewBuiltinID == BuiltinID)
3628 NewBuiltinDecl = FDecl;
3629 else {
3630 // Perform builtin lookup to avoid redeclaring it.
3631 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3632 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3633 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3634 assert(Res.getFoundDecl());
3635 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00003636 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003637 return ExprError();
3638 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003639
John McCallcf142162010-08-07 06:22:56 +00003640 // The first argument --- the pointer --- has a fixed type; we
3641 // deduce the types of the rest of the arguments accordingly. Walk
3642 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00003643 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00003644 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00003645
Chris Lattnerdc046542009-05-08 06:58:22 +00003646 // GCC does an implicit conversion to the pointer or integer ValType. This
3647 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00003648 // Initialize the argument.
3649 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3650 ValType, /*consume*/ false);
3651 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00003652 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003653 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003654
Chris Lattnerdc046542009-05-08 06:58:22 +00003655 // Okay, we have something that *can* be converted to the right type. Check
3656 // to see if there is a potentially weird extension going on here. This can
3657 // happen when you do an atomic operation on something like an char* and
3658 // pass in 42. The 42 gets converted to char. This is even more strange
3659 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00003660 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003661 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00003662 }
Mike Stump11289f42009-09-09 15:08:12 +00003663
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003664 ASTContext& Context = this->getASTContext();
3665
3666 // Create a new DeclRefExpr to refer to the new decl.
3667 DeclRefExpr* NewDRE = DeclRefExpr::Create(
3668 Context,
3669 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00003670 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003671 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00003672 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003673 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00003674 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003675 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00003676
Chris Lattnerdc046542009-05-08 06:58:22 +00003677 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00003678 // FIXME: This loses syntactic information.
3679 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3680 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3681 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003682 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00003683
Chandler Carruthbc8cab12010-07-18 07:23:17 +00003684 // Change the result type of the call to match the original value type. This
3685 // is arbitrary, but the codegen for these builtins ins design to handle it
3686 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00003687 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003688
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003689 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00003690}
3691
Michael Zolotukhin84df1232015-09-08 23:52:33 +00003692/// SemaBuiltinNontemporalOverloaded - We have a call to
3693/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3694/// overloaded function based on the pointer type of its last argument.
3695///
3696/// This function goes through and does final semantic checking for these
3697/// builtins.
3698ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3699 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3700 DeclRefExpr *DRE =
3701 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3702 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3703 unsigned BuiltinID = FDecl->getBuiltinID();
3704 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3705 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3706 "Unexpected nontemporal load/store builtin!");
3707 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3708 unsigned numArgs = isStore ? 2 : 1;
3709
3710 // Ensure that we have the proper number of arguments.
3711 if (checkArgCount(*this, TheCall, numArgs))
3712 return ExprError();
3713
3714 // Inspect the last argument of the nontemporal builtin. This should always
3715 // be a pointer type, from which we imply the type of the memory access.
3716 // Because it is a pointer type, we don't have to worry about any implicit
3717 // casts here.
3718 Expr *PointerArg = TheCall->getArg(numArgs - 1);
3719 ExprResult PointerArgResult =
3720 DefaultFunctionArrayLvalueConversion(PointerArg);
3721
3722 if (PointerArgResult.isInvalid())
3723 return ExprError();
3724 PointerArg = PointerArgResult.get();
3725 TheCall->setArg(numArgs - 1, PointerArg);
3726
3727 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3728 if (!pointerType) {
3729 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3730 << PointerArg->getType() << PointerArg->getSourceRange();
3731 return ExprError();
3732 }
3733
3734 QualType ValType = pointerType->getPointeeType();
3735
3736 // Strip any qualifiers off ValType.
3737 ValType = ValType.getUnqualifiedType();
3738 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3739 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3740 !ValType->isVectorType()) {
3741 Diag(DRE->getLocStart(),
3742 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3743 << PointerArg->getType() << PointerArg->getSourceRange();
3744 return ExprError();
3745 }
3746
3747 if (!isStore) {
3748 TheCall->setType(ValType);
3749 return TheCallResult;
3750 }
3751
3752 ExprResult ValArg = TheCall->getArg(0);
3753 InitializedEntity Entity = InitializedEntity::InitializeParameter(
3754 Context, ValType, /*consume*/ false);
3755 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3756 if (ValArg.isInvalid())
3757 return ExprError();
3758
3759 TheCall->setArg(0, ValArg.get());
3760 TheCall->setType(Context.VoidTy);
3761 return TheCallResult;
3762}
3763
Chris Lattner6436fb62009-02-18 06:01:06 +00003764/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00003765/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00003766/// Note: It might also make sense to do the UTF-16 conversion here (would
3767/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00003768bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00003769 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00003770 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3771
Douglas Gregorfb65e592011-07-27 05:40:30 +00003772 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003773 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3774 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00003775 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00003776 }
Mike Stump11289f42009-09-09 15:08:12 +00003777
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003778 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003779 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003780 unsigned NumBytes = String.size();
Justin Lebar90910552016-09-30 00:38:45 +00003781 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3782 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3783 llvm::UTF16 *ToPtr = &ToBuf[0];
3784
3785 llvm::ConversionResult Result =
3786 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3787 ToPtr + NumBytes, llvm::strictConversion);
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003788 // Check for conversion failure.
Justin Lebar90910552016-09-30 00:38:45 +00003789 if (Result != llvm::conversionOK)
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003790 Diag(Arg->getLocStart(),
3791 diag::warn_cfstring_truncated) << Arg->getSourceRange();
3792 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00003793 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003794}
3795
Mehdi Amini06d367c2016-10-24 20:39:34 +00003796/// CheckObjCString - Checks that the format string argument to the os_log()
3797/// and os_trace() functions is correct, and converts it to const char *.
3798ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3799 Arg = Arg->IgnoreParenCasts();
3800 auto *Literal = dyn_cast<StringLiteral>(Arg);
3801 if (!Literal) {
3802 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3803 Literal = ObjcLiteral->getString();
3804 }
3805 }
3806
3807 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3808 return ExprError(
3809 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3810 << Arg->getSourceRange());
3811 }
3812
3813 ExprResult Result(Literal);
3814 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3815 InitializedEntity Entity =
3816 InitializedEntity::InitializeParameter(Context, ResultTy, false);
3817 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3818 return Result;
3819}
3820
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003821/// Check that the user is calling the appropriate va_start builtin for the
3822/// target and calling convention.
3823static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
3824 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
3825 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
Martin Storsjo022e7822017-07-17 20:49:45 +00003826 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003827 bool IsWindows = TT.isOSWindows();
Martin Storsjo022e7822017-07-17 20:49:45 +00003828 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
3829 if (IsX64 || IsAArch64) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003830 CallingConv CC = CC_C;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003831 if (const FunctionDecl *FD = S.getCurFunctionDecl())
3832 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3833 if (IsMSVAStart) {
3834 // Don't allow this in System V ABI functions.
Martin Storsjo022e7822017-07-17 20:49:45 +00003835 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003836 return S.Diag(Fn->getLocStart(),
3837 diag::err_ms_va_start_used_in_sysv_function);
3838 } else {
Martin Storsjo022e7822017-07-17 20:49:45 +00003839 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003840 // On x64 Windows, don't allow this in System V ABI functions.
3841 // (Yes, that means there's no corresponding way to support variadic
3842 // System V ABI functions on Windows.)
3843 if ((IsWindows && CC == CC_X86_64SysV) ||
Martin Storsjo022e7822017-07-17 20:49:45 +00003844 (!IsWindows && CC == CC_Win64))
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003845 return S.Diag(Fn->getLocStart(),
3846 diag::err_va_start_used_in_wrong_abi_function)
3847 << !IsWindows;
3848 }
3849 return false;
3850 }
3851
3852 if (IsMSVAStart)
Martin Storsjo022e7822017-07-17 20:49:45 +00003853 return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003854 return false;
3855}
3856
3857static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
3858 ParmVarDecl **LastParam = nullptr) {
3859 // Determine whether the current function, block, or obj-c method is variadic
3860 // and get its parameter list.
3861 bool IsVariadic = false;
3862 ArrayRef<ParmVarDecl *> Params;
Reid Klecknerf1deb832017-05-04 19:51:05 +00003863 DeclContext *Caller = S.CurContext;
3864 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
3865 IsVariadic = Block->isVariadic();
3866 Params = Block->parameters();
3867 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003868 IsVariadic = FD->isVariadic();
3869 Params = FD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00003870 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003871 IsVariadic = MD->isVariadic();
3872 // FIXME: This isn't correct for methods (results in bogus warning).
3873 Params = MD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00003874 } else if (isa<CapturedDecl>(Caller)) {
3875 // We don't support va_start in a CapturedDecl.
3876 S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
3877 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003878 } else {
Reid Klecknerf1deb832017-05-04 19:51:05 +00003879 // This must be some other declcontext that parses exprs.
3880 S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
3881 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003882 }
3883
3884 if (!IsVariadic) {
Reid Klecknerf1deb832017-05-04 19:51:05 +00003885 S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003886 return true;
3887 }
3888
3889 if (LastParam)
3890 *LastParam = Params.empty() ? nullptr : Params.back();
3891
3892 return false;
3893}
3894
Charles Davisc7d5c942015-09-17 20:55:33 +00003895/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3896/// for validity. Emit an error and return true on failure; return false
3897/// on success.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003898bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00003899 Expr *Fn = TheCall->getCallee();
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003900
3901 if (checkVAStartABI(*this, BuiltinID, Fn))
3902 return true;
3903
Chris Lattner08464942007-12-28 05:29:59 +00003904 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00003905 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003906 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003907 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3908 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00003909 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003910 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00003911 return true;
3912 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003913
3914 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00003915 return Diag(TheCall->getLocEnd(),
3916 diag::err_typecheck_call_too_few_args_at_least)
3917 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003918 }
3919
John McCall29ad95b2011-08-27 01:09:30 +00003920 // Type-check the first argument normally.
3921 if (checkBuiltinArgument(*this, TheCall, 0))
3922 return true;
3923
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003924 // Check that the current function is variadic, and get its last parameter.
3925 ParmVarDecl *LastParam;
3926 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
Chris Lattner43be2e62007-12-19 23:59:04 +00003927 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003928
Chris Lattner43be2e62007-12-19 23:59:04 +00003929 // Verify that the second argument to the builtin is the last argument of the
3930 // current function or method.
3931 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00003932 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003933
Nico Weber9eea7642013-05-24 23:31:57 +00003934 // These are valid if SecondArgIsLastNamedArgument is false after the next
3935 // block.
3936 QualType Type;
3937 SourceLocation ParamLoc;
Aaron Ballman1de59c52016-04-24 13:30:21 +00003938 bool IsCRegister = false;
Nico Weber9eea7642013-05-24 23:31:57 +00003939
Anders Carlsson6a8350b2008-02-11 04:20:54 +00003940 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3941 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003942 SecondArgIsLastNamedArgument = PV == LastParam;
Nico Weber9eea7642013-05-24 23:31:57 +00003943
3944 Type = PV->getType();
3945 ParamLoc = PV->getLocation();
Aaron Ballman1de59c52016-04-24 13:30:21 +00003946 IsCRegister =
3947 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
Chris Lattner43be2e62007-12-19 23:59:04 +00003948 }
3949 }
Mike Stump11289f42009-09-09 15:08:12 +00003950
Chris Lattner43be2e62007-12-19 23:59:04 +00003951 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00003952 Diag(TheCall->getArg(1)->getLocStart(),
Aaron Ballman05164812016-04-18 18:10:53 +00003953 diag::warn_second_arg_of_va_start_not_last_named_param);
Aaron Ballman1de59c52016-04-24 13:30:21 +00003954 else if (IsCRegister || Type->isReferenceType() ||
Aaron Ballmana4f597f2016-09-15 18:07:51 +00003955 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3956 // Promotable integers are UB, but enumerations need a bit of
3957 // extra checking to see what their promotable type actually is.
3958 if (!Type->isPromotableIntegerType())
3959 return false;
3960 if (!Type->isEnumeralType())
3961 return true;
3962 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3963 return !(ED &&
3964 Context.typesAreCompatible(ED->getPromotionType(), Type));
3965 }()) {
Aaron Ballman1de59c52016-04-24 13:30:21 +00003966 unsigned Reason = 0;
3967 if (Type->isReferenceType()) Reason = 1;
3968 else if (IsCRegister) Reason = 2;
3969 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
Nico Weber9eea7642013-05-24 23:31:57 +00003970 Diag(ParamLoc, diag::note_parameter_type) << Type;
3971 }
3972
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00003973 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00003974 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00003975}
Chris Lattner43be2e62007-12-19 23:59:04 +00003976
Saleem Abdulrasool3450aa72017-09-26 20:12:04 +00003977bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003978 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3979 // const char *named_addr);
3980
3981 Expr *Func = Call->getCallee();
3982
3983 if (Call->getNumArgs() < 3)
3984 return Diag(Call->getLocEnd(),
3985 diag::err_typecheck_call_too_few_args_at_least)
3986 << 0 /*function call*/ << 3 << Call->getNumArgs();
3987
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003988 // Type-check the first argument normally.
3989 if (checkBuiltinArgument(*this, Call, 0))
3990 return true;
3991
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003992 // Check that the current function is variadic.
3993 if (checkVAStartIsInVariadicFunction(*this, Func))
3994 return true;
3995
Saleem Abdulrasool448e8ad2017-09-26 17:44:10 +00003996 // __va_start on Windows does not validate the parameter qualifiers
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003997
Saleem Abdulrasool448e8ad2017-09-26 17:44:10 +00003998 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
3999 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
4000
4001 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
4002 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
4003
4004 const QualType &ConstCharPtrTy =
4005 Context.getPointerType(Context.CharTy.withConst());
4006 if (!Arg1Ty->isPointerType() ||
4007 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
4008 Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible)
4009 << Arg1->getType() << ConstCharPtrTy
4010 << 1 /* different class */
4011 << 0 /* qualifier difference */
4012 << 3 /* parameter mismatch */
4013 << 2 << Arg1->getType() << ConstCharPtrTy;
4014
4015 const QualType SizeTy = Context.getSizeType();
4016 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
4017 Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible)
4018 << Arg2->getType() << SizeTy
4019 << 1 /* different class */
4020 << 0 /* qualifier difference */
4021 << 3 /* parameter mismatch */
4022 << 3 << Arg2->getType() << SizeTy;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004023
4024 return false;
4025}
4026
Chris Lattner2da14fb2007-12-20 00:26:33 +00004027/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
4028/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00004029bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
4030 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00004031 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00004032 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00004033 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00004034 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004035 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004036 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00004037 << SourceRange(TheCall->getArg(2)->getLocStart(),
4038 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00004039
John Wiegley01296292011-04-08 18:41:53 +00004040 ExprResult OrigArg0 = TheCall->getArg(0);
4041 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00004042
Chris Lattner2da14fb2007-12-20 00:26:33 +00004043 // Do standard promotions between the two arguments, returning their common
4044 // type.
Chris Lattner08464942007-12-28 05:29:59 +00004045 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00004046 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
4047 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00004048
4049 // Make sure any conversions are pushed back into the call; this is
4050 // type safe since unordered compare builtins are declared as "_Bool
4051 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00004052 TheCall->setArg(0, OrigArg0.get());
4053 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00004054
John Wiegley01296292011-04-08 18:41:53 +00004055 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00004056 return false;
4057
Chris Lattner2da14fb2007-12-20 00:26:33 +00004058 // If the common type isn't a real floating type, then the arguments were
4059 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00004060 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00004061 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004062 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00004063 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
4064 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00004065
Chris Lattner2da14fb2007-12-20 00:26:33 +00004066 return false;
4067}
4068
Benjamin Kramer634fc102010-02-15 22:42:31 +00004069/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
4070/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00004071/// to check everything. We expect the last argument to be a floating point
4072/// value.
4073bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
4074 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00004075 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00004076 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00004077 if (TheCall->getNumArgs() > NumArgs)
4078 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004079 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004080 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00004081 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004082 (*(TheCall->arg_end()-1))->getLocEnd());
4083
Benjamin Kramer64aae502010-02-16 10:07:31 +00004084 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00004085
Eli Friedman7e4faac2009-08-31 20:06:00 +00004086 if (OrigArg->isTypeDependent())
4087 return false;
4088
Chris Lattner68784ef2010-05-06 05:50:07 +00004089 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00004090 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00004091 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004092 diag::err_typecheck_call_invalid_unary_fp)
4093 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004094
Neil Hickey88c0fac2016-12-13 16:22:50 +00004095 // If this is an implicit conversion from float -> float or double, remove it.
Chris Lattner68784ef2010-05-06 05:50:07 +00004096 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
Neil Hickey7b5ddab2016-12-14 13:18:48 +00004097 // Only remove standard FloatCasts, leaving other casts inplace
4098 if (Cast->getCastKind() == CK_FloatingCast) {
4099 Expr *CastArg = Cast->getSubExpr();
4100 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
4101 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
4102 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
4103 "promotion from float to either float or double is the only expected cast here");
4104 Cast->setSubExpr(nullptr);
4105 TheCall->setArg(NumArgs-1, CastArg);
4106 }
Chris Lattner68784ef2010-05-06 05:50:07 +00004107 }
4108 }
4109
Eli Friedman7e4faac2009-08-31 20:06:00 +00004110 return false;
4111}
4112
Tony Jiangbbc48e92017-05-24 15:13:32 +00004113// Customized Sema Checking for VSX builtins that have the following signature:
4114// vector [...] builtinName(vector [...], vector [...], const int);
4115// Which takes the same type of vectors (any legal vector type) for the first
4116// two arguments and takes compile time constant for the third argument.
4117// Example builtins are :
4118// vector double vec_xxpermdi(vector double, vector double, int);
4119// vector short vec_xxsldwi(vector short, vector short, int);
4120bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
4121 unsigned ExpectedNumArgs = 3;
4122 if (TheCall->getNumArgs() < ExpectedNumArgs)
4123 return Diag(TheCall->getLocEnd(),
4124 diag::err_typecheck_call_too_few_args_at_least)
4125 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4126 << TheCall->getSourceRange();
4127
4128 if (TheCall->getNumArgs() > ExpectedNumArgs)
4129 return Diag(TheCall->getLocEnd(),
4130 diag::err_typecheck_call_too_many_args_at_most)
4131 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4132 << TheCall->getSourceRange();
4133
4134 // Check the third argument is a compile time constant
4135 llvm::APSInt Value;
4136 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
4137 return Diag(TheCall->getLocStart(),
4138 diag::err_vsx_builtin_nonconstant_argument)
4139 << 3 /* argument index */ << TheCall->getDirectCallee()
4140 << SourceRange(TheCall->getArg(2)->getLocStart(),
4141 TheCall->getArg(2)->getLocEnd());
4142
4143 QualType Arg1Ty = TheCall->getArg(0)->getType();
4144 QualType Arg2Ty = TheCall->getArg(1)->getType();
4145
4146 // Check the type of argument 1 and argument 2 are vectors.
4147 SourceLocation BuiltinLoc = TheCall->getLocStart();
4148 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
4149 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
4150 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
4151 << TheCall->getDirectCallee()
4152 << SourceRange(TheCall->getArg(0)->getLocStart(),
4153 TheCall->getArg(1)->getLocEnd());
4154 }
4155
4156 // Check the first two arguments are the same type.
4157 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
4158 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
4159 << TheCall->getDirectCallee()
4160 << SourceRange(TheCall->getArg(0)->getLocStart(),
4161 TheCall->getArg(1)->getLocEnd());
4162 }
4163
4164 // When default clang type checking is turned off and the customized type
4165 // checking is used, the returning type of the function must be explicitly
4166 // set. Otherwise it is _Bool by default.
4167 TheCall->setType(Arg1Ty);
4168
4169 return false;
4170}
4171
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004172/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
4173// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00004174ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00004175 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004176 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00004177 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00004178 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4179 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004180
Nate Begemana0110022010-06-08 00:16:34 +00004181 // Determine which of the following types of shufflevector we're checking:
4182 // 1) unary, vector mask: (lhs, mask)
Craig Topperb3174a82016-05-18 04:11:25 +00004183 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
Nate Begemana0110022010-06-08 00:16:34 +00004184 QualType resType = TheCall->getArg(0)->getType();
4185 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00004186
Douglas Gregorc25f7662009-05-19 22:10:17 +00004187 if (!TheCall->getArg(0)->isTypeDependent() &&
4188 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00004189 QualType LHSType = TheCall->getArg(0)->getType();
4190 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00004191
Craig Topperbaca3892013-07-29 06:47:04 +00004192 if (!LHSType->isVectorType() || !RHSType->isVectorType())
4193 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004194 diag::err_vec_builtin_non_vector)
4195 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004196 << SourceRange(TheCall->getArg(0)->getLocStart(),
4197 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00004198
Nate Begemana0110022010-06-08 00:16:34 +00004199 numElements = LHSType->getAs<VectorType>()->getNumElements();
4200 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00004201
Nate Begemana0110022010-06-08 00:16:34 +00004202 // Check to see if we have a call with 2 vector arguments, the unary shuffle
4203 // with mask. If so, verify that RHS is an integer vector type with the
4204 // same number of elts as lhs.
4205 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00004206 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00004207 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00004208 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004209 diag::err_vec_builtin_incompatible_vector)
4210 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004211 << SourceRange(TheCall->getArg(1)->getLocStart(),
4212 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00004213 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00004214 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004215 diag::err_vec_builtin_incompatible_vector)
4216 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004217 << SourceRange(TheCall->getArg(0)->getLocStart(),
4218 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00004219 } else if (numElements != numResElements) {
4220 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00004221 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00004222 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00004223 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004224 }
4225
4226 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00004227 if (TheCall->getArg(i)->isTypeDependent() ||
4228 TheCall->getArg(i)->isValueDependent())
4229 continue;
4230
Nate Begemana0110022010-06-08 00:16:34 +00004231 llvm::APSInt Result(32);
4232 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
4233 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004234 diag::err_shufflevector_nonconstant_argument)
4235 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004236
Craig Topper50ad5b72013-08-03 17:40:38 +00004237 // Allow -1 which will be translated to undef in the IR.
4238 if (Result.isSigned() && Result.isAllOnesValue())
4239 continue;
4240
Chris Lattner7ab824e2008-08-10 02:05:13 +00004241 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004242 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004243 diag::err_shufflevector_argument_too_large)
4244 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004245 }
4246
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004247 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004248
Chris Lattner7ab824e2008-08-10 02:05:13 +00004249 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004250 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00004251 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004252 }
4253
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004254 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
4255 TheCall->getCallee()->getLocStart(),
4256 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004257}
Chris Lattner43be2e62007-12-19 23:59:04 +00004258
Hal Finkelc4d7c822013-09-18 03:29:45 +00004259/// SemaConvertVectorExpr - Handle __builtin_convertvector
4260ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
4261 SourceLocation BuiltinLoc,
4262 SourceLocation RParenLoc) {
4263 ExprValueKind VK = VK_RValue;
4264 ExprObjectKind OK = OK_Ordinary;
4265 QualType DstTy = TInfo->getType();
4266 QualType SrcTy = E->getType();
4267
4268 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
4269 return ExprError(Diag(BuiltinLoc,
4270 diag::err_convertvector_non_vector)
4271 << E->getSourceRange());
4272 if (!DstTy->isVectorType() && !DstTy->isDependentType())
4273 return ExprError(Diag(BuiltinLoc,
4274 diag::err_convertvector_non_vector_type));
4275
4276 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
4277 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
4278 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
4279 if (SrcElts != DstElts)
4280 return ExprError(Diag(BuiltinLoc,
4281 diag::err_convertvector_incompatible_vector)
4282 << E->getSourceRange());
4283 }
4284
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004285 return new (Context)
4286 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00004287}
4288
Daniel Dunbarb7257262008-07-21 22:59:13 +00004289/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
4290// This is declared to take (const void*, ...) and can take two
4291// optional constant int args.
4292bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00004293 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004294
Chris Lattner3b054132008-11-19 05:08:23 +00004295 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004296 return Diag(TheCall->getLocEnd(),
4297 diag::err_typecheck_call_too_many_args_at_most)
4298 << 0 /*function call*/ << 3 << NumArgs
4299 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004300
4301 // Argument 0 is checked for us and the remaining arguments must be
4302 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00004303 for (unsigned i = 1; i != NumArgs; ++i)
4304 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004305 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004306
Warren Hunt20e4a5d2014-02-21 23:08:53 +00004307 return false;
4308}
4309
Hal Finkelf0417332014-07-17 14:25:55 +00004310/// SemaBuiltinAssume - Handle __assume (MS Extension).
4311// __assume does not evaluate its arguments, and should warn if its argument
4312// has side effects.
4313bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
4314 Expr *Arg = TheCall->getArg(0);
4315 if (Arg->isInstantiationDependent()) return false;
4316
4317 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00004318 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00004319 << Arg->getSourceRange()
4320 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
4321
4322 return false;
4323}
4324
David Majnemer86b1bfa2016-10-31 18:07:57 +00004325/// Handle __builtin_alloca_with_align. This is declared
David Majnemer51169932016-10-31 05:37:48 +00004326/// as (size_t, size_t) where the second size_t must be a power of 2 greater
4327/// than 8.
4328bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
4329 // The alignment must be a constant integer.
4330 Expr *Arg = TheCall->getArg(1);
4331
4332 // We can't check the value of a dependent argument.
4333 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
David Majnemer86b1bfa2016-10-31 18:07:57 +00004334 if (const auto *UE =
4335 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
4336 if (UE->getKind() == UETT_AlignOf)
4337 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
4338 << Arg->getSourceRange();
4339
David Majnemer51169932016-10-31 05:37:48 +00004340 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
4341
4342 if (!Result.isPowerOf2())
4343 return Diag(TheCall->getLocStart(),
4344 diag::err_alignment_not_power_of_two)
4345 << Arg->getSourceRange();
4346
4347 if (Result < Context.getCharWidth())
4348 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
4349 << (unsigned)Context.getCharWidth()
4350 << Arg->getSourceRange();
4351
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004352 if (Result > std::numeric_limits<int32_t>::max())
David Majnemer51169932016-10-31 05:37:48 +00004353 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004354 << std::numeric_limits<int32_t>::max()
David Majnemer51169932016-10-31 05:37:48 +00004355 << Arg->getSourceRange();
4356 }
4357
4358 return false;
4359}
4360
4361/// Handle __builtin_assume_aligned. This is declared
Hal Finkelbcc06082014-09-07 22:58:14 +00004362/// as (const void*, size_t, ...) and can take one optional constant int arg.
4363bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
4364 unsigned NumArgs = TheCall->getNumArgs();
4365
4366 if (NumArgs > 3)
4367 return Diag(TheCall->getLocEnd(),
4368 diag::err_typecheck_call_too_many_args_at_most)
4369 << 0 /*function call*/ << 3 << NumArgs
4370 << TheCall->getSourceRange();
4371
4372 // The alignment must be a constant integer.
4373 Expr *Arg = TheCall->getArg(1);
4374
4375 // We can't check the value of a dependent argument.
4376 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4377 llvm::APSInt Result;
4378 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4379 return true;
4380
4381 if (!Result.isPowerOf2())
4382 return Diag(TheCall->getLocStart(),
4383 diag::err_alignment_not_power_of_two)
4384 << Arg->getSourceRange();
4385 }
4386
4387 if (NumArgs > 2) {
4388 ExprResult Arg(TheCall->getArg(2));
4389 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4390 Context.getSizeType(), false);
4391 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4392 if (Arg.isInvalid()) return true;
4393 TheCall->setArg(2, Arg.get());
4394 }
Hal Finkelf0417332014-07-17 14:25:55 +00004395
4396 return false;
4397}
4398
Mehdi Amini06d367c2016-10-24 20:39:34 +00004399bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4400 unsigned BuiltinID =
4401 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4402 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4403
4404 unsigned NumArgs = TheCall->getNumArgs();
4405 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4406 if (NumArgs < NumRequiredArgs) {
4407 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4408 << 0 /* function call */ << NumRequiredArgs << NumArgs
4409 << TheCall->getSourceRange();
4410 }
4411 if (NumArgs >= NumRequiredArgs + 0x100) {
4412 return Diag(TheCall->getLocEnd(),
4413 diag::err_typecheck_call_too_many_args_at_most)
4414 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4415 << TheCall->getSourceRange();
4416 }
4417 unsigned i = 0;
4418
4419 // For formatting call, check buffer arg.
4420 if (!IsSizeCall) {
4421 ExprResult Arg(TheCall->getArg(i));
4422 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4423 Context, Context.VoidPtrTy, false);
4424 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4425 if (Arg.isInvalid())
4426 return true;
4427 TheCall->setArg(i, Arg.get());
4428 i++;
4429 }
4430
4431 // Check string literal arg.
4432 unsigned FormatIdx = i;
4433 {
4434 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4435 if (Arg.isInvalid())
4436 return true;
4437 TheCall->setArg(i, Arg.get());
4438 i++;
4439 }
4440
4441 // Make sure variadic args are scalar.
4442 unsigned FirstDataArg = i;
4443 while (i < NumArgs) {
4444 ExprResult Arg = DefaultVariadicArgumentPromotion(
4445 TheCall->getArg(i), VariadicFunction, nullptr);
4446 if (Arg.isInvalid())
4447 return true;
4448 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4449 if (ArgSize.getQuantity() >= 0x100) {
4450 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4451 << i << (int)ArgSize.getQuantity() << 0xff
4452 << TheCall->getSourceRange();
4453 }
4454 TheCall->setArg(i, Arg.get());
4455 i++;
4456 }
4457
4458 // Check formatting specifiers. NOTE: We're only doing this for the non-size
4459 // call to avoid duplicate diagnostics.
4460 if (!IsSizeCall) {
4461 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4462 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4463 bool Success = CheckFormatArguments(
4464 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4465 VariadicFunction, TheCall->getLocStart(), SourceRange(),
4466 CheckedVarArgs);
4467 if (!Success)
4468 return true;
4469 }
4470
4471 if (IsSizeCall) {
4472 TheCall->setType(Context.getSizeType());
4473 } else {
4474 TheCall->setType(Context.VoidPtrTy);
4475 }
4476 return false;
4477}
4478
Eric Christopher8d0c6212010-04-17 02:26:23 +00004479/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4480/// TheCall is a constant expression.
4481bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4482 llvm::APSInt &Result) {
4483 Expr *Arg = TheCall->getArg(ArgNum);
4484 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4485 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4486
4487 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4488
4489 if (!Arg->isIntegerConstantExpr(Result, Context))
4490 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00004491 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00004492
Chris Lattnerd545ad12009-09-23 06:06:36 +00004493 return false;
4494}
4495
Richard Sandiford28940af2014-04-16 08:47:51 +00004496/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4497/// TheCall is a constant expression in the range [Low, High].
4498bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4499 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00004500 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004501
4502 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00004503 Expr *Arg = TheCall->getArg(ArgNum);
4504 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004505 return false;
4506
Eric Christopher8d0c6212010-04-17 02:26:23 +00004507 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00004508 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004509 return true;
4510
Richard Sandiford28940af2014-04-16 08:47:51 +00004511 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00004512 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00004513 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00004514
4515 return false;
4516}
4517
Simon Dardis1f90f2d2016-10-19 17:50:52 +00004518/// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4519/// TheCall is a constant expression is a multiple of Num..
4520bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4521 unsigned Num) {
4522 llvm::APSInt Result;
4523
4524 // We can't check the value of a dependent argument.
4525 Expr *Arg = TheCall->getArg(ArgNum);
4526 if (Arg->isTypeDependent() || Arg->isValueDependent())
4527 return false;
4528
4529 // Check constant-ness first.
4530 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4531 return true;
4532
4533 if (Result.getSExtValue() % Num != 0)
4534 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4535 << Num << Arg->getSourceRange();
4536
4537 return false;
4538}
4539
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004540/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4541/// TheCall is an ARM/AArch64 special register string literal.
4542bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4543 int ArgNum, unsigned ExpectedFieldNum,
4544 bool AllowName) {
4545 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4546 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4547 BuiltinID == ARM::BI__builtin_arm_rsr ||
4548 BuiltinID == ARM::BI__builtin_arm_rsrp ||
4549 BuiltinID == ARM::BI__builtin_arm_wsr ||
4550 BuiltinID == ARM::BI__builtin_arm_wsrp;
4551 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4552 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4553 BuiltinID == AArch64::BI__builtin_arm_rsr ||
4554 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4555 BuiltinID == AArch64::BI__builtin_arm_wsr ||
4556 BuiltinID == AArch64::BI__builtin_arm_wsrp;
4557 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4558
4559 // We can't check the value of a dependent argument.
4560 Expr *Arg = TheCall->getArg(ArgNum);
4561 if (Arg->isTypeDependent() || Arg->isValueDependent())
4562 return false;
4563
4564 // Check if the argument is a string literal.
4565 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4566 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4567 << Arg->getSourceRange();
4568
4569 // Check the type of special register given.
4570 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4571 SmallVector<StringRef, 6> Fields;
4572 Reg.split(Fields, ":");
4573
4574 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4575 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4576 << Arg->getSourceRange();
4577
4578 // If the string is the name of a register then we cannot check that it is
4579 // valid here but if the string is of one the forms described in ACLE then we
4580 // can check that the supplied fields are integers and within the valid
4581 // ranges.
4582 if (Fields.size() > 1) {
4583 bool FiveFields = Fields.size() == 5;
4584
4585 bool ValidString = true;
4586 if (IsARMBuiltin) {
4587 ValidString &= Fields[0].startswith_lower("cp") ||
4588 Fields[0].startswith_lower("p");
4589 if (ValidString)
4590 Fields[0] =
4591 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4592
4593 ValidString &= Fields[2].startswith_lower("c");
4594 if (ValidString)
4595 Fields[2] = Fields[2].drop_front(1);
4596
4597 if (FiveFields) {
4598 ValidString &= Fields[3].startswith_lower("c");
4599 if (ValidString)
4600 Fields[3] = Fields[3].drop_front(1);
4601 }
4602 }
4603
4604 SmallVector<int, 5> Ranges;
4605 if (FiveFields)
Oleg Ranevskyy85d93a82016-11-18 21:00:08 +00004606 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004607 else
4608 Ranges.append({15, 7, 15});
4609
4610 for (unsigned i=0; i<Fields.size(); ++i) {
4611 int IntField;
4612 ValidString &= !Fields[i].getAsInteger(10, IntField);
4613 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4614 }
4615
4616 if (!ValidString)
4617 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4618 << Arg->getSourceRange();
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004619 } else if (IsAArch64Builtin && Fields.size() == 1) {
4620 // If the register name is one of those that appear in the condition below
4621 // and the special register builtin being used is one of the write builtins,
4622 // then we require that the argument provided for writing to the register
4623 // is an integer constant expression. This is because it will be lowered to
4624 // an MSR (immediate) instruction, so we need to know the immediate at
4625 // compile time.
4626 if (TheCall->getNumArgs() != 2)
4627 return false;
4628
4629 std::string RegLower = Reg.lower();
4630 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4631 RegLower != "pan" && RegLower != "uao")
4632 return false;
4633
4634 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4635 }
4636
4637 return false;
4638}
4639
Eli Friedmanc97d0142009-05-03 06:04:26 +00004640/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004641/// This checks that the target supports __builtin_longjmp and
4642/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004643bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004644 if (!Context.getTargetInfo().hasSjLjLowering())
4645 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4646 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4647
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004648 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00004649 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00004650
Eric Christopher8d0c6212010-04-17 02:26:23 +00004651 // TODO: This is less than ideal. Overload this to take a value.
4652 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4653 return true;
4654
4655 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004656 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4657 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4658
4659 return false;
4660}
4661
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004662/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4663/// This checks that the target supports __builtin_setjmp.
4664bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4665 if (!Context.getTargetInfo().hasSjLjLowering())
4666 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4667 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4668 return false;
4669}
4670
Richard Smithd7293d72013-08-05 18:49:43 +00004671namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004672
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004673class UncoveredArgHandler {
4674 enum { Unknown = -1, AllCovered = -2 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004675
4676 signed FirstUncoveredArg = Unknown;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004677 SmallVector<const Expr *, 4> DiagnosticExprs;
4678
4679public:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004680 UncoveredArgHandler() = default;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004681
4682 bool hasUncoveredArg() const {
4683 return (FirstUncoveredArg >= 0);
4684 }
4685
4686 unsigned getUncoveredArg() const {
4687 assert(hasUncoveredArg() && "no uncovered argument");
4688 return FirstUncoveredArg;
4689 }
4690
4691 void setAllCovered() {
4692 // A string has been found with all arguments covered, so clear out
4693 // the diagnostics.
4694 DiagnosticExprs.clear();
4695 FirstUncoveredArg = AllCovered;
4696 }
4697
4698 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4699 assert(NewFirstUncoveredArg >= 0 && "Outside range");
4700
4701 // Don't update if a previous string covers all arguments.
4702 if (FirstUncoveredArg == AllCovered)
4703 return;
4704
4705 // UncoveredArgHandler tracks the highest uncovered argument index
4706 // and with it all the strings that match this index.
4707 if (NewFirstUncoveredArg == FirstUncoveredArg)
4708 DiagnosticExprs.push_back(StrExpr);
4709 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4710 DiagnosticExprs.clear();
4711 DiagnosticExprs.push_back(StrExpr);
4712 FirstUncoveredArg = NewFirstUncoveredArg;
4713 }
4714 }
4715
4716 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4717};
4718
Richard Smithd7293d72013-08-05 18:49:43 +00004719enum StringLiteralCheckType {
4720 SLCT_NotALiteral,
4721 SLCT_UncheckedLiteral,
4722 SLCT_CheckedLiteral
4723};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004724
4725} // namespace
Richard Smithd7293d72013-08-05 18:49:43 +00004726
Stephen Hines648c3692016-09-16 01:07:04 +00004727static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4728 BinaryOperatorKind BinOpKind,
4729 bool AddendIsRight) {
4730 unsigned BitWidth = Offset.getBitWidth();
4731 unsigned AddendBitWidth = Addend.getBitWidth();
4732 // There might be negative interim results.
4733 if (Addend.isUnsigned()) {
4734 Addend = Addend.zext(++AddendBitWidth);
4735 Addend.setIsSigned(true);
4736 }
4737 // Adjust the bit width of the APSInts.
4738 if (AddendBitWidth > BitWidth) {
4739 Offset = Offset.sext(AddendBitWidth);
4740 BitWidth = AddendBitWidth;
4741 } else if (BitWidth > AddendBitWidth) {
4742 Addend = Addend.sext(BitWidth);
4743 }
4744
4745 bool Ov = false;
4746 llvm::APSInt ResOffset = Offset;
4747 if (BinOpKind == BO_Add)
4748 ResOffset = Offset.sadd_ov(Addend, Ov);
4749 else {
4750 assert(AddendIsRight && BinOpKind == BO_Sub &&
4751 "operator must be add or sub with addend on the right");
4752 ResOffset = Offset.ssub_ov(Addend, Ov);
4753 }
4754
4755 // We add an offset to a pointer here so we should support an offset as big as
4756 // possible.
4757 if (Ov) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004758 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
4759 "index (intermediate) result too big");
Stephen Hinesfec73ad2016-09-16 07:21:24 +00004760 Offset = Offset.sext(2 * BitWidth);
Stephen Hines648c3692016-09-16 01:07:04 +00004761 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4762 return;
4763 }
4764
4765 Offset = ResOffset;
4766}
4767
4768namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004769
Stephen Hines648c3692016-09-16 01:07:04 +00004770// This is a wrapper class around StringLiteral to support offsetted string
4771// literals as format strings. It takes the offset into account when returning
4772// the string and its length or the source locations to display notes correctly.
4773class FormatStringLiteral {
4774 const StringLiteral *FExpr;
4775 int64_t Offset;
4776
4777 public:
4778 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4779 : FExpr(fexpr), Offset(Offset) {}
4780
4781 StringRef getString() const {
4782 return FExpr->getString().drop_front(Offset);
4783 }
4784
4785 unsigned getByteLength() const {
4786 return FExpr->getByteLength() - getCharByteWidth() * Offset;
4787 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004788
Stephen Hines648c3692016-09-16 01:07:04 +00004789 unsigned getLength() const { return FExpr->getLength() - Offset; }
4790 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4791
4792 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4793
4794 QualType getType() const { return FExpr->getType(); }
4795
4796 bool isAscii() const { return FExpr->isAscii(); }
4797 bool isWide() const { return FExpr->isWide(); }
4798 bool isUTF8() const { return FExpr->isUTF8(); }
4799 bool isUTF16() const { return FExpr->isUTF16(); }
4800 bool isUTF32() const { return FExpr->isUTF32(); }
4801 bool isPascal() const { return FExpr->isPascal(); }
4802
4803 SourceLocation getLocationOfByte(
4804 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4805 const TargetInfo &Target, unsigned *StartToken = nullptr,
4806 unsigned *StartTokenByteOffset = nullptr) const {
4807 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4808 StartToken, StartTokenByteOffset);
4809 }
4810
4811 SourceLocation getLocStart() const LLVM_READONLY {
4812 return FExpr->getLocStart().getLocWithOffset(Offset);
4813 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004814
Stephen Hines648c3692016-09-16 01:07:04 +00004815 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4816};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004817
4818} // namespace
Stephen Hines648c3692016-09-16 01:07:04 +00004819
4820static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004821 const Expr *OrigFormatExpr,
4822 ArrayRef<const Expr *> Args,
4823 bool HasVAListArg, unsigned format_idx,
4824 unsigned firstDataArg,
4825 Sema::FormatStringType Type,
4826 bool inFunctionCall,
4827 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004828 llvm::SmallBitVector &CheckedVarArgs,
4829 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004830
Richard Smith55ce3522012-06-25 20:30:08 +00004831// Determine if an expression is a string literal or constant string.
4832// If this function returns false on the arguments to a function expecting a
4833// format string, we will usually need to emit a warning.
4834// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00004835static StringLiteralCheckType
4836checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4837 bool HasVAListArg, unsigned format_idx,
4838 unsigned firstDataArg, Sema::FormatStringType Type,
4839 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004840 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004841 UncoveredArgHandler &UncoveredArg,
4842 llvm::APSInt Offset) {
Ted Kremenek808829352010-09-09 03:51:39 +00004843 tryAgain:
Stephen Hines648c3692016-09-16 01:07:04 +00004844 assert(Offset.isSigned() && "invalid offset");
4845
Douglas Gregorc25f7662009-05-19 22:10:17 +00004846 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00004847 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004848
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004849 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00004850
Richard Smithd7293d72013-08-05 18:49:43 +00004851 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00004852 // Technically -Wformat-nonliteral does not warn about this case.
4853 // The behavior of printf and friends in this case is implementation
4854 // dependent. Ideally if the format string cannot be null then
4855 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00004856 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00004857
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004858 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00004859 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004860 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00004861 // The expression is a literal if both sub-expressions were, and it was
4862 // completely checked only if both sub-expressions were checked.
4863 const AbstractConditionalOperator *C =
4864 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004865
4866 // Determine whether it is necessary to check both sub-expressions, for
4867 // example, because the condition expression is a constant that can be
4868 // evaluated at compile time.
4869 bool CheckLeft = true, CheckRight = true;
4870
4871 bool Cond;
4872 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4873 if (Cond)
4874 CheckRight = false;
4875 else
4876 CheckLeft = false;
4877 }
4878
Stephen Hines648c3692016-09-16 01:07:04 +00004879 // We need to maintain the offsets for the right and the left hand side
4880 // separately to check if every possible indexed expression is a valid
4881 // string literal. They might have different offsets for different string
4882 // literals in the end.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004883 StringLiteralCheckType Left;
4884 if (!CheckLeft)
4885 Left = SLCT_UncheckedLiteral;
4886 else {
4887 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4888 HasVAListArg, format_idx, firstDataArg,
4889 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004890 CheckedVarArgs, UncoveredArg, Offset);
4891 if (Left == SLCT_NotALiteral || !CheckRight) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004892 return Left;
Stephen Hines648c3692016-09-16 01:07:04 +00004893 }
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004894 }
4895
Richard Smith55ce3522012-06-25 20:30:08 +00004896 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00004897 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004898 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004899 Type, CallType, InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004900 UncoveredArg, Offset);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004901
4902 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004903 }
4904
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004905 case Stmt::ImplicitCastExprClass:
Ted Kremenek808829352010-09-09 03:51:39 +00004906 E = cast<ImplicitCastExpr>(E)->getSubExpr();
4907 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004908
John McCallc07a0c72011-02-17 10:25:35 +00004909 case Stmt::OpaqueValueExprClass:
4910 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4911 E = src;
4912 goto tryAgain;
4913 }
Richard Smith55ce3522012-06-25 20:30:08 +00004914 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00004915
Ted Kremeneka8890832011-02-24 23:03:04 +00004916 case Stmt::PredefinedExprClass:
4917 // While __func__, etc., are technically not string literals, they
4918 // cannot contain format specifiers and thus are not a security
4919 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00004920 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00004921
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004922 case Stmt::DeclRefExprClass: {
4923 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004924
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004925 // As an exception, do not flag errors for variables binding to
4926 // const string literals.
4927 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4928 bool isConstant = false;
4929 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004930
Richard Smithd7293d72013-08-05 18:49:43 +00004931 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4932 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00004933 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00004934 isConstant = T.isConstant(S.Context) &&
4935 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00004936 } else if (T->isObjCObjectPointerType()) {
4937 // In ObjC, there is usually no "const ObjectPointer" type,
4938 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00004939 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004940 }
Mike Stump11289f42009-09-09 15:08:12 +00004941
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004942 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004943 if (const Expr *Init = VD->getAnyInitializer()) {
4944 // Look through initializers like const char c[] = { "foo" }
4945 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4946 if (InitList->isStringLiteralInit())
4947 Init = InitList->getInit(0)->IgnoreParenImpCasts();
4948 }
Richard Smithd7293d72013-08-05 18:49:43 +00004949 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004950 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004951 firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00004952 /*InFunctionCall*/ false, CheckedVarArgs,
4953 UncoveredArg, Offset);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004954 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004955 }
Mike Stump11289f42009-09-09 15:08:12 +00004956
Anders Carlssonb012ca92009-06-28 19:55:58 +00004957 // For vprintf* functions (i.e., HasVAListArg==true), we add a
4958 // special check to see if the format string is a function parameter
4959 // of the function calling the printf function. If the function
4960 // has an attribute indicating it is a printf-like function, then we
4961 // should suppress warnings concerning non-literals being used in a call
4962 // to a vprintf function. For example:
4963 //
4964 // void
4965 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4966 // va_list ap;
4967 // va_start(ap, fmt);
4968 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
4969 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00004970 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004971 if (HasVAListArg) {
4972 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4973 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4974 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00004975 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004976 // adjust for implicit parameter
4977 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4978 if (MD->isInstance())
4979 ++PVIndex;
4980 // We also check if the formats are compatible.
4981 // We can't pass a 'scanf' string to a 'printf' function.
4982 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00004983 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00004984 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004985 }
4986 }
4987 }
4988 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004989 }
Mike Stump11289f42009-09-09 15:08:12 +00004990
Richard Smith55ce3522012-06-25 20:30:08 +00004991 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004992 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004993
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004994 case Stmt::CallExprClass:
4995 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004996 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004997 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
4998 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
Joel E. Denny81508102018-03-13 14:51:22 +00004999 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
Richard Smithd7293d72013-08-05 18:49:43 +00005000 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005001 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00005002 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00005003 CheckedVarArgs, UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005004 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5005 unsigned BuiltinID = FD->getBuiltinID();
5006 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
5007 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
5008 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00005009 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005010 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005011 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005012 InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00005013 UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005014 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005015 }
5016 }
Mike Stump11289f42009-09-09 15:08:12 +00005017
Richard Smith55ce3522012-06-25 20:30:08 +00005018 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005019 }
Alex Lorenzd9007142016-10-24 09:42:34 +00005020 case Stmt::ObjCMessageExprClass: {
5021 const auto *ME = cast<ObjCMessageExpr>(E);
5022 if (const auto *ND = ME->getMethodDecl()) {
5023 if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
Joel E. Denny81508102018-03-13 14:51:22 +00005024 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
Alex Lorenzd9007142016-10-24 09:42:34 +00005025 return checkFormatStringExpr(
5026 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
5027 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
5028 }
5029 }
5030
5031 return SLCT_NotALiteral;
5032 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005033 case Stmt::ObjCStringLiteralClass:
5034 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00005035 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005036
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005037 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005038 StrE = ObjCFExpr->getString();
5039 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005040 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005041
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005042 if (StrE) {
Stephen Hines648c3692016-09-16 01:07:04 +00005043 if (Offset.isNegative() || Offset > StrE->getLength()) {
5044 // TODO: It would be better to have an explicit warning for out of
5045 // bounds literals.
5046 return SLCT_NotALiteral;
5047 }
5048 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
5049 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005050 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005051 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00005052 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005053 }
Mike Stump11289f42009-09-09 15:08:12 +00005054
Richard Smith55ce3522012-06-25 20:30:08 +00005055 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005056 }
Stephen Hines648c3692016-09-16 01:07:04 +00005057 case Stmt::BinaryOperatorClass: {
5058 llvm::APSInt LResult;
5059 llvm::APSInt RResult;
5060
5061 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
5062
5063 // A string literal + an int offset is still a string literal.
5064 if (BinOp->isAdditiveOp()) {
5065 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
5066 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
5067
5068 if (LIsInt != RIsInt) {
5069 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
5070
5071 if (LIsInt) {
5072 if (BinOpKind == BO_Add) {
5073 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
5074 E = BinOp->getRHS();
5075 goto tryAgain;
5076 }
5077 } else {
5078 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
5079 E = BinOp->getLHS();
5080 goto tryAgain;
5081 }
5082 }
Stephen Hines648c3692016-09-16 01:07:04 +00005083 }
George Burgess IVd273aab2016-09-22 00:00:26 +00005084
5085 return SLCT_NotALiteral;
Stephen Hines648c3692016-09-16 01:07:04 +00005086 }
5087 case Stmt::UnaryOperatorClass: {
5088 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
5089 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005090 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
Stephen Hines648c3692016-09-16 01:07:04 +00005091 llvm::APSInt IndexResult;
5092 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
5093 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
5094 E = ASE->getBase();
5095 goto tryAgain;
5096 }
5097 }
5098
5099 return SLCT_NotALiteral;
5100 }
Mike Stump11289f42009-09-09 15:08:12 +00005101
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005102 default:
Richard Smith55ce3522012-06-25 20:30:08 +00005103 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005104 }
5105}
5106
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005107Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00005108 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Mehdi Amini06d367c2016-10-24 20:39:34 +00005109 .Case("scanf", FST_Scanf)
5110 .Cases("printf", "printf0", FST_Printf)
5111 .Cases("NSString", "CFString", FST_NSString)
5112 .Case("strftime", FST_Strftime)
5113 .Case("strfmon", FST_Strfmon)
5114 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
5115 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
5116 .Case("os_trace", FST_OSLog)
5117 .Case("os_log", FST_OSLog)
5118 .Default(FST_Unknown);
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005119}
5120
Jordan Rose3e0ec582012-07-19 18:10:23 +00005121/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00005122/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00005123/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005124bool Sema::CheckFormatArguments(const FormatAttr *Format,
5125 ArrayRef<const Expr *> Args,
5126 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005127 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00005128 SourceLocation Loc, SourceRange Range,
5129 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00005130 FormatStringInfo FSI;
5131 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005132 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00005133 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00005134 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00005135 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005136}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00005137
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005138bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005139 bool HasVAListArg, unsigned format_idx,
5140 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005141 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00005142 SourceLocation Loc, SourceRange Range,
5143 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00005144 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005145 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005146 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00005147 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005148 }
Mike Stump11289f42009-09-09 15:08:12 +00005149
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005150 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00005151
Chris Lattnerb87b1b32007-08-10 20:18:51 +00005152 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00005153 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005154 // Dynamically generated format strings are difficult to
5155 // automatically vet at compile time. Requiring that format strings
5156 // are string literals: (1) permits the checking of format strings by
5157 // the compiler and thereby (2) can practically remove the source of
5158 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00005159
Mike Stump11289f42009-09-09 15:08:12 +00005160 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00005161 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00005162 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00005163 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005164 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00005165 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00005166 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
5167 format_idx, firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00005168 /*IsFunctionCall*/ true, CheckedVarArgs,
5169 UncoveredArg,
5170 /*no string offset*/ llvm::APSInt(64, false) = 0);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005171
5172 // Generate a diagnostic where an uncovered argument is detected.
5173 if (UncoveredArg.hasUncoveredArg()) {
5174 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
5175 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
5176 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
5177 }
5178
Richard Smith55ce3522012-06-25 20:30:08 +00005179 if (CT != SLCT_NotALiteral)
5180 // Literal format string found, check done!
5181 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00005182
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00005183 // Strftime is particular as it always uses a single 'time' argument,
5184 // so it is safe to pass a non-literal string.
5185 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00005186 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00005187
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00005188 // Do not emit diag when the string param is a macro expansion and the
5189 // format is either NSString or CFString. This is a hack to prevent
5190 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
5191 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005192 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
5193 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00005194 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00005195
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005196 // If there are no arguments specified, warn with -Wformat-security, otherwise
5197 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005198 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00005199 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
5200 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005201 switch (Type) {
5202 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005203 break;
5204 case FST_Kprintf:
5205 case FST_FreeBSDKPrintf:
5206 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00005207 Diag(FormatLoc, diag::note_format_security_fixit)
5208 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005209 break;
5210 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00005211 Diag(FormatLoc, diag::note_format_security_fixit)
5212 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005213 break;
5214 }
5215 } else {
5216 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005217 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005218 }
Richard Smith55ce3522012-06-25 20:30:08 +00005219 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005220}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005221
Ted Kremenekab278de2010-01-28 23:39:18 +00005222namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005223
Ted Kremenek02087932010-07-16 02:11:22 +00005224class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
5225protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00005226 Sema &S;
Stephen Hines648c3692016-09-16 01:07:04 +00005227 const FormatStringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00005228 const Expr *OrigFormatExpr;
Mehdi Amini06d367c2016-10-24 20:39:34 +00005229 const Sema::FormatStringType FSType;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00005230 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00005231 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00005232 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00005233 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005234 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00005235 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00005236 llvm::SmallBitVector CoveredArgs;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005237 bool usesPositionalArgs = false;
5238 bool atFirstArg = true;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005239 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00005240 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00005241 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005242 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005243
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005244public:
Stephen Hines648c3692016-09-16 01:07:04 +00005245 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005246 const Expr *origFormatExpr,
5247 const Sema::FormatStringType type, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005248 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005249 ArrayRef<const Expr *> Args, unsigned formatIdx,
5250 bool inFunctionCall, Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005251 llvm::SmallBitVector &CheckedVarArgs,
5252 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005253 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
5254 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
5255 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
Mehdi Amini06d367c2016-10-24 20:39:34 +00005256 inFunctionCall(inFunctionCall), CallType(callType),
5257 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00005258 CoveredArgs.resize(numDataArgs);
5259 CoveredArgs.reset();
5260 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005261
Ted Kremenek019d2242010-01-29 01:50:07 +00005262 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005263
Ted Kremenek02087932010-07-16 02:11:22 +00005264 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005265 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005266
Jordan Rose92303592012-09-08 04:00:03 +00005267 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005268 const analyze_format_string::FormatSpecifier &FS,
5269 const analyze_format_string::ConversionSpecifier &CS,
5270 const char *startSpecifier, unsigned specifierLen,
5271 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00005272
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005273 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005274 const analyze_format_string::FormatSpecifier &FS,
5275 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005276
5277 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005278 const analyze_format_string::ConversionSpecifier &CS,
5279 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005280
Craig Toppere14c0f82014-03-12 04:55:44 +00005281 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005282
Craig Toppere14c0f82014-03-12 04:55:44 +00005283 void HandleInvalidPosition(const char *startSpecifier,
5284 unsigned specifierLen,
5285 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005286
Craig Toppere14c0f82014-03-12 04:55:44 +00005287 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005288
Craig Toppere14c0f82014-03-12 04:55:44 +00005289 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005290
Richard Trieu03cf7b72011-10-28 00:41:25 +00005291 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00005292 static void
5293 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
5294 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
5295 bool IsStringLocation, Range StringRange,
5296 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005297
Ted Kremenek02087932010-07-16 02:11:22 +00005298protected:
Ted Kremenekce815422010-07-19 21:25:57 +00005299 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
5300 const char *startSpec,
5301 unsigned specifierLen,
5302 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005303
5304 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
5305 const char *startSpec,
5306 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00005307
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005308 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00005309 CharSourceRange getSpecifierRange(const char *startSpecifier,
5310 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00005311 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005312
Ted Kremenek5739de72010-01-29 01:06:55 +00005313 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005314
5315 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
5316 const analyze_format_string::ConversionSpecifier &CS,
5317 const char *startSpecifier, unsigned specifierLen,
5318 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005319
5320 template <typename Range>
5321 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5322 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00005323 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00005324};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005325
5326} // namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00005327
Ted Kremenek02087932010-07-16 02:11:22 +00005328SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00005329 return OrigFormatExpr->getSourceRange();
5330}
5331
Ted Kremenek02087932010-07-16 02:11:22 +00005332CharSourceRange CheckFormatHandler::
5333getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00005334 SourceLocation Start = getLocationOfByte(startSpecifier);
5335 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
5336
5337 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00005338 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00005339
5340 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005341}
5342
Ted Kremenek02087932010-07-16 02:11:22 +00005343SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines648c3692016-09-16 01:07:04 +00005344 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
5345 S.getLangOpts(), S.Context.getTargetInfo());
Ted Kremenekab278de2010-01-28 23:39:18 +00005346}
5347
Ted Kremenek02087932010-07-16 02:11:22 +00005348void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
5349 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00005350 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
5351 getLocationOfByte(startSpecifier),
5352 /*IsStringLocation*/true,
5353 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00005354}
5355
Jordan Rose92303592012-09-08 04:00:03 +00005356void CheckFormatHandler::HandleInvalidLengthModifier(
5357 const analyze_format_string::FormatSpecifier &FS,
5358 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00005359 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00005360 using namespace analyze_format_string;
5361
5362 const LengthModifier &LM = FS.getLengthModifier();
5363 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5364
5365 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005366 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00005367 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005368 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005369 getLocationOfByte(LM.getStart()),
5370 /*IsStringLocation*/true,
5371 getSpecifierRange(startSpecifier, specifierLen));
5372
5373 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5374 << FixedLM->toString()
5375 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5376
5377 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005378 FixItHint Hint;
5379 if (DiagID == diag::warn_format_nonsensical_length)
5380 Hint = FixItHint::CreateRemoval(LMRange);
5381
5382 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005383 getLocationOfByte(LM.getStart()),
5384 /*IsStringLocation*/true,
5385 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00005386 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00005387 }
5388}
5389
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005390void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00005391 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005392 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005393 using namespace analyze_format_string;
5394
5395 const LengthModifier &LM = FS.getLengthModifier();
5396 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5397
5398 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005399 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00005400 if (FixedLM) {
5401 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5402 << LM.toString() << 0,
5403 getLocationOfByte(LM.getStart()),
5404 /*IsStringLocation*/true,
5405 getSpecifierRange(startSpecifier, specifierLen));
5406
5407 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5408 << FixedLM->toString()
5409 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5410
5411 } else {
5412 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5413 << LM.toString() << 0,
5414 getLocationOfByte(LM.getStart()),
5415 /*IsStringLocation*/true,
5416 getSpecifierRange(startSpecifier, specifierLen));
5417 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005418}
5419
5420void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5421 const analyze_format_string::ConversionSpecifier &CS,
5422 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00005423 using namespace analyze_format_string;
5424
5425 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00005426 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00005427 if (FixedCS) {
5428 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5429 << CS.toString() << /*conversion specifier*/1,
5430 getLocationOfByte(CS.getStart()),
5431 /*IsStringLocation*/true,
5432 getSpecifierRange(startSpecifier, specifierLen));
5433
5434 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5435 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5436 << FixedCS->toString()
5437 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5438 } else {
5439 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5440 << CS.toString() << /*conversion specifier*/1,
5441 getLocationOfByte(CS.getStart()),
5442 /*IsStringLocation*/true,
5443 getSpecifierRange(startSpecifier, specifierLen));
5444 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005445}
5446
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005447void CheckFormatHandler::HandlePosition(const char *startPos,
5448 unsigned posLen) {
5449 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5450 getLocationOfByte(startPos),
5451 /*IsStringLocation*/true,
5452 getSpecifierRange(startPos, posLen));
5453}
5454
Ted Kremenekd1668192010-02-27 01:41:03 +00005455void
Ted Kremenek02087932010-07-16 02:11:22 +00005456CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5457 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005458 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5459 << (unsigned) p,
5460 getLocationOfByte(startPos), /*IsStringLocation*/true,
5461 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005462}
5463
Ted Kremenek02087932010-07-16 02:11:22 +00005464void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00005465 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005466 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5467 getLocationOfByte(startPos),
5468 /*IsStringLocation*/true,
5469 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005470}
5471
Ted Kremenek02087932010-07-16 02:11:22 +00005472void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005473 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005474 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005475 EmitFormatDiagnostic(
5476 S.PDiag(diag::warn_printf_format_string_contains_null_char),
5477 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5478 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005479 }
Ted Kremenek02087932010-07-16 02:11:22 +00005480}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005481
Jordan Rose58bbe422012-07-19 18:10:08 +00005482// Note that this may return NULL if there was an error parsing or building
5483// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00005484const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005485 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00005486}
5487
5488void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005489 // Does the number of data arguments exceed the number of
5490 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00005491 if (!HasVAListArg) {
5492 // Find any arguments that weren't covered.
5493 CoveredArgs.flip();
5494 signed notCoveredArg = CoveredArgs.find_first();
5495 if (notCoveredArg >= 0) {
5496 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005497 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5498 } else {
5499 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00005500 }
5501 }
5502}
5503
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005504void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5505 const Expr *ArgExpr) {
5506 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5507 "Invalid state");
5508
5509 if (!ArgExpr)
5510 return;
5511
5512 SourceLocation Loc = ArgExpr->getLocStart();
5513
5514 if (S.getSourceManager().isInSystemMacro(Loc))
5515 return;
5516
5517 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5518 for (auto E : DiagnosticExprs)
5519 PDiag << E->getSourceRange();
5520
5521 CheckFormatHandler::EmitFormatDiagnostic(
5522 S, IsFunctionCall, DiagnosticExprs[0],
5523 PDiag, Loc, /*IsStringLocation*/false,
5524 DiagnosticExprs[0]->getSourceRange());
5525}
5526
Ted Kremenekce815422010-07-19 21:25:57 +00005527bool
5528CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5529 SourceLocation Loc,
5530 const char *startSpec,
5531 unsigned specifierLen,
5532 const char *csStart,
5533 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00005534 bool keepGoing = true;
5535 if (argIndex < NumDataArgs) {
5536 // Consider the argument coverered, even though the specifier doesn't
5537 // make sense.
5538 CoveredArgs.set(argIndex);
5539 }
5540 else {
5541 // If argIndex exceeds the number of data arguments we
5542 // don't issue a warning because that is just a cascade of warnings (and
5543 // they may have intended '%%' anyway). We don't want to continue processing
5544 // the format string after this point, however, as we will like just get
5545 // gibberish when trying to match arguments.
5546 keepGoing = false;
5547 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005548
5549 StringRef Specifier(csStart, csLen);
5550
5551 // If the specifier in non-printable, it could be the first byte of a UTF-8
5552 // sequence. In that case, print the UTF-8 code point. If not, print the byte
5553 // hex value.
5554 std::string CodePointStr;
5555 if (!llvm::sys::locale::isPrint(*csStart)) {
Justin Lebar90910552016-09-30 00:38:45 +00005556 llvm::UTF32 CodePoint;
5557 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5558 const llvm::UTF8 *E =
5559 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5560 llvm::ConversionResult Result =
5561 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005562
Justin Lebar90910552016-09-30 00:38:45 +00005563 if (Result != llvm::conversionOK) {
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005564 unsigned char FirstChar = *csStart;
Justin Lebar90910552016-09-30 00:38:45 +00005565 CodePoint = (llvm::UTF32)FirstChar;
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005566 }
5567
5568 llvm::raw_string_ostream OS(CodePointStr);
5569 if (CodePoint < 256)
5570 OS << "\\x" << llvm::format("%02x", CodePoint);
5571 else if (CodePoint <= 0xFFFF)
5572 OS << "\\u" << llvm::format("%04x", CodePoint);
5573 else
5574 OS << "\\U" << llvm::format("%08x", CodePoint);
5575 OS.flush();
5576 Specifier = CodePointStr;
5577 }
5578
5579 EmitFormatDiagnostic(
5580 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5581 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5582
Ted Kremenekce815422010-07-19 21:25:57 +00005583 return keepGoing;
5584}
5585
Richard Trieu03cf7b72011-10-28 00:41:25 +00005586void
5587CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5588 const char *startSpec,
5589 unsigned specifierLen) {
5590 EmitFormatDiagnostic(
5591 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5592 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5593}
5594
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005595bool
5596CheckFormatHandler::CheckNumArgs(
5597 const analyze_format_string::FormatSpecifier &FS,
5598 const analyze_format_string::ConversionSpecifier &CS,
5599 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5600
5601 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005602 PartialDiagnostic PDiag = FS.usesPositionalArg()
5603 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5604 << (argIndex+1) << NumDataArgs)
5605 : S.PDiag(diag::warn_printf_insufficient_data_args);
5606 EmitFormatDiagnostic(
5607 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5608 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005609
5610 // Since more arguments than conversion tokens are given, by extension
5611 // all arguments are covered, so mark this as so.
5612 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005613 return false;
5614 }
5615 return true;
5616}
5617
Richard Trieu03cf7b72011-10-28 00:41:25 +00005618template<typename Range>
5619void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5620 SourceLocation Loc,
5621 bool IsStringLocation,
5622 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00005623 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005624 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00005625 Loc, IsStringLocation, StringRange, FixIt);
5626}
5627
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005628/// \brief If the format string is not within the function call, emit a note
Richard Trieu03cf7b72011-10-28 00:41:25 +00005629/// so that the function call and string are in diagnostic messages.
5630///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005631/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00005632/// call and only one diagnostic message will be produced. Otherwise, an
5633/// extra note will be emitted pointing to location of the format string.
5634///
5635/// \param ArgumentExpr the expression that is passed as the format string
5636/// argument in the function call. Used for getting locations when two
5637/// diagnostics are emitted.
5638///
5639/// \param PDiag the callee should already have provided any strings for the
5640/// diagnostic message. This function only adds locations and fixits
5641/// to diagnostics.
5642///
5643/// \param Loc primary location for diagnostic. If two diagnostics are
5644/// required, one will be at Loc and a new SourceLocation will be created for
5645/// the other one.
5646///
5647/// \param IsStringLocation if true, Loc points to the format string should be
5648/// used for the note. Otherwise, Loc points to the argument list and will
5649/// be used with PDiag.
5650///
5651/// \param StringRange some or all of the string to highlight. This is
5652/// templated so it can accept either a CharSourceRange or a SourceRange.
5653///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005654/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00005655template <typename Range>
5656void CheckFormatHandler::EmitFormatDiagnostic(
5657 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5658 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5659 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00005660 if (InFunctionCall) {
5661 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5662 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005663 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00005664 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005665 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5666 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00005667
5668 const Sema::SemaDiagnosticBuilder &Note =
5669 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5670 diag::note_format_string_defined);
5671
5672 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005673 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005674 }
5675}
5676
Ted Kremenek02087932010-07-16 02:11:22 +00005677//===--- CHECK: Printf format string checking ------------------------------===//
5678
5679namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005680
Ted Kremenek02087932010-07-16 02:11:22 +00005681class CheckPrintfHandler : public CheckFormatHandler {
5682public:
Stephen Hines648c3692016-09-16 01:07:04 +00005683 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005684 const Expr *origFormatExpr,
5685 const Sema::FormatStringType type, unsigned firstDataArg,
5686 unsigned numDataArgs, bool isObjC, const char *beg,
5687 bool hasVAListArg, ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005688 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00005689 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005690 llvm::SmallBitVector &CheckedVarArgs,
5691 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005692 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5693 numDataArgs, beg, hasVAListArg, Args, formatIdx,
5694 inFunctionCall, CallType, CheckedVarArgs,
5695 UncoveredArg) {}
5696
5697 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5698
5699 /// Returns true if '%@' specifiers are allowed in the format string.
5700 bool allowsObjCArg() const {
5701 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5702 FSType == Sema::FST_OSTrace;
5703 }
Jordan Rose3e0ec582012-07-19 18:10:23 +00005704
Ted Kremenek02087932010-07-16 02:11:22 +00005705 bool HandleInvalidPrintfConversionSpecifier(
5706 const analyze_printf::PrintfSpecifier &FS,
5707 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005708 unsigned specifierLen) override;
5709
Ted Kremenek02087932010-07-16 02:11:22 +00005710 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5711 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005712 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005713 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5714 const char *StartSpecifier,
5715 unsigned SpecifierLen,
5716 const Expr *E);
5717
Ted Kremenek02087932010-07-16 02:11:22 +00005718 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5719 const char *startSpecifier, unsigned specifierLen);
5720 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5721 const analyze_printf::OptionalAmount &Amt,
5722 unsigned type,
5723 const char *startSpecifier, unsigned specifierLen);
5724 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5725 const analyze_printf::OptionalFlag &flag,
5726 const char *startSpecifier, unsigned specifierLen);
5727 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5728 const analyze_printf::OptionalFlag &ignoredFlag,
5729 const analyze_printf::OptionalFlag &flag,
5730 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005731 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00005732 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00005733
5734 void HandleEmptyObjCModifierFlag(const char *startFlag,
5735 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005736
Ted Kremenek2b417712015-07-02 05:39:16 +00005737 void HandleInvalidObjCModifierFlag(const char *startFlag,
5738 unsigned flagLen) override;
5739
5740 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5741 const char *flagsEnd,
5742 const char *conversionPosition)
5743 override;
5744};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005745
5746} // namespace
Ted Kremenek02087932010-07-16 02:11:22 +00005747
5748bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5749 const analyze_printf::PrintfSpecifier &FS,
5750 const char *startSpecifier,
5751 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005752 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00005753 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00005754
Ted Kremenekce815422010-07-19 21:25:57 +00005755 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5756 getLocationOfByte(CS.getStart()),
5757 startSpecifier, specifierLen,
5758 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00005759}
5760
Ted Kremenek02087932010-07-16 02:11:22 +00005761bool CheckPrintfHandler::HandleAmount(
5762 const analyze_format_string::OptionalAmount &Amt,
5763 unsigned k, const char *startSpecifier,
5764 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005765 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005766 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00005767 unsigned argIndex = Amt.getArgIndex();
5768 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005769 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5770 << k,
5771 getLocationOfByte(Amt.getStart()),
5772 /*IsStringLocation*/true,
5773 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005774 // Don't do any more checking. We will just emit
5775 // spurious errors.
5776 return false;
5777 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005778
Ted Kremenek5739de72010-01-29 01:06:55 +00005779 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00005780 // Although not in conformance with C99, we also allow the argument to be
5781 // an 'unsigned int' as that is a reasonably safe case. GCC also
5782 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00005783 CoveredArgs.set(argIndex);
5784 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00005785 if (!Arg)
5786 return false;
5787
Ted Kremenek5739de72010-01-29 01:06:55 +00005788 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005789
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005790 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5791 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005792
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005793 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005794 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005795 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00005796 << T << Arg->getSourceRange(),
5797 getLocationOfByte(Amt.getStart()),
5798 /*IsStringLocation*/true,
5799 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005800 // Don't do any more checking. We will just emit
5801 // spurious errors.
5802 return false;
5803 }
5804 }
5805 }
5806 return true;
5807}
Ted Kremenek5739de72010-01-29 01:06:55 +00005808
Tom Careb49ec692010-06-17 19:00:27 +00005809void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00005810 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005811 const analyze_printf::OptionalAmount &Amt,
5812 unsigned type,
5813 const char *startSpecifier,
5814 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005815 const analyze_printf::PrintfConversionSpecifier &CS =
5816 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00005817
Richard Trieu03cf7b72011-10-28 00:41:25 +00005818 FixItHint fixit =
5819 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5820 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5821 Amt.getConstantLength()))
5822 : FixItHint();
5823
5824 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5825 << type << CS.toString(),
5826 getLocationOfByte(Amt.getStart()),
5827 /*IsStringLocation*/true,
5828 getSpecifierRange(startSpecifier, specifierLen),
5829 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00005830}
5831
Ted Kremenek02087932010-07-16 02:11:22 +00005832void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005833 const analyze_printf::OptionalFlag &flag,
5834 const char *startSpecifier,
5835 unsigned specifierLen) {
5836 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005837 const analyze_printf::PrintfConversionSpecifier &CS =
5838 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00005839 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5840 << flag.toString() << CS.toString(),
5841 getLocationOfByte(flag.getPosition()),
5842 /*IsStringLocation*/true,
5843 getSpecifierRange(startSpecifier, specifierLen),
5844 FixItHint::CreateRemoval(
5845 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005846}
5847
5848void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00005849 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005850 const analyze_printf::OptionalFlag &ignoredFlag,
5851 const analyze_printf::OptionalFlag &flag,
5852 const char *startSpecifier,
5853 unsigned specifierLen) {
5854 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005855 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5856 << ignoredFlag.toString() << flag.toString(),
5857 getLocationOfByte(ignoredFlag.getPosition()),
5858 /*IsStringLocation*/true,
5859 getSpecifierRange(startSpecifier, specifierLen),
5860 FixItHint::CreateRemoval(
5861 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005862}
5863
Ted Kremenek2b417712015-07-02 05:39:16 +00005864void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5865 unsigned flagLen) {
5866 // Warn about an empty flag.
5867 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5868 getLocationOfByte(startFlag),
5869 /*IsStringLocation*/true,
5870 getSpecifierRange(startFlag, flagLen));
5871}
5872
5873void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5874 unsigned flagLen) {
5875 // Warn about an invalid flag.
5876 auto Range = getSpecifierRange(startFlag, flagLen);
5877 StringRef flag(startFlag, flagLen);
5878 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5879 getLocationOfByte(startFlag),
5880 /*IsStringLocation*/true,
5881 Range, FixItHint::CreateRemoval(Range));
5882}
5883
5884void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5885 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5886 // Warn about using '[...]' without a '@' conversion.
5887 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5888 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5889 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5890 getLocationOfByte(conversionPosition),
5891 /*IsStringLocation*/true,
5892 Range, FixItHint::CreateRemoval(Range));
5893}
5894
Richard Smith55ce3522012-06-25 20:30:08 +00005895// Determines if the specified is a C++ class or struct containing
5896// a member with the specified name and kind (e.g. a CXXMethodDecl named
5897// "c_str()").
5898template<typename MemberKind>
5899static llvm::SmallPtrSet<MemberKind*, 1>
5900CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5901 const RecordType *RT = Ty->getAs<RecordType>();
5902 llvm::SmallPtrSet<MemberKind*, 1> Results;
5903
5904 if (!RT)
5905 return Results;
5906 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00005907 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00005908 return Results;
5909
Alp Tokerb6cc5922014-05-03 03:45:55 +00005910 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00005911 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00005912 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00005913
5914 // We just need to include all members of the right kind turned up by the
5915 // filter, at this point.
5916 if (S.LookupQualifiedName(R, RT->getDecl()))
5917 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5918 NamedDecl *decl = (*I)->getUnderlyingDecl();
5919 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5920 Results.insert(FK);
5921 }
5922 return Results;
5923}
5924
Richard Smith2868a732014-02-28 01:36:39 +00005925/// Check if we could call '.c_str()' on an object.
5926///
5927/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5928/// allow the call, or if it would be ambiguous).
5929bool Sema::hasCStrMethod(const Expr *E) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005930 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
5931
Richard Smith2868a732014-02-28 01:36:39 +00005932 MethodSet Results =
5933 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5934 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5935 MI != ME; ++MI)
5936 if ((*MI)->getMinRequiredArguments() == 0)
5937 return true;
5938 return false;
5939}
5940
Richard Smith55ce3522012-06-25 20:30:08 +00005941// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005942// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00005943// Returns true when a c_str() conversion method is found.
5944bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00005945 const analyze_printf::ArgType &AT, const Expr *E) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005946 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
Richard Smith55ce3522012-06-25 20:30:08 +00005947
5948 MethodSet Results =
5949 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5950
5951 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5952 MI != ME; ++MI) {
5953 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00005954 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00005955 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00005956 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00005957 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00005958 S.Diag(E->getLocStart(), diag::note_printf_c_str)
5959 << "c_str()"
5960 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5961 return true;
5962 }
5963 }
5964
5965 return false;
5966}
5967
Ted Kremenekab278de2010-01-28 23:39:18 +00005968bool
Ted Kremenek02087932010-07-16 02:11:22 +00005969CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00005970 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00005971 const char *startSpecifier,
5972 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005973 using namespace analyze_format_string;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005974 using namespace analyze_printf;
5975
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005976 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00005977
Ted Kremenek6cd69422010-07-19 22:01:06 +00005978 if (FS.consumesDataArgument()) {
5979 if (atFirstArg) {
5980 atFirstArg = false;
5981 usesPositionalArgs = FS.usesPositionalArg();
5982 }
5983 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005984 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5985 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00005986 return false;
5987 }
Ted Kremenek5739de72010-01-29 01:06:55 +00005988 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005989
Ted Kremenekd1668192010-02-27 01:41:03 +00005990 // First check if the field width, precision, and conversion specifier
5991 // have matching data arguments.
5992 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
5993 startSpecifier, specifierLen)) {
5994 return false;
5995 }
5996
5997 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
5998 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005999 return false;
6000 }
6001
Ted Kremenek8d9842d2010-01-29 20:55:36 +00006002 if (!CS.consumesDataArgument()) {
6003 // FIXME: Technically specifying a precision or field width here
6004 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00006005 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00006006 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006007
Ted Kremenek4a49d982010-02-26 19:18:41 +00006008 // Consume the argument.
6009 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00006010 if (argIndex < NumDataArgs) {
6011 // The check to see if the argIndex is valid will come later.
6012 // We set the bit here because we may exit early from this
6013 // function if we encounter some other error.
6014 CoveredArgs.set(argIndex);
6015 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00006016
Dimitry Andric6b5ed342015-02-19 22:32:33 +00006017 // FreeBSD kernel extensions.
6018 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
6019 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
6020 // We need at least two arguments.
6021 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
6022 return false;
6023
6024 // Claim the second argument.
6025 CoveredArgs.set(argIndex + 1);
6026
6027 // Type check the first argument (int for %b, pointer for %D)
6028 const Expr *Ex = getDataArg(argIndex);
6029 const analyze_printf::ArgType &AT =
6030 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
6031 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
6032 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
6033 EmitFormatDiagnostic(
6034 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6035 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
6036 << false << Ex->getSourceRange(),
6037 Ex->getLocStart(), /*IsStringLocation*/false,
6038 getSpecifierRange(startSpecifier, specifierLen));
6039
6040 // Type check the second argument (char * for both %b and %D)
6041 Ex = getDataArg(argIndex + 1);
6042 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
6043 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
6044 EmitFormatDiagnostic(
6045 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6046 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
6047 << false << Ex->getSourceRange(),
6048 Ex->getLocStart(), /*IsStringLocation*/false,
6049 getSpecifierRange(startSpecifier, specifierLen));
6050
6051 return true;
6052 }
6053
Ted Kremenek4a49d982010-02-26 19:18:41 +00006054 // Check for using an Objective-C specific conversion specifier
6055 // in a non-ObjC literal.
Mehdi Amini06d367c2016-10-24 20:39:34 +00006056 if (!allowsObjCArg() && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00006057 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6058 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00006059 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006060
Mehdi Amini06d367c2016-10-24 20:39:34 +00006061 // %P can only be used with os_log.
6062 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
6063 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6064 specifierLen);
6065 }
6066
6067 // %n is not allowed with os_log.
6068 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
6069 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
6070 getLocationOfByte(CS.getStart()),
6071 /*IsStringLocation*/ false,
6072 getSpecifierRange(startSpecifier, specifierLen));
6073
6074 return true;
6075 }
6076
6077 // Only scalars are allowed for os_trace.
6078 if (FSType == Sema::FST_OSTrace &&
6079 (CS.getKind() == ConversionSpecifier::PArg ||
6080 CS.getKind() == ConversionSpecifier::sArg ||
6081 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
6082 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6083 specifierLen);
6084 }
6085
6086 // Check for use of public/private annotation outside of os_log().
6087 if (FSType != Sema::FST_OSLog) {
6088 if (FS.isPublic().isSet()) {
6089 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6090 << "public",
6091 getLocationOfByte(FS.isPublic().getPosition()),
6092 /*IsStringLocation*/ false,
6093 getSpecifierRange(startSpecifier, specifierLen));
6094 }
6095 if (FS.isPrivate().isSet()) {
6096 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6097 << "private",
6098 getLocationOfByte(FS.isPrivate().getPosition()),
6099 /*IsStringLocation*/ false,
6100 getSpecifierRange(startSpecifier, specifierLen));
6101 }
6102 }
6103
Tom Careb49ec692010-06-17 19:00:27 +00006104 // Check for invalid use of field width
6105 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00006106 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00006107 startSpecifier, specifierLen);
6108 }
6109
6110 // Check for invalid use of precision
6111 if (!FS.hasValidPrecision()) {
6112 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
6113 startSpecifier, specifierLen);
6114 }
6115
Mehdi Amini06d367c2016-10-24 20:39:34 +00006116 // Precision is mandatory for %P specifier.
6117 if (CS.getKind() == ConversionSpecifier::PArg &&
6118 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
6119 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
6120 getLocationOfByte(startSpecifier),
6121 /*IsStringLocation*/ false,
6122 getSpecifierRange(startSpecifier, specifierLen));
6123 }
6124
Tom Careb49ec692010-06-17 19:00:27 +00006125 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00006126 if (!FS.hasValidThousandsGroupingPrefix())
6127 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006128 if (!FS.hasValidLeadingZeros())
6129 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
6130 if (!FS.hasValidPlusPrefix())
6131 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00006132 if (!FS.hasValidSpacePrefix())
6133 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006134 if (!FS.hasValidAlternativeForm())
6135 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
6136 if (!FS.hasValidLeftJustified())
6137 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
6138
6139 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00006140 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
6141 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
6142 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006143 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
6144 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
6145 startSpecifier, specifierLen);
6146
6147 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006148 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006149 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6150 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006151 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006152 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006153 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006154 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6155 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00006156
Jordan Rose92303592012-09-08 04:00:03 +00006157 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6158 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6159
Ted Kremenek9fcd8302010-01-29 01:43:31 +00006160 // The remaining checks depend on the data arguments.
6161 if (HasVAListArg)
6162 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006163
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006164 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00006165 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006166
Jordan Rose58bbe422012-07-19 18:10:08 +00006167 const Expr *Arg = getDataArg(argIndex);
6168 if (!Arg)
6169 return true;
6170
6171 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00006172}
6173
Jordan Roseaee34382012-09-05 22:56:26 +00006174static bool requiresParensToAddCast(const Expr *E) {
6175 // FIXME: We should have a general way to reason about operator
6176 // precedence and whether parens are actually needed here.
6177 // Take care of a few common cases where they aren't.
6178 const Expr *Inside = E->IgnoreImpCasts();
6179 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
6180 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
6181
6182 switch (Inside->getStmtClass()) {
6183 case Stmt::ArraySubscriptExprClass:
6184 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006185 case Stmt::CharacterLiteralClass:
6186 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006187 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006188 case Stmt::FloatingLiteralClass:
6189 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006190 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006191 case Stmt::ObjCArrayLiteralClass:
6192 case Stmt::ObjCBoolLiteralExprClass:
6193 case Stmt::ObjCBoxedExprClass:
6194 case Stmt::ObjCDictionaryLiteralClass:
6195 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006196 case Stmt::ObjCIvarRefExprClass:
6197 case Stmt::ObjCMessageExprClass:
6198 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006199 case Stmt::ObjCStringLiteralClass:
6200 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006201 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006202 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006203 case Stmt::UnaryOperatorClass:
6204 return false;
6205 default:
6206 return true;
6207 }
6208}
6209
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006210static std::pair<QualType, StringRef>
6211shouldNotPrintDirectly(const ASTContext &Context,
6212 QualType IntendedTy,
6213 const Expr *E) {
6214 // Use a 'while' to peel off layers of typedefs.
6215 QualType TyTy = IntendedTy;
6216 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
6217 StringRef Name = UserTy->getDecl()->getName();
6218 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Saleem Abdulrasoola01ed932017-10-17 17:39:32 +00006219 .Case("CFIndex", Context.getNSIntegerType())
6220 .Case("NSInteger", Context.getNSIntegerType())
6221 .Case("NSUInteger", Context.getNSUIntegerType())
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006222 .Case("SInt32", Context.IntTy)
6223 .Case("UInt32", Context.UnsignedIntTy)
6224 .Default(QualType());
6225
6226 if (!CastTy.isNull())
6227 return std::make_pair(CastTy, Name);
6228
6229 TyTy = UserTy->desugar();
6230 }
6231
6232 // Strip parens if necessary.
6233 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
6234 return shouldNotPrintDirectly(Context,
6235 PE->getSubExpr()->getType(),
6236 PE->getSubExpr());
6237
6238 // If this is a conditional expression, then its result type is constructed
6239 // via usual arithmetic conversions and thus there might be no necessary
6240 // typedef sugar there. Recurse to operands to check for NSInteger &
6241 // Co. usage condition.
6242 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6243 QualType TrueTy, FalseTy;
6244 StringRef TrueName, FalseName;
6245
6246 std::tie(TrueTy, TrueName) =
6247 shouldNotPrintDirectly(Context,
6248 CO->getTrueExpr()->getType(),
6249 CO->getTrueExpr());
6250 std::tie(FalseTy, FalseName) =
6251 shouldNotPrintDirectly(Context,
6252 CO->getFalseExpr()->getType(),
6253 CO->getFalseExpr());
6254
6255 if (TrueTy == FalseTy)
6256 return std::make_pair(TrueTy, TrueName);
6257 else if (TrueTy.isNull())
6258 return std::make_pair(FalseTy, FalseName);
6259 else if (FalseTy.isNull())
6260 return std::make_pair(TrueTy, TrueName);
6261 }
6262
6263 return std::make_pair(QualType(), StringRef());
6264}
6265
Richard Smith55ce3522012-06-25 20:30:08 +00006266bool
6267CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6268 const char *StartSpecifier,
6269 unsigned SpecifierLen,
6270 const Expr *E) {
6271 using namespace analyze_format_string;
6272 using namespace analyze_printf;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006273
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006274 // Now type check the data expression that matches the
6275 // format specifier.
Mehdi Amini06d367c2016-10-24 20:39:34 +00006276 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
Jordan Rose22b74712012-09-05 22:56:19 +00006277 if (!AT.isValid())
6278 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00006279
Jordan Rose598ec092012-12-05 18:44:40 +00006280 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00006281 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
6282 ExprTy = TET->getUnderlyingExpr()->getType();
6283 }
6284
Seth Cantrellb4802962015-03-04 03:12:10 +00006285 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
6286
6287 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00006288 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006289 }
Jordan Rose98709982012-06-04 22:48:57 +00006290
Jordan Rose22b74712012-09-05 22:56:19 +00006291 // Look through argument promotions for our error message's reported type.
6292 // This includes the integral and floating promotions, but excludes array
6293 // and function pointer decay; seeing that an argument intended to be a
6294 // string has type 'char [6]' is probably more confusing than 'char *'.
6295 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6296 if (ICE->getCastKind() == CK_IntegralCast ||
6297 ICE->getCastKind() == CK_FloatingCast) {
6298 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00006299 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00006300
6301 // Check if we didn't match because of an implicit cast from a 'char'
6302 // or 'short' to an 'int'. This is done because printf is a varargs
6303 // function.
6304 if (ICE->getType() == S.Context.IntTy ||
6305 ICE->getType() == S.Context.UnsignedIntTy) {
6306 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00006307 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00006308 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00006309 }
Jordan Rose98709982012-06-04 22:48:57 +00006310 }
Jordan Rose598ec092012-12-05 18:44:40 +00006311 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
6312 // Special case for 'a', which has type 'int' in C.
6313 // Note, however, that we do /not/ want to treat multibyte constants like
6314 // 'MooV' as characters! This form is deprecated but still exists.
6315 if (ExprTy == S.Context.IntTy)
6316 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6317 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00006318 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006319
Jordan Rosebc53ed12014-05-31 04:12:14 +00006320 // Look through enums to their underlying type.
6321 bool IsEnum = false;
6322 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
6323 ExprTy = EnumTy->getDecl()->getIntegerType();
6324 IsEnum = true;
6325 }
6326
Jordan Rose0e5badd2012-12-05 18:44:49 +00006327 // %C in an Objective-C context prints a unichar, not a wchar_t.
6328 // If the argument is an integer of some kind, believe the %C and suggest
6329 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00006330 QualType IntendedTy = ExprTy;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006331 if (isObjCContext() &&
Jordan Rose0e5badd2012-12-05 18:44:49 +00006332 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
6333 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6334 !ExprTy->isCharType()) {
6335 // 'unichar' is defined as a typedef of unsigned short, but we should
6336 // prefer using the typedef if it is visible.
6337 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00006338
6339 // While we are here, check if the value is an IntegerLiteral that happens
6340 // to be within the valid range.
6341 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
6342 const llvm::APInt &V = IL->getValue();
6343 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6344 return true;
6345 }
6346
Jordan Rose0e5badd2012-12-05 18:44:49 +00006347 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
6348 Sema::LookupOrdinaryName);
6349 if (S.LookupName(Result, S.getCurScope())) {
6350 NamedDecl *ND = Result.getFoundDecl();
6351 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
6352 if (TD->getUnderlyingType() == IntendedTy)
6353 IntendedTy = S.Context.getTypedefType(TD);
6354 }
6355 }
6356 }
6357
6358 // Special-case some of Darwin's platform-independence types by suggesting
6359 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006360 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00006361 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006362 QualType CastTy;
6363 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
6364 if (!CastTy.isNull()) {
6365 IntendedTy = CastTy;
6366 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00006367 }
6368 }
6369
Jordan Rose22b74712012-09-05 22:56:19 +00006370 // We may be able to offer a FixItHint if it is a supported type.
6371 PrintfSpecifier fixedFS = FS;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006372 bool success =
6373 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006374
Jordan Rose22b74712012-09-05 22:56:19 +00006375 if (success) {
6376 // Get the fix string from the fixed format specifier
6377 SmallString<16> buf;
6378 llvm::raw_svector_ostream os(buf);
6379 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006380
Jordan Roseaee34382012-09-05 22:56:26 +00006381 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6382
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006383 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00006384 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6385 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6386 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6387 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00006388 // In this case, the specifier is wrong and should be changed to match
6389 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00006390 EmitFormatDiagnostic(S.PDiag(diag)
6391 << AT.getRepresentativeTypeName(S.Context)
6392 << IntendedTy << IsEnum << E->getSourceRange(),
6393 E->getLocStart(),
6394 /*IsStringLocation*/ false, SpecRange,
6395 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00006396 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00006397 // The canonical type for formatting this value is different from the
6398 // actual type of the expression. (This occurs, for example, with Darwin's
6399 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6400 // should be printed as 'long' for 64-bit compatibility.)
6401 // Rather than emitting a normal format/argument mismatch, we want to
6402 // add a cast to the recommended type (and correct the format string
6403 // if necessary).
6404 SmallString<16> CastBuf;
6405 llvm::raw_svector_ostream CastFix(CastBuf);
6406 CastFix << "(";
6407 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6408 CastFix << ")";
6409
6410 SmallVector<FixItHint,4> Hints;
Alexander Shaposhnikov1788a9b2017-09-22 18:36:06 +00006411 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
Jordan Roseaee34382012-09-05 22:56:26 +00006412 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6413
6414 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6415 // If there's already a cast present, just replace it.
6416 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6417 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6418
6419 } else if (!requiresParensToAddCast(E)) {
6420 // If the expression has high enough precedence,
6421 // just write the C-style cast.
6422 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6423 CastFix.str()));
6424 } else {
6425 // Otherwise, add parens around the expression as well as the cast.
6426 CastFix << "(";
6427 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6428 CastFix.str()));
6429
Alp Tokerb6cc5922014-05-03 03:45:55 +00006430 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00006431 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6432 }
6433
Jordan Rose0e5badd2012-12-05 18:44:49 +00006434 if (ShouldNotPrintDirectly) {
6435 // The expression has a type that should not be printed directly.
6436 // We extract the name from the typedef because we don't want to show
6437 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006438 StringRef Name;
6439 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6440 Name = TypedefTy->getDecl()->getName();
6441 else
6442 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00006443 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00006444 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006445 << E->getSourceRange(),
6446 E->getLocStart(), /*IsStringLocation=*/false,
6447 SpecRange, Hints);
6448 } else {
6449 // In this case, the expression could be printed using a different
6450 // specifier, but we've decided that the specifier is probably correct
6451 // and we should cast instead. Just use the normal warning message.
6452 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00006453 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6454 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006455 << E->getSourceRange(),
6456 E->getLocStart(), /*IsStringLocation*/false,
6457 SpecRange, Hints);
6458 }
Jordan Roseaee34382012-09-05 22:56:26 +00006459 }
Jordan Rose22b74712012-09-05 22:56:19 +00006460 } else {
6461 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6462 SpecifierLen);
6463 // Since the warning for passing non-POD types to variadic functions
6464 // was deferred until now, we emit a warning for non-POD
6465 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00006466 switch (S.isValidVarArgType(ExprTy)) {
6467 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00006468 case Sema::VAK_ValidInCXX11: {
6469 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6470 if (match == analyze_printf::ArgType::NoMatchPedantic) {
6471 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6472 }
Richard Smithd7293d72013-08-05 18:49:43 +00006473
Seth Cantrellb4802962015-03-04 03:12:10 +00006474 EmitFormatDiagnostic(
6475 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6476 << IsEnum << CSR << E->getSourceRange(),
6477 E->getLocStart(), /*IsStringLocation*/ false, CSR);
6478 break;
6479 }
Richard Smithd7293d72013-08-05 18:49:43 +00006480 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00006481 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00006482 EmitFormatDiagnostic(
6483 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006484 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00006485 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00006486 << CallType
6487 << AT.getRepresentativeTypeName(S.Context)
6488 << CSR
6489 << E->getSourceRange(),
6490 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00006491 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00006492 break;
6493
6494 case Sema::VAK_Invalid:
6495 if (ExprTy->isObjCObjectType())
6496 EmitFormatDiagnostic(
6497 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6498 << S.getLangOpts().CPlusPlus11
6499 << ExprTy
6500 << CallType
6501 << AT.getRepresentativeTypeName(S.Context)
6502 << CSR
6503 << E->getSourceRange(),
6504 E->getLocStart(), /*IsStringLocation*/false, CSR);
6505 else
6506 // FIXME: If this is an initializer list, suggest removing the braces
6507 // or inserting a cast to the target type.
6508 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6509 << isa<InitListExpr>(E) << ExprTy << CallType
6510 << AT.getRepresentativeTypeName(S.Context)
6511 << E->getSourceRange();
6512 break;
6513 }
6514
6515 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6516 "format string specifier index out of range");
6517 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006518 }
6519
Ted Kremenekab278de2010-01-28 23:39:18 +00006520 return true;
6521}
6522
Ted Kremenek02087932010-07-16 02:11:22 +00006523//===--- CHECK: Scanf format string checking ------------------------------===//
6524
6525namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006526
Ted Kremenek02087932010-07-16 02:11:22 +00006527class CheckScanfHandler : public CheckFormatHandler {
6528public:
Stephen Hines648c3692016-09-16 01:07:04 +00006529 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006530 const Expr *origFormatExpr, Sema::FormatStringType type,
6531 unsigned firstDataArg, unsigned numDataArgs,
6532 const char *beg, bool hasVAListArg,
6533 ArrayRef<const Expr *> Args, unsigned formatIdx,
6534 bool inFunctionCall, Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006535 llvm::SmallBitVector &CheckedVarArgs,
6536 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006537 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6538 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6539 inFunctionCall, CallType, CheckedVarArgs,
6540 UncoveredArg) {}
6541
Ted Kremenek02087932010-07-16 02:11:22 +00006542 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6543 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006544 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00006545
6546 bool HandleInvalidScanfConversionSpecifier(
6547 const analyze_scanf::ScanfSpecifier &FS,
6548 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006549 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006550
Craig Toppere14c0f82014-03-12 04:55:44 +00006551 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00006552};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006553
6554} // namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00006555
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006556void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6557 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006558 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6559 getLocationOfByte(end), /*IsStringLocation*/true,
6560 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006561}
6562
Ted Kremenekce815422010-07-19 21:25:57 +00006563bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6564 const analyze_scanf::ScanfSpecifier &FS,
6565 const char *startSpecifier,
6566 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006567 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00006568 FS.getConversionSpecifier();
6569
6570 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6571 getLocationOfByte(CS.getStart()),
6572 startSpecifier, specifierLen,
6573 CS.getStart(), CS.getLength());
6574}
6575
Ted Kremenek02087932010-07-16 02:11:22 +00006576bool CheckScanfHandler::HandleScanfSpecifier(
6577 const analyze_scanf::ScanfSpecifier &FS,
6578 const char *startSpecifier,
6579 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00006580 using namespace analyze_scanf;
6581 using namespace analyze_format_string;
6582
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006583 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00006584
Ted Kremenek6cd69422010-07-19 22:01:06 +00006585 // Handle case where '%' and '*' don't consume an argument. These shouldn't
6586 // be used to decide if we are using positional arguments consistently.
6587 if (FS.consumesDataArgument()) {
6588 if (atFirstArg) {
6589 atFirstArg = false;
6590 usesPositionalArgs = FS.usesPositionalArg();
6591 }
6592 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006593 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6594 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00006595 return false;
6596 }
Ted Kremenek02087932010-07-16 02:11:22 +00006597 }
6598
6599 // Check if the field with is non-zero.
6600 const OptionalAmount &Amt = FS.getFieldWidth();
6601 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6602 if (Amt.getConstantAmount() == 0) {
6603 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6604 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00006605 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6606 getLocationOfByte(Amt.getStart()),
6607 /*IsStringLocation*/true, R,
6608 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00006609 }
6610 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006611
Ted Kremenek02087932010-07-16 02:11:22 +00006612 if (!FS.consumesDataArgument()) {
6613 // FIXME: Technically specifying a precision or field width here
6614 // makes no sense. Worth issuing a warning at some point.
6615 return true;
6616 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006617
Ted Kremenek02087932010-07-16 02:11:22 +00006618 // Consume the argument.
6619 unsigned argIndex = FS.getArgIndex();
6620 if (argIndex < NumDataArgs) {
6621 // The check to see if the argIndex is valid will come later.
6622 // We set the bit here because we may exit early from this
6623 // function if we encounter some other error.
6624 CoveredArgs.set(argIndex);
6625 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006626
Ted Kremenek4407ea42010-07-20 20:04:47 +00006627 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006628 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006629 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6630 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006631 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006632 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006633 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006634 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6635 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006636
Jordan Rose92303592012-09-08 04:00:03 +00006637 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6638 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6639
Ted Kremenek02087932010-07-16 02:11:22 +00006640 // The remaining checks depend on the data arguments.
6641 if (HasVAListArg)
6642 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006643
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006644 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00006645 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00006646
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006647 // Check that the argument type matches the format specifier.
6648 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00006649 if (!Ex)
6650 return true;
6651
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00006652 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00006653
6654 if (!AT.isValid()) {
6655 return true;
6656 }
6657
Seth Cantrellb4802962015-03-04 03:12:10 +00006658 analyze_format_string::ArgType::MatchKind match =
6659 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00006660 if (match == analyze_format_string::ArgType::Match) {
6661 return true;
6662 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006663
Seth Cantrell79340072015-03-04 05:58:08 +00006664 ScanfSpecifier fixedFS = FS;
6665 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6666 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006667
Seth Cantrell79340072015-03-04 05:58:08 +00006668 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6669 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6670 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6671 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006672
Seth Cantrell79340072015-03-04 05:58:08 +00006673 if (success) {
6674 // Get the fix string from the fixed format specifier.
6675 SmallString<128> buf;
6676 llvm::raw_svector_ostream os(buf);
6677 fixedFS.toString(os);
6678
6679 EmitFormatDiagnostic(
6680 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6681 << Ex->getType() << false << Ex->getSourceRange(),
6682 Ex->getLocStart(),
6683 /*IsStringLocation*/ false,
6684 getSpecifierRange(startSpecifier, specifierLen),
6685 FixItHint::CreateReplacement(
6686 getSpecifierRange(startSpecifier, specifierLen), os.str()));
6687 } else {
6688 EmitFormatDiagnostic(S.PDiag(diag)
6689 << AT.getRepresentativeTypeName(S.Context)
6690 << Ex->getType() << false << Ex->getSourceRange(),
6691 Ex->getLocStart(),
6692 /*IsStringLocation*/ false,
6693 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006694 }
6695
Ted Kremenek02087932010-07-16 02:11:22 +00006696 return true;
6697}
6698
Stephen Hines648c3692016-09-16 01:07:04 +00006699static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006700 const Expr *OrigFormatExpr,
6701 ArrayRef<const Expr *> Args,
6702 bool HasVAListArg, unsigned format_idx,
6703 unsigned firstDataArg,
6704 Sema::FormatStringType Type,
6705 bool inFunctionCall,
6706 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006707 llvm::SmallBitVector &CheckedVarArgs,
6708 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00006709 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00006710 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006711 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006712 S, inFunctionCall, Args[format_idx],
6713 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006714 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006715 return;
6716 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006717
Ted Kremenekab278de2010-01-28 23:39:18 +00006718 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006719 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00006720 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006721 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006722 const ConstantArrayType *T =
6723 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006724 assert(T && "String literal not of constant array type!");
6725 size_t TypeSize = T->getSize().getZExtValue();
6726 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006727 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006728
6729 // Emit a warning if the string literal is truncated and does not contain an
6730 // embedded null character.
6731 if (TypeSize <= StrRef.size() &&
6732 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6733 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006734 S, inFunctionCall, Args[format_idx],
6735 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006736 FExpr->getLocStart(),
6737 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6738 return;
6739 }
6740
Ted Kremenekab278de2010-01-28 23:39:18 +00006741 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00006742 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006743 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006744 S, inFunctionCall, Args[format_idx],
6745 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006746 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006747 return;
6748 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006749
6750 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
Mehdi Amini06d367c2016-10-24 20:39:34 +00006751 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6752 Type == Sema::FST_OSTrace) {
6753 CheckPrintfHandler H(
6754 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6755 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6756 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6757 CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006758
Hans Wennborg23926bd2011-12-15 10:25:47 +00006759 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006760 S.getLangOpts(),
6761 S.Context.getTargetInfo(),
6762 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00006763 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006764 } else if (Type == Sema::FST_Scanf) {
Mehdi Amini06d367c2016-10-24 20:39:34 +00006765 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6766 numDataArgs, Str, HasVAListArg, Args, format_idx,
6767 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006768
Hans Wennborg23926bd2011-12-15 10:25:47 +00006769 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006770 S.getLangOpts(),
6771 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00006772 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006773 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00006774}
6775
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00006776bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6777 // Str - The format string. NOTE: this is NOT null-terminated!
6778 StringRef StrRef = FExpr->getString();
6779 const char *Str = StrRef.data();
6780 // Account for cases where the string literal is truncated in a declaration.
6781 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6782 assert(T && "String literal not of constant array type!");
6783 size_t TypeSize = T->getSize().getZExtValue();
6784 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6785 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6786 getLangOpts(),
6787 Context.getTargetInfo());
6788}
6789
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006790//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6791
6792// Returns the related absolute value function that is larger, of 0 if one
6793// does not exist.
6794static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6795 switch (AbsFunction) {
6796 default:
6797 return 0;
6798
6799 case Builtin::BI__builtin_abs:
6800 return Builtin::BI__builtin_labs;
6801 case Builtin::BI__builtin_labs:
6802 return Builtin::BI__builtin_llabs;
6803 case Builtin::BI__builtin_llabs:
6804 return 0;
6805
6806 case Builtin::BI__builtin_fabsf:
6807 return Builtin::BI__builtin_fabs;
6808 case Builtin::BI__builtin_fabs:
6809 return Builtin::BI__builtin_fabsl;
6810 case Builtin::BI__builtin_fabsl:
6811 return 0;
6812
6813 case Builtin::BI__builtin_cabsf:
6814 return Builtin::BI__builtin_cabs;
6815 case Builtin::BI__builtin_cabs:
6816 return Builtin::BI__builtin_cabsl;
6817 case Builtin::BI__builtin_cabsl:
6818 return 0;
6819
6820 case Builtin::BIabs:
6821 return Builtin::BIlabs;
6822 case Builtin::BIlabs:
6823 return Builtin::BIllabs;
6824 case Builtin::BIllabs:
6825 return 0;
6826
6827 case Builtin::BIfabsf:
6828 return Builtin::BIfabs;
6829 case Builtin::BIfabs:
6830 return Builtin::BIfabsl;
6831 case Builtin::BIfabsl:
6832 return 0;
6833
6834 case Builtin::BIcabsf:
6835 return Builtin::BIcabs;
6836 case Builtin::BIcabs:
6837 return Builtin::BIcabsl;
6838 case Builtin::BIcabsl:
6839 return 0;
6840 }
6841}
6842
6843// Returns the argument type of the absolute value function.
6844static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6845 unsigned AbsType) {
6846 if (AbsType == 0)
6847 return QualType();
6848
6849 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6850 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6851 if (Error != ASTContext::GE_None)
6852 return QualType();
6853
6854 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6855 if (!FT)
6856 return QualType();
6857
6858 if (FT->getNumParams() != 1)
6859 return QualType();
6860
6861 return FT->getParamType(0);
6862}
6863
6864// Returns the best absolute value function, or zero, based on type and
6865// current absolute value function.
6866static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6867 unsigned AbsFunctionKind) {
6868 unsigned BestKind = 0;
6869 uint64_t ArgSize = Context.getTypeSize(ArgType);
6870 for (unsigned Kind = AbsFunctionKind; Kind != 0;
6871 Kind = getLargerAbsoluteValueFunction(Kind)) {
6872 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6873 if (Context.getTypeSize(ParamType) >= ArgSize) {
6874 if (BestKind == 0)
6875 BestKind = Kind;
6876 else if (Context.hasSameType(ParamType, ArgType)) {
6877 BestKind = Kind;
6878 break;
6879 }
6880 }
6881 }
6882 return BestKind;
6883}
6884
6885enum AbsoluteValueKind {
6886 AVK_Integer,
6887 AVK_Floating,
6888 AVK_Complex
6889};
6890
6891static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6892 if (T->isIntegralOrEnumerationType())
6893 return AVK_Integer;
6894 if (T->isRealFloatingType())
6895 return AVK_Floating;
6896 if (T->isAnyComplexType())
6897 return AVK_Complex;
6898
6899 llvm_unreachable("Type not integer, floating, or complex");
6900}
6901
6902// Changes the absolute value function to a different type. Preserves whether
6903// the function is a builtin.
6904static unsigned changeAbsFunction(unsigned AbsKind,
6905 AbsoluteValueKind ValueKind) {
6906 switch (ValueKind) {
6907 case AVK_Integer:
6908 switch (AbsKind) {
6909 default:
6910 return 0;
6911 case Builtin::BI__builtin_fabsf:
6912 case Builtin::BI__builtin_fabs:
6913 case Builtin::BI__builtin_fabsl:
6914 case Builtin::BI__builtin_cabsf:
6915 case Builtin::BI__builtin_cabs:
6916 case Builtin::BI__builtin_cabsl:
6917 return Builtin::BI__builtin_abs;
6918 case Builtin::BIfabsf:
6919 case Builtin::BIfabs:
6920 case Builtin::BIfabsl:
6921 case Builtin::BIcabsf:
6922 case Builtin::BIcabs:
6923 case Builtin::BIcabsl:
6924 return Builtin::BIabs;
6925 }
6926 case AVK_Floating:
6927 switch (AbsKind) {
6928 default:
6929 return 0;
6930 case Builtin::BI__builtin_abs:
6931 case Builtin::BI__builtin_labs:
6932 case Builtin::BI__builtin_llabs:
6933 case Builtin::BI__builtin_cabsf:
6934 case Builtin::BI__builtin_cabs:
6935 case Builtin::BI__builtin_cabsl:
6936 return Builtin::BI__builtin_fabsf;
6937 case Builtin::BIabs:
6938 case Builtin::BIlabs:
6939 case Builtin::BIllabs:
6940 case Builtin::BIcabsf:
6941 case Builtin::BIcabs:
6942 case Builtin::BIcabsl:
6943 return Builtin::BIfabsf;
6944 }
6945 case AVK_Complex:
6946 switch (AbsKind) {
6947 default:
6948 return 0;
6949 case Builtin::BI__builtin_abs:
6950 case Builtin::BI__builtin_labs:
6951 case Builtin::BI__builtin_llabs:
6952 case Builtin::BI__builtin_fabsf:
6953 case Builtin::BI__builtin_fabs:
6954 case Builtin::BI__builtin_fabsl:
6955 return Builtin::BI__builtin_cabsf;
6956 case Builtin::BIabs:
6957 case Builtin::BIlabs:
6958 case Builtin::BIllabs:
6959 case Builtin::BIfabsf:
6960 case Builtin::BIfabs:
6961 case Builtin::BIfabsl:
6962 return Builtin::BIcabsf;
6963 }
6964 }
6965 llvm_unreachable("Unable to convert function");
6966}
6967
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00006968static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006969 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6970 if (!FnInfo)
6971 return 0;
6972
6973 switch (FDecl->getBuiltinID()) {
6974 default:
6975 return 0;
6976 case Builtin::BI__builtin_abs:
6977 case Builtin::BI__builtin_fabs:
6978 case Builtin::BI__builtin_fabsf:
6979 case Builtin::BI__builtin_fabsl:
6980 case Builtin::BI__builtin_labs:
6981 case Builtin::BI__builtin_llabs:
6982 case Builtin::BI__builtin_cabs:
6983 case Builtin::BI__builtin_cabsf:
6984 case Builtin::BI__builtin_cabsl:
6985 case Builtin::BIabs:
6986 case Builtin::BIlabs:
6987 case Builtin::BIllabs:
6988 case Builtin::BIfabs:
6989 case Builtin::BIfabsf:
6990 case Builtin::BIfabsl:
6991 case Builtin::BIcabs:
6992 case Builtin::BIcabsf:
6993 case Builtin::BIcabsl:
6994 return FDecl->getBuiltinID();
6995 }
6996 llvm_unreachable("Unknown Builtin type");
6997}
6998
6999// If the replacement is valid, emit a note with replacement function.
7000// Additionally, suggest including the proper header if not already included.
7001static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00007002 unsigned AbsKind, QualType ArgType) {
7003 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00007004 const char *HeaderName = nullptr;
Mehdi Amini7186a432016-10-11 19:04:24 +00007005 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00007006 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
7007 FunctionName = "std::abs";
7008 if (ArgType->isIntegralOrEnumerationType()) {
7009 HeaderName = "cstdlib";
7010 } else if (ArgType->isRealFloatingType()) {
7011 HeaderName = "cmath";
7012 } else {
7013 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007014 }
Richard Trieubeffb832014-04-15 23:47:53 +00007015
7016 // Lookup all std::abs
7017 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00007018 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00007019 R.suppressDiagnostics();
7020 S.LookupQualifiedName(R, Std);
7021
7022 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007023 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00007024 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
7025 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
7026 } else {
7027 FDecl = dyn_cast<FunctionDecl>(I);
7028 }
7029 if (!FDecl)
7030 continue;
7031
7032 // Found std::abs(), check that they are the right ones.
7033 if (FDecl->getNumParams() != 1)
7034 continue;
7035
7036 // Check that the parameter type can handle the argument.
7037 QualType ParamType = FDecl->getParamDecl(0)->getType();
7038 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
7039 S.Context.getTypeSize(ArgType) <=
7040 S.Context.getTypeSize(ParamType)) {
7041 // Found a function, don't need the header hint.
7042 EmitHeaderHint = false;
7043 break;
7044 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007045 }
Richard Trieubeffb832014-04-15 23:47:53 +00007046 }
7047 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00007048 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00007049 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
7050
7051 if (HeaderName) {
7052 DeclarationName DN(&S.Context.Idents.get(FunctionName));
7053 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
7054 R.suppressDiagnostics();
7055 S.LookupName(R, S.getCurScope());
7056
7057 if (R.isSingleResult()) {
7058 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
7059 if (FD && FD->getBuiltinID() == AbsKind) {
7060 EmitHeaderHint = false;
7061 } else {
7062 return;
7063 }
7064 } else if (!R.empty()) {
7065 return;
7066 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007067 }
7068 }
7069
7070 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00007071 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007072
Richard Trieubeffb832014-04-15 23:47:53 +00007073 if (!HeaderName)
7074 return;
7075
7076 if (!EmitHeaderHint)
7077 return;
7078
Alp Toker5d96e0a2014-07-11 20:53:51 +00007079 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
7080 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00007081}
7082
Richard Trieua7f30b12016-12-06 01:42:28 +00007083template <std::size_t StrLen>
7084static bool IsStdFunction(const FunctionDecl *FDecl,
7085 const char (&Str)[StrLen]) {
Richard Trieubeffb832014-04-15 23:47:53 +00007086 if (!FDecl)
7087 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00007088 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
Richard Trieubeffb832014-04-15 23:47:53 +00007089 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00007090 if (!FDecl->isInStdNamespace())
Richard Trieubeffb832014-04-15 23:47:53 +00007091 return false;
7092
7093 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007094}
7095
7096// Warn when using the wrong abs() function.
7097void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
Richard Trieua7f30b12016-12-06 01:42:28 +00007098 const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007099 if (Call->getNumArgs() != 1)
7100 return;
7101
7102 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieua7f30b12016-12-06 01:42:28 +00007103 bool IsStdAbs = IsStdFunction(FDecl, "abs");
Richard Trieubeffb832014-04-15 23:47:53 +00007104 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007105 return;
7106
7107 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7108 QualType ParamType = Call->getArg(0)->getType();
7109
Alp Toker5d96e0a2014-07-11 20:53:51 +00007110 // Unsigned types cannot be negative. Suggest removing the absolute value
7111 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007112 if (ArgType->isUnsignedIntegerType()) {
Mehdi Amini7186a432016-10-11 19:04:24 +00007113 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00007114 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007115 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
7116 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00007117 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007118 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
7119 return;
7120 }
7121
David Majnemer7f77eb92015-11-15 03:04:34 +00007122 // Taking the absolute value of a pointer is very suspicious, they probably
7123 // wanted to index into an array, dereference a pointer, call a function, etc.
7124 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
7125 unsigned DiagType = 0;
7126 if (ArgType->isFunctionType())
7127 DiagType = 1;
7128 else if (ArgType->isArrayType())
7129 DiagType = 2;
7130
7131 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
7132 return;
7133 }
7134
Richard Trieubeffb832014-04-15 23:47:53 +00007135 // std::abs has overloads which prevent most of the absolute value problems
7136 // from occurring.
7137 if (IsStdAbs)
7138 return;
7139
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007140 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
7141 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
7142
7143 // The argument and parameter are the same kind. Check if they are the right
7144 // size.
7145 if (ArgValueKind == ParamValueKind) {
7146 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
7147 return;
7148
7149 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
7150 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
7151 << FDecl << ArgType << ParamType;
7152
7153 if (NewAbsKind == 0)
7154 return;
7155
7156 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00007157 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007158 return;
7159 }
7160
7161 // ArgValueKind != ParamValueKind
7162 // The wrong type of absolute value function was used. Attempt to find the
7163 // proper one.
7164 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
7165 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
7166 if (NewAbsKind == 0)
7167 return;
7168
7169 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
7170 << FDecl << ParamValueKind << ArgValueKind;
7171
7172 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00007173 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007174}
7175
Richard Trieu67c00712016-12-05 23:41:46 +00007176//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
Richard Trieua7f30b12016-12-06 01:42:28 +00007177void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
7178 const FunctionDecl *FDecl) {
Richard Trieu67c00712016-12-05 23:41:46 +00007179 if (!Call || !FDecl) return;
7180
7181 // Ignore template specializations and macros.
Richard Smith51ec0cf2017-02-21 01:17:38 +00007182 if (inTemplateInstantiation()) return;
Richard Trieu67c00712016-12-05 23:41:46 +00007183 if (Call->getExprLoc().isMacroID()) return;
7184
7185 // Only care about the one template argument, two function parameter std::max
7186 if (Call->getNumArgs() != 2) return;
Richard Trieua7f30b12016-12-06 01:42:28 +00007187 if (!IsStdFunction(FDecl, "max")) return;
Richard Trieu67c00712016-12-05 23:41:46 +00007188 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
7189 if (!ArgList) return;
7190 if (ArgList->size() != 1) return;
7191
7192 // Check that template type argument is unsigned integer.
7193 const auto& TA = ArgList->get(0);
7194 if (TA.getKind() != TemplateArgument::Type) return;
7195 QualType ArgType = TA.getAsType();
7196 if (!ArgType->isUnsignedIntegerType()) return;
7197
7198 // See if either argument is a literal zero.
7199 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
7200 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
7201 if (!MTE) return false;
7202 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
7203 if (!Num) return false;
7204 if (Num->getValue() != 0) return false;
7205 return true;
7206 };
7207
7208 const Expr *FirstArg = Call->getArg(0);
7209 const Expr *SecondArg = Call->getArg(1);
7210 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
7211 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
7212
7213 // Only warn when exactly one argument is zero.
7214 if (IsFirstArgZero == IsSecondArgZero) return;
7215
7216 SourceRange FirstRange = FirstArg->getSourceRange();
7217 SourceRange SecondRange = SecondArg->getSourceRange();
7218
7219 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
7220
7221 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
7222 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
7223
7224 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
7225 SourceRange RemovalRange;
7226 if (IsFirstArgZero) {
7227 RemovalRange = SourceRange(FirstRange.getBegin(),
7228 SecondRange.getBegin().getLocWithOffset(-1));
7229 } else {
7230 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
7231 SecondRange.getEnd());
7232 }
7233
7234 Diag(Call->getExprLoc(), diag::note_remove_max_call)
7235 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
7236 << FixItHint::CreateRemoval(RemovalRange);
7237}
7238
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007239//===--- CHECK: Standard memory functions ---------------------------------===//
7240
Nico Weber0e6daef2013-12-26 23:38:39 +00007241/// \brief Takes the expression passed to the size_t parameter of functions
7242/// such as memcmp, strncat, etc and warns if it's a comparison.
7243///
7244/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
7245static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
7246 IdentifierInfo *FnName,
7247 SourceLocation FnLoc,
7248 SourceLocation RParenLoc) {
7249 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
7250 if (!Size)
7251 return false;
7252
Richard Smithc70f1d62017-12-14 15:16:18 +00007253 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
7254 if (!Size->isComparisonOp() && !Size->isLogicalOp())
Nico Weber0e6daef2013-12-26 23:38:39 +00007255 return false;
7256
Nico Weber0e6daef2013-12-26 23:38:39 +00007257 SourceRange SizeRange = Size->getSourceRange();
7258 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
7259 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00007260 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007261 << FnName << FixItHint::CreateInsertion(
7262 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00007263 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00007264 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00007265 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00007266 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
7267 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00007268
7269 return true;
7270}
7271
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007272/// \brief Determine whether the given type is or contains a dynamic class type
7273/// (e.g., whether it has a vtable).
7274static const CXXRecordDecl *getContainedDynamicClass(QualType T,
7275 bool &IsContained) {
7276 // Look through array types while ignoring qualifiers.
7277 const Type *Ty = T->getBaseElementTypeUnsafe();
7278 IsContained = false;
7279
7280 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
7281 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00007282 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007283 return nullptr;
7284
7285 if (RD->isDynamicClass())
7286 return RD;
7287
7288 // Check all the fields. If any bases were dynamic, the class is dynamic.
7289 // It's impossible for a class to transitively contain itself by value, so
7290 // infinite recursion is impossible.
7291 for (auto *FD : RD->fields()) {
7292 bool SubContained;
7293 if (const CXXRecordDecl *ContainedRD =
7294 getContainedDynamicClass(FD->getType(), SubContained)) {
7295 IsContained = true;
7296 return ContainedRD;
7297 }
7298 }
7299
7300 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00007301}
7302
Chandler Carruth889ed862011-06-21 23:04:20 +00007303/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007304/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00007305static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00007306 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007307 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007308 if (SizeOf->getKind() == UETT_SizeOf && !SizeOf->isArgumentType())
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007309 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007310
Craig Topperc3ec1492014-05-26 06:22:03 +00007311 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007312}
7313
Chandler Carruth889ed862011-06-21 23:04:20 +00007314/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00007315static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007316 if (const UnaryExprOrTypeTraitExpr *SizeOf =
7317 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007318 if (SizeOf->getKind() == UETT_SizeOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007319 return SizeOf->getTypeOfArgument();
7320
7321 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00007322}
7323
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007324/// \brief Check for dangerous or invalid arguments to memset().
7325///
Chandler Carruthac687262011-06-03 06:23:57 +00007326/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007327/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
7328/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007329///
7330/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007331void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00007332 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007333 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00007334 assert(BId != 0);
7335
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007336 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00007337 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007338 unsigned ExpectedNumArgs =
7339 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00007340 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007341 return;
7342
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007343 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00007344 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007345 unsigned LenArg =
7346 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00007347 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007348
Nico Weber0e6daef2013-12-26 23:38:39 +00007349 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
7350 Call->getLocStart(), Call->getRParenLoc()))
7351 return;
7352
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007353 // We have special checking when the length is a sizeof expression.
7354 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
7355 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
7356 llvm::FoldingSetNodeID SizeOfArgID;
7357
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00007358 // Although widely used, 'bzero' is not a standard function. Be more strict
7359 // with the argument types before allowing diagnostics and only allow the
7360 // form bzero(ptr, sizeof(...)).
7361 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7362 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
7363 return;
7364
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007365 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7366 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007367 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007368
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007369 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00007370 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007371 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00007372 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00007373
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007374 // Never warn about void type pointers. This can be used to suppress
7375 // false positives.
7376 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007377 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007378
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007379 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
7380 // actually comparing the expressions for equality. Because computing the
7381 // expression IDs can be expensive, we only do this if the diagnostic is
7382 // enabled.
7383 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007384 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
7385 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007386 // We only compute IDs for expressions if the warning is enabled, and
7387 // cache the sizeof arg's ID.
7388 if (SizeOfArgID == llvm::FoldingSetNodeID())
7389 SizeOfArg->Profile(SizeOfArgID, Context, true);
7390 llvm::FoldingSetNodeID DestID;
7391 Dest->Profile(DestID, Context, true);
7392 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00007393 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
7394 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007395 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00007396 StringRef ReadableName = FnName->getName();
7397
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007398 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00007399 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007400 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00007401 if (!PointeeTy->isIncompleteType() &&
7402 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007403 ActionIdx = 2; // If the pointee's size is sizeof(char),
7404 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00007405
7406 // If the function is defined as a builtin macro, do not show macro
7407 // expansion.
7408 SourceLocation SL = SizeOfArg->getExprLoc();
7409 SourceRange DSR = Dest->getSourceRange();
7410 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007411 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00007412
7413 if (SM.isMacroArgExpansion(SL)) {
7414 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7415 SL = SM.getSpellingLoc(SL);
7416 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7417 SM.getSpellingLoc(DSR.getEnd()));
7418 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7419 SM.getSpellingLoc(SSR.getEnd()));
7420 }
7421
Anna Zaksd08d9152012-05-30 23:14:52 +00007422 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007423 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00007424 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00007425 << PointeeTy
7426 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00007427 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00007428 << SSR);
7429 DiagRuntimeBehavior(SL, SizeOfArg,
7430 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7431 << ActionIdx
7432 << SSR);
7433
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007434 break;
7435 }
7436 }
7437
7438 // Also check for cases where the sizeof argument is the exact same
7439 // type as the memory argument, and where it points to a user-defined
7440 // record type.
7441 if (SizeOfArgTy != QualType()) {
7442 if (PointeeTy->isRecordType() &&
7443 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7444 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7445 PDiag(diag::warn_sizeof_pointer_type_memaccess)
7446 << FnName << SizeOfArgTy << ArgIdx
7447 << PointeeTy << Dest->getSourceRange()
7448 << LenExpr->getSourceRange());
7449 break;
7450 }
Nico Weberc5e73862011-06-14 16:14:58 +00007451 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00007452 } else if (DestTy->isArrayType()) {
7453 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00007454 }
Nico Weberc5e73862011-06-14 16:14:58 +00007455
Nico Weberc44b35e2015-03-21 17:37:46 +00007456 if (PointeeTy == QualType())
7457 continue;
Anna Zaks22122702012-01-17 00:37:07 +00007458
Nico Weberc44b35e2015-03-21 17:37:46 +00007459 // Always complain about dynamic classes.
7460 bool IsContained;
7461 if (const CXXRecordDecl *ContainedRD =
7462 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00007463
Nico Weberc44b35e2015-03-21 17:37:46 +00007464 unsigned OperationType = 0;
7465 // "overwritten" if we're warning about the destination for any call
7466 // but memcmp; otherwise a verb appropriate to the call.
7467 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7468 if (BId == Builtin::BImemcpy)
7469 OperationType = 1;
7470 else if(BId == Builtin::BImemmove)
7471 OperationType = 2;
7472 else if (BId == Builtin::BImemcmp)
7473 OperationType = 3;
7474 }
7475
John McCall31168b02011-06-15 23:02:42 +00007476 DiagRuntimeBehavior(
7477 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00007478 PDiag(diag::warn_dyn_class_memaccess)
7479 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7480 << FnName << IsContained << ContainedRD << OperationType
7481 << Call->getCallee()->getSourceRange());
7482 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7483 BId != Builtin::BImemset)
7484 DiagRuntimeBehavior(
7485 Dest->getExprLoc(), Dest,
7486 PDiag(diag::warn_arc_object_memaccess)
7487 << ArgIdx << FnName << PointeeTy
7488 << Call->getCallee()->getSourceRange());
7489 else
7490 continue;
7491
7492 DiagRuntimeBehavior(
7493 Dest->getExprLoc(), Dest,
7494 PDiag(diag::note_bad_memaccess_silence)
7495 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7496 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007497 }
7498}
7499
Ted Kremenek6865f772011-08-18 20:55:45 +00007500// A little helper routine: ignore addition and subtraction of integer literals.
7501// This intentionally does not ignore all integer constant expressions because
7502// we don't want to remove sizeof().
7503static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7504 Ex = Ex->IgnoreParenCasts();
7505
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007506 while (true) {
Ted Kremenek6865f772011-08-18 20:55:45 +00007507 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7508 if (!BO || !BO->isAdditiveOp())
7509 break;
7510
7511 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7512 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7513
7514 if (isa<IntegerLiteral>(RHS))
7515 Ex = LHS;
7516 else if (isa<IntegerLiteral>(LHS))
7517 Ex = RHS;
7518 else
7519 break;
7520 }
7521
7522 return Ex;
7523}
7524
Anna Zaks13b08572012-08-08 21:42:23 +00007525static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7526 ASTContext &Context) {
7527 // Only handle constant-sized or VLAs, but not flexible members.
7528 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7529 // Only issue the FIXIT for arrays of size > 1.
7530 if (CAT->getSize().getSExtValue() <= 1)
7531 return false;
7532 } else if (!Ty->isVariableArrayType()) {
7533 return false;
7534 }
7535 return true;
7536}
7537
Ted Kremenek6865f772011-08-18 20:55:45 +00007538// Warn if the user has made the 'size' argument to strlcpy or strlcat
7539// be the size of the source, instead of the destination.
7540void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7541 IdentifierInfo *FnName) {
7542
7543 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00007544 unsigned NumArgs = Call->getNumArgs();
7545 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00007546 return;
7547
7548 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7549 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00007550 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00007551
7552 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7553 Call->getLocStart(), Call->getRParenLoc()))
7554 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00007555
7556 // Look for 'strlcpy(dst, x, sizeof(x))'
7557 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7558 CompareWithSrc = Ex;
7559 else {
7560 // Look for 'strlcpy(dst, x, strlen(x))'
7561 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00007562 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7563 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00007564 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7565 }
7566 }
7567
7568 if (!CompareWithSrc)
7569 return;
7570
7571 // Determine if the argument to sizeof/strlen is equal to the source
7572 // argument. In principle there's all kinds of things you could do
7573 // here, for instance creating an == expression and evaluating it with
7574 // EvaluateAsBooleanCondition, but this uses a more direct technique:
7575 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7576 if (!SrcArgDRE)
7577 return;
7578
7579 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7580 if (!CompareWithSrcDRE ||
7581 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7582 return;
7583
7584 const Expr *OriginalSizeArg = Call->getArg(2);
7585 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7586 << OriginalSizeArg->getSourceRange() << FnName;
7587
7588 // Output a FIXIT hint if the destination is an array (rather than a
7589 // pointer to an array). This could be enhanced to handle some
7590 // pointers if we know the actual size, like if DstArg is 'array+2'
7591 // we could say 'sizeof(array)-2'.
7592 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00007593 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00007594 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007595
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007596 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007597 llvm::raw_svector_ostream OS(sizeString);
7598 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007599 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00007600 OS << ")";
7601
7602 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7603 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7604 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00007605}
7606
Anna Zaks314cd092012-02-01 19:08:57 +00007607/// Check if two expressions refer to the same declaration.
7608static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7609 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7610 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7611 return D1->getDecl() == D2->getDecl();
7612 return false;
7613}
7614
7615static const Expr *getStrlenExprArg(const Expr *E) {
7616 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7617 const FunctionDecl *FD = CE->getDirectCallee();
7618 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00007619 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007620 return CE->getArg(0)->IgnoreParenCasts();
7621 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007622 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007623}
7624
7625// Warn on anti-patterns as the 'size' argument to strncat.
7626// The correct size argument should look like following:
7627// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7628void Sema::CheckStrncatArguments(const CallExpr *CE,
7629 IdentifierInfo *FnName) {
7630 // Don't crash if the user has the wrong number of arguments.
7631 if (CE->getNumArgs() < 3)
7632 return;
7633 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7634 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7635 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7636
Nico Weber0e6daef2013-12-26 23:38:39 +00007637 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7638 CE->getRParenLoc()))
7639 return;
7640
Anna Zaks314cd092012-02-01 19:08:57 +00007641 // Identify common expressions, which are wrongly used as the size argument
7642 // to strncat and may lead to buffer overflows.
7643 unsigned PatternType = 0;
7644 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7645 // - sizeof(dst)
7646 if (referToTheSameDecl(SizeOfArg, DstArg))
7647 PatternType = 1;
7648 // - sizeof(src)
7649 else if (referToTheSameDecl(SizeOfArg, SrcArg))
7650 PatternType = 2;
7651 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7652 if (BE->getOpcode() == BO_Sub) {
7653 const Expr *L = BE->getLHS()->IgnoreParenCasts();
7654 const Expr *R = BE->getRHS()->IgnoreParenCasts();
7655 // - sizeof(dst) - strlen(dst)
7656 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7657 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7658 PatternType = 1;
7659 // - sizeof(src) - (anything)
7660 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7661 PatternType = 2;
7662 }
7663 }
7664
7665 if (PatternType == 0)
7666 return;
7667
Anna Zaks5069aa32012-02-03 01:27:37 +00007668 // Generate the diagnostic.
7669 SourceLocation SL = LenArg->getLocStart();
7670 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007671 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00007672
7673 // If the function is defined as a builtin macro, do not show macro expansion.
7674 if (SM.isMacroArgExpansion(SL)) {
7675 SL = SM.getSpellingLoc(SL);
7676 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7677 SM.getSpellingLoc(SR.getEnd()));
7678 }
7679
Anna Zaks13b08572012-08-08 21:42:23 +00007680 // Check if the destination is an array (rather than a pointer to an array).
7681 QualType DstTy = DstArg->getType();
7682 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7683 Context);
7684 if (!isKnownSizeArray) {
7685 if (PatternType == 1)
7686 Diag(SL, diag::warn_strncat_wrong_size) << SR;
7687 else
7688 Diag(SL, diag::warn_strncat_src_size) << SR;
7689 return;
7690 }
7691
Anna Zaks314cd092012-02-01 19:08:57 +00007692 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00007693 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007694 else
Anna Zaks5069aa32012-02-03 01:27:37 +00007695 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007696
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007697 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00007698 llvm::raw_svector_ostream OS(sizeString);
7699 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007700 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007701 OS << ") - ";
7702 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007703 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007704 OS << ") - 1";
7705
Anna Zaks5069aa32012-02-03 01:27:37 +00007706 Diag(SL, diag::note_strncat_wrong_size)
7707 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00007708}
7709
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007710//===--- CHECK: Return Address of Stack Variable --------------------------===//
7711
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007712static const Expr *EvalVal(const Expr *E,
7713 SmallVectorImpl<const DeclRefExpr *> &refVars,
7714 const Decl *ParentDecl);
7715static const Expr *EvalAddr(const Expr *E,
7716 SmallVectorImpl<const DeclRefExpr *> &refVars,
7717 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007718
7719/// CheckReturnStackAddr - Check if a return statement returns the address
7720/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007721static void
7722CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7723 SourceLocation ReturnLoc) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007724 const Expr *stackE = nullptr;
7725 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007726
7727 // Perform checking for returned stack addresses, local blocks,
7728 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00007729 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007730 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007731 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00007732 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007733 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007734 }
7735
Craig Topperc3ec1492014-05-26 06:22:03 +00007736 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007737 return; // Nothing suspicious was found.
7738
Simon Pilgrim750bde62017-03-31 11:00:53 +00007739 // Parameters are initialized in the calling scope, so taking the address
Richard Trieu81b6c562016-08-05 23:24:47 +00007740 // of a parameter reference doesn't need a warning.
7741 for (auto *DRE : refVars)
7742 if (isa<ParmVarDecl>(DRE->getDecl()))
7743 return;
7744
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007745 SourceLocation diagLoc;
7746 SourceRange diagRange;
7747 if (refVars.empty()) {
7748 diagLoc = stackE->getLocStart();
7749 diagRange = stackE->getSourceRange();
7750 } else {
7751 // We followed through a reference variable. 'stackE' contains the
7752 // problematic expression but we will warn at the return statement pointing
7753 // at the reference variable. We will later display the "trail" of
7754 // reference variables using notes.
7755 diagLoc = refVars[0]->getLocStart();
7756 diagRange = refVars[0]->getSourceRange();
7757 }
7758
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007759 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7760 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00007761 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007762 << DR->getDecl()->getDeclName() << diagRange;
7763 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007764 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007765 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007766 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007767 } else { // local temporary.
Richard Trieu81b6c562016-08-05 23:24:47 +00007768 // If there is an LValue->RValue conversion, then the value of the
7769 // reference type is used, not the reference.
7770 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7771 if (ICE->getCastKind() == CK_LValueToRValue) {
7772 return;
7773 }
7774 }
Craig Topperda7b27f2015-11-17 05:40:09 +00007775 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7776 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007777 }
7778
7779 // Display the "trail" of reference variables that we followed until we
7780 // found the problematic expression using notes.
7781 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007782 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007783 // If this var binds to another reference var, show the range of the next
7784 // var, otherwise the var binds to the problematic expression, in which case
7785 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007786 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7787 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007788 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7789 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007790 }
7791}
7792
7793/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7794/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007795/// to a location on the stack, a local block, an address of a label, or a
7796/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007797/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007798/// encounter a subexpression that (1) clearly does not lead to one of the
7799/// above problematic expressions (2) is something we cannot determine leads to
7800/// a problematic expression based on such local checking.
7801///
7802/// Both EvalAddr and EvalVal follow through reference variables to evaluate
7803/// the expression that they point to. Such variables are added to the
7804/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007805///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00007806/// EvalAddr processes expressions that are pointers that are used as
7807/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007808/// At the base case of the recursion is a check for the above problematic
7809/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007810///
7811/// This implementation handles:
7812///
7813/// * pointer-to-pointer casts
7814/// * implicit conversions from array references to pointers
7815/// * taking the address of fields
7816/// * arbitrary interplay between "&" and "*" operators
7817/// * pointer arithmetic from an address of a stack variable
7818/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007819static const Expr *EvalAddr(const Expr *E,
7820 SmallVectorImpl<const DeclRefExpr *> &refVars,
7821 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007822 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00007823 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007824
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007825 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00007826 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00007827 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007828 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00007829 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00007830
Peter Collingbourne91147592011-04-15 00:35:48 +00007831 E = E->IgnoreParens();
7832
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007833 // Our "symbolic interpreter" is just a dispatch off the currently
7834 // viewed AST node. We then recursively traverse the AST by calling
7835 // EvalAddr and EvalVal appropriately.
7836 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007837 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007838 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007839
Richard Smith40f08eb2014-01-30 22:05:38 +00007840 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00007841 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00007842 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00007843
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007844 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007845 // If this is a reference variable, follow through to the expression that
7846 // it points to.
7847 if (V->hasLocalStorage() &&
7848 V->getType()->isReferenceType() && V->hasInit()) {
7849 // Add the reference variable to the "trail".
7850 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007851 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007852 }
7853
Craig Topperc3ec1492014-05-26 06:22:03 +00007854 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007855 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007856
Chris Lattner934edb22007-12-28 05:31:15 +00007857 case Stmt::UnaryOperatorClass: {
7858 // The only unary operator that make sense to handle here
7859 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007860 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007861
John McCalle3027922010-08-25 11:45:40 +00007862 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007863 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007864 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007865 }
Mike Stump11289f42009-09-09 15:08:12 +00007866
Chris Lattner934edb22007-12-28 05:31:15 +00007867 case Stmt::BinaryOperatorClass: {
7868 // Handle pointer arithmetic. All other binary operators are not valid
7869 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007870 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00007871 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00007872
John McCalle3027922010-08-25 11:45:40 +00007873 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00007874 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007875
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007876 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00007877
7878 // Determine which argument is the real pointer base. It could be
7879 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007880 if (!Base->getType()->isPointerType())
7881 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00007882
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007883 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007884 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007885 }
Steve Naroff2752a172008-09-10 19:17:48 +00007886
Chris Lattner934edb22007-12-28 05:31:15 +00007887 // For conditional operators we need to see if either the LHS or RHS are
7888 // valid DeclRefExpr*s. If one of them is valid, we return it.
7889 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007890 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007891
Chris Lattner934edb22007-12-28 05:31:15 +00007892 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007893 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007894 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007895 // In C++, we can have a throw-expression, which has 'void' type.
7896 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007897 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007898 return LHS;
7899 }
Chris Lattner934edb22007-12-28 05:31:15 +00007900
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007901 // In C++, we can have a throw-expression, which has 'void' type.
7902 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00007903 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007904
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007905 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007906 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007907
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007908 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00007909 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007910 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00007911 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007912
7913 case Stmt::AddrLabelExprClass:
7914 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00007915
John McCall28fc7092011-11-10 05:35:25 +00007916 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007917 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7918 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00007919
Ted Kremenekc3b4c522008-08-07 00:49:01 +00007920 // For casts, we need to handle conversions from arrays to
7921 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00007922 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00007923 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00007924 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00007925 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00007926 case Stmt::CXXStaticCastExprClass:
7927 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00007928 case Stmt::CXXConstCastExprClass:
7929 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007930 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00007931 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00007932 case CK_LValueToRValue:
7933 case CK_NoOp:
7934 case CK_BaseToDerived:
7935 case CK_DerivedToBase:
7936 case CK_UncheckedDerivedToBase:
7937 case CK_Dynamic:
7938 case CK_CPointerToObjCPointerCast:
7939 case CK_BlockPointerToObjCPointerCast:
7940 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007941 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007942
7943 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007944 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007945
Richard Trieudadefde2014-07-02 04:39:38 +00007946 case CK_BitCast:
7947 if (SubExpr->getType()->isAnyPointerType() ||
7948 SubExpr->getType()->isBlockPointerType() ||
7949 SubExpr->getType()->isObjCQualifiedIdType())
7950 return EvalAddr(SubExpr, refVars, ParentDecl);
7951 else
7952 return nullptr;
7953
Eli Friedman8195ad72012-02-23 23:04:32 +00007954 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007955 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00007956 }
Chris Lattner934edb22007-12-28 05:31:15 +00007957 }
Mike Stump11289f42009-09-09 15:08:12 +00007958
Douglas Gregorfe314812011-06-21 17:03:29 +00007959 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007960 if (const Expr *Result =
7961 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7962 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00007963 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00007964 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007965
Chris Lattner934edb22007-12-28 05:31:15 +00007966 // Everything else: we simply don't reason about them.
7967 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007968 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00007969 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007970}
Mike Stump11289f42009-09-09 15:08:12 +00007971
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007972/// EvalVal - This function is complements EvalAddr in the mutual recursion.
7973/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007974static const Expr *EvalVal(const Expr *E,
7975 SmallVectorImpl<const DeclRefExpr *> &refVars,
7976 const Decl *ParentDecl) {
7977 do {
7978 // We should only be called for evaluating non-pointer expressions, or
7979 // expressions with a pointer type that are not used as references but
7980 // instead
7981 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00007982
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007983 // Our "symbolic interpreter" is just a dispatch off the currently
7984 // viewed AST node. We then recursively traverse the AST by calling
7985 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00007986
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007987 E = E->IgnoreParens();
7988 switch (E->getStmtClass()) {
7989 case Stmt::ImplicitCastExprClass: {
7990 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
7991 if (IE->getValueKind() == VK_LValue) {
7992 E = IE->getSubExpr();
7993 continue;
7994 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007995 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007996 }
Richard Smith40f08eb2014-01-30 22:05:38 +00007997
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007998 case Stmt::ExprWithCleanupsClass:
7999 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
8000 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008001
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008002 case Stmt::DeclRefExprClass: {
8003 // When we hit a DeclRefExpr we are looking at code that refers to a
8004 // variable's name. If it's not a reference variable we check if it has
8005 // local storage within the function, and if so, return the expression.
8006 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
8007
8008 // If we leave the immediate function, the lifetime isn't about to end.
8009 if (DR->refersToEnclosingVariableOrCapture())
8010 return nullptr;
8011
8012 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
8013 // Check if it refers to itself, e.g. "int& i = i;".
8014 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008015 return DR;
8016
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008017 if (V->hasLocalStorage()) {
8018 if (!V->getType()->isReferenceType())
8019 return DR;
8020
8021 // Reference variable, follow through to the expression that
8022 // it points to.
8023 if (V->hasInit()) {
8024 // Add the reference variable to the "trail".
8025 refVars.push_back(DR);
8026 return EvalVal(V->getInit(), refVars, V);
8027 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008028 }
8029 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008030
8031 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008032 }
Mike Stump11289f42009-09-09 15:08:12 +00008033
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008034 case Stmt::UnaryOperatorClass: {
8035 // The only unary operator that make sense to handle here
8036 // is Deref. All others don't resolve to a "name." This includes
8037 // handling all sorts of rvalues passed to a unary operator.
8038 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00008039
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008040 if (U->getOpcode() == UO_Deref)
8041 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00008042
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008043 return nullptr;
8044 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008045
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008046 case Stmt::ArraySubscriptExprClass: {
8047 // Array subscripts are potential references to data on the stack. We
8048 // retrieve the DeclRefExpr* for the array variable if it indeed
8049 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00008050 const auto *ASE = cast<ArraySubscriptExpr>(E);
8051 if (ASE->isTypeDependent())
8052 return nullptr;
8053 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008054 }
Mike Stump11289f42009-09-09 15:08:12 +00008055
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008056 case Stmt::OMPArraySectionExprClass: {
8057 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
8058 ParentDecl);
8059 }
Mike Stump11289f42009-09-09 15:08:12 +00008060
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008061 case Stmt::ConditionalOperatorClass: {
8062 // For conditional operators we need to see if either the LHS or RHS are
8063 // non-NULL Expr's. If one is non-NULL, we return it.
8064 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00008065
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008066 // Handle the GNU extension for missing LHS.
8067 if (const Expr *LHSExpr = C->getLHS()) {
8068 // In C++, we can have a throw-expression, which has 'void' type.
8069 if (!LHSExpr->getType()->isVoidType())
8070 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
8071 return LHS;
8072 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008073
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008074 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008075 if (C->getRHS()->getType()->isVoidType())
8076 return nullptr;
8077
8078 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008079 }
8080
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008081 // Accesses to members are potential references to data on the stack.
8082 case Stmt::MemberExprClass: {
8083 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00008084
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008085 // Check for indirect access. We only want direct field accesses.
8086 if (M->isArrow())
8087 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008088
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008089 // Check whether the member type is itself a reference, in which case
8090 // we're not going to refer to the member, but to what the member refers
8091 // to.
8092 if (M->getMemberDecl()->getType()->isReferenceType())
8093 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008094
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008095 return EvalVal(M->getBase(), refVars, ParentDecl);
8096 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00008097
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008098 case Stmt::MaterializeTemporaryExprClass:
8099 if (const Expr *Result =
8100 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8101 refVars, ParentDecl))
8102 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008103 return E;
8104
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008105 default:
8106 // Check that we don't return or take the address of a reference to a
8107 // temporary. This is only useful in C++.
8108 if (!E->isTypeDependent() && E->isRValue())
8109 return E;
8110
8111 // Everything else: we simply don't reason about them.
8112 return nullptr;
8113 }
8114 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008115}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008116
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008117void
8118Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
8119 SourceLocation ReturnLoc,
8120 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00008121 const AttrVec *Attrs,
8122 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008123 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
8124
8125 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00008126 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
8127 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00008128 CheckNonNullExpr(*this, RetValExp))
8129 Diag(ReturnLoc, diag::warn_null_ret)
8130 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00008131
8132 // C++11 [basic.stc.dynamic.allocation]p4:
8133 // If an allocation function declared with a non-throwing
8134 // exception-specification fails to allocate storage, it shall return
8135 // a null pointer. Any other allocation function that fails to allocate
8136 // storage shall indicate failure only by throwing an exception [...]
8137 if (FD) {
8138 OverloadedOperatorKind Op = FD->getOverloadedOperator();
8139 if (Op == OO_New || Op == OO_Array_New) {
8140 const FunctionProtoType *Proto
8141 = FD->getType()->castAs<FunctionProtoType>();
8142 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
8143 CheckNonNullExpr(*this, RetValExp))
8144 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
8145 << FD << getLangOpts().CPlusPlus11;
8146 }
8147 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008148}
8149
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008150//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
8151
8152/// Check for comparisons of floating point operands using != and ==.
8153/// Issue a warning if these are no self-comparisons, as they are not likely
8154/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00008155void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00008156 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
8157 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008158
8159 // Special case: check for x == x (which is OK).
8160 // Do not emit warnings for such cases.
8161 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
8162 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
8163 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00008164 return;
Mike Stump11289f42009-09-09 15:08:12 +00008165
Ted Kremenekeda40e22007-11-29 00:59:04 +00008166 // Special case: check for comparisons against literals that can be exactly
8167 // represented by APFloat. In such cases, do not emit a warning. This
8168 // is a heuristic: often comparison against such literals are used to
8169 // detect if a value in a variable has not changed. This clearly can
8170 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00008171 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
8172 if (FLL->isExact())
8173 return;
8174 } else
8175 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
8176 if (FLR->isExact())
8177 return;
Mike Stump11289f42009-09-09 15:08:12 +00008178
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008179 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00008180 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00008181 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00008182 return;
Mike Stump11289f42009-09-09 15:08:12 +00008183
David Blaikie1f4ff152012-07-16 20:47:22 +00008184 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00008185 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00008186 return;
Mike Stump11289f42009-09-09 15:08:12 +00008187
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008188 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00008189 Diag(Loc, diag::warn_floatingpoint_eq)
8190 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008191}
John McCallca01b222010-01-04 23:21:16 +00008192
John McCall70aa5392010-01-06 05:24:50 +00008193//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
8194//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00008195
John McCall70aa5392010-01-06 05:24:50 +00008196namespace {
John McCallca01b222010-01-04 23:21:16 +00008197
John McCall70aa5392010-01-06 05:24:50 +00008198/// Structure recording the 'active' range of an integer-valued
8199/// expression.
8200struct IntRange {
8201 /// The number of bits active in the int.
8202 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00008203
John McCall70aa5392010-01-06 05:24:50 +00008204 /// True if the int is known not to have negative values.
8205 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00008206
John McCall70aa5392010-01-06 05:24:50 +00008207 IntRange(unsigned Width, bool NonNegative)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008208 : Width(Width), NonNegative(NonNegative) {}
John McCallca01b222010-01-04 23:21:16 +00008209
John McCall817d4af2010-11-10 23:38:19 +00008210 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00008211 static IntRange forBoolType() {
8212 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00008213 }
8214
John McCall817d4af2010-11-10 23:38:19 +00008215 /// Returns the range of an opaque value of the given integral type.
8216 static IntRange forValueOfType(ASTContext &C, QualType T) {
8217 return forValueOfCanonicalType(C,
8218 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00008219 }
8220
John McCall817d4af2010-11-10 23:38:19 +00008221 /// Returns the range of an opaque value of a canonical integral type.
8222 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00008223 assert(T->isCanonicalUnqualified());
8224
8225 if (const VectorType *VT = dyn_cast<VectorType>(T))
8226 T = VT->getElementType().getTypePtr();
8227 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8228 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008229 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8230 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00008231
Roman Lebedevca1aaac2017-10-21 16:44:03 +00008232 if (!C.getLangOpts().CPlusPlus) {
8233 // For enum types in C code, use the underlying datatype.
8234 if (const EnumType *ET = dyn_cast<EnumType>(T))
8235 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
8236 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
8237 // For enum types in C++, use the known bit width of the enumerators.
David Majnemer6a426652013-06-07 22:07:20 +00008238 EnumDecl *Enum = ET->getDecl();
Richard Smith371e9e8a2017-12-06 03:00:51 +00008239 // In C++11, enums can have a fixed underlying type. Use this type to
8240 // compute the range.
8241 if (Enum->isFixed()) {
Erich Keane69dbbb02017-09-21 19:58:55 +00008242 return IntRange(C.getIntWidth(QualType(T, 0)),
8243 !ET->isSignedIntegerOrEnumerationType());
Richard Smith371e9e8a2017-12-06 03:00:51 +00008244 }
John McCall18a2c2c2010-11-09 22:22:12 +00008245
David Majnemer6a426652013-06-07 22:07:20 +00008246 unsigned NumPositive = Enum->getNumPositiveBits();
8247 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00008248
David Majnemer6a426652013-06-07 22:07:20 +00008249 if (NumNegative == 0)
8250 return IntRange(NumPositive, true/*NonNegative*/);
8251 else
8252 return IntRange(std::max(NumPositive + 1, NumNegative),
8253 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00008254 }
John McCall70aa5392010-01-06 05:24:50 +00008255
8256 const BuiltinType *BT = cast<BuiltinType>(T);
8257 assert(BT->isInteger());
8258
8259 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8260 }
8261
John McCall817d4af2010-11-10 23:38:19 +00008262 /// Returns the "target" range of a canonical integral type, i.e.
8263 /// the range of values expressible in the type.
8264 ///
8265 /// This matches forValueOfCanonicalType except that enums have the
8266 /// full range of their type, not the range of their enumerators.
8267 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
8268 assert(T->isCanonicalUnqualified());
8269
8270 if (const VectorType *VT = dyn_cast<VectorType>(T))
8271 T = VT->getElementType().getTypePtr();
8272 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8273 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008274 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8275 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008276 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00008277 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008278
8279 const BuiltinType *BT = cast<BuiltinType>(T);
8280 assert(BT->isInteger());
8281
8282 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8283 }
8284
8285 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00008286 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00008287 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00008288 L.NonNegative && R.NonNegative);
8289 }
8290
John McCall817d4af2010-11-10 23:38:19 +00008291 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00008292 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00008293 return IntRange(std::min(L.Width, R.Width),
8294 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00008295 }
8296};
8297
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008298} // namespace
8299
8300static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
8301 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008302 if (value.isSigned() && value.isNegative())
8303 return IntRange(value.getMinSignedBits(), false);
8304
8305 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00008306 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008307
8308 // isNonNegative() just checks the sign bit without considering
8309 // signedness.
8310 return IntRange(value.getActiveBits(), true);
8311}
8312
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008313static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
8314 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008315 if (result.isInt())
8316 return GetValueRange(C, result.getInt(), MaxWidth);
8317
8318 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00008319 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
8320 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
8321 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
8322 R = IntRange::join(R, El);
8323 }
John McCall70aa5392010-01-06 05:24:50 +00008324 return R;
8325 }
8326
8327 if (result.isComplexInt()) {
8328 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
8329 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
8330 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00008331 }
8332
8333 // This can happen with lossless casts to intptr_t of "based" lvalues.
8334 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00008335 // FIXME: The only reason we need to pass the type in here is to get
8336 // the sign right on this one case. It would be nice if APValue
8337 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008338 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00008339 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00008340}
John McCall70aa5392010-01-06 05:24:50 +00008341
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008342static QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008343 QualType Ty = E->getType();
8344 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
8345 Ty = AtomicRHS->getValueType();
8346 return Ty;
8347}
8348
John McCall70aa5392010-01-06 05:24:50 +00008349/// Pseudo-evaluate the given integer expression, estimating the
8350/// range of values it might take.
8351///
8352/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008353static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008354 E = E->IgnoreParens();
8355
8356 // Try a full evaluation first.
8357 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00008358 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00008359 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008360
8361 // I think we only want to look through implicit casts here; if the
8362 // user has an explicit widening cast, we should treat the value as
8363 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008364 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00008365 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00008366 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
8367
Eli Friedmane6d33952013-07-08 20:20:06 +00008368 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00008369
George Burgess IVdf1ed002016-01-13 01:52:39 +00008370 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
8371 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00008372
John McCall70aa5392010-01-06 05:24:50 +00008373 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00008374 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00008375 return OutputTypeRange;
8376
8377 IntRange SubRange
8378 = GetExprRange(C, CE->getSubExpr(),
8379 std::min(MaxWidth, OutputTypeRange.Width));
8380
8381 // Bail out if the subexpr's range is as wide as the cast type.
8382 if (SubRange.Width >= OutputTypeRange.Width)
8383 return OutputTypeRange;
8384
8385 // Otherwise, we take the smaller width, and we're non-negative if
8386 // either the output type or the subexpr is.
8387 return IntRange(SubRange.Width,
8388 SubRange.NonNegative || OutputTypeRange.NonNegative);
8389 }
8390
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008391 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008392 // If we can fold the condition, just take that operand.
8393 bool CondResult;
8394 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
8395 return GetExprRange(C, CondResult ? CO->getTrueExpr()
8396 : CO->getFalseExpr(),
8397 MaxWidth);
8398
8399 // Otherwise, conservatively merge.
8400 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
8401 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
8402 return IntRange::join(L, R);
8403 }
8404
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008405 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008406 switch (BO->getOpcode()) {
Richard Smithc70f1d62017-12-14 15:16:18 +00008407 case BO_Cmp:
8408 llvm_unreachable("builtin <=> should have class type");
John McCall70aa5392010-01-06 05:24:50 +00008409
8410 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00008411 case BO_LAnd:
8412 case BO_LOr:
8413 case BO_LT:
8414 case BO_GT:
8415 case BO_LE:
8416 case BO_GE:
8417 case BO_EQ:
8418 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00008419 return IntRange::forBoolType();
8420
John McCallc3688382011-07-13 06:35:24 +00008421 // The type of the assignments is the type of the LHS, so the RHS
8422 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00008423 case BO_MulAssign:
8424 case BO_DivAssign:
8425 case BO_RemAssign:
8426 case BO_AddAssign:
8427 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00008428 case BO_XorAssign:
8429 case BO_OrAssign:
8430 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00008431 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00008432
John McCallc3688382011-07-13 06:35:24 +00008433 // Simple assignments just pass through the RHS, which will have
8434 // been coerced to the LHS type.
8435 case BO_Assign:
8436 // TODO: bitfields?
8437 return GetExprRange(C, BO->getRHS(), MaxWidth);
8438
John McCall70aa5392010-01-06 05:24:50 +00008439 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008440 case BO_PtrMemD:
8441 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00008442 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008443
John McCall2ce81ad2010-01-06 22:07:33 +00008444 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00008445 case BO_And:
8446 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00008447 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8448 GetExprRange(C, BO->getRHS(), MaxWidth));
8449
John McCall70aa5392010-01-06 05:24:50 +00008450 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00008451 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00008452 // ...except that we want to treat '1 << (blah)' as logically
8453 // positive. It's an important idiom.
8454 if (IntegerLiteral *I
8455 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8456 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008457 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00008458 return IntRange(R.Width, /*NonNegative*/ true);
8459 }
8460 }
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008461 LLVM_FALLTHROUGH;
John McCall1bff9932010-04-07 01:14:35 +00008462
John McCalle3027922010-08-25 11:45:40 +00008463 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00008464 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008465
John McCall2ce81ad2010-01-06 22:07:33 +00008466 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00008467 case BO_Shr:
8468 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00008469 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8470
8471 // If the shift amount is a positive constant, drop the width by
8472 // that much.
8473 llvm::APSInt shift;
8474 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8475 shift.isNonNegative()) {
8476 unsigned zext = shift.getZExtValue();
8477 if (zext >= L.Width)
8478 L.Width = (L.NonNegative ? 0 : 1);
8479 else
8480 L.Width -= zext;
8481 }
8482
8483 return L;
8484 }
8485
8486 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00008487 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00008488 return GetExprRange(C, BO->getRHS(), MaxWidth);
8489
John McCall2ce81ad2010-01-06 22:07:33 +00008490 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00008491 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00008492 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00008493 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008494 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00008495
John McCall51431812011-07-14 22:39:48 +00008496 // The width of a division result is mostly determined by the size
8497 // of the LHS.
8498 case BO_Div: {
8499 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008500 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008501 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8502
8503 // If the divisor is constant, use that.
8504 llvm::APSInt divisor;
8505 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8506 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8507 if (log2 >= L.Width)
8508 L.Width = (L.NonNegative ? 0 : 1);
8509 else
8510 L.Width = std::min(L.Width - log2, MaxWidth);
8511 return L;
8512 }
8513
8514 // Otherwise, just use the LHS's width.
8515 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8516 return IntRange(L.Width, L.NonNegative && R.NonNegative);
8517 }
8518
8519 // The result of a remainder can't be larger than the result of
8520 // either side.
8521 case BO_Rem: {
8522 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008523 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008524 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8525 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8526
8527 IntRange meet = IntRange::meet(L, R);
8528 meet.Width = std::min(meet.Width, MaxWidth);
8529 return meet;
8530 }
8531
8532 // The default behavior is okay for these.
8533 case BO_Mul:
8534 case BO_Add:
8535 case BO_Xor:
8536 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00008537 break;
8538 }
8539
John McCall51431812011-07-14 22:39:48 +00008540 // The default case is to treat the operation as if it were closed
8541 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00008542 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8543 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8544 return IntRange::join(L, R);
8545 }
8546
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008547 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008548 switch (UO->getOpcode()) {
8549 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00008550 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00008551 return IntRange::forBoolType();
8552
8553 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008554 case UO_Deref:
8555 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00008556 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008557
8558 default:
8559 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8560 }
8561 }
8562
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008563 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00008564 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8565
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008566 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00008567 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00008568 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00008569
Eli Friedmane6d33952013-07-08 20:20:06 +00008570 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008571}
John McCall263a48b2010-01-04 23:31:57 +00008572
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008573static IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008574 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00008575}
8576
John McCall263a48b2010-01-04 23:31:57 +00008577/// Checks whether the given value, which currently has the given
8578/// source semantics, has the same value when coerced through the
8579/// target semantics.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008580static bool IsSameFloatAfterCast(const llvm::APFloat &value,
8581 const llvm::fltSemantics &Src,
8582 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008583 llvm::APFloat truncated = value;
8584
8585 bool ignored;
8586 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8587 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8588
8589 return truncated.bitwiseIsEqual(value);
8590}
8591
8592/// Checks whether the given value, which currently has the given
8593/// source semantics, has the same value when coerced through the
8594/// target semantics.
8595///
8596/// The value might be a vector of floats (or a complex number).
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008597static bool IsSameFloatAfterCast(const APValue &value,
8598 const llvm::fltSemantics &Src,
8599 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008600 if (value.isFloat())
8601 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8602
8603 if (value.isVector()) {
8604 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8605 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8606 return false;
8607 return true;
8608 }
8609
8610 assert(value.isComplexFloat());
8611 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8612 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8613}
8614
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008615static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008616
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008617static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00008618 // Suppress cases where we are comparing against an enum constant.
8619 if (const DeclRefExpr *DR =
8620 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8621 if (isa<EnumConstantDecl>(DR->getDecl()))
Roman Lebedev6de129e2017-10-15 20:13:17 +00008622 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +00008623
8624 // Suppress cases where the '0' value is expanded from a macro.
8625 if (E->getLocStart().isMacroID())
Roman Lebedev6de129e2017-10-15 20:13:17 +00008626 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +00008627
Roman Lebedev6de129e2017-10-15 20:13:17 +00008628 return false;
8629}
8630
Richard Smith692f66ab2017-12-06 19:23:19 +00008631static bool isKnownToHaveUnsignedValue(Expr *E) {
8632 return E->getType()->isIntegerType() &&
Roman Lebedev6de129e2017-10-15 20:13:17 +00008633 (!E->getType()->isSignedIntegerType() ||
8634 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
8635}
8636
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008637namespace {
Richard Smitha5370fb2017-12-08 22:57:11 +00008638/// The promoted range of values of a type. In general this has the
8639/// following structure:
8640///
8641/// |-----------| . . . |-----------|
8642/// ^ ^ ^ ^
8643/// Min HoleMin HoleMax Max
8644///
8645/// ... where there is only a hole if a signed type is promoted to unsigned
8646/// (in which case Min and Max are the smallest and largest representable
8647/// values).
8648struct PromotedRange {
8649 // Min, or HoleMax if there is a hole.
8650 llvm::APSInt PromotedMin;
8651 // Max, or HoleMin if there is a hole.
8652 llvm::APSInt PromotedMax;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008653
Richard Smitha5370fb2017-12-08 22:57:11 +00008654 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
8655 if (R.Width == 0)
8656 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
8657 else if (R.Width >= BitWidth && !Unsigned) {
8658 // Promotion made the type *narrower*. This happens when promoting
8659 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
8660 // Treat all values of 'signed int' as being in range for now.
8661 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
8662 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
8663 } else {
8664 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
8665 .extOrTrunc(BitWidth);
8666 PromotedMin.setIsUnsigned(Unsigned);
8667
8668 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
8669 .extOrTrunc(BitWidth);
8670 PromotedMax.setIsUnsigned(Unsigned);
8671 }
8672 }
8673
8674 // Determine whether this range is contiguous (has no hole).
8675 bool isContiguous() const { return PromotedMin <= PromotedMax; }
8676
8677 // Where a constant value is within the range.
8678 enum ComparisonResult {
8679 LT = 0x1,
8680 LE = 0x2,
8681 GT = 0x4,
8682 GE = 0x8,
8683 EQ = 0x10,
8684 NE = 0x20,
8685 InRangeFlag = 0x40,
8686
8687 Less = LE | LT | NE,
8688 Min = LE | InRangeFlag,
8689 InRange = InRangeFlag,
8690 Max = GE | InRangeFlag,
8691 Greater = GE | GT | NE,
8692
8693 OnlyValue = LE | GE | EQ | InRangeFlag,
8694 InHole = NE
8695 };
8696
8697 ComparisonResult compare(const llvm::APSInt &Value) const {
8698 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
8699 Value.isUnsigned() == PromotedMin.isUnsigned());
8700 if (!isContiguous()) {
8701 assert(Value.isUnsigned() && "discontiguous range for signed compare");
8702 if (Value.isMinValue()) return Min;
8703 if (Value.isMaxValue()) return Max;
8704 if (Value >= PromotedMin) return InRange;
8705 if (Value <= PromotedMax) return InRange;
8706 return InHole;
8707 }
8708
8709 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
8710 case -1: return Less;
8711 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
8712 case 1:
8713 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
8714 case -1: return InRange;
8715 case 0: return Max;
8716 case 1: return Greater;
8717 }
8718 }
8719
8720 llvm_unreachable("impossible compare result");
8721 }
8722
Richard Smithc70f1d62017-12-14 15:16:18 +00008723 static llvm::Optional<StringRef>
8724 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
8725 if (Op == BO_Cmp) {
8726 ComparisonResult LTFlag = LT, GTFlag = GT;
8727 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
8728
8729 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
8730 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
8731 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
8732 return llvm::None;
8733 }
8734
Richard Smitha5370fb2017-12-08 22:57:11 +00008735 ComparisonResult TrueFlag, FalseFlag;
8736 if (Op == BO_EQ) {
8737 TrueFlag = EQ;
8738 FalseFlag = NE;
8739 } else if (Op == BO_NE) {
8740 TrueFlag = NE;
8741 FalseFlag = EQ;
8742 } else {
8743 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
8744 TrueFlag = LT;
8745 FalseFlag = GE;
8746 } else {
8747 TrueFlag = GT;
8748 FalseFlag = LE;
8749 }
8750 if (Op == BO_GE || Op == BO_LE)
8751 std::swap(TrueFlag, FalseFlag);
8752 }
8753 if (R & TrueFlag)
Richard Smithc70f1d62017-12-14 15:16:18 +00008754 return StringRef("true");
Richard Smitha5370fb2017-12-08 22:57:11 +00008755 if (R & FalseFlag)
Richard Smithc70f1d62017-12-14 15:16:18 +00008756 return StringRef("false");
Richard Smitha5370fb2017-12-08 22:57:11 +00008757 return llvm::None;
8758 }
Roman Lebedev6de129e2017-10-15 20:13:17 +00008759};
John McCallcc7e5bf2010-05-06 08:58:33 +00008760}
8761
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008762static bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00008763 // Strip off implicit integral promotions.
8764 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008765 if (ICE->getCastKind() != CK_IntegralCast &&
8766 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00008767 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008768 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00008769 }
8770
8771 return E->getType()->isEnumeralType();
8772}
8773
Richard Smith692f66ab2017-12-06 19:23:19 +00008774static int classifyConstantValue(Expr *Constant) {
8775 // The values of this enumeration are used in the diagnostics
8776 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
8777 enum ConstantValueKind {
8778 Miscellaneous = 0,
8779 LiteralTrue,
8780 LiteralFalse
8781 };
8782 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
8783 return BL->getValue() ? ConstantValueKind::LiteralTrue
8784 : ConstantValueKind::LiteralFalse;
8785 return ConstantValueKind::Miscellaneous;
8786}
8787
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008788static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
8789 Expr *Constant, Expr *Other,
8790 const llvm::APSInt &Value,
8791 bool RhsConstant) {
Hans Wennborg5bb88e02017-12-08 05:19:12 +00008792 if (S.inTemplateInstantiation())
8793 return false;
8794
Richard Smitha5370fb2017-12-08 22:57:11 +00008795 Expr *OriginalOther = Other;
8796
Hans Wennborg5bb88e02017-12-08 05:19:12 +00008797 Constant = Constant->IgnoreParenImpCasts();
8798 Other = Other->IgnoreParenImpCasts();
8799
Richard Smitha5370fb2017-12-08 22:57:11 +00008800 // Suppress warnings on tautological comparisons between values of the same
8801 // enumeration type. There are only two ways we could warn on this:
8802 // - If the constant is outside the range of representable values of
8803 // the enumeration. In such a case, we should warn about the cast
8804 // to enumeration type, not about the comparison.
8805 // - If the constant is the maximum / minimum in-range value. For an
8806 // enumeratin type, such comparisons can be meaningful and useful.
8807 if (Constant->getType()->isEnumeralType() &&
8808 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
8809 return false;
8810
Hans Wennborg5bb88e02017-12-08 05:19:12 +00008811 // TODO: Investigate using GetExprRange() to get tighter bounds
8812 // on the bit ranges.
8813 QualType OtherT = Other->getType();
8814 if (const auto *AT = OtherT->getAs<AtomicType>())
8815 OtherT = AT->getValueType();
8816 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8817
8818 // Whether we're treating Other as being a bool because of the form of
8819 // expression despite it having another type (typically 'int' in C).
8820 bool OtherIsBooleanDespiteType =
8821 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
8822 if (OtherIsBooleanDespiteType)
8823 OtherRange = IntRange::forBoolType();
8824
Richard Smitha5370fb2017-12-08 22:57:11 +00008825 // Determine the promoted range of the other type and see if a comparison of
8826 // the constant against that range is tautological.
8827 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
8828 Value.isUnsigned());
8829 auto Cmp = OtherPromotedRange.compare(Value);
8830 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
8831 if (!Result)
8832 return false;
Hans Wennborg5791ce72017-12-08 16:54:08 +00008833
Richard Smitha5370fb2017-12-08 22:57:11 +00008834 // Suppress the diagnostic for an in-range comparison if the constant comes
8835 // from a macro or enumerator. We don't want to diagnose
8836 //
8837 // some_long_value <= INT_MAX
8838 //
8839 // when sizeof(int) == sizeof(long).
8840 bool InRange = Cmp & PromotedRange::InRangeFlag;
8841 if (InRange && IsEnumConstOrFromMacro(S, Constant))
8842 return false;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008843
8844 // If this is a comparison to an enum constant, include that
8845 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00008846 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008847 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8848 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8849
Richard Smitha5370fb2017-12-08 22:57:11 +00008850 // Should be enough for uint128 (39 decimal digits)
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008851 SmallString<64> PrettySourceValue;
8852 llvm::raw_svector_ostream OS(PrettySourceValue);
8853 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00008854 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008855 else
8856 OS << Value;
8857
Richard Smitha5370fb2017-12-08 22:57:11 +00008858 // FIXME: We use a somewhat different formatting for the in-range cases and
8859 // cases involving boolean values for historical reasons. We should pick a
8860 // consistent way of presenting these diagnostics.
8861 if (!InRange || Other->isKnownToHaveBooleanValue()) {
8862 S.DiagRuntimeBehavior(
8863 E->getOperatorLoc(), E,
8864 S.PDiag(!InRange ? diag::warn_out_of_range_compare
8865 : diag::warn_tautological_bool_compare)
8866 << OS.str() << classifyConstantValue(Constant)
8867 << OtherT << OtherIsBooleanDespiteType << *Result
8868 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
8869 } else {
8870 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
8871 ? (HasEnumType(OriginalOther)
8872 ? diag::warn_unsigned_enum_always_true_comparison
8873 : diag::warn_unsigned_always_true_comparison)
8874 : diag::warn_tautological_constant_compare;
Roman Lebedev6de129e2017-10-15 20:13:17 +00008875
Richard Smitha5370fb2017-12-08 22:57:11 +00008876 S.Diag(E->getOperatorLoc(), Diag)
8877 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
8878 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8879 }
8880
8881 return true;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008882}
8883
John McCallcc7e5bf2010-05-06 08:58:33 +00008884/// Analyze the operands of the given comparison. Implements the
8885/// fallback case from AnalyzeComparison.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008886static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00008887 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8888 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00008889}
John McCall263a48b2010-01-04 23:31:57 +00008890
John McCallca01b222010-01-04 23:21:16 +00008891/// \brief Implements -Wsign-compare.
8892///
Richard Trieu82402a02011-09-15 21:56:47 +00008893/// \param E the binary operator to check for warnings
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008894static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008895 // The type the comparison is being performed in.
8896 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00008897
8898 // Only analyze comparison operators where both sides have been converted to
8899 // the same type.
8900 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8901 return AnalyzeImpConvsInComparison(S, E);
8902
8903 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00008904 if (E->isValueDependent())
8905 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008906
Roman Lebedev6de129e2017-10-15 20:13:17 +00008907 Expr *LHS = E->getLHS();
8908 Expr *RHS = E->getRHS();
8909
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008910 if (T->isIntegralType(S.Context)) {
8911 llvm::APSInt RHSValue;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008912 llvm::APSInt LHSValue;
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008913
Roman Lebedev6de129e2017-10-15 20:13:17 +00008914 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
8915 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
Roman Lebedevbd1fc222017-10-12 20:16:51 +00008916
Roman Lebedev6de129e2017-10-15 20:13:17 +00008917 // We don't care about expressions whose result is a constant.
8918 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8919 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6f405db2017-10-12 22:03:20 +00008920
Roman Lebedev6de129e2017-10-15 20:13:17 +00008921 // We only care about expressions where just one side is literal
8922 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
8923 // Is the constant on the RHS or LHS?
8924 const bool RhsConstant = IsRHSIntegralLiteral;
8925 Expr *Const = RhsConstant ? RHS : LHS;
8926 Expr *Other = RhsConstant ? LHS : RHS;
8927 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
8928
8929 // Check whether an integer constant comparison results in a value
8930 // of 'true' or 'false'.
Roman Lebedev6de129e2017-10-15 20:13:17 +00008931 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
8932 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6de129e2017-10-15 20:13:17 +00008933 }
8934 }
8935
8936 if (!T->hasUnsignedIntegerRepresentation()) {
8937 // We don't do anything special if this isn't an unsigned integral
8938 // comparison: we're only interested in integral comparisons, and
8939 // signed comparisons only happen in cases we don't care to warn about.
Roman Lebedev6f405db2017-10-12 22:03:20 +00008940 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6de129e2017-10-15 20:13:17 +00008941 }
8942
8943 LHS = LHS->IgnoreParenImpCasts();
8944 RHS = RHS->IgnoreParenImpCasts();
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008945
Alex Lorenzb57409f2018-02-07 20:45:39 +00008946 if (!S.getLangOpts().CPlusPlus) {
8947 // Avoid warning about comparison of integers with different signs when
8948 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
8949 // the type of `E`.
8950 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
8951 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
8952 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
8953 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
8954 }
8955
John McCallcc7e5bf2010-05-06 08:58:33 +00008956 // Check to see if one of the (unmodified) operands is of different
8957 // signedness.
8958 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00008959 if (LHS->getType()->hasSignedIntegerRepresentation()) {
8960 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00008961 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00008962 signedOperand = LHS;
8963 unsignedOperand = RHS;
8964 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
8965 signedOperand = RHS;
8966 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00008967 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00008968 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008969 }
8970
John McCallcc7e5bf2010-05-06 08:58:33 +00008971 // Otherwise, calculate the effective range of the signed operand.
8972 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00008973
John McCallcc7e5bf2010-05-06 08:58:33 +00008974 // Go ahead and analyze implicit conversions in the operands. Note
8975 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00008976 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
8977 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00008978
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008979 // If the signed range is non-negative, -Wsign-compare won't fire.
John McCallcc7e5bf2010-05-06 08:58:33 +00008980 if (signedRange.NonNegative)
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008981 return;
John McCallca01b222010-01-04 23:21:16 +00008982
8983 // For (in)equality comparisons, if the unsigned operand is a
8984 // constant which cannot collide with a overflowed signed operand,
8985 // then reinterpreting the signed operand as unsigned will not
8986 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00008987 if (E->isEqualityOp()) {
8988 unsigned comparisonWidth = S.Context.getIntWidth(T);
8989 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00008990
John McCallcc7e5bf2010-05-06 08:58:33 +00008991 // We should never be unable to prove that the unsigned operand is
8992 // non-negative.
8993 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
8994
8995 if (unsignedRange.Width < comparisonWidth)
8996 return;
8997 }
8998
Douglas Gregorbfb4a212012-05-01 01:53:49 +00008999 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
9000 S.PDiag(diag::warn_mixed_sign_comparison)
9001 << LHS->getType() << RHS->getType()
9002 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00009003}
9004
John McCall1f425642010-11-11 03:21:53 +00009005/// Analyzes an attempt to assign the given value to a bitfield.
9006///
9007/// Returns true if there was something fishy about the attempt.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009008static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
9009 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00009010 assert(Bitfield->isBitField());
9011 if (Bitfield->isInvalidDecl())
9012 return false;
9013
John McCalldeebbcf2010-11-11 05:33:51 +00009014 // White-list bool bitfields.
Reid Klecknerad425622016-11-16 23:40:00 +00009015 QualType BitfieldType = Bitfield->getType();
9016 if (BitfieldType->isBooleanType())
9017 return false;
9018
9019 if (BitfieldType->isEnumeralType()) {
9020 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
9021 // If the underlying enum type was not explicitly specified as an unsigned
9022 // type and the enum contain only positive values, MSVC++ will cause an
9023 // inconsistency by storing this as a signed type.
9024 if (S.getLangOpts().CPlusPlus11 &&
9025 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
9026 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
9027 BitfieldEnumDecl->getNumNegativeBits() == 0) {
9028 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
9029 << BitfieldEnumDecl->getNameAsString();
9030 }
9031 }
9032
John McCalldeebbcf2010-11-11 05:33:51 +00009033 if (Bitfield->getType()->isBooleanType())
9034 return false;
9035
Douglas Gregor789adec2011-02-04 13:09:01 +00009036 // Ignore value- or type-dependent expressions.
9037 if (Bitfield->getBitWidth()->isValueDependent() ||
9038 Bitfield->getBitWidth()->isTypeDependent() ||
9039 Init->isValueDependent() ||
9040 Init->isTypeDependent())
9041 return false;
9042
John McCall1f425642010-11-11 03:21:53 +00009043 Expr *OriginalInit = Init->IgnoreParenImpCasts();
Reid Kleckner329f24d2017-03-14 18:01:02 +00009044 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00009045
Richard Smith5fab0c92011-12-28 19:48:30 +00009046 llvm::APSInt Value;
Reid Kleckner329f24d2017-03-14 18:01:02 +00009047 if (!OriginalInit->EvaluateAsInt(Value, S.Context,
9048 Expr::SE_AllowSideEffects)) {
9049 // The RHS is not constant. If the RHS has an enum type, make sure the
9050 // bitfield is wide enough to hold all the values of the enum without
9051 // truncation.
9052 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
9053 EnumDecl *ED = EnumTy->getDecl();
9054 bool SignedBitfield = BitfieldType->isSignedIntegerType();
9055
9056 // Enum types are implicitly signed on Windows, so check if there are any
9057 // negative enumerators to see if the enum was intended to be signed or
9058 // not.
9059 bool SignedEnum = ED->getNumNegativeBits() > 0;
9060
9061 // Check for surprising sign changes when assigning enum values to a
9062 // bitfield of different signedness. If the bitfield is signed and we
9063 // have exactly the right number of bits to store this unsigned enum,
9064 // suggest changing the enum to an unsigned type. This typically happens
9065 // on Windows where unfixed enums always use an underlying type of 'int'.
9066 unsigned DiagID = 0;
9067 if (SignedEnum && !SignedBitfield) {
9068 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
9069 } else if (SignedBitfield && !SignedEnum &&
9070 ED->getNumPositiveBits() == FieldWidth) {
9071 DiagID = diag::warn_signed_bitfield_enum_conversion;
9072 }
9073
9074 if (DiagID) {
9075 S.Diag(InitLoc, DiagID) << Bitfield << ED;
9076 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
9077 SourceRange TypeRange =
9078 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
9079 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
9080 << SignedEnum << TypeRange;
9081 }
9082
9083 // Compute the required bitwidth. If the enum has negative values, we need
9084 // one more bit than the normal number of positive bits to represent the
9085 // sign bit.
9086 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
9087 ED->getNumNegativeBits())
9088 : ED->getNumPositiveBits();
9089
9090 // Check the bitwidth.
9091 if (BitsNeeded > FieldWidth) {
9092 Expr *WidthExpr = Bitfield->getBitWidth();
9093 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
9094 << Bitfield << ED;
9095 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
9096 << BitsNeeded << ED << WidthExpr->getSourceRange();
9097 }
9098 }
9099
John McCall1f425642010-11-11 03:21:53 +00009100 return false;
Reid Kleckner329f24d2017-03-14 18:01:02 +00009101 }
John McCall1f425642010-11-11 03:21:53 +00009102
John McCall1f425642010-11-11 03:21:53 +00009103 unsigned OriginalWidth = Value.getBitWidth();
John McCall1f425642010-11-11 03:21:53 +00009104
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00009105 if (!Value.isSigned() || Value.isNegative())
Richard Trieu7561ed02016-08-05 02:39:30 +00009106 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00009107 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
9108 OriginalWidth = Value.getMinSignedBits();
Richard Trieu7561ed02016-08-05 02:39:30 +00009109
John McCall1f425642010-11-11 03:21:53 +00009110 if (OriginalWidth <= FieldWidth)
9111 return false;
9112
Eli Friedmanc267a322012-01-26 23:11:39 +00009113 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00009114 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Reid Klecknerad425622016-11-16 23:40:00 +00009115 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00009116
Eli Friedmanc267a322012-01-26 23:11:39 +00009117 // Check whether the stored value is equal to the original value.
9118 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00009119 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00009120 return false;
9121
Eli Friedmanc267a322012-01-26 23:11:39 +00009122 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00009123 // therefore don't strictly fit into a signed bitfield of width 1.
9124 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00009125 return false;
9126
John McCall1f425642010-11-11 03:21:53 +00009127 std::string PrettyValue = Value.toString(10);
9128 std::string PrettyTrunc = TruncatedValue.toString(10);
9129
9130 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
9131 << PrettyValue << PrettyTrunc << OriginalInit->getType()
9132 << Init->getSourceRange();
9133
9134 return true;
9135}
9136
John McCalld2a53122010-11-09 23:24:47 +00009137/// Analyze the given simple or compound assignment for warning-worthy
9138/// operations.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009139static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00009140 // Just recurse on the LHS.
9141 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9142
9143 // We want to recurse on the RHS as normal unless we're assigning to
9144 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00009145 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009146 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00009147 E->getOperatorLoc())) {
9148 // Recurse, ignoring any implicit conversions on the RHS.
9149 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
9150 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00009151 }
9152 }
9153
9154 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9155}
9156
John McCall263a48b2010-01-04 23:31:57 +00009157/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009158static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
9159 SourceLocation CContext, unsigned diag,
9160 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00009161 if (pruneControlFlow) {
9162 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9163 S.PDiag(diag)
9164 << SourceType << T << E->getSourceRange()
9165 << SourceRange(CContext));
9166 return;
9167 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00009168 S.Diag(E->getExprLoc(), diag)
9169 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
9170}
9171
Chandler Carruth7f3654f2011-04-05 06:47:57 +00009172/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009173static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
9174 SourceLocation CContext,
9175 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00009176 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00009177}
9178
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +00009179/// Analyze the given compound assignment for the possible losing of
9180/// floating-point precision.
9181static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
9182 assert(isa<CompoundAssignOperator>(E) &&
9183 "Must be compound assignment operation");
9184 // Recurse on the LHS and RHS in here
9185 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9186 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9187
9188 // Now check the outermost expression
9189 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
9190 const auto *RBT = cast<CompoundAssignOperator>(E)
9191 ->getComputationResultType()
9192 ->getAs<BuiltinType>();
9193
9194 // If both source and target are floating points.
9195 if (ResultBT && ResultBT->isFloatingPoint() && RBT && RBT->isFloatingPoint())
9196 // Builtin FP kinds are ordered by increasing FP rank.
9197 if (ResultBT->getKind() < RBT->getKind())
9198 // We don't want to warn for system macro.
9199 if (!S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
9200 // warn about dropping FP rank.
9201 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(),
9202 E->getOperatorLoc(),
9203 diag::warn_impcast_float_result_precision);
9204}
Richard Trieube234c32016-04-21 21:04:55 +00009205
9206/// Diagnose an implicit cast from a floating point value to an integer value.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009207static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
9208 SourceLocation CContext) {
Richard Trieube234c32016-04-21 21:04:55 +00009209 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
Richard Smith51ec0cf2017-02-21 01:17:38 +00009210 const bool PruneWarnings = S.inTemplateInstantiation();
Richard Trieube234c32016-04-21 21:04:55 +00009211
9212 Expr *InnerE = E->IgnoreParenImpCasts();
9213 // We also want to warn on, e.g., "int i = -1.234"
9214 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
9215 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
9216 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
9217
9218 const bool IsLiteral =
9219 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
9220
9221 llvm::APFloat Value(0.0);
9222 bool IsConstant =
9223 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
9224 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00009225 return DiagnoseImpCast(S, E, T, CContext,
9226 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00009227 }
9228
Chandler Carruth016ef402011-04-10 08:36:24 +00009229 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00009230
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00009231 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
9232 T->hasUnsignedIntegerRepresentation());
Richard Trieube234c32016-04-21 21:04:55 +00009233 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
9234 &isExact) == llvm::APFloat::opOK &&
Richard Trieu891f0f12016-04-22 22:14:32 +00009235 isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00009236 if (IsLiteral) return;
9237 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
9238 PruneWarnings);
9239 }
9240
9241 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00009242 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00009243 // Warn on floating point literal to integer.
9244 DiagID = diag::warn_impcast_literal_float_to_integer;
9245 } else if (IntegerValue == 0) {
9246 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
9247 return DiagnoseImpCast(S, E, T, CContext,
9248 diag::warn_impcast_float_integer, PruneWarnings);
9249 }
9250 // Warn on non-zero to zero conversion.
9251 DiagID = diag::warn_impcast_float_to_integer_zero;
9252 } else {
9253 if (IntegerValue.isUnsigned()) {
9254 if (!IntegerValue.isMaxValue()) {
9255 return DiagnoseImpCast(S, E, T, CContext,
9256 diag::warn_impcast_float_integer, PruneWarnings);
9257 }
9258 } else { // IntegerValue.isSigned()
9259 if (!IntegerValue.isMaxSignedValue() &&
9260 !IntegerValue.isMinSignedValue()) {
9261 return DiagnoseImpCast(S, E, T, CContext,
9262 diag::warn_impcast_float_integer, PruneWarnings);
9263 }
9264 }
9265 // Warn on evaluatable floating point expression to integer conversion.
9266 DiagID = diag::warn_impcast_float_to_integer;
9267 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009268
Eli Friedman07185912013-08-29 23:44:43 +00009269 // FIXME: Force the precision of the source value down so we don't print
9270 // digits which are usually useless (we don't really care here if we
9271 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
9272 // would automatically print the shortest representation, but it's a bit
9273 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00009274 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00009275 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
9276 precision = (precision * 59 + 195) / 196;
9277 Value.toString(PrettySourceValue, precision);
9278
David Blaikie9b88cc02012-05-15 17:18:27 +00009279 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00009280 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00009281 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00009282 else
David Blaikie9b88cc02012-05-15 17:18:27 +00009283 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00009284
Richard Trieube234c32016-04-21 21:04:55 +00009285 if (PruneWarnings) {
9286 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9287 S.PDiag(DiagID)
9288 << E->getType() << T.getUnqualifiedType()
9289 << PrettySourceValue << PrettyTargetValue
9290 << E->getSourceRange() << SourceRange(CContext));
9291 } else {
9292 S.Diag(E->getExprLoc(), DiagID)
9293 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
9294 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
9295 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009296}
9297
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009298static std::string PrettyPrintInRange(const llvm::APSInt &Value,
9299 IntRange Range) {
John McCall18a2c2c2010-11-09 22:22:12 +00009300 if (!Range.Width) return "0";
9301
9302 llvm::APSInt ValueInRange = Value;
9303 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00009304 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00009305 return ValueInRange.toString(10);
9306}
9307
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009308static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009309 if (!isa<ImplicitCastExpr>(Ex))
9310 return false;
9311
9312 Expr *InnerE = Ex->IgnoreParenImpCasts();
9313 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
9314 const Type *Source =
9315 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
9316 if (Target->isDependentType())
9317 return false;
9318
9319 const BuiltinType *FloatCandidateBT =
9320 dyn_cast<BuiltinType>(ToBool ? Source : Target);
9321 const Type *BoolCandidateType = ToBool ? Target : Source;
9322
9323 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
9324 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
9325}
9326
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009327static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
9328 SourceLocation CC) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009329 unsigned NumArgs = TheCall->getNumArgs();
9330 for (unsigned i = 0; i < NumArgs; ++i) {
9331 Expr *CurrA = TheCall->getArg(i);
9332 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
9333 continue;
9334
9335 bool IsSwapped = ((i > 0) &&
9336 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
9337 IsSwapped |= ((i < (NumArgs - 1)) &&
9338 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
9339 if (IsSwapped) {
9340 // Warn on this floating-point to bool conversion.
9341 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
9342 CurrA->getType(), CC,
9343 diag::warn_impcast_floating_point_to_bool);
9344 }
9345 }
9346}
9347
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009348static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
9349 SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00009350 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
9351 E->getExprLoc()))
9352 return;
9353
Richard Trieu09d6b802016-01-08 23:35:06 +00009354 // Don't warn on functions which have return type nullptr_t.
9355 if (isa<CallExpr>(E))
9356 return;
9357
Richard Trieu5b993502014-10-15 03:42:06 +00009358 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
9359 const Expr::NullPointerConstantKind NullKind =
9360 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
9361 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
9362 return;
9363
9364 // Return if target type is a safe conversion.
9365 if (T->isAnyPointerType() || T->isBlockPointerType() ||
9366 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
9367 return;
9368
9369 SourceLocation Loc = E->getSourceRange().getBegin();
9370
Richard Trieu0a5e1662016-02-13 00:58:53 +00009371 // Venture through the macro stacks to get to the source of macro arguments.
9372 // The new location is a better location than the complete location that was
9373 // passed in.
George Karpenkov441e8fd2018-02-09 23:30:07 +00009374 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
9375 CC = S.SourceMgr.getTopMacroCallerLoc(CC);
Richard Trieu0a5e1662016-02-13 00:58:53 +00009376
Richard Trieu5b993502014-10-15 03:42:06 +00009377 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00009378 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
9379 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
9380 Loc, S.SourceMgr, S.getLangOpts());
9381 if (MacroName == "NULL")
9382 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00009383 }
9384
9385 // Only warn if the null and context location are in the same macro expansion.
9386 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
9387 return;
9388
9389 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009390 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
Richard Trieu5b993502014-10-15 03:42:06 +00009391 << FixItHint::CreateReplacement(Loc,
9392 S.getFixItZeroLiteralForType(T, Loc));
9393}
9394
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009395static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9396 ObjCArrayLiteral *ArrayLiteral);
9397
9398static void
9399checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9400 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00009401
9402/// Check a single element within a collection literal against the
9403/// target element type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009404static void checkObjCCollectionLiteralElement(Sema &S,
9405 QualType TargetElementType,
9406 Expr *Element,
9407 unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009408 // Skip a bitcast to 'id' or qualified 'id'.
9409 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
9410 if (ICE->getCastKind() == CK_BitCast &&
9411 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
9412 Element = ICE->getSubExpr();
9413 }
9414
9415 QualType ElementType = Element->getType();
9416 ExprResult ElementResult(Element);
9417 if (ElementType->getAs<ObjCObjectPointerType>() &&
9418 S.CheckSingleAssignmentConstraints(TargetElementType,
9419 ElementResult,
9420 false, false)
9421 != Sema::Compatible) {
9422 S.Diag(Element->getLocStart(),
9423 diag::warn_objc_collection_literal_element)
9424 << ElementType << ElementKind << TargetElementType
9425 << Element->getSourceRange();
9426 }
9427
9428 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
9429 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
9430 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
9431 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
9432}
9433
9434/// Check an Objective-C array literal being converted to the given
9435/// target type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009436static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9437 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009438 if (!S.NSArrayDecl)
9439 return;
9440
9441 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9442 if (!TargetObjCPtr)
9443 return;
9444
9445 if (TargetObjCPtr->isUnspecialized() ||
9446 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9447 != S.NSArrayDecl->getCanonicalDecl())
9448 return;
9449
9450 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9451 if (TypeArgs.size() != 1)
9452 return;
9453
9454 QualType TargetElementType = TypeArgs[0];
9455 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
9456 checkObjCCollectionLiteralElement(S, TargetElementType,
9457 ArrayLiteral->getElement(I),
9458 0);
9459 }
9460}
9461
9462/// Check an Objective-C dictionary literal being converted to the given
9463/// target type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009464static void
9465checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9466 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009467 if (!S.NSDictionaryDecl)
9468 return;
9469
9470 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9471 if (!TargetObjCPtr)
9472 return;
9473
9474 if (TargetObjCPtr->isUnspecialized() ||
9475 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9476 != S.NSDictionaryDecl->getCanonicalDecl())
9477 return;
9478
9479 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9480 if (TypeArgs.size() != 2)
9481 return;
9482
9483 QualType TargetKeyType = TypeArgs[0];
9484 QualType TargetObjectType = TypeArgs[1];
9485 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
9486 auto Element = DictionaryLiteral->getKeyValueElement(I);
9487 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
9488 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
9489 }
9490}
9491
Richard Trieufc404c72016-02-05 23:02:38 +00009492// Helper function to filter out cases for constant width constant conversion.
9493// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009494static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
9495 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00009496 // If initializing from a constant, and the constant starts with '0',
9497 // then it is a binary, octal, or hexadecimal. Allow these constants
9498 // to fill all the bits, even if there is a sign change.
9499 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
9500 const char FirstLiteralCharacter =
9501 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
9502 if (FirstLiteralCharacter == '0')
9503 return false;
9504 }
9505
9506 // If the CC location points to a '{', and the type is char, then assume
9507 // assume it is an array initialization.
9508 if (CC.isValid() && T->isCharType()) {
9509 const char FirstContextCharacter =
9510 S.getSourceManager().getCharacterData(CC)[0];
9511 if (FirstContextCharacter == '{')
9512 return false;
9513 }
9514
9515 return true;
9516}
9517
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009518static void
9519CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
9520 bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009521 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00009522
John McCallcc7e5bf2010-05-06 08:58:33 +00009523 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
9524 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
9525 if (Source == Target) return;
9526 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00009527
Chandler Carruthc22845a2011-07-26 05:40:03 +00009528 // If the conversion context location is invalid don't complain. We also
9529 // don't want to emit a warning if the issue occurs from the expansion of
9530 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
9531 // delay this check as long as possible. Once we detect we are in that
9532 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009533 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00009534 return;
9535
Richard Trieu021baa32011-09-23 20:10:00 +00009536 // Diagnose implicit casts to bool.
9537 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
9538 if (isa<StringLiteral>(E))
9539 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00009540 // and expressions, for instance, assert(0 && "error here"), are
9541 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00009542 return DiagnoseImpCast(S, E, T, CC,
9543 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00009544 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
9545 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
9546 // This covers the literal expressions that evaluate to Objective-C
9547 // objects.
9548 return DiagnoseImpCast(S, E, T, CC,
9549 diag::warn_impcast_objective_c_literal_to_bool);
9550 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00009551 if (Source->isPointerType() || Source->canDecayToPointerType()) {
9552 // Warn on pointer to bool conversion that is always true.
9553 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
9554 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00009555 }
Richard Trieu021baa32011-09-23 20:10:00 +00009556 }
John McCall263a48b2010-01-04 23:31:57 +00009557
Douglas Gregor5054cb02015-07-07 03:58:22 +00009558 // Check implicit casts from Objective-C collection literals to specialized
9559 // collection types, e.g., NSArray<NSString *> *.
9560 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
9561 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
9562 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
9563 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
9564
John McCall263a48b2010-01-04 23:31:57 +00009565 // Strip vector types.
9566 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009567 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009568 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009569 return;
John McCallacf0ee52010-10-08 02:01:28 +00009570 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009571 }
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +00009572
Chris Lattneree7286f2011-06-14 04:51:15 +00009573 // If the vector cast is cast between two vectors of the same size, it is
9574 // a bitcast, not a conversion.
9575 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
9576 return;
John McCall263a48b2010-01-04 23:31:57 +00009577
9578 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
9579 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
9580 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00009581 if (auto VecTy = dyn_cast<VectorType>(Target))
9582 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00009583
9584 // Strip complex types.
9585 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009586 if (!isa<ComplexType>(Target)) {
Tim Northover02416372017-08-08 23:18:05 +00009587 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009588 return;
9589
Tim Northover02416372017-08-08 23:18:05 +00009590 return DiagnoseImpCast(S, E, T, CC,
9591 S.getLangOpts().CPlusPlus
9592 ? diag::err_impcast_complex_scalar
9593 : diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009594 }
John McCall263a48b2010-01-04 23:31:57 +00009595
9596 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
9597 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
9598 }
9599
9600 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
9601 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
9602
9603 // If the source is floating point...
9604 if (SourceBT && SourceBT->isFloatingPoint()) {
9605 // ...and the target is floating point...
9606 if (TargetBT && TargetBT->isFloatingPoint()) {
9607 // ...then warn if we're dropping FP rank.
9608
9609 // Builtin FP kinds are ordered by increasing FP rank.
9610 if (SourceBT->getKind() > TargetBT->getKind()) {
9611 // Don't warn about float constants that are precisely
9612 // representable in the target type.
9613 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00009614 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00009615 // Value might be a float, a float vector, or a float complex.
9616 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00009617 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9618 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00009619 return;
9620 }
9621
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009622 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009623 return;
9624
John McCallacf0ee52010-10-08 02:01:28 +00009625 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00009626 }
9627 // ... or possibly if we're increasing rank, too
9628 else if (TargetBT->getKind() > SourceBT->getKind()) {
9629 if (S.SourceMgr.isInSystemMacro(CC))
9630 return;
9631
9632 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00009633 }
9634 return;
9635 }
9636
Richard Trieube234c32016-04-21 21:04:55 +00009637 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00009638 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009639 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009640 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00009641
Richard Trieube234c32016-04-21 21:04:55 +00009642 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00009643 }
John McCall263a48b2010-01-04 23:31:57 +00009644
Richard Smith54894fd2015-12-30 01:06:52 +00009645 // Detect the case where a call result is converted from floating-point to
9646 // to bool, and the final argument to the call is converted from bool, to
9647 // discover this typo:
9648 //
9649 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
9650 //
9651 // FIXME: This is an incredibly special case; is there some more general
9652 // way to detect this class of misplaced-parentheses bug?
9653 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009654 // Check last argument of function call to see if it is an
9655 // implicit cast from a type matching the type the result
9656 // is being cast to.
9657 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00009658 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009659 Expr *LastA = CEx->getArg(NumArgs - 1);
9660 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00009661 if (isa<ImplicitCastExpr>(LastA) &&
9662 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009663 // Warn on this floating-point to bool conversion
9664 DiagnoseImpCast(S, E, T, CC,
9665 diag::warn_impcast_floating_point_to_bool);
9666 }
9667 }
9668 }
John McCall263a48b2010-01-04 23:31:57 +00009669 return;
9670 }
9671
Richard Trieu5b993502014-10-15 03:42:06 +00009672 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00009673
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00009674 S.DiscardMisalignedMemberAddress(Target, E);
9675
David Blaikie9366d2b2012-06-19 21:19:06 +00009676 if (!Source->isIntegerType() || !Target->isIntegerType())
9677 return;
9678
David Blaikie7555b6a2012-05-15 16:56:36 +00009679 // TODO: remove this early return once the false positives for constant->bool
9680 // in templates, macros, etc, are reduced or removed.
9681 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9682 return;
9683
John McCallcc7e5bf2010-05-06 08:58:33 +00009684 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00009685 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00009686
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009687 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00009688 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009689 // TODO: this should happen for bitfield stores, too.
9690 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00009691 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009692 if (S.SourceMgr.isInSystemMacro(CC))
9693 return;
9694
John McCall18a2c2c2010-11-09 22:22:12 +00009695 std::string PrettySourceValue = Value.toString(10);
9696 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009697
Ted Kremenek33ba9952011-10-22 02:37:33 +00009698 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9699 S.PDiag(diag::warn_impcast_integer_precision_constant)
9700 << PrettySourceValue << PrettyTargetValue
9701 << E->getType() << T << E->getSourceRange()
9702 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00009703 return;
9704 }
9705
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009706 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9707 if (S.SourceMgr.isInSystemMacro(CC))
9708 return;
9709
David Blaikie9455da02012-04-12 22:40:54 +00009710 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00009711 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9712 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00009713 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00009714 }
9715
Richard Trieudcb55572016-01-29 23:51:16 +00009716 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9717 SourceRange.NonNegative && Source->isSignedIntegerType()) {
9718 // Warn when doing a signed to signed conversion, warn if the positive
9719 // source value is exactly the width of the target type, which will
9720 // cause a negative value to be stored.
9721
9722 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00009723 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9724 !S.SourceMgr.isInSystemMacro(CC)) {
9725 if (isSameWidthConstantConversion(S, E, T, CC)) {
9726 std::string PrettySourceValue = Value.toString(10);
9727 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00009728
Richard Trieufc404c72016-02-05 23:02:38 +00009729 S.DiagRuntimeBehavior(
9730 E->getExprLoc(), E,
9731 S.PDiag(diag::warn_impcast_integer_precision_constant)
9732 << PrettySourceValue << PrettyTargetValue << E->getType() << T
9733 << E->getSourceRange() << clang::SourceRange(CC));
9734 return;
Richard Trieudcb55572016-01-29 23:51:16 +00009735 }
9736 }
Richard Trieufc404c72016-02-05 23:02:38 +00009737
Richard Trieudcb55572016-01-29 23:51:16 +00009738 // Fall through for non-constants to give a sign conversion warning.
9739 }
9740
John McCallcc7e5bf2010-05-06 08:58:33 +00009741 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9742 (!TargetRange.NonNegative && SourceRange.NonNegative &&
9743 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009744 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009745 return;
9746
John McCallcc7e5bf2010-05-06 08:58:33 +00009747 unsigned DiagID = diag::warn_impcast_integer_sign;
9748
9749 // Traditionally, gcc has warned about this under -Wsign-compare.
9750 // We also want to warn about it in -Wconversion.
9751 // So if -Wconversion is off, use a completely identical diagnostic
9752 // in the sign-compare group.
9753 // The conditional-checking code will
9754 if (ICContext) {
9755 DiagID = diag::warn_impcast_integer_sign_conditional;
9756 *ICContext = true;
9757 }
9758
John McCallacf0ee52010-10-08 02:01:28 +00009759 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00009760 }
9761
Douglas Gregora78f1932011-02-22 02:45:07 +00009762 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00009763 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9764 // type, to give us better diagnostics.
9765 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00009766 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00009767 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9768 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9769 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9770 SourceType = S.Context.getTypeDeclType(Enum);
9771 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9772 }
9773 }
9774
Douglas Gregora78f1932011-02-22 02:45:07 +00009775 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9776 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00009777 if (SourceEnum->getDecl()->hasNameForLinkage() &&
9778 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009779 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009780 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009781 return;
9782
Douglas Gregor364f7db2011-03-12 00:14:31 +00009783 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00009784 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009785 }
John McCall263a48b2010-01-04 23:31:57 +00009786}
9787
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009788static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9789 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009790
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009791static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
9792 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009793 E = E->IgnoreParenImpCasts();
9794
9795 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00009796 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009797
John McCallacf0ee52010-10-08 02:01:28 +00009798 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009799 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009800 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00009801}
9802
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009803static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9804 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00009805 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00009806
9807 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00009808 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9809 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009810
9811 // If -Wconversion would have warned about either of the candidates
9812 // for a signedness conversion to the context type...
9813 if (!Suspicious) return;
9814
9815 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009816 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00009817 return;
9818
John McCallcc7e5bf2010-05-06 08:58:33 +00009819 // ...then check whether it would have warned about either of the
9820 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00009821 if (E->getType() == T) return;
9822
9823 Suspicious = false;
9824 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
9825 E->getType(), CC, &Suspicious);
9826 if (!Suspicious)
9827 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00009828 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009829}
9830
Richard Trieu65724892014-11-15 06:37:39 +00009831/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9832/// Input argument E is a logical expression.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009833static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00009834 if (S.getLangOpts().Bool)
9835 return;
9836 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
9837}
9838
John McCallcc7e5bf2010-05-06 08:58:33 +00009839/// AnalyzeImplicitConversions - Find and report any interesting
9840/// implicit conversions in the given expression. There are a couple
9841/// of competing diagnostics here, -Wconversion and -Wsign-compare.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009842static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
9843 SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00009844 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00009845 Expr *E = OrigE->IgnoreParenImpCasts();
9846
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00009847 if (E->isTypeDependent() || E->isValueDependent())
9848 return;
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +00009849
John McCallcc7e5bf2010-05-06 08:58:33 +00009850 // For conditional operators, we analyze the arguments as if they
9851 // were being fed directly into the output.
9852 if (isa<ConditionalOperator>(E)) {
9853 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00009854 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009855 return;
9856 }
9857
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009858 // Check implicit argument conversions for function calls.
9859 if (CallExpr *Call = dyn_cast<CallExpr>(E))
9860 CheckImplicitArgumentConversions(S, Call, CC);
9861
John McCallcc7e5bf2010-05-06 08:58:33 +00009862 // Go ahead and check any implicit conversions we might have skipped.
9863 // The non-canonical typecheck is just an optimization;
9864 // CheckImplicitConversion will filter out dead implicit conversions.
9865 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009866 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009867
9868 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00009869
9870 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
9871 // The bound subexpressions in a PseudoObjectExpr are not reachable
9872 // as transitive children.
9873 // FIXME: Use a more uniform representation for this.
9874 for (auto *SE : POE->semantics())
9875 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9876 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00009877 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00009878
John McCallcc7e5bf2010-05-06 08:58:33 +00009879 // Skip past explicit casts.
9880 if (isa<ExplicitCastExpr>(E)) {
9881 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00009882 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009883 }
9884
John McCalld2a53122010-11-09 23:24:47 +00009885 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9886 // Do a somewhat different check with comparison operators.
9887 if (BO->isComparisonOp())
9888 return AnalyzeComparison(S, BO);
9889
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009890 // And with simple assignments.
9891 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00009892 return AnalyzeAssignment(S, BO);
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +00009893 // And with compound assignments.
9894 if (BO->isAssignmentOp())
9895 return AnalyzeCompoundAssignment(S, BO);
John McCalld2a53122010-11-09 23:24:47 +00009896 }
John McCallcc7e5bf2010-05-06 08:58:33 +00009897
9898 // These break the otherwise-useful invariant below. Fortunately,
9899 // we don't really need to recurse into them, because any internal
9900 // expressions should have been analyzed already when they were
9901 // built into statements.
9902 if (isa<StmtExpr>(E)) return;
9903
9904 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00009905 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00009906
9907 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00009908 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00009909 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00009910 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00009911 for (Stmt *SubStmt : E->children()) {
9912 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00009913 if (!ChildExpr)
9914 continue;
9915
Richard Trieu955231d2014-01-25 01:10:35 +00009916 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00009917 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00009918 // Ignore checking string literals that are in logical and operators.
9919 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00009920 continue;
9921 AnalyzeImplicitConversions(S, ChildExpr, CC);
9922 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009923
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009924 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00009925 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
9926 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009927 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00009928
9929 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
9930 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009931 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009932 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009933
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009934 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
9935 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00009936 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009937}
9938
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00009939/// Diagnose integer type and any valid implicit conversion to it.
Anastasia Stulova0df4ac32016-11-14 17:39:58 +00009940static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
9941 // Taking into account implicit conversions,
9942 // allow any integer.
9943 if (!E->getType()->isIntegerType()) {
9944 S.Diag(E->getLocStart(),
9945 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
9946 return true;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009947 }
Anastasia Stulova0df4ac32016-11-14 17:39:58 +00009948 // Potentially emit standard warnings for implicit conversions if enabled
9949 // using -Wconversion.
9950 CheckImplicitConversion(S, E, IntT, E->getLocStart());
9951 return false;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009952}
9953
Richard Trieuc1888e02014-06-28 23:25:37 +00009954// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
9955// Returns true when emitting a warning about taking the address of a reference.
9956static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +00009957 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +00009958 E = E->IgnoreParenImpCasts();
9959
9960 const FunctionDecl *FD = nullptr;
9961
9962 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9963 if (!DRE->getDecl()->getType()->isReferenceType())
9964 return false;
9965 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9966 if (!M->getMemberDecl()->getType()->isReferenceType())
9967 return false;
9968 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00009969 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00009970 return false;
9971 FD = Call->getDirectCallee();
9972 } else {
9973 return false;
9974 }
9975
9976 SemaRef.Diag(E->getExprLoc(), PD);
9977
9978 // If possible, point to location of function.
9979 if (FD) {
9980 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
9981 }
9982
9983 return true;
9984}
9985
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009986// Returns true if the SourceLocation is expanded from any macro body.
9987// Returns false if the SourceLocation is invalid, is from not in a macro
9988// expansion, or is from expanded from a top-level macro argument.
9989static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
9990 if (Loc.isInvalid())
9991 return false;
9992
9993 while (Loc.isMacroID()) {
9994 if (SM.isMacroBodyExpansion(Loc))
9995 return true;
9996 Loc = SM.getImmediateMacroCallerLoc(Loc);
9997 }
9998
9999 return false;
10000}
10001
Richard Trieu3bb8b562014-02-26 02:36:06 +000010002/// \brief Diagnose pointers that are always non-null.
10003/// \param E the expression containing the pointer
10004/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
10005/// compared to a null pointer
10006/// \param IsEqual True when the comparison is equal to a null pointer
10007/// \param Range Extra SourceRange to highlight in the diagnostic
10008void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
10009 Expr::NullPointerConstantKind NullKind,
10010 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +000010011 if (!E)
10012 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010013
10014 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +000010015 if (E->getExprLoc().isMacroID()) {
10016 const SourceManager &SM = getSourceManager();
10017 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
10018 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +000010019 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +000010020 }
Richard Trieu3bb8b562014-02-26 02:36:06 +000010021 E = E->IgnoreImpCasts();
10022
10023 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
10024
Richard Trieuf7432752014-06-06 21:39:26 +000010025 if (isa<CXXThisExpr>(E)) {
10026 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
10027 : diag::warn_this_bool_conversion;
10028 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
10029 return;
10030 }
10031
Richard Trieu3bb8b562014-02-26 02:36:06 +000010032 bool IsAddressOf = false;
10033
10034 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10035 if (UO->getOpcode() != UO_AddrOf)
10036 return;
10037 IsAddressOf = true;
10038 E = UO->getSubExpr();
10039 }
10040
Richard Trieuc1888e02014-06-28 23:25:37 +000010041 if (IsAddressOf) {
10042 unsigned DiagID = IsCompare
10043 ? diag::warn_address_of_reference_null_compare
10044 : diag::warn_address_of_reference_bool_conversion;
10045 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
10046 << IsEqual;
10047 if (CheckForReference(*this, E, PD)) {
10048 return;
10049 }
10050 }
10051
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010052 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
10053 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +000010054 std::string Str;
10055 llvm::raw_string_ostream S(Str);
10056 E->printPretty(S, nullptr, getPrintingPolicy());
10057 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
10058 : diag::warn_cast_nonnull_to_bool;
10059 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
10060 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010061 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +000010062 };
10063
10064 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
10065 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
10066 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010067 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
10068 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000010069 return;
10070 }
10071 }
10072 }
10073
Richard Trieu3bb8b562014-02-26 02:36:06 +000010074 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +000010075 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010076 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
10077 D = R->getDecl();
10078 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10079 D = M->getMemberDecl();
10080 }
10081
10082 // Weak Decls can be null.
10083 if (!D || D->isWeak())
10084 return;
George Burgess IV850269a2015-12-08 22:02:00 +000010085
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010086 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +000010087 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
10088 if (getCurFunction() &&
10089 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010090 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
10091 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000010092 return;
10093 }
10094
10095 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +000010096 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +000010097 assert(ParamIter != FD->param_end());
10098 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
10099
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010100 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
10101 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010102 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +000010103 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010104 }
George Burgess IV850269a2015-12-08 22:02:00 +000010105
Joel E. Denny81508102018-03-13 14:51:22 +000010106 for (const ParamIdx &ArgNo : NonNull->args()) {
10107 if (ArgNo.getASTIndex() == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010108 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010109 return;
10110 }
George Burgess IV850269a2015-12-08 22:02:00 +000010111 }
10112 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010113 }
10114 }
George Burgess IV850269a2015-12-08 22:02:00 +000010115 }
10116
Richard Trieu3bb8b562014-02-26 02:36:06 +000010117 QualType T = D->getType();
10118 const bool IsArray = T->isArrayType();
10119 const bool IsFunction = T->isFunctionType();
10120
Richard Trieuc1888e02014-06-28 23:25:37 +000010121 // Address of function is used to silence the function warning.
10122 if (IsAddressOf && IsFunction) {
10123 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010124 }
10125
10126 // Found nothing.
10127 if (!IsAddressOf && !IsFunction && !IsArray)
10128 return;
10129
10130 // Pretty print the expression for the diagnostic.
10131 std::string Str;
10132 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +000010133 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +000010134
10135 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
10136 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +000010137 enum {
10138 AddressOf,
10139 FunctionPointer,
10140 ArrayPointer
10141 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010142 if (IsAddressOf)
10143 DiagType = AddressOf;
10144 else if (IsFunction)
10145 DiagType = FunctionPointer;
10146 else if (IsArray)
10147 DiagType = ArrayPointer;
10148 else
10149 llvm_unreachable("Could not determine diagnostic.");
10150 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
10151 << Range << IsEqual;
10152
10153 if (!IsFunction)
10154 return;
10155
10156 // Suggest '&' to silence the function warning.
10157 Diag(E->getExprLoc(), diag::note_function_warning_silence)
10158 << FixItHint::CreateInsertion(E->getLocStart(), "&");
10159
10160 // Check to see if '()' fixit should be emitted.
10161 QualType ReturnType;
10162 UnresolvedSet<4> NonTemplateOverloads;
10163 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
10164 if (ReturnType.isNull())
10165 return;
10166
10167 if (IsCompare) {
10168 // There are two cases here. If there is null constant, the only suggest
10169 // for a pointer return type. If the null is 0, then suggest if the return
10170 // type is a pointer or an integer type.
10171 if (!ReturnType->isPointerType()) {
10172 if (NullKind == Expr::NPCK_ZeroExpression ||
10173 NullKind == Expr::NPCK_ZeroLiteral) {
10174 if (!ReturnType->isIntegerType())
10175 return;
10176 } else {
10177 return;
10178 }
10179 }
10180 } else { // !IsCompare
10181 // For function to bool, only suggest if the function pointer has bool
10182 // return type.
10183 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
10184 return;
10185 }
10186 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +000010187 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +000010188}
10189
John McCallcc7e5bf2010-05-06 08:58:33 +000010190/// Diagnoses "dangerous" implicit conversions within the given
10191/// expression (which is a full expression). Implements -Wconversion
10192/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +000010193///
10194/// \param CC the "context" location of the implicit conversion, i.e.
10195/// the most location of the syntactic entity requiring the implicit
10196/// conversion
10197void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010198 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +000010199 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +000010200 return;
10201
10202 // Don't diagnose for value- or type-dependent expressions.
10203 if (E->isTypeDependent() || E->isValueDependent())
10204 return;
10205
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010206 // Check for array bounds violations in cases where the check isn't triggered
10207 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
10208 // ArraySubscriptExpr is on the RHS of a variable initialization.
10209 CheckArrayAccess(E);
10210
John McCallacf0ee52010-10-08 02:01:28 +000010211 // This is not the right CC for (e.g.) a variable initialization.
10212 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010213}
10214
Richard Trieu65724892014-11-15 06:37:39 +000010215/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10216/// Input argument E is a logical expression.
10217void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
10218 ::CheckBoolLikeConversion(*this, E, CC);
10219}
10220
Richard Smith9f7df0c2017-06-26 23:19:32 +000010221/// Diagnose when expression is an integer constant expression and its evaluation
10222/// results in integer overflow
10223void Sema::CheckForIntOverflow (Expr *E) {
10224 // Use a work list to deal with nested struct initializers.
10225 SmallVector<Expr *, 2> Exprs(1, E);
10226
10227 do {
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010228 Expr *OriginalE = Exprs.pop_back_val();
10229 Expr *E = OriginalE->IgnoreParenCasts();
Richard Smith9f7df0c2017-06-26 23:19:32 +000010230
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010231 if (isa<BinaryOperator>(E)) {
10232 E->EvaluateForOverflow(Context);
Richard Smith9f7df0c2017-06-26 23:19:32 +000010233 continue;
10234 }
10235
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010236 if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
Richard Smith9f7df0c2017-06-26 23:19:32 +000010237 Exprs.append(InitList->inits().begin(), InitList->inits().end());
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010238 else if (isa<ObjCBoxedExpr>(OriginalE))
10239 E->EvaluateForOverflow(Context);
10240 else if (auto Call = dyn_cast<CallExpr>(E))
10241 Exprs.append(Call->arg_begin(), Call->arg_end());
10242 else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
10243 Exprs.append(Message->arg_begin(), Message->arg_end());
Richard Smith9f7df0c2017-06-26 23:19:32 +000010244 } while (!Exprs.empty());
10245}
10246
Richard Smithc406cb72013-01-17 01:17:56 +000010247namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010248
Richard Smithc406cb72013-01-17 01:17:56 +000010249/// \brief Visitor for expressions which looks for unsequenced operations on the
10250/// same object.
10251class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010252 using Base = EvaluatedExprVisitor<SequenceChecker>;
Richard Smithe3dbfe02013-06-30 10:40:20 +000010253
Richard Smithc406cb72013-01-17 01:17:56 +000010254 /// \brief A tree of sequenced regions within an expression. Two regions are
10255 /// unsequenced if one is an ancestor or a descendent of the other. When we
10256 /// finish processing an expression with sequencing, such as a comma
10257 /// expression, we fold its tree nodes into its parent, since they are
10258 /// unsequenced with respect to nodes we will visit later.
10259 class SequenceTree {
10260 struct Value {
10261 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
10262 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +000010263 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +000010264 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010265 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +000010266
10267 public:
10268 /// \brief A region within an expression which may be sequenced with respect
10269 /// to some other region.
10270 class Seq {
Richard Smithc406cb72013-01-17 01:17:56 +000010271 friend class SequenceTree;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010272
10273 unsigned Index = 0;
10274
10275 explicit Seq(unsigned N) : Index(N) {}
10276
Richard Smithc406cb72013-01-17 01:17:56 +000010277 public:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010278 Seq() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010279 };
10280
10281 SequenceTree() { Values.push_back(Value(0)); }
10282 Seq root() const { return Seq(0); }
10283
10284 /// \brief Create a new sequence of operations, which is an unsequenced
10285 /// subset of \p Parent. This sequence of operations is sequenced with
10286 /// respect to other children of \p Parent.
10287 Seq allocate(Seq Parent) {
10288 Values.push_back(Value(Parent.Index));
10289 return Seq(Values.size() - 1);
10290 }
10291
10292 /// \brief Merge a sequence of operations into its parent.
10293 void merge(Seq S) {
10294 Values[S.Index].Merged = true;
10295 }
10296
10297 /// \brief Determine whether two operations are unsequenced. This operation
10298 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
10299 /// should have been merged into its parent as appropriate.
10300 bool isUnsequenced(Seq Cur, Seq Old) {
10301 unsigned C = representative(Cur.Index);
10302 unsigned Target = representative(Old.Index);
10303 while (C >= Target) {
10304 if (C == Target)
10305 return true;
10306 C = Values[C].Parent;
10307 }
10308 return false;
10309 }
10310
10311 private:
10312 /// \brief Pick a representative for a sequence.
10313 unsigned representative(unsigned K) {
10314 if (Values[K].Merged)
10315 // Perform path compression as we go.
10316 return Values[K].Parent = representative(Values[K].Parent);
10317 return K;
10318 }
10319 };
10320
10321 /// An object for which we can track unsequenced uses.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010322 using Object = NamedDecl *;
Richard Smithc406cb72013-01-17 01:17:56 +000010323
10324 /// Different flavors of object usage which we track. We only track the
10325 /// least-sequenced usage of each kind.
10326 enum UsageKind {
10327 /// A read of an object. Multiple unsequenced reads are OK.
10328 UK_Use,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010329
Richard Smithc406cb72013-01-17 01:17:56 +000010330 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +000010331 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +000010332 UK_ModAsValue,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010333
Richard Smithc406cb72013-01-17 01:17:56 +000010334 /// A modification of an object which is not sequenced before the value
10335 /// computation of the expression, such as n++.
10336 UK_ModAsSideEffect,
10337
10338 UK_Count = UK_ModAsSideEffect + 1
10339 };
10340
10341 struct Usage {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010342 Expr *Use = nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000010343 SequenceTree::Seq Seq;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010344
10345 Usage() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010346 };
10347
10348 struct UsageInfo {
Richard Smithc406cb72013-01-17 01:17:56 +000010349 Usage Uses[UK_Count];
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010350
Richard Smithc406cb72013-01-17 01:17:56 +000010351 /// Have we issued a diagnostic for this variable already?
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010352 bool Diagnosed = false;
10353
10354 UsageInfo() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010355 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010356 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
Richard Smithc406cb72013-01-17 01:17:56 +000010357
10358 Sema &SemaRef;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010359
Richard Smithc406cb72013-01-17 01:17:56 +000010360 /// Sequenced regions within the expression.
10361 SequenceTree Tree;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010362
Richard Smithc406cb72013-01-17 01:17:56 +000010363 /// Declaration modifications and references which we have seen.
10364 UsageInfoMap UsageMap;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010365
Richard Smithc406cb72013-01-17 01:17:56 +000010366 /// The region we are currently within.
10367 SequenceTree::Seq Region;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010368
Richard Smithc406cb72013-01-17 01:17:56 +000010369 /// Filled in with declarations which were modified as a side-effect
10370 /// (that is, post-increment operations).
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010371 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
10372
Richard Smithd33f5202013-01-17 23:18:09 +000010373 /// Expressions to check later. We defer checking these to reduce
10374 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010375 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +000010376
10377 /// RAII object wrapping the visitation of a sequenced subexpression of an
10378 /// expression. At the end of this process, the side-effects of the evaluation
10379 /// become sequenced with respect to the value computation of the result, so
10380 /// we downgrade any UK_ModAsSideEffect within the evaluation to
10381 /// UK_ModAsValue.
10382 struct SequencedSubexpression {
10383 SequencedSubexpression(SequenceChecker &Self)
10384 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
10385 Self.ModAsSideEffect = &ModAsSideEffect;
10386 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010387
Richard Smithc406cb72013-01-17 01:17:56 +000010388 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +000010389 for (auto &M : llvm::reverse(ModAsSideEffect)) {
10390 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +000010391 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +000010392 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
10393 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +000010394 }
10395 Self.ModAsSideEffect = OldModAsSideEffect;
10396 }
10397
10398 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010399 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010400 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +000010401 };
10402
Richard Smith40238f02013-06-20 22:21:56 +000010403 /// RAII object wrapping the visitation of a subexpression which we might
10404 /// choose to evaluate as a constant. If any subexpression is evaluated and
10405 /// found to be non-constant, this allows us to suppress the evaluation of
10406 /// the outer expression.
10407 class EvaluationTracker {
10408 public:
10409 EvaluationTracker(SequenceChecker &Self)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010410 : Self(Self), Prev(Self.EvalTracker) {
Richard Smith40238f02013-06-20 22:21:56 +000010411 Self.EvalTracker = this;
10412 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010413
Richard Smith40238f02013-06-20 22:21:56 +000010414 ~EvaluationTracker() {
10415 Self.EvalTracker = Prev;
10416 if (Prev)
10417 Prev->EvalOK &= EvalOK;
10418 }
10419
10420 bool evaluate(const Expr *E, bool &Result) {
10421 if (!EvalOK || E->isValueDependent())
10422 return false;
10423 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
10424 return EvalOK;
10425 }
10426
10427 private:
10428 SequenceChecker &Self;
10429 EvaluationTracker *Prev;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010430 bool EvalOK = true;
10431 } *EvalTracker = nullptr;
Richard Smith40238f02013-06-20 22:21:56 +000010432
Richard Smithc406cb72013-01-17 01:17:56 +000010433 /// \brief Find the object which is produced by the specified expression,
10434 /// if any.
10435 Object getObject(Expr *E, bool Mod) const {
10436 E = E->IgnoreParenCasts();
10437 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10438 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
10439 return getObject(UO->getSubExpr(), Mod);
10440 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10441 if (BO->getOpcode() == BO_Comma)
10442 return getObject(BO->getRHS(), Mod);
10443 if (Mod && BO->isAssignmentOp())
10444 return getObject(BO->getLHS(), Mod);
10445 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10446 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
10447 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
10448 return ME->getMemberDecl();
10449 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10450 // FIXME: If this is a reference, map through to its value.
10451 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +000010452 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000010453 }
10454
10455 /// \brief Note that an object was modified or used by an expression.
10456 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
10457 Usage &U = UI.Uses[UK];
10458 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
10459 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
10460 ModAsSideEffect->push_back(std::make_pair(O, U));
10461 U.Use = Ref;
10462 U.Seq = Region;
10463 }
10464 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010465
Richard Smithc406cb72013-01-17 01:17:56 +000010466 /// \brief Check whether a modification or use conflicts with a prior usage.
10467 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
10468 bool IsModMod) {
10469 if (UI.Diagnosed)
10470 return;
10471
10472 const Usage &U = UI.Uses[OtherKind];
10473 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
10474 return;
10475
10476 Expr *Mod = U.Use;
10477 Expr *ModOrUse = Ref;
10478 if (OtherKind == UK_Use)
10479 std::swap(Mod, ModOrUse);
10480
10481 SemaRef.Diag(Mod->getExprLoc(),
10482 IsModMod ? diag::warn_unsequenced_mod_mod
10483 : diag::warn_unsequenced_mod_use)
10484 << O << SourceRange(ModOrUse->getExprLoc());
10485 UI.Diagnosed = true;
10486 }
10487
10488 void notePreUse(Object O, Expr *Use) {
10489 UsageInfo &U = UsageMap[O];
10490 // Uses conflict with other modifications.
10491 checkUsage(O, U, Use, UK_ModAsValue, false);
10492 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010493
Richard Smithc406cb72013-01-17 01:17:56 +000010494 void notePostUse(Object O, Expr *Use) {
10495 UsageInfo &U = UsageMap[O];
10496 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
10497 addUsage(U, O, Use, UK_Use);
10498 }
10499
10500 void notePreMod(Object O, Expr *Mod) {
10501 UsageInfo &U = UsageMap[O];
10502 // Modifications conflict with other modifications and with uses.
10503 checkUsage(O, U, Mod, UK_ModAsValue, true);
10504 checkUsage(O, U, Mod, UK_Use, false);
10505 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010506
Richard Smithc406cb72013-01-17 01:17:56 +000010507 void notePostMod(Object O, Expr *Use, UsageKind UK) {
10508 UsageInfo &U = UsageMap[O];
10509 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
10510 addUsage(U, O, Use, UK);
10511 }
10512
10513public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010514 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010515 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
Richard Smithc406cb72013-01-17 01:17:56 +000010516 Visit(E);
10517 }
10518
10519 void VisitStmt(Stmt *S) {
10520 // Skip all statements which aren't expressions for now.
10521 }
10522
10523 void VisitExpr(Expr *E) {
10524 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +000010525 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +000010526 }
10527
10528 void VisitCastExpr(CastExpr *E) {
10529 Object O = Object();
10530 if (E->getCastKind() == CK_LValueToRValue)
10531 O = getObject(E->getSubExpr(), false);
10532
10533 if (O)
10534 notePreUse(O, E);
10535 VisitExpr(E);
10536 if (O)
10537 notePostUse(O, E);
10538 }
10539
10540 void VisitBinComma(BinaryOperator *BO) {
10541 // C++11 [expr.comma]p1:
10542 // Every value computation and side effect associated with the left
10543 // expression is sequenced before every value computation and side
10544 // effect associated with the right expression.
10545 SequenceTree::Seq LHS = Tree.allocate(Region);
10546 SequenceTree::Seq RHS = Tree.allocate(Region);
10547 SequenceTree::Seq OldRegion = Region;
10548
10549 {
10550 SequencedSubexpression SeqLHS(*this);
10551 Region = LHS;
10552 Visit(BO->getLHS());
10553 }
10554
10555 Region = RHS;
10556 Visit(BO->getRHS());
10557
10558 Region = OldRegion;
10559
10560 // Forget that LHS and RHS are sequenced. They are both unsequenced
10561 // with respect to other stuff.
10562 Tree.merge(LHS);
10563 Tree.merge(RHS);
10564 }
10565
10566 void VisitBinAssign(BinaryOperator *BO) {
10567 // The modification is sequenced after the value computation of the LHS
10568 // and RHS, so check it before inspecting the operands and update the
10569 // map afterwards.
10570 Object O = getObject(BO->getLHS(), true);
10571 if (!O)
10572 return VisitExpr(BO);
10573
10574 notePreMod(O, BO);
10575
10576 // C++11 [expr.ass]p7:
10577 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
10578 // only once.
10579 //
10580 // Therefore, for a compound assignment operator, O is considered used
10581 // everywhere except within the evaluation of E1 itself.
10582 if (isa<CompoundAssignOperator>(BO))
10583 notePreUse(O, BO);
10584
10585 Visit(BO->getLHS());
10586
10587 if (isa<CompoundAssignOperator>(BO))
10588 notePostUse(O, BO);
10589
10590 Visit(BO->getRHS());
10591
Richard Smith83e37bee2013-06-26 23:16:51 +000010592 // C++11 [expr.ass]p1:
10593 // the assignment is sequenced [...] before the value computation of the
10594 // assignment expression.
10595 // C11 6.5.16/3 has no such rule.
10596 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10597 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010598 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010599
Richard Smithc406cb72013-01-17 01:17:56 +000010600 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
10601 VisitBinAssign(CAO);
10602 }
10603
10604 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10605 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10606 void VisitUnaryPreIncDec(UnaryOperator *UO) {
10607 Object O = getObject(UO->getSubExpr(), true);
10608 if (!O)
10609 return VisitExpr(UO);
10610
10611 notePreMod(O, UO);
10612 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +000010613 // C++11 [expr.pre.incr]p1:
10614 // the expression ++x is equivalent to x+=1
10615 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10616 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010617 }
10618
10619 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10620 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10621 void VisitUnaryPostIncDec(UnaryOperator *UO) {
10622 Object O = getObject(UO->getSubExpr(), true);
10623 if (!O)
10624 return VisitExpr(UO);
10625
10626 notePreMod(O, UO);
10627 Visit(UO->getSubExpr());
10628 notePostMod(O, UO, UK_ModAsSideEffect);
10629 }
10630
10631 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
10632 void VisitBinLOr(BinaryOperator *BO) {
10633 // The side-effects of the LHS of an '&&' are sequenced before the
10634 // value computation of the RHS, and hence before the value computation
10635 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10636 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +000010637 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010638 {
10639 SequencedSubexpression Sequenced(*this);
10640 Visit(BO->getLHS());
10641 }
10642
10643 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010644 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010645 if (!Result)
10646 Visit(BO->getRHS());
10647 } else {
10648 // Check for unsequenced operations in the RHS, treating it as an
10649 // entirely separate evaluation.
10650 //
10651 // FIXME: If there are operations in the RHS which are unsequenced
10652 // with respect to operations outside the RHS, and those operations
10653 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +000010654 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010655 }
Richard Smithc406cb72013-01-17 01:17:56 +000010656 }
10657 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +000010658 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010659 {
10660 SequencedSubexpression Sequenced(*this);
10661 Visit(BO->getLHS());
10662 }
10663
10664 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010665 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010666 if (Result)
10667 Visit(BO->getRHS());
10668 } else {
Richard Smithd33f5202013-01-17 23:18:09 +000010669 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010670 }
Richard Smithc406cb72013-01-17 01:17:56 +000010671 }
10672
10673 // Only visit the condition, unless we can be sure which subexpression will
10674 // be chosen.
10675 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +000010676 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +000010677 {
10678 SequencedSubexpression Sequenced(*this);
10679 Visit(CO->getCond());
10680 }
Richard Smithc406cb72013-01-17 01:17:56 +000010681
10682 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010683 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +000010684 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010685 else {
Richard Smithd33f5202013-01-17 23:18:09 +000010686 WorkList.push_back(CO->getTrueExpr());
10687 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010688 }
Richard Smithc406cb72013-01-17 01:17:56 +000010689 }
10690
Richard Smithe3dbfe02013-06-30 10:40:20 +000010691 void VisitCallExpr(CallExpr *CE) {
10692 // C++11 [intro.execution]p15:
10693 // When calling a function [...], every value computation and side effect
10694 // associated with any argument expression, or with the postfix expression
10695 // designating the called function, is sequenced before execution of every
10696 // expression or statement in the body of the function [and thus before
10697 // the value computation of its result].
10698 SequencedSubexpression Sequenced(*this);
10699 Base::VisitCallExpr(CE);
10700
10701 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10702 }
10703
Richard Smithc406cb72013-01-17 01:17:56 +000010704 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +000010705 // This is a call, so all subexpressions are sequenced before the result.
10706 SequencedSubexpression Sequenced(*this);
10707
Richard Smithc406cb72013-01-17 01:17:56 +000010708 if (!CCE->isListInitialization())
10709 return VisitExpr(CCE);
10710
10711 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010712 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010713 SequenceTree::Seq Parent = Region;
10714 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10715 E = CCE->arg_end();
10716 I != E; ++I) {
10717 Region = Tree.allocate(Parent);
10718 Elts.push_back(Region);
10719 Visit(*I);
10720 }
10721
10722 // Forget that the initializers are sequenced.
10723 Region = Parent;
10724 for (unsigned I = 0; I < Elts.size(); ++I)
10725 Tree.merge(Elts[I]);
10726 }
10727
10728 void VisitInitListExpr(InitListExpr *ILE) {
10729 if (!SemaRef.getLangOpts().CPlusPlus11)
10730 return VisitExpr(ILE);
10731
10732 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010733 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010734 SequenceTree::Seq Parent = Region;
10735 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10736 Expr *E = ILE->getInit(I);
10737 if (!E) continue;
10738 Region = Tree.allocate(Parent);
10739 Elts.push_back(Region);
10740 Visit(E);
10741 }
10742
10743 // Forget that the initializers are sequenced.
10744 Region = Parent;
10745 for (unsigned I = 0; I < Elts.size(); ++I)
10746 Tree.merge(Elts[I]);
10747 }
10748};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010749
10750} // namespace
Richard Smithc406cb72013-01-17 01:17:56 +000010751
10752void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010753 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +000010754 WorkList.push_back(E);
10755 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +000010756 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +000010757 SequenceChecker(*this, Item, WorkList);
10758 }
Richard Smithc406cb72013-01-17 01:17:56 +000010759}
10760
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010761void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10762 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +000010763 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +000010764 if (!E->isInstantiationDependent())
10765 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010766 if (!IsConstexpr && !E->isValueDependent())
Richard Smith9f7df0c2017-06-26 23:19:32 +000010767 CheckForIntOverflow(E);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000010768 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +000010769}
10770
John McCall1f425642010-11-11 03:21:53 +000010771void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10772 FieldDecl *BitField,
10773 Expr *Init) {
10774 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10775}
10776
David Majnemer61a5bbf2015-04-07 22:08:51 +000010777static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
10778 SourceLocation Loc) {
10779 if (!PType->isVariablyModifiedType())
10780 return;
10781 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10782 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10783 return;
10784 }
David Majnemerdf8f73f2015-04-09 19:53:25 +000010785 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10786 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10787 return;
10788 }
David Majnemer61a5bbf2015-04-07 22:08:51 +000010789 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10790 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10791 return;
10792 }
10793
10794 const ArrayType *AT = S.Context.getAsArrayType(PType);
10795 if (!AT)
10796 return;
10797
10798 if (AT->getSizeModifier() != ArrayType::Star) {
10799 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
10800 return;
10801 }
10802
10803 S.Diag(Loc, diag::err_array_star_in_function_definition);
10804}
10805
Mike Stump0c2ec772010-01-21 03:59:47 +000010806/// CheckParmsForFunctionDef - Check that the parameters of the given
10807/// function are appropriate for the definition of a function. This
10808/// takes care of any checks that cannot be performed on the
10809/// declaration itself, e.g., that the types of each of the function
10810/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +000010811bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +000010812 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010813 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +000010814 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010815 // C99 6.7.5.3p4: the parameters in a parameter type list in a
10816 // function declarator that is part of a function definition of
10817 // that function shall not have incomplete type.
10818 //
10819 // This is also C++ [dcl.fct]p6.
10820 if (!Param->isInvalidDecl() &&
10821 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000010822 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010823 Param->setInvalidDecl();
10824 HasInvalidParm = true;
10825 }
10826
10827 // C99 6.9.1p5: If the declarator includes a parameter type list, the
10828 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +000010829 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +000010830 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +000010831 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000010832 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +000010833 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +000010834
10835 // C99 6.7.5.3p12:
10836 // If the function declarator is not part of a definition of that
10837 // function, parameters may have incomplete type and may use the [*]
10838 // notation in their sequences of declarator specifiers to specify
10839 // variable length array types.
10840 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +000010841 // FIXME: This diagnostic should point the '[*]' if source-location
10842 // information is added for it.
10843 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010844
Akira Hatanaka02914dc2018-02-05 20:23:22 +000010845 // If the parameter is a c++ class type and it has to be destructed in the
10846 // callee function, declare the destructor so that it can be called by the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +000010847 // callee function. Do not perform any direct access check on the dtor here.
Akira Hatanaka02914dc2018-02-05 20:23:22 +000010848 if (!Param->isInvalidDecl()) {
10849 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
10850 if (!ClassDecl->isInvalidDecl() &&
10851 !ClassDecl->hasIrrelevantDestructor() &&
10852 !ClassDecl->isDependentContext() &&
10853 Context.isParamDestroyedInCallee(Param->getType())) {
10854 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10855 MarkFunctionReferenced(Param->getLocation(), Destructor);
10856 DiagnoseUseOfDecl(Destructor, Param->getLocation());
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010857 }
10858 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010859 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010860
10861 // Parameters with the pass_object_size attribute only need to be marked
10862 // constant at function definitions. Because we lack information about
10863 // whether we're on a declaration or definition when we're instantiating the
10864 // attribute, we need to check for constness here.
10865 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
10866 if (!Param->getType().isConstQualified())
10867 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10868 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +000010869 }
10870
10871 return HasInvalidParm;
10872}
John McCall2b5c1b22010-08-12 21:44:57 +000010873
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000010874/// A helper function to get the alignment of a Decl referred to by DeclRefExpr
10875/// or MemberExpr.
10876static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
10877 ASTContext &Context) {
10878 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
10879 return Context.getDeclAlign(DRE->getDecl());
10880
10881 if (const auto *ME = dyn_cast<MemberExpr>(E))
10882 return Context.getDeclAlign(ME->getMemberDecl());
10883
10884 return TypeAlign;
10885}
10886
John McCall2b5c1b22010-08-12 21:44:57 +000010887/// CheckCastAlign - Implements -Wcast-align, which warns when a
10888/// pointer cast increases the alignment requirements.
10889void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
10890 // This is actually a lot of work to potentially be doing on every
10891 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010892 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +000010893 return;
10894
10895 // Ignore dependent types.
10896 if (T->isDependentType() || Op->getType()->isDependentType())
10897 return;
10898
10899 // Require that the destination be a pointer type.
10900 const PointerType *DestPtr = T->getAs<PointerType>();
10901 if (!DestPtr) return;
10902
10903 // If the destination has alignment 1, we're done.
10904 QualType DestPointee = DestPtr->getPointeeType();
10905 if (DestPointee->isIncompleteType()) return;
10906 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
10907 if (DestAlign.isOne()) return;
10908
10909 // Require that the source be a pointer type.
10910 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
10911 if (!SrcPtr) return;
10912 QualType SrcPointee = SrcPtr->getPointeeType();
10913
10914 // Whitelist casts from cv void*. We already implicitly
10915 // whitelisted casts to cv void*, since they have alignment 1.
10916 // Also whitelist casts involving incomplete types, which implicitly
10917 // includes 'void'.
10918 if (SrcPointee->isIncompleteType()) return;
10919
10920 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000010921
10922 if (auto *CE = dyn_cast<CastExpr>(Op)) {
10923 if (CE->getCastKind() == CK_ArrayToPointerDecay)
10924 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
10925 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
10926 if (UO->getOpcode() == UO_AddrOf)
10927 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
10928 }
10929
John McCall2b5c1b22010-08-12 21:44:57 +000010930 if (SrcAlign >= DestAlign) return;
10931
10932 Diag(TRange.getBegin(), diag::warn_cast_align)
10933 << Op->getType() << T
10934 << static_cast<unsigned>(SrcAlign.getQuantity())
10935 << static_cast<unsigned>(DestAlign.getQuantity())
10936 << TRange << Op->getSourceRange();
10937}
10938
Chandler Carruth28389f02011-08-05 09:10:50 +000010939/// \brief Check whether this array fits the idiom of a size-one tail padded
10940/// array member of a struct.
10941///
10942/// We avoid emitting out-of-bounds access warnings for such arrays as they are
10943/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +000010944static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +000010945 const NamedDecl *ND) {
10946 if (Size != 1 || !ND) return false;
10947
10948 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
10949 if (!FD) return false;
10950
10951 // Don't consider sizes resulting from macro expansions or template argument
10952 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +000010953
10954 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010955 while (TInfo) {
10956 TypeLoc TL = TInfo->getTypeLoc();
10957 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +000010958 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
10959 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010960 TInfo = TDL->getTypeSourceInfo();
10961 continue;
10962 }
David Blaikie6adc78e2013-02-18 22:06:02 +000010963 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
10964 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +000010965 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
10966 return false;
10967 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010968 break;
Sean Callanan06a48a62012-05-04 18:22:53 +000010969 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010970
10971 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +000010972 if (!RD) return false;
10973 if (RD->isUnion()) return false;
10974 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10975 if (!CRD->isStandardLayout()) return false;
10976 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010977
Benjamin Kramer8c543672011-08-06 03:04:42 +000010978 // See if this is the last field decl in the record.
10979 const Decl *D = FD;
10980 while ((D = D->getNextDeclInContext()))
10981 if (isa<FieldDecl>(D))
10982 return false;
10983 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +000010984}
10985
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010986void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010987 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +000010988 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010989 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010990 if (IndexExpr->isValueDependent())
10991 return;
10992
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010993 const Type *EffectiveType =
10994 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010995 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010996 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010997 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010998 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +000010999 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +000011000
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011001 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +000011002 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +000011003 return;
Richard Smith13f67182011-12-16 19:31:14 +000011004 if (IndexNegated)
11005 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +000011006
Craig Topperc3ec1492014-05-26 06:22:03 +000011007 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +000011008 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011009 ND = DRE->getDecl();
Chandler Carruth28389f02011-08-05 09:10:50 +000011010 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011011 ND = ME->getMemberDecl();
Chandler Carruth126b1552011-08-05 08:07:29 +000011012
Ted Kremeneke4b316c2011-02-23 23:06:04 +000011013 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011014 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +000011015 if (!size.isStrictlyPositive())
11016 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011017
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000011018 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +000011019 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011020 // Make sure we're comparing apples to apples when comparing index to size
11021 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
11022 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +000011023 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +000011024 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011025 if (ptrarith_typesize != array_typesize) {
11026 // There's a cast to a different size type involved
11027 uint64_t ratio = array_typesize / ptrarith_typesize;
11028 // TODO: Be smarter about handling cases where array_typesize is not a
11029 // multiple of ptrarith_typesize
11030 if (ptrarith_typesize * ratio == array_typesize)
11031 size *= llvm::APInt(size.getBitWidth(), ratio);
11032 }
11033 }
11034
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011035 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011036 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011037 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011038 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011039
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011040 // For array subscripting the index must be less than size, but for pointer
11041 // arithmetic also allow the index (offset) to be equal to size since
11042 // computing the next address after the end of the array is legal and
11043 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011044 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +000011045 return;
11046
11047 // Also don't warn for arrays of size 1 which are members of some
11048 // structure. These are often used to approximate flexible arrays in C89
11049 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011050 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +000011051 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011052
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011053 // Suppress the warning if the subscript expression (as identified by the
11054 // ']' location) and the index expression are both from macro expansions
11055 // within a system header.
11056 if (ASE) {
11057 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
11058 ASE->getRBracketLoc());
11059 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
11060 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
11061 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +000011062 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011063 return;
11064 }
11065 }
11066
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011067 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011068 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011069 DiagID = diag::warn_array_index_exceeds_bounds;
11070
11071 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11072 PDiag(DiagID) << index.toString(10, true)
11073 << size.toString(10, true)
11074 << (unsigned)size.getLimitedValue(~0U)
11075 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011076 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011077 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011078 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011079 DiagID = diag::warn_ptr_arith_precedes_bounds;
11080 if (index.isNegative()) index = -index;
11081 }
11082
11083 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11084 PDiag(DiagID) << index.toString(10, true)
11085 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +000011086 }
Chandler Carruth1af88f12011-02-17 21:10:52 +000011087
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000011088 if (!ND) {
11089 // Try harder to find a NamedDecl to point at in the note.
11090 while (const ArraySubscriptExpr *ASE =
11091 dyn_cast<ArraySubscriptExpr>(BaseExpr))
11092 BaseExpr = ASE->getBase()->IgnoreParenCasts();
11093 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011094 ND = DRE->getDecl();
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000011095 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011096 ND = ME->getMemberDecl();
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000011097 }
11098
Chandler Carruth1af88f12011-02-17 21:10:52 +000011099 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011100 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
11101 PDiag(diag::note_array_index_out_of_bounds)
11102 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +000011103}
11104
Ted Kremenekdf26df72011-03-01 18:41:00 +000011105void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011106 int AllowOnePastEnd = 0;
11107 while (expr) {
11108 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +000011109 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011110 case Stmt::ArraySubscriptExprClass: {
11111 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011112 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011113 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +000011114 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011115 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +000011116 case Stmt::OMPArraySectionExprClass: {
11117 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
11118 if (ASE->getLowerBound())
11119 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
11120 /*ASE=*/nullptr, AllowOnePastEnd > 0);
11121 return;
11122 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011123 case Stmt::UnaryOperatorClass: {
11124 // Only unwrap the * and & unary operators
11125 const UnaryOperator *UO = cast<UnaryOperator>(expr);
11126 expr = UO->getSubExpr();
11127 switch (UO->getOpcode()) {
11128 case UO_AddrOf:
11129 AllowOnePastEnd++;
11130 break;
11131 case UO_Deref:
11132 AllowOnePastEnd--;
11133 break;
11134 default:
11135 return;
11136 }
11137 break;
11138 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011139 case Stmt::ConditionalOperatorClass: {
11140 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
11141 if (const Expr *lhs = cond->getLHS())
11142 CheckArrayAccess(lhs);
11143 if (const Expr *rhs = cond->getRHS())
11144 CheckArrayAccess(rhs);
11145 return;
11146 }
Daniel Marjamaki20a209e2017-02-28 14:53:50 +000011147 case Stmt::CXXOperatorCallExprClass: {
11148 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
11149 for (const auto *Arg : OCE->arguments())
11150 CheckArrayAccess(Arg);
11151 return;
11152 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011153 default:
11154 return;
11155 }
Peter Collingbourne91147592011-04-15 00:35:48 +000011156 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011157}
John McCall31168b02011-06-15 23:02:42 +000011158
11159//===--- CHECK: Objective-C retain cycles ----------------------------------//
11160
11161namespace {
John McCall31168b02011-06-15 23:02:42 +000011162
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011163struct RetainCycleOwner {
11164 VarDecl *Variable = nullptr;
11165 SourceRange Range;
11166 SourceLocation Loc;
11167 bool Indirect = false;
11168
11169 RetainCycleOwner() = default;
11170
11171 void setLocsFrom(Expr *e) {
11172 Loc = e->getExprLoc();
11173 Range = e->getSourceRange();
11174 }
11175};
11176
11177} // namespace
John McCall31168b02011-06-15 23:02:42 +000011178
11179/// Consider whether capturing the given variable can possibly lead to
11180/// a retain cycle.
11181static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000011182 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +000011183 // lifetime. In MRR, it's captured strongly if the variable is
11184 // __block and has an appropriate type.
11185 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11186 return false;
11187
11188 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011189 if (ref)
11190 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +000011191 return true;
11192}
11193
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011194static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +000011195 while (true) {
11196 e = e->IgnoreParens();
11197 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
11198 switch (cast->getCastKind()) {
11199 case CK_BitCast:
11200 case CK_LValueBitCast:
11201 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +000011202 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +000011203 e = cast->getSubExpr();
11204 continue;
11205
John McCall31168b02011-06-15 23:02:42 +000011206 default:
11207 return false;
11208 }
11209 }
11210
11211 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
11212 ObjCIvarDecl *ivar = ref->getDecl();
11213 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11214 return false;
11215
11216 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011217 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +000011218 return false;
11219
11220 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
11221 owner.Indirect = true;
11222 return true;
11223 }
11224
11225 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
11226 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
11227 if (!var) return false;
11228 return considerVariable(var, ref, owner);
11229 }
11230
John McCall31168b02011-06-15 23:02:42 +000011231 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
11232 if (member->isArrow()) return false;
11233
11234 // Don't count this as an indirect ownership.
11235 e = member->getBase();
11236 continue;
11237 }
11238
John McCallfe96e0b2011-11-06 09:01:30 +000011239 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
11240 // Only pay attention to pseudo-objects on property references.
11241 ObjCPropertyRefExpr *pre
11242 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
11243 ->IgnoreParens());
11244 if (!pre) return false;
11245 if (pre->isImplicitProperty()) return false;
11246 ObjCPropertyDecl *property = pre->getExplicitProperty();
11247 if (!property->isRetaining() &&
11248 !(property->getPropertyIvarDecl() &&
11249 property->getPropertyIvarDecl()->getType()
11250 .getObjCLifetime() == Qualifiers::OCL_Strong))
11251 return false;
11252
11253 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011254 if (pre->isSuperReceiver()) {
11255 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
11256 if (!owner.Variable)
11257 return false;
11258 owner.Loc = pre->getLocation();
11259 owner.Range = pre->getSourceRange();
11260 return true;
11261 }
John McCallfe96e0b2011-11-06 09:01:30 +000011262 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
11263 ->getSourceExpr());
11264 continue;
11265 }
11266
John McCall31168b02011-06-15 23:02:42 +000011267 // Array ivars?
11268
11269 return false;
11270 }
11271}
11272
11273namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011274
John McCall31168b02011-06-15 23:02:42 +000011275 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011276 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +000011277 VarDecl *Variable;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011278 Expr *Capturer = nullptr;
11279 bool VarWillBeReased = false;
11280
11281 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
11282 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
11283 Context(Context), Variable(variable) {}
John McCall31168b02011-06-15 23:02:42 +000011284
11285 void VisitDeclRefExpr(DeclRefExpr *ref) {
11286 if (ref->getDecl() == Variable && !Capturer)
11287 Capturer = ref;
11288 }
11289
John McCall31168b02011-06-15 23:02:42 +000011290 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
11291 if (Capturer) return;
11292 Visit(ref->getBase());
11293 if (Capturer && ref->isFreeIvar())
11294 Capturer = ref;
11295 }
11296
11297 void VisitBlockExpr(BlockExpr *block) {
11298 // Look inside nested blocks
11299 if (block->getBlockDecl()->capturesVariable(Variable))
11300 Visit(block->getBlockDecl()->getBody());
11301 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +000011302
11303 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
11304 if (Capturer) return;
11305 if (OVE->getSourceExpr())
11306 Visit(OVE->getSourceExpr());
11307 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011308
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011309 void VisitBinaryOperator(BinaryOperator *BinOp) {
11310 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
11311 return;
11312 Expr *LHS = BinOp->getLHS();
11313 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
11314 if (DRE->getDecl() != Variable)
11315 return;
11316 if (Expr *RHS = BinOp->getRHS()) {
11317 RHS = RHS->IgnoreParenCasts();
11318 llvm::APSInt Value;
11319 VarWillBeReased =
11320 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
11321 }
11322 }
11323 }
John McCall31168b02011-06-15 23:02:42 +000011324 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011325
11326} // namespace
John McCall31168b02011-06-15 23:02:42 +000011327
11328/// Check whether the given argument is a block which captures a
11329/// variable.
11330static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
11331 assert(owner.Variable && owner.Loc.isValid());
11332
11333 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000011334
11335 // Look through [^{...} copy] and Block_copy(^{...}).
11336 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
11337 Selector Cmd = ME->getSelector();
11338 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
11339 e = ME->getInstanceReceiver();
11340 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000011341 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000011342 e = e->IgnoreParenCasts();
11343 }
11344 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
11345 if (CE->getNumArgs() == 1) {
11346 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000011347 if (Fn) {
11348 const IdentifierInfo *FnI = Fn->getIdentifier();
11349 if (FnI && FnI->isStr("_Block_copy")) {
11350 e = CE->getArg(0)->IgnoreParenCasts();
11351 }
11352 }
Jordan Rose67e887c2012-09-17 17:54:30 +000011353 }
11354 }
11355
John McCall31168b02011-06-15 23:02:42 +000011356 BlockExpr *block = dyn_cast<BlockExpr>(e);
11357 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000011358 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000011359
11360 FindCaptureVisitor visitor(S.Context, owner.Variable);
11361 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011362 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000011363}
11364
11365static void diagnoseRetainCycle(Sema &S, Expr *capturer,
11366 RetainCycleOwner &owner) {
11367 assert(capturer);
11368 assert(owner.Variable && owner.Loc.isValid());
11369
11370 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
11371 << owner.Variable << capturer->getSourceRange();
11372 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
11373 << owner.Indirect << owner.Range;
11374}
11375
11376/// Check for a keyword selector that starts with the word 'add' or
11377/// 'set'.
11378static bool isSetterLikeSelector(Selector sel) {
11379 if (sel.isUnarySelector()) return false;
11380
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011381 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000011382 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011383 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000011384 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011385 else if (str.startswith("add")) {
11386 // Specially whitelist 'addOperationWithBlock:'.
11387 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
11388 return false;
11389 str = str.substr(3);
11390 }
John McCall31168b02011-06-15 23:02:42 +000011391 else
11392 return false;
11393
11394 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000011395 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000011396}
11397
Benjamin Kramer3a743452015-03-09 15:03:32 +000011398static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
11399 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011400 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
11401 Message->getReceiverInterface(),
11402 NSAPI::ClassId_NSMutableArray);
11403 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011404 return None;
11405 }
11406
11407 Selector Sel = Message->getSelector();
11408
11409 Optional<NSAPI::NSArrayMethodKind> MKOpt =
11410 S.NSAPIObj->getNSArrayMethodKind(Sel);
11411 if (!MKOpt) {
11412 return None;
11413 }
11414
11415 NSAPI::NSArrayMethodKind MK = *MKOpt;
11416
11417 switch (MK) {
11418 case NSAPI::NSMutableArr_addObject:
11419 case NSAPI::NSMutableArr_insertObjectAtIndex:
11420 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
11421 return 0;
11422 case NSAPI::NSMutableArr_replaceObjectAtIndex:
11423 return 1;
11424
11425 default:
11426 return None;
11427 }
11428
11429 return None;
11430}
11431
11432static
11433Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
11434 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011435 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
11436 Message->getReceiverInterface(),
11437 NSAPI::ClassId_NSMutableDictionary);
11438 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011439 return None;
11440 }
11441
11442 Selector Sel = Message->getSelector();
11443
11444 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
11445 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
11446 if (!MKOpt) {
11447 return None;
11448 }
11449
11450 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
11451
11452 switch (MK) {
11453 case NSAPI::NSMutableDict_setObjectForKey:
11454 case NSAPI::NSMutableDict_setValueForKey:
11455 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
11456 return 0;
11457
11458 default:
11459 return None;
11460 }
11461
11462 return None;
11463}
11464
11465static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011466 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
11467 Message->getReceiverInterface(),
11468 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000011469
Alex Denisov5dfac812015-08-06 04:51:14 +000011470 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
11471 Message->getReceiverInterface(),
11472 NSAPI::ClassId_NSMutableOrderedSet);
11473 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011474 return None;
11475 }
11476
11477 Selector Sel = Message->getSelector();
11478
11479 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
11480 if (!MKOpt) {
11481 return None;
11482 }
11483
11484 NSAPI::NSSetMethodKind MK = *MKOpt;
11485
11486 switch (MK) {
11487 case NSAPI::NSMutableSet_addObject:
11488 case NSAPI::NSOrderedSet_setObjectAtIndex:
11489 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
11490 case NSAPI::NSOrderedSet_insertObjectAtIndex:
11491 return 0;
11492 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
11493 return 1;
11494 }
11495
11496 return None;
11497}
11498
11499void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
11500 if (!Message->isInstanceMessage()) {
11501 return;
11502 }
11503
11504 Optional<int> ArgOpt;
11505
11506 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
11507 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
11508 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
11509 return;
11510 }
11511
11512 int ArgIndex = *ArgOpt;
11513
Alex Denisove1d882c2015-03-04 17:55:52 +000011514 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
11515 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
11516 Arg = OE->getSourceExpr()->IgnoreImpCasts();
11517 }
11518
Alex Denisov5dfac812015-08-06 04:51:14 +000011519 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011520 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011521 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011522 Diag(Message->getSourceRange().getBegin(),
11523 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000011524 << ArgRE->getDecl() << StringRef("'super'");
Alex Denisove1d882c2015-03-04 17:55:52 +000011525 }
11526 }
Alex Denisov5dfac812015-08-06 04:51:14 +000011527 } else {
11528 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
11529
11530 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
11531 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
11532 }
11533
11534 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
11535 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11536 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
11537 ValueDecl *Decl = ReceiverRE->getDecl();
11538 Diag(Message->getSourceRange().getBegin(),
11539 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000011540 << Decl << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000011541 if (!ArgRE->isObjCSelfExpr()) {
11542 Diag(Decl->getLocation(),
11543 diag::note_objc_circular_container_declared_here)
Richard Trieub4025802018-03-28 04:16:13 +000011544 << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000011545 }
11546 }
11547 }
11548 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
11549 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
11550 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
11551 ObjCIvarDecl *Decl = IvarRE->getDecl();
11552 Diag(Message->getSourceRange().getBegin(),
11553 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000011554 << Decl << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000011555 Diag(Decl->getLocation(),
11556 diag::note_objc_circular_container_declared_here)
Richard Trieub4025802018-03-28 04:16:13 +000011557 << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000011558 }
Alex Denisove1d882c2015-03-04 17:55:52 +000011559 }
11560 }
11561 }
Alex Denisove1d882c2015-03-04 17:55:52 +000011562}
11563
John McCall31168b02011-06-15 23:02:42 +000011564/// Check a message send to see if it's likely to cause a retain cycle.
11565void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
11566 // Only check instance methods whose selector looks like a setter.
11567 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
11568 return;
11569
11570 // Try to find a variable that the receiver is strongly owned by.
11571 RetainCycleOwner owner;
11572 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011573 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000011574 return;
11575 } else {
11576 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
11577 owner.Variable = getCurMethodDecl()->getSelfDecl();
11578 owner.Loc = msg->getSuperLoc();
11579 owner.Range = msg->getSuperLoc();
11580 }
11581
11582 // Check whether the receiver is captured by any of the arguments.
Alex Lorenz42a97a92017-11-17 20:44:25 +000011583 const ObjCMethodDecl *MD = msg->getMethodDecl();
11584 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
11585 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
11586 // noescape blocks should not be retained by the method.
11587 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
11588 continue;
John McCall31168b02011-06-15 23:02:42 +000011589 return diagnoseRetainCycle(*this, capturer, owner);
Alex Lorenz42a97a92017-11-17 20:44:25 +000011590 }
11591 }
John McCall31168b02011-06-15 23:02:42 +000011592}
11593
11594/// Check a property assign to see if it's likely to cause a retain cycle.
11595void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
11596 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011597 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000011598 return;
11599
11600 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
11601 diagnoseRetainCycle(*this, capturer, owner);
11602}
11603
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011604void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
11605 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000011606 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011607 return;
11608
11609 // Because we don't have an expression for the variable, we have to set the
11610 // location explicitly here.
11611 Owner.Loc = Var->getLocation();
11612 Owner.Range = Var->getSourceRange();
11613
11614 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
11615 diagnoseRetainCycle(*this, Capturer, Owner);
11616}
11617
Ted Kremenek9304da92012-12-21 08:04:28 +000011618static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
11619 Expr *RHS, bool isProperty) {
11620 // Check if RHS is an Objective-C object literal, which also can get
11621 // immediately zapped in a weak reference. Note that we explicitly
11622 // allow ObjCStringLiterals, since those are designed to never really die.
11623 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011624
Ted Kremenek64873352012-12-21 22:46:35 +000011625 // This enum needs to match with the 'select' in
11626 // warn_objc_arc_literal_assign (off-by-1).
11627 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
11628 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
11629 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011630
11631 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000011632 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000011633 << (isProperty ? 0 : 1)
11634 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011635
11636 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000011637}
11638
Ted Kremenekc1f014a2012-12-21 19:45:30 +000011639static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
11640 Qualifiers::ObjCLifetime LT,
11641 Expr *RHS, bool isProperty) {
11642 // Strip off any implicit cast added to get to the one ARC-specific.
11643 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11644 if (cast->getCastKind() == CK_ARCConsumeObject) {
11645 S.Diag(Loc, diag::warn_arc_retained_assign)
11646 << (LT == Qualifiers::OCL_ExplicitNone)
11647 << (isProperty ? 0 : 1)
11648 << RHS->getSourceRange();
11649 return true;
11650 }
11651 RHS = cast->getSubExpr();
11652 }
11653
11654 if (LT == Qualifiers::OCL_Weak &&
11655 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
11656 return true;
11657
11658 return false;
11659}
11660
Ted Kremenekb36234d2012-12-21 08:04:20 +000011661bool Sema::checkUnsafeAssigns(SourceLocation Loc,
11662 QualType LHS, Expr *RHS) {
11663 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
11664
11665 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
11666 return false;
11667
11668 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
11669 return true;
11670
11671 return false;
11672}
11673
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011674void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
11675 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011676 QualType LHSType;
11677 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000011678 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011679 ObjCPropertyRefExpr *PRE
11680 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11681 if (PRE && !PRE->isImplicitProperty()) {
11682 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11683 if (PD)
11684 LHSType = PD->getType();
11685 }
11686
11687 if (LHSType.isNull())
11688 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000011689
11690 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
11691
11692 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011693 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000011694 getCurFunction()->markSafeWeakUse(LHS);
11695 }
11696
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011697 if (checkUnsafeAssigns(Loc, LHSType, RHS))
11698 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000011699
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011700 // FIXME. Check for other life times.
11701 if (LT != Qualifiers::OCL_None)
11702 return;
11703
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011704 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011705 if (PRE->isImplicitProperty())
11706 return;
11707 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11708 if (!PD)
11709 return;
11710
Bill Wendling44426052012-12-20 19:22:21 +000011711 unsigned Attributes = PD->getPropertyAttributes();
11712 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011713 // when 'assign' attribute was not explicitly specified
11714 // by user, ignore it and rely on property type itself
11715 // for lifetime info.
11716 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11717 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11718 LHSType->isObjCRetainableType())
11719 return;
11720
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011721 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000011722 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011723 Diag(Loc, diag::warn_arc_retained_property_assign)
11724 << RHS->getSourceRange();
11725 return;
11726 }
11727 RHS = cast->getSubExpr();
11728 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011729 }
Bill Wendling44426052012-12-20 19:22:21 +000011730 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000011731 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11732 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000011733 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011734 }
11735}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011736
11737//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11738
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011739static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11740 SourceLocation StmtLoc,
11741 const NullStmt *Body) {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011742 // Do not warn if the body is a macro that expands to nothing, e.g:
11743 //
11744 // #define CALL(x)
11745 // if (condition)
11746 // CALL(0);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011747 if (Body->hasLeadingEmptyMacro())
11748 return false;
11749
11750 // Get line numbers of statement and body.
11751 bool StmtLineInvalid;
Hans Wennborg95419752017-11-20 17:38:16 +000011752 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011753 &StmtLineInvalid);
11754 if (StmtLineInvalid)
11755 return false;
11756
11757 bool BodyLineInvalid;
11758 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11759 &BodyLineInvalid);
11760 if (BodyLineInvalid)
11761 return false;
11762
11763 // Warn if null statement and body are on the same line.
11764 if (StmtLine != BodyLine)
11765 return false;
11766
11767 return true;
11768}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011769
11770void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
11771 const Stmt *Body,
11772 unsigned DiagID) {
11773 // Since this is a syntactic check, don't emit diagnostic for template
11774 // instantiations, this just adds noise.
11775 if (CurrentInstantiationScope)
11776 return;
11777
11778 // The body should be a null statement.
11779 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11780 if (!NBody)
11781 return;
11782
11783 // Do the usual checks.
11784 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11785 return;
11786
11787 Diag(NBody->getSemiLoc(), DiagID);
11788 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11789}
11790
11791void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
11792 const Stmt *PossibleBody) {
11793 assert(!CurrentInstantiationScope); // Ensured by caller
11794
11795 SourceLocation StmtLoc;
11796 const Stmt *Body;
11797 unsigned DiagID;
11798 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11799 StmtLoc = FS->getRParenLoc();
11800 Body = FS->getBody();
11801 DiagID = diag::warn_empty_for_body;
11802 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11803 StmtLoc = WS->getCond()->getSourceRange().getEnd();
11804 Body = WS->getBody();
11805 DiagID = diag::warn_empty_while_body;
11806 } else
11807 return; // Neither `for' nor `while'.
11808
11809 // The body should be a null statement.
11810 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11811 if (!NBody)
11812 return;
11813
11814 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011815 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011816 return;
11817
11818 // Do the usual checks.
11819 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11820 return;
11821
11822 // `for(...);' and `while(...);' are popular idioms, so in order to keep
11823 // noise level low, emit diagnostics only if for/while is followed by a
11824 // CompoundStmt, e.g.:
11825 // for (int i = 0; i < n; i++);
11826 // {
11827 // a(i);
11828 // }
11829 // or if for/while is followed by a statement with more indentation
11830 // than for/while itself:
11831 // for (int i = 0; i < n; i++);
11832 // a(i);
11833 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
11834 if (!ProbableTypo) {
11835 bool BodyColInvalid;
11836 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
11837 PossibleBody->getLocStart(),
11838 &BodyColInvalid);
11839 if (BodyColInvalid)
11840 return;
11841
11842 bool StmtColInvalid;
11843 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
11844 S->getLocStart(),
11845 &StmtColInvalid);
11846 if (StmtColInvalid)
11847 return;
11848
11849 if (BodyCol > StmtCol)
11850 ProbableTypo = true;
11851 }
11852
11853 if (ProbableTypo) {
11854 Diag(NBody->getSemiLoc(), DiagID);
11855 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11856 }
11857}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011858
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011859//===--- CHECK: Warn on self move with std::move. -------------------------===//
11860
11861/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
11862void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
11863 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011864 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11865 return;
11866
Richard Smith51ec0cf2017-02-21 01:17:38 +000011867 if (inTemplateInstantiation())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011868 return;
11869
11870 // Strip parens and casts away.
11871 LHSExpr = LHSExpr->IgnoreParenImpCasts();
11872 RHSExpr = RHSExpr->IgnoreParenImpCasts();
11873
11874 // Check for a call expression
11875 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
11876 if (!CE || CE->getNumArgs() != 1)
11877 return;
11878
11879 // Check for a call to std::move
Nico Weberb688d132017-09-28 16:16:39 +000011880 if (!CE->isCallToStdMove())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011881 return;
11882
11883 // Get argument from std::move
11884 RHSExpr = CE->getArg(0);
11885
11886 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11887 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11888
11889 // Two DeclRefExpr's, check that the decls are the same.
11890 if (LHSDeclRef && RHSDeclRef) {
11891 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11892 return;
11893 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11894 RHSDeclRef->getDecl()->getCanonicalDecl())
11895 return;
11896
11897 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11898 << LHSExpr->getSourceRange()
11899 << RHSExpr->getSourceRange();
11900 return;
11901 }
11902
11903 // Member variables require a different approach to check for self moves.
11904 // MemberExpr's are the same if every nested MemberExpr refers to the same
11905 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
11906 // the base Expr's are CXXThisExpr's.
11907 const Expr *LHSBase = LHSExpr;
11908 const Expr *RHSBase = RHSExpr;
11909 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
11910 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
11911 if (!LHSME || !RHSME)
11912 return;
11913
11914 while (LHSME && RHSME) {
11915 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
11916 RHSME->getMemberDecl()->getCanonicalDecl())
11917 return;
11918
11919 LHSBase = LHSME->getBase();
11920 RHSBase = RHSME->getBase();
11921 LHSME = dyn_cast<MemberExpr>(LHSBase);
11922 RHSME = dyn_cast<MemberExpr>(RHSBase);
11923 }
11924
11925 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
11926 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
11927 if (LHSDeclRef && RHSDeclRef) {
11928 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11929 return;
11930 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11931 RHSDeclRef->getDecl()->getCanonicalDecl())
11932 return;
11933
11934 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11935 << LHSExpr->getSourceRange()
11936 << RHSExpr->getSourceRange();
11937 return;
11938 }
11939
11940 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
11941 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11942 << LHSExpr->getSourceRange()
11943 << RHSExpr->getSourceRange();
11944}
11945
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011946//===--- Layout compatibility ----------------------------------------------//
11947
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011948static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011949
11950/// \brief Check if two enumeration types are layout-compatible.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011951static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011952 // C++11 [dcl.enum] p8:
11953 // Two enumeration types are layout-compatible if they have the same
11954 // underlying type.
11955 return ED1->isComplete() && ED2->isComplete() &&
11956 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
11957}
11958
11959/// \brief Check if two fields are layout-compatible.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011960static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
11961 FieldDecl *Field2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011962 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
11963 return false;
11964
11965 if (Field1->isBitField() != Field2->isBitField())
11966 return false;
11967
11968 if (Field1->isBitField()) {
11969 // Make sure that the bit-fields are the same length.
11970 unsigned Bits1 = Field1->getBitWidthValue(C);
11971 unsigned Bits2 = Field2->getBitWidthValue(C);
11972
11973 if (Bits1 != Bits2)
11974 return false;
11975 }
11976
11977 return true;
11978}
11979
11980/// \brief Check if two standard-layout structs are layout-compatible.
11981/// (C++11 [class.mem] p17)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011982static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
11983 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011984 // If both records are C++ classes, check that base classes match.
11985 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
11986 // If one of records is a CXXRecordDecl we are in C++ mode,
11987 // thus the other one is a CXXRecordDecl, too.
11988 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
11989 // Check number of base classes.
11990 if (D1CXX->getNumBases() != D2CXX->getNumBases())
11991 return false;
11992
11993 // Check the base classes.
11994 for (CXXRecordDecl::base_class_const_iterator
11995 Base1 = D1CXX->bases_begin(),
11996 BaseEnd1 = D1CXX->bases_end(),
11997 Base2 = D2CXX->bases_begin();
11998 Base1 != BaseEnd1;
11999 ++Base1, ++Base2) {
12000 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
12001 return false;
12002 }
12003 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
12004 // If only RD2 is a C++ class, it should have zero base classes.
12005 if (D2CXX->getNumBases() > 0)
12006 return false;
12007 }
12008
12009 // Check the fields.
12010 RecordDecl::field_iterator Field2 = RD2->field_begin(),
12011 Field2End = RD2->field_end(),
12012 Field1 = RD1->field_begin(),
12013 Field1End = RD1->field_end();
12014 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
12015 if (!isLayoutCompatible(C, *Field1, *Field2))
12016 return false;
12017 }
12018 if (Field1 != Field1End || Field2 != Field2End)
12019 return false;
12020
12021 return true;
12022}
12023
12024/// \brief Check if two standard-layout unions are layout-compatible.
12025/// (C++11 [class.mem] p18)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012026static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
12027 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012028 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012029 for (auto *Field2 : RD2->fields())
12030 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012031
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012032 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012033 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
12034 I = UnmatchedFields.begin(),
12035 E = UnmatchedFields.end();
12036
12037 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012038 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012039 bool Result = UnmatchedFields.erase(*I);
12040 (void) Result;
12041 assert(Result);
12042 break;
12043 }
12044 }
12045 if (I == E)
12046 return false;
12047 }
12048
12049 return UnmatchedFields.empty();
12050}
12051
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012052static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
12053 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012054 if (RD1->isUnion() != RD2->isUnion())
12055 return false;
12056
12057 if (RD1->isUnion())
12058 return isLayoutCompatibleUnion(C, RD1, RD2);
12059 else
12060 return isLayoutCompatibleStruct(C, RD1, RD2);
12061}
12062
12063/// \brief Check if two types are layout-compatible in C++11 sense.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012064static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012065 if (T1.isNull() || T2.isNull())
12066 return false;
12067
12068 // C++11 [basic.types] p11:
12069 // If two types T1 and T2 are the same type, then T1 and T2 are
12070 // layout-compatible types.
12071 if (C.hasSameType(T1, T2))
12072 return true;
12073
12074 T1 = T1.getCanonicalType().getUnqualifiedType();
12075 T2 = T2.getCanonicalType().getUnqualifiedType();
12076
12077 const Type::TypeClass TC1 = T1->getTypeClass();
12078 const Type::TypeClass TC2 = T2->getTypeClass();
12079
12080 if (TC1 != TC2)
12081 return false;
12082
12083 if (TC1 == Type::Enum) {
12084 return isLayoutCompatible(C,
12085 cast<EnumType>(T1)->getDecl(),
12086 cast<EnumType>(T2)->getDecl());
12087 } else if (TC1 == Type::Record) {
12088 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
12089 return false;
12090
12091 return isLayoutCompatible(C,
12092 cast<RecordType>(T1)->getDecl(),
12093 cast<RecordType>(T2)->getDecl());
12094 }
12095
12096 return false;
12097}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012098
12099//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
12100
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012101/// \brief Given a type tag expression find the type tag itself.
12102///
12103/// \param TypeExpr Type tag expression, as it appears in user's code.
12104///
12105/// \param VD Declaration of an identifier that appears in a type tag.
12106///
12107/// \param MagicValue Type tag magic value.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012108static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
12109 const ValueDecl **VD, uint64_t *MagicValue) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012110 while(true) {
12111 if (!TypeExpr)
12112 return false;
12113
12114 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
12115
12116 switch (TypeExpr->getStmtClass()) {
12117 case Stmt::UnaryOperatorClass: {
12118 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
12119 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
12120 TypeExpr = UO->getSubExpr();
12121 continue;
12122 }
12123 return false;
12124 }
12125
12126 case Stmt::DeclRefExprClass: {
12127 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
12128 *VD = DRE->getDecl();
12129 return true;
12130 }
12131
12132 case Stmt::IntegerLiteralClass: {
12133 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
12134 llvm::APInt MagicValueAPInt = IL->getValue();
12135 if (MagicValueAPInt.getActiveBits() <= 64) {
12136 *MagicValue = MagicValueAPInt.getZExtValue();
12137 return true;
12138 } else
12139 return false;
12140 }
12141
12142 case Stmt::BinaryConditionalOperatorClass:
12143 case Stmt::ConditionalOperatorClass: {
12144 const AbstractConditionalOperator *ACO =
12145 cast<AbstractConditionalOperator>(TypeExpr);
12146 bool Result;
12147 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
12148 if (Result)
12149 TypeExpr = ACO->getTrueExpr();
12150 else
12151 TypeExpr = ACO->getFalseExpr();
12152 continue;
12153 }
12154 return false;
12155 }
12156
12157 case Stmt::BinaryOperatorClass: {
12158 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
12159 if (BO->getOpcode() == BO_Comma) {
12160 TypeExpr = BO->getRHS();
12161 continue;
12162 }
12163 return false;
12164 }
12165
12166 default:
12167 return false;
12168 }
12169 }
12170}
12171
12172/// \brief Retrieve the C type corresponding to type tag TypeExpr.
12173///
12174/// \param TypeExpr Expression that specifies a type tag.
12175///
12176/// \param MagicValues Registered magic values.
12177///
12178/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
12179/// kind.
12180///
12181/// \param TypeInfo Information about the corresponding C type.
12182///
12183/// \returns true if the corresponding C type was found.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012184static bool GetMatchingCType(
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012185 const IdentifierInfo *ArgumentKind,
12186 const Expr *TypeExpr, const ASTContext &Ctx,
12187 const llvm::DenseMap<Sema::TypeTagMagicValue,
12188 Sema::TypeTagData> *MagicValues,
12189 bool &FoundWrongKind,
12190 Sema::TypeTagData &TypeInfo) {
12191 FoundWrongKind = false;
12192
12193 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000012194 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012195
12196 uint64_t MagicValue;
12197
12198 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
12199 return false;
12200
12201 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000012202 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012203 if (I->getArgumentKind() != ArgumentKind) {
12204 FoundWrongKind = true;
12205 return false;
12206 }
12207 TypeInfo.Type = I->getMatchingCType();
12208 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
12209 TypeInfo.MustBeNull = I->getMustBeNull();
12210 return true;
12211 }
12212 return false;
12213 }
12214
12215 if (!MagicValues)
12216 return false;
12217
12218 llvm::DenseMap<Sema::TypeTagMagicValue,
12219 Sema::TypeTagData>::const_iterator I =
12220 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
12221 if (I == MagicValues->end())
12222 return false;
12223
12224 TypeInfo = I->second;
12225 return true;
12226}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012227
12228void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
12229 uint64_t MagicValue, QualType Type,
12230 bool LayoutCompatible,
12231 bool MustBeNull) {
12232 if (!TypeTagForDatatypeMagicValues)
12233 TypeTagForDatatypeMagicValues.reset(
12234 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
12235
12236 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
12237 (*TypeTagForDatatypeMagicValues)[Magic] =
12238 TypeTagData(Type, LayoutCompatible, MustBeNull);
12239}
12240
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012241static bool IsSameCharType(QualType T1, QualType T2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012242 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
12243 if (!BT1)
12244 return false;
12245
12246 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
12247 if (!BT2)
12248 return false;
12249
12250 BuiltinType::Kind T1Kind = BT1->getKind();
12251 BuiltinType::Kind T2Kind = BT2->getKind();
12252
12253 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
12254 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
12255 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
12256 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
12257}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012258
12259void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012260 const ArrayRef<const Expr *> ExprArgs,
12261 SourceLocation CallSiteLoc) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012262 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
12263 bool IsPointerAttr = Attr->getIsPointer();
12264
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012265 // Retrieve the argument representing the 'type_tag'.
Joel E. Denny81508102018-03-13 14:51:22 +000012266 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
12267 if (TypeTagIdxAST >= ExprArgs.size()) {
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012268 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
Joel E. Denny81508102018-03-13 14:51:22 +000012269 << 0 << Attr->getTypeTagIdx().getSourceIndex();
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012270 return;
12271 }
Joel E. Denny81508102018-03-13 14:51:22 +000012272 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012273 bool FoundWrongKind;
12274 TypeTagData TypeInfo;
12275 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
12276 TypeTagForDatatypeMagicValues.get(),
12277 FoundWrongKind, TypeInfo)) {
12278 if (FoundWrongKind)
12279 Diag(TypeTagExpr->getExprLoc(),
12280 diag::warn_type_tag_for_datatype_wrong_kind)
12281 << TypeTagExpr->getSourceRange();
12282 return;
12283 }
12284
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012285 // Retrieve the argument representing the 'arg_idx'.
Joel E. Denny81508102018-03-13 14:51:22 +000012286 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
12287 if (ArgumentIdxAST >= ExprArgs.size()) {
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012288 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
Joel E. Denny81508102018-03-13 14:51:22 +000012289 << 1 << Attr->getArgumentIdx().getSourceIndex();
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012290 return;
12291 }
Joel E. Denny81508102018-03-13 14:51:22 +000012292 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012293 if (IsPointerAttr) {
12294 // Skip implicit cast of pointer to `void *' (as a function argument).
12295 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000012296 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000012297 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012298 ArgumentExpr = ICE->getSubExpr();
12299 }
12300 QualType ArgumentType = ArgumentExpr->getType();
12301
12302 // Passing a `void*' pointer shouldn't trigger a warning.
12303 if (IsPointerAttr && ArgumentType->isVoidPointerType())
12304 return;
12305
12306 if (TypeInfo.MustBeNull) {
12307 // Type tag with matching void type requires a null pointer.
12308 if (!ArgumentExpr->isNullPointerConstant(Context,
12309 Expr::NPC_ValueDependentIsNotNull)) {
12310 Diag(ArgumentExpr->getExprLoc(),
12311 diag::warn_type_safety_null_pointer_required)
12312 << ArgumentKind->getName()
12313 << ArgumentExpr->getSourceRange()
12314 << TypeTagExpr->getSourceRange();
12315 }
12316 return;
12317 }
12318
12319 QualType RequiredType = TypeInfo.Type;
12320 if (IsPointerAttr)
12321 RequiredType = Context.getPointerType(RequiredType);
12322
12323 bool mismatch = false;
12324 if (!TypeInfo.LayoutCompatible) {
12325 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
12326
12327 // C++11 [basic.fundamental] p1:
12328 // Plain char, signed char, and unsigned char are three distinct types.
12329 //
12330 // But we treat plain `char' as equivalent to `signed char' or `unsigned
12331 // char' depending on the current char signedness mode.
12332 if (mismatch)
12333 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
12334 RequiredType->getPointeeType())) ||
12335 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
12336 mismatch = false;
12337 } else
12338 if (IsPointerAttr)
12339 mismatch = !isLayoutCompatible(Context,
12340 ArgumentType->getPointeeType(),
12341 RequiredType->getPointeeType());
12342 else
12343 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
12344
12345 if (mismatch)
12346 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000012347 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012348 << TypeInfo.LayoutCompatible << RequiredType
12349 << ArgumentExpr->getSourceRange()
12350 << TypeTagExpr->getSourceRange();
12351}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012352
12353void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
12354 CharUnits Alignment) {
12355 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
12356}
12357
12358void Sema::DiagnoseMisalignedMembers() {
12359 for (MisalignedMember &m : MisalignedMembers) {
Alex Lorenz014181e2016-10-05 09:27:48 +000012360 const NamedDecl *ND = m.RD;
12361 if (ND->getName().empty()) {
12362 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
12363 ND = TD;
12364 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012365 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
Alex Lorenz014181e2016-10-05 09:27:48 +000012366 << m.MD << ND << m.E->getSourceRange();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012367 }
12368 MisalignedMembers.clear();
12369}
12370
12371void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012372 E = E->IgnoreParens();
12373 if (!T->isPointerType() && !T->isIntegerType())
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012374 return;
12375 if (isa<UnaryOperator>(E) &&
12376 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
12377 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12378 if (isa<MemberExpr>(Op)) {
12379 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
12380 MisalignedMember(Op));
12381 if (MA != MisalignedMembers.end() &&
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012382 (T->isIntegerType() ||
Roger Ferrer Ibanezd80d6c52017-12-07 09:23:50 +000012383 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
12384 Context.getTypeAlignInChars(
12385 T->getPointeeType()) <= MA->Alignment))))
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012386 MisalignedMembers.erase(MA);
12387 }
12388 }
12389}
12390
12391void Sema::RefersToMemberWithReducedAlignment(
12392 Expr *E,
Benjamin Kramera8c3e672016-12-12 14:41:19 +000012393 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
12394 Action) {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012395 const auto *ME = dyn_cast<MemberExpr>(E);
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012396 if (!ME)
12397 return;
12398
Roger Ferrer Ibanez9f963472017-03-13 13:18:21 +000012399 // No need to check expressions with an __unaligned-qualified type.
12400 if (E->getType().getQualifiers().hasUnaligned())
12401 return;
12402
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012403 // For a chain of MemberExpr like "a.b.c.d" this list
12404 // will keep FieldDecl's like [d, c, b].
12405 SmallVector<FieldDecl *, 4> ReverseMemberChain;
12406 const MemberExpr *TopME = nullptr;
12407 bool AnyIsPacked = false;
12408 do {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012409 QualType BaseType = ME->getBase()->getType();
12410 if (ME->isArrow())
12411 BaseType = BaseType->getPointeeType();
12412 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
Olivier Goffart67049f02017-07-07 09:38:59 +000012413 if (RD->isInvalidDecl())
12414 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012415
12416 ValueDecl *MD = ME->getMemberDecl();
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012417 auto *FD = dyn_cast<FieldDecl>(MD);
12418 // We do not care about non-data members.
12419 if (!FD || FD->isInvalidDecl())
12420 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012421
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012422 AnyIsPacked =
12423 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
12424 ReverseMemberChain.push_back(FD);
12425
12426 TopME = ME;
12427 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
12428 } while (ME);
12429 assert(TopME && "We did not compute a topmost MemberExpr!");
12430
12431 // Not the scope of this diagnostic.
12432 if (!AnyIsPacked)
12433 return;
12434
12435 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
12436 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
12437 // TODO: The innermost base of the member expression may be too complicated.
12438 // For now, just disregard these cases. This is left for future
12439 // improvement.
12440 if (!DRE && !isa<CXXThisExpr>(TopBase))
12441 return;
12442
12443 // Alignment expected by the whole expression.
12444 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
12445
12446 // No need to do anything else with this case.
12447 if (ExpectedAlignment.isOne())
12448 return;
12449
12450 // Synthesize offset of the whole access.
12451 CharUnits Offset;
12452 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
12453 I++) {
12454 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
12455 }
12456
12457 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
12458 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
12459 ReverseMemberChain.back()->getParent()->getTypeForDecl());
12460
12461 // The base expression of the innermost MemberExpr may give
12462 // stronger guarantees than the class containing the member.
12463 if (DRE && !TopME->isArrow()) {
12464 const ValueDecl *VD = DRE->getDecl();
12465 if (!VD->getType()->isReferenceType())
12466 CompleteObjectAlignment =
12467 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
12468 }
12469
12470 // Check if the synthesized offset fulfills the alignment.
12471 if (Offset % ExpectedAlignment != 0 ||
12472 // It may fulfill the offset it but the effective alignment may still be
12473 // lower than the expected expression alignment.
12474 CompleteObjectAlignment < ExpectedAlignment) {
12475 // If this happens, we want to determine a sensible culprit of this.
12476 // Intuitively, watching the chain of member expressions from right to
12477 // left, we start with the required alignment (as required by the field
12478 // type) but some packed attribute in that chain has reduced the alignment.
12479 // It may happen that another packed structure increases it again. But if
12480 // we are here such increase has not been enough. So pointing the first
12481 // FieldDecl that either is packed or else its RecordDecl is,
12482 // seems reasonable.
12483 FieldDecl *FD = nullptr;
12484 CharUnits Alignment;
12485 for (FieldDecl *FDI : ReverseMemberChain) {
12486 if (FDI->hasAttr<PackedAttr>() ||
12487 FDI->getParent()->hasAttr<PackedAttr>()) {
12488 FD = FDI;
12489 Alignment = std::min(
12490 Context.getTypeAlignInChars(FD->getType()),
12491 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
12492 break;
12493 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012494 }
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012495 assert(FD && "We did not find a packed FieldDecl!");
12496 Action(E, FD->getParent(), FD, Alignment);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012497 }
12498}
12499
12500void Sema::CheckAddressOfPackedMember(Expr *rhs) {
12501 using namespace std::placeholders;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012502
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012503 RefersToMemberWithReducedAlignment(
12504 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
12505 _2, _3, _4));
12506}