blob: 5530bd8fe767cf999225a39eb2f552056a43a20d [file] [log] [blame]
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00001//===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerb87b1b32007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump11289f42009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattnerb87b1b32007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000015#include "clang/AST/APValue.h"
Chris Lattnerb87b1b32007-08-10 20:18:51 +000016#include "clang/AST/ASTContext.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000017#include "clang/AST/Attr.h"
18#include "clang/AST/AttrIterator.h"
Ken Dyck40775002010-01-11 17:06:35 +000019#include "clang/AST/CharUnits.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000020#include "clang/AST/Decl.h"
21#include "clang/AST/DeclBase.h"
John McCall28a0cf72010-08-25 07:42:41 +000022#include "clang/AST/DeclCXX.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000023#include "clang/AST/DeclObjC.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000024#include "clang/AST/DeclarationName.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/AST/EvaluatedExprVisitor.h"
David Blaikie7555b6a2012-05-15 16:56:36 +000026#include "clang/AST/Expr.h"
Ted Kremenekc81614d2007-08-20 16:18:38 +000027#include "clang/AST/ExprCXX.h"
Ted Kremenek34f664d2008-06-16 18:00:42 +000028#include "clang/AST/ExprObjC.h"
Alexey Bataev1a3320e2015-08-25 14:24:04 +000029#include "clang/AST/ExprOpenMP.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000030#include "clang/AST/NSAPI.h"
Akira Hatanaka2be04412018-04-17 19:13:41 +000031#include "clang/AST/NonTrivialTypeVisitor.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000032#include "clang/AST/OperationKinds.h"
33#include "clang/AST/Stmt.h"
34#include "clang/AST/TemplateBase.h"
35#include "clang/AST/Type.h"
36#include "clang/AST/TypeLoc.h"
37#include "clang/AST/UnresolvedSet.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000038#include "clang/Analysis/Analyses/FormatString.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000039#include "clang/Basic/AddressSpaces.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000040#include "clang/Basic/CharInfo.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000041#include "clang/Basic/Diagnostic.h"
42#include "clang/Basic/IdentifierTable.h"
43#include "clang/Basic/LLVM.h"
44#include "clang/Basic/LangOptions.h"
45#include "clang/Basic/OpenCLOptions.h"
46#include "clang/Basic/OperatorKinds.h"
47#include "clang/Basic/PartialDiagnostic.h"
48#include "clang/Basic/SourceLocation.h"
49#include "clang/Basic/SourceManager.h"
50#include "clang/Basic/Specifiers.h"
Yaxun Liu39195062017-08-04 18:16:31 +000051#include "clang/Basic/SyncScope.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000052#include "clang/Basic/TargetBuiltins.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000053#include "clang/Basic/TargetCXXABI.h"
Nate Begeman4904e322010-06-08 02:47:44 +000054#include "clang/Basic/TargetInfo.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000055#include "clang/Basic/TypeTraits.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000056#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
Chandler Carruth3a022472012-12-04 09:13:33 +000057#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000058#include "clang/Sema/Lookup.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000059#include "clang/Sema/Ownership.h"
60#include "clang/Sema/Scope.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000061#include "clang/Sema/ScopeInfo.h"
62#include "clang/Sema/Sema.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000063#include "clang/Sema/SemaInternal.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000064#include "llvm/ADT/APFloat.h"
65#include "llvm/ADT/APInt.h"
66#include "llvm/ADT/APSInt.h"
67#include "llvm/ADT/ArrayRef.h"
68#include "llvm/ADT/DenseMap.h"
69#include "llvm/ADT/FoldingSet.h"
70#include "llvm/ADT/None.h"
71#include "llvm/ADT/Optional.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000072#include "llvm/ADT/STLExtras.h"
Richard Smithd7293d72013-08-05 18:49:43 +000073#include "llvm/ADT/SmallBitVector.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000074#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000075#include "llvm/ADT/SmallString.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000076#include "llvm/ADT/SmallVector.h"
77#include "llvm/ADT/StringRef.h"
78#include "llvm/ADT/StringSwitch.h"
79#include "llvm/ADT/Triple.h"
80#include "llvm/Support/AtomicOrdering.h"
81#include "llvm/Support/Casting.h"
82#include "llvm/Support/Compiler.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000083#include "llvm/Support/ConvertUTF.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000084#include "llvm/Support/ErrorHandling.h"
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +000085#include "llvm/Support/Format.h"
86#include "llvm/Support/Locale.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000087#include "llvm/Support/MathExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000088#include "llvm/Support/raw_ostream.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000089#include <algorithm>
90#include <cassert>
91#include <cstddef>
92#include <cstdint>
93#include <functional>
94#include <limits>
95#include <string>
96#include <tuple>
97#include <utility>
Eugene Zelenko1ced5092016-02-12 22:53:10 +000098
Chris Lattnerb87b1b32007-08-10 20:18:51 +000099using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +0000100using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +0000101
Chris Lattnera26fb342009-02-18 17:49:48 +0000102SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
103 unsigned ByteNo) const {
Alp Tokerb6cc5922014-05-03 03:45:55 +0000104 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
105 Context.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +0000106}
107
John McCallbebede42011-02-26 05:39:39 +0000108/// Checks that a call expression's argument count is the desired number.
109/// This is useful when doing custom type-checking. Returns true on error.
110static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
111 unsigned argCount = call->getNumArgs();
112 if (argCount == desiredArgCount) return false;
113
114 if (argCount < desiredArgCount)
115 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
116 << 0 /*function call*/ << desiredArgCount << argCount
117 << call->getSourceRange();
118
119 // Highlight all the excess arguments.
120 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
121 call->getArg(argCount - 1)->getLocEnd());
Nico Weberade321e2018-04-10 18:53:28 +0000122
John McCallbebede42011-02-26 05:39:39 +0000123 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
124 << 0 /*function call*/ << desiredArgCount << argCount
125 << call->getArg(1)->getSourceRange();
126}
127
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000128/// Check that the first argument to __builtin_annotation is an integer
129/// and the second argument is a non-wide string literal.
130static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
131 if (checkArgCount(S, TheCall, 2))
132 return true;
133
134 // First argument should be an integer.
135 Expr *ValArg = TheCall->getArg(0);
136 QualType Ty = ValArg->getType();
137 if (!Ty->isIntegerType()) {
138 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
139 << ValArg->getSourceRange();
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000140 return true;
141 }
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000142
143 // Second argument should be a constant string.
144 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
145 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
146 if (!Literal || !Literal->isAscii()) {
147 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
148 << StrArg->getSourceRange();
149 return true;
150 }
151
152 TheCall->setType(Ty);
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000153 return false;
154}
155
Reid Kleckner30701ed2017-09-05 20:27:35 +0000156static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
157 // We need at least one argument.
158 if (TheCall->getNumArgs() < 1) {
159 S.Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
160 << 0 << 1 << TheCall->getNumArgs()
161 << TheCall->getCallee()->getSourceRange();
162 return true;
163 }
164
165 // All arguments should be wide string literals.
166 for (Expr *Arg : TheCall->arguments()) {
167 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
168 if (!Literal || !Literal->isWide()) {
169 S.Diag(Arg->getLocStart(), diag::err_msvc_annotation_wide_str)
170 << Arg->getSourceRange();
171 return true;
172 }
173 }
174
175 return false;
176}
177
Richard Smith6cbd65d2013-07-11 02:27:57 +0000178/// Check that the argument to __builtin_addressof is a glvalue, and set the
179/// result type to the corresponding pointer type.
180static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
181 if (checkArgCount(S, TheCall, 1))
182 return true;
183
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000184 ExprResult Arg(TheCall->getArg(0));
Richard Smith6cbd65d2013-07-11 02:27:57 +0000185 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
186 if (ResultType.isNull())
187 return true;
188
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000189 TheCall->setArg(0, Arg.get());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000190 TheCall->setType(ResultType);
191 return false;
192}
193
John McCall03107a42015-10-29 20:48:01 +0000194static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
195 if (checkArgCount(S, TheCall, 3))
196 return true;
197
198 // First two arguments should be integers.
199 for (unsigned I = 0; I < 2; ++I) {
Erich Keane1d73d1a2018-06-13 13:25:11 +0000200 ExprResult Arg = TheCall->getArg(I);
201 QualType Ty = Arg.get()->getType();
John McCall03107a42015-10-29 20:48:01 +0000202 if (!Ty->isIntegerType()) {
Erich Keane1d73d1a2018-06-13 13:25:11 +0000203 S.Diag(Arg.get()->getLocStart(), diag::err_overflow_builtin_must_be_int)
204 << Ty << Arg.get()->getSourceRange();
John McCall03107a42015-10-29 20:48:01 +0000205 return true;
206 }
Erich Keane1d73d1a2018-06-13 13:25:11 +0000207 InitializedEntity Entity = InitializedEntity::InitializeParameter(
208 S.getASTContext(), Ty, /*consume*/ false);
209 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
210 if (Arg.isInvalid())
211 return true;
212 TheCall->setArg(I, Arg.get());
John McCall03107a42015-10-29 20:48:01 +0000213 }
214
215 // Third argument should be a pointer to a non-const integer.
216 // IRGen correctly handles volatile, restrict, and address spaces, and
217 // the other qualifiers aren't possible.
218 {
Erich Keane1d73d1a2018-06-13 13:25:11 +0000219 ExprResult Arg = TheCall->getArg(2);
220 QualType Ty = Arg.get()->getType();
John McCall03107a42015-10-29 20:48:01 +0000221 const auto *PtrTy = Ty->getAs<PointerType>();
222 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
223 !PtrTy->getPointeeType().isConstQualified())) {
Erich Keane1d73d1a2018-06-13 13:25:11 +0000224 S.Diag(Arg.get()->getLocStart(),
225 diag::err_overflow_builtin_must_be_ptr_int)
226 << Ty << Arg.get()->getSourceRange();
John McCall03107a42015-10-29 20:48:01 +0000227 return true;
228 }
Erich Keane1d73d1a2018-06-13 13:25:11 +0000229 InitializedEntity Entity = InitializedEntity::InitializeParameter(
230 S.getASTContext(), Ty, /*consume*/ false);
231 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
232 if (Arg.isInvalid())
233 return true;
234 TheCall->setArg(2, Arg.get());
John McCall03107a42015-10-29 20:48:01 +0000235 }
John McCall03107a42015-10-29 20:48:01 +0000236 return false;
237}
238
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000239static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
Nico Weberade321e2018-04-10 18:53:28 +0000240 CallExpr *TheCall, unsigned SizeIdx,
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000241 unsigned DstSizeIdx) {
242 if (TheCall->getNumArgs() <= SizeIdx ||
243 TheCall->getNumArgs() <= DstSizeIdx)
244 return;
245
246 const Expr *SizeArg = TheCall->getArg(SizeIdx);
247 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
248
249 llvm::APSInt Size, DstSize;
250
251 // find out if both sizes are known at compile time
252 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
253 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
254 return;
255
256 if (Size.ule(DstSize))
257 return;
258
259 // confirmed overflow so generate the diagnostic.
260 IdentifierInfo *FnName = FDecl->getIdentifier();
261 SourceLocation SL = TheCall->getLocStart();
262 SourceRange SR = TheCall->getSourceRange();
263
264 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
265}
266
Peter Collingbournef7706832014-12-12 23:41:25 +0000267static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
268 if (checkArgCount(S, BuiltinCall, 2))
269 return true;
270
271 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
272 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
273 Expr *Call = BuiltinCall->getArg(0);
274 Expr *Chain = BuiltinCall->getArg(1);
275
276 if (Call->getStmtClass() != Stmt::CallExprClass) {
277 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
278 << Call->getSourceRange();
279 return true;
280 }
281
282 auto CE = cast<CallExpr>(Call);
283 if (CE->getCallee()->getType()->isBlockPointerType()) {
284 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
285 << Call->getSourceRange();
286 return true;
287 }
288
289 const Decl *TargetDecl = CE->getCalleeDecl();
290 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
291 if (FD->getBuiltinID()) {
292 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
293 << Call->getSourceRange();
294 return true;
295 }
296
297 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
298 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
299 << Call->getSourceRange();
300 return true;
301 }
302
303 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
304 if (ChainResult.isInvalid())
305 return true;
306 if (!ChainResult.get()->getType()->isPointerType()) {
307 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
308 << Chain->getSourceRange();
309 return true;
310 }
311
David Majnemerced8bdf2015-02-25 17:36:15 +0000312 QualType ReturnTy = CE->getCallReturnType(S.Context);
Peter Collingbournef7706832014-12-12 23:41:25 +0000313 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
314 QualType BuiltinTy = S.Context.getFunctionType(
315 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
316 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
317
318 Builtin =
319 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
320
321 BuiltinCall->setType(CE->getType());
322 BuiltinCall->setValueKind(CE->getValueKind());
323 BuiltinCall->setObjectKind(CE->getObjectKind());
324 BuiltinCall->setCallee(Builtin);
325 BuiltinCall->setArg(1, ChainResult.get());
326
327 return false;
328}
329
Reid Kleckner1d59f992015-01-22 01:36:17 +0000330static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
331 Scope::ScopeFlags NeededScopeFlags,
332 unsigned DiagID) {
333 // Scopes aren't available during instantiation. Fortunately, builtin
334 // functions cannot be template args so they cannot be formed through template
335 // instantiation. Therefore checking once during the parse is sufficient.
Richard Smith51ec0cf2017-02-21 01:17:38 +0000336 if (SemaRef.inTemplateInstantiation())
Reid Kleckner1d59f992015-01-22 01:36:17 +0000337 return false;
338
339 Scope *S = SemaRef.getCurScope();
340 while (S && !S->isSEHExceptScope())
341 S = S->getParent();
342 if (!S || !(S->getFlags() & NeededScopeFlags)) {
343 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
344 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
345 << DRE->getDecl()->getIdentifier();
346 return true;
347 }
348
349 return false;
350}
351
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000352static inline bool isBlockPointer(Expr *Arg) {
353 return Arg->getType()->isBlockPointerType();
354}
355
356/// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
357/// void*, which is a requirement of device side enqueue.
358static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
359 const BlockPointerType *BPT =
360 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
361 ArrayRef<QualType> Params =
362 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
363 unsigned ArgCounter = 0;
364 bool IllegalParams = false;
365 // Iterate through the block parameters until either one is found that is not
366 // a local void*, or the block is valid.
367 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
368 I != E; ++I, ++ArgCounter) {
369 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
370 (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
371 LangAS::opencl_local) {
372 // Get the location of the error. If a block literal has been passed
373 // (BlockExpr) then we can point straight to the offending argument,
374 // else we just point to the variable reference.
375 SourceLocation ErrorLoc;
376 if (isa<BlockExpr>(BlockArg)) {
377 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
378 ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
379 } else if (isa<DeclRefExpr>(BlockArg)) {
380 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
381 }
382 S.Diag(ErrorLoc,
383 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
384 IllegalParams = true;
385 }
386 }
387
388 return IllegalParams;
389}
390
Joey Gouly84ae3362017-07-31 15:15:59 +0000391static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
392 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
393 S.Diag(Call->getLocStart(), diag::err_opencl_requires_extension)
394 << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
395 return true;
396 }
397 return false;
398}
399
Joey Goulyfa76b492017-08-01 13:27:09 +0000400static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
401 if (checkArgCount(S, TheCall, 2))
402 return true;
403
404 if (checkOpenCLSubgroupExt(S, TheCall))
405 return true;
406
407 // First argument is an ndrange_t type.
408 Expr *NDRangeArg = TheCall->getArg(0);
Yaxun Liub7318e02017-10-13 03:37:48 +0000409 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
Joey Goulyfa76b492017-08-01 13:27:09 +0000410 S.Diag(NDRangeArg->getLocStart(),
411 diag::err_opencl_builtin_expected_type)
412 << TheCall->getDirectCallee() << "'ndrange_t'";
413 return true;
414 }
415
416 Expr *BlockArg = TheCall->getArg(1);
417 if (!isBlockPointer(BlockArg)) {
418 S.Diag(BlockArg->getLocStart(),
419 diag::err_opencl_builtin_expected_type)
420 << TheCall->getDirectCallee() << "block";
421 return true;
422 }
423 return checkOpenCLBlockArgs(S, BlockArg);
424}
425
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000426/// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
427/// get_kernel_work_group_size
428/// and get_kernel_preferred_work_group_size_multiple builtin functions.
429static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
430 if (checkArgCount(S, TheCall, 1))
431 return true;
432
433 Expr *BlockArg = TheCall->getArg(0);
434 if (!isBlockPointer(BlockArg)) {
435 S.Diag(BlockArg->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000436 diag::err_opencl_builtin_expected_type)
437 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000438 return true;
439 }
440 return checkOpenCLBlockArgs(S, BlockArg);
441}
442
Simon Pilgrim2c518802017-03-30 14:13:19 +0000443/// Diagnose integer type and any valid implicit conversion to it.
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000444static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
445 const QualType &IntType);
446
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000447static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000448 unsigned Start, unsigned End) {
449 bool IllegalParams = false;
450 for (unsigned I = Start; I <= End; ++I)
451 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
452 S.Context.getSizeType());
453 return IllegalParams;
454}
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000455
456/// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
457/// 'local void*' parameter of passed block.
458static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
459 Expr *BlockArg,
460 unsigned NumNonVarArgs) {
461 const BlockPointerType *BPT =
462 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
463 unsigned NumBlockParams =
464 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
465 unsigned TotalNumArgs = TheCall->getNumArgs();
466
467 // For each argument passed to the block, a corresponding uint needs to
468 // be passed to describe the size of the local memory.
469 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
470 S.Diag(TheCall->getLocStart(),
471 diag::err_opencl_enqueue_kernel_local_size_args);
472 return true;
473 }
474
475 // Check that the sizes of the local memory are specified by integers.
476 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
477 TotalNumArgs - 1);
478}
479
480/// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
481/// overload formats specified in Table 6.13.17.1.
482/// int enqueue_kernel(queue_t queue,
483/// kernel_enqueue_flags_t flags,
484/// const ndrange_t ndrange,
485/// void (^block)(void))
486/// int enqueue_kernel(queue_t queue,
487/// kernel_enqueue_flags_t flags,
488/// const ndrange_t ndrange,
489/// uint num_events_in_wait_list,
490/// clk_event_t *event_wait_list,
491/// clk_event_t *event_ret,
492/// void (^block)(void))
493/// int enqueue_kernel(queue_t queue,
494/// kernel_enqueue_flags_t flags,
495/// const ndrange_t ndrange,
496/// void (^block)(local void*, ...),
497/// uint size0, ...)
498/// int enqueue_kernel(queue_t queue,
499/// kernel_enqueue_flags_t flags,
500/// const ndrange_t ndrange,
501/// uint num_events_in_wait_list,
502/// clk_event_t *event_wait_list,
503/// clk_event_t *event_ret,
504/// void (^block)(local void*, ...),
505/// uint size0, ...)
506static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
507 unsigned NumArgs = TheCall->getNumArgs();
508
509 if (NumArgs < 4) {
510 S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
511 return true;
512 }
513
514 Expr *Arg0 = TheCall->getArg(0);
515 Expr *Arg1 = TheCall->getArg(1);
516 Expr *Arg2 = TheCall->getArg(2);
517 Expr *Arg3 = TheCall->getArg(3);
518
519 // First argument always needs to be a queue_t type.
520 if (!Arg0->getType()->isQueueT()) {
521 S.Diag(TheCall->getArg(0)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000522 diag::err_opencl_builtin_expected_type)
523 << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000524 return true;
525 }
526
527 // Second argument always needs to be a kernel_enqueue_flags_t enum value.
528 if (!Arg1->getType()->isIntegerType()) {
529 S.Diag(TheCall->getArg(1)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000530 diag::err_opencl_builtin_expected_type)
531 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000532 return true;
533 }
534
535 // Third argument is always an ndrange_t type.
Anastasia Stulovab42f3c02017-04-21 15:13:24 +0000536 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000537 S.Diag(TheCall->getArg(2)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000538 diag::err_opencl_builtin_expected_type)
539 << TheCall->getDirectCallee() << "'ndrange_t'";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000540 return true;
541 }
542
543 // With four arguments, there is only one form that the function could be
544 // called in: no events and no variable arguments.
545 if (NumArgs == 4) {
546 // check that the last argument is the right block type.
547 if (!isBlockPointer(Arg3)) {
Joey Gouly6b03d952017-07-04 11:50:23 +0000548 S.Diag(Arg3->getLocStart(), diag::err_opencl_builtin_expected_type)
549 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000550 return true;
551 }
552 // we have a block type, check the prototype
553 const BlockPointerType *BPT =
554 cast<BlockPointerType>(Arg3->getType().getCanonicalType());
555 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
556 S.Diag(Arg3->getLocStart(),
557 diag::err_opencl_enqueue_kernel_blocks_no_args);
558 return true;
559 }
560 return false;
561 }
562 // we can have block + varargs.
563 if (isBlockPointer(Arg3))
564 return (checkOpenCLBlockArgs(S, Arg3) ||
565 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
566 // last two cases with either exactly 7 args or 7 args and varargs.
567 if (NumArgs >= 7) {
568 // check common block argument.
569 Expr *Arg6 = TheCall->getArg(6);
570 if (!isBlockPointer(Arg6)) {
Joey Gouly6b03d952017-07-04 11:50:23 +0000571 S.Diag(Arg6->getLocStart(), diag::err_opencl_builtin_expected_type)
572 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000573 return true;
574 }
575 if (checkOpenCLBlockArgs(S, Arg6))
576 return true;
577
578 // Forth argument has to be any integer type.
579 if (!Arg3->getType()->isIntegerType()) {
580 S.Diag(TheCall->getArg(3)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000581 diag::err_opencl_builtin_expected_type)
582 << TheCall->getDirectCallee() << "integer";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000583 return true;
584 }
585 // check remaining common arguments.
586 Expr *Arg4 = TheCall->getArg(4);
587 Expr *Arg5 = TheCall->getArg(5);
588
Anastasia Stulova2b461202016-11-14 15:34:01 +0000589 // Fifth argument is always passed as a pointer to clk_event_t.
590 if (!Arg4->isNullPointerConstant(S.Context,
591 Expr::NPC_ValueDependentIsNotNull) &&
592 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000593 S.Diag(TheCall->getArg(4)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000594 diag::err_opencl_builtin_expected_type)
595 << TheCall->getDirectCallee()
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000596 << S.Context.getPointerType(S.Context.OCLClkEventTy);
597 return true;
598 }
599
Anastasia Stulova2b461202016-11-14 15:34:01 +0000600 // Sixth argument is always passed as a pointer to clk_event_t.
601 if (!Arg5->isNullPointerConstant(S.Context,
602 Expr::NPC_ValueDependentIsNotNull) &&
603 !(Arg5->getType()->isPointerType() &&
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000604 Arg5->getType()->getPointeeType()->isClkEventT())) {
605 S.Diag(TheCall->getArg(5)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000606 diag::err_opencl_builtin_expected_type)
607 << TheCall->getDirectCallee()
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000608 << S.Context.getPointerType(S.Context.OCLClkEventTy);
609 return true;
610 }
611
612 if (NumArgs == 7)
613 return false;
614
615 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
616 }
617
618 // None of the specific case has been detected, give generic error
619 S.Diag(TheCall->getLocStart(),
620 diag::err_opencl_enqueue_kernel_incorrect_args);
621 return true;
622}
623
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000624/// Returns OpenCL access qual.
Xiuli Pan11e13f62016-02-26 03:13:03 +0000625static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
Xiuli Pan11e13f62016-02-26 03:13:03 +0000626 return D->getAttr<OpenCLAccessAttr>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000627}
628
629/// Returns true if pipe element type is different from the pointer.
630static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
631 const Expr *Arg0 = Call->getArg(0);
632 // First argument type should always be pipe.
633 if (!Arg0->getType()->isPipeType()) {
634 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000635 << Call->getDirectCallee() << Arg0->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000636 return true;
637 }
Xiuli Pan11e13f62016-02-26 03:13:03 +0000638 OpenCLAccessAttr *AccessQual =
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000639 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
640 // Validates the access qualifier is compatible with the call.
641 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
642 // read_only and write_only, and assumed to be read_only if no qualifier is
643 // specified.
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000644 switch (Call->getDirectCallee()->getBuiltinID()) {
645 case Builtin::BIread_pipe:
646 case Builtin::BIreserve_read_pipe:
647 case Builtin::BIcommit_read_pipe:
648 case Builtin::BIwork_group_reserve_read_pipe:
649 case Builtin::BIsub_group_reserve_read_pipe:
650 case Builtin::BIwork_group_commit_read_pipe:
651 case Builtin::BIsub_group_commit_read_pipe:
652 if (!(!AccessQual || AccessQual->isReadOnly())) {
653 S.Diag(Arg0->getLocStart(),
654 diag::err_opencl_builtin_pipe_invalid_access_modifier)
655 << "read_only" << Arg0->getSourceRange();
656 return true;
657 }
658 break;
659 case Builtin::BIwrite_pipe:
660 case Builtin::BIreserve_write_pipe:
661 case Builtin::BIcommit_write_pipe:
662 case Builtin::BIwork_group_reserve_write_pipe:
663 case Builtin::BIsub_group_reserve_write_pipe:
664 case Builtin::BIwork_group_commit_write_pipe:
665 case Builtin::BIsub_group_commit_write_pipe:
666 if (!(AccessQual && AccessQual->isWriteOnly())) {
667 S.Diag(Arg0->getLocStart(),
668 diag::err_opencl_builtin_pipe_invalid_access_modifier)
669 << "write_only" << Arg0->getSourceRange();
670 return true;
671 }
672 break;
673 default:
674 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000675 }
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000676 return false;
677}
678
679/// Returns true if pipe element type is different from the pointer.
680static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
681 const Expr *Arg0 = Call->getArg(0);
682 const Expr *ArgIdx = Call->getArg(Idx);
683 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000684 const QualType EltTy = PipeTy->getElementType();
685 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000686 // The Idx argument should be a pointer and the type of the pointer and
687 // the type of pipe element should also be the same.
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000688 if (!ArgTy ||
689 !S.Context.hasSameType(
690 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000691 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000692 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000693 << ArgIdx->getType() << ArgIdx->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000694 return true;
695 }
696 return false;
697}
698
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000699// Performs semantic analysis for the read/write_pipe call.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000700// \param S Reference to the semantic analyzer.
701// \param Call A pointer to the builtin call.
702// \return True if a semantic error has been found, false otherwise.
703static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000704 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
705 // functions have two forms.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000706 switch (Call->getNumArgs()) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +0000707 case 2:
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000708 if (checkOpenCLPipeArg(S, Call))
709 return true;
710 // The call with 2 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000711 // read/write_pipe(pipe T, T*).
712 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000713 if (checkOpenCLPipePacketType(S, Call, 1))
714 return true;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +0000715 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000716
717 case 4: {
718 if (checkOpenCLPipeArg(S, Call))
719 return true;
720 // The call with 4 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000721 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
722 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000723 if (!Call->getArg(1)->getType()->isReserveIDT()) {
724 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000725 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000726 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000727 return true;
728 }
729
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000730 // Check the index.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000731 const Expr *Arg2 = Call->getArg(2);
732 if (!Arg2->getType()->isIntegerType() &&
733 !Arg2->getType()->isUnsignedIntegerType()) {
734 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000735 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000736 << Arg2->getType() << Arg2->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000737 return true;
738 }
739
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000740 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000741 if (checkOpenCLPipePacketType(S, Call, 3))
742 return true;
743 } break;
744 default:
745 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000746 << Call->getDirectCallee() << Call->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000747 return true;
748 }
749
750 return false;
751}
752
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000753// Performs a semantic analysis on the {work_group_/sub_group_
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000754// /_}reserve_{read/write}_pipe
755// \param S Reference to the semantic analyzer.
756// \param Call The call to the builtin function to be analyzed.
757// \return True if a semantic error was found, false otherwise.
758static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
759 if (checkArgCount(S, Call, 2))
760 return true;
761
762 if (checkOpenCLPipeArg(S, Call))
763 return true;
764
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000765 // Check the reserve size.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000766 if (!Call->getArg(1)->getType()->isIntegerType() &&
767 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
768 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000769 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000770 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000771 return true;
772 }
773
Joey Gouly922ca232017-08-09 14:52:47 +0000774 // Since return type of reserve_read/write_pipe built-in function is
775 // reserve_id_t, which is not defined in the builtin def file , we used int
776 // as return type and need to override the return type of these functions.
777 Call->setType(S.Context.OCLReserveIDTy);
778
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000779 return false;
780}
781
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000782// Performs a semantic analysis on {work_group_/sub_group_
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000783// /_}commit_{read/write}_pipe
784// \param S Reference to the semantic analyzer.
785// \param Call The call to the builtin function to be analyzed.
786// \return True if a semantic error was found, false otherwise.
787static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
788 if (checkArgCount(S, Call, 2))
789 return true;
790
791 if (checkOpenCLPipeArg(S, Call))
792 return true;
793
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000794 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000795 if (!Call->getArg(1)->getType()->isReserveIDT()) {
796 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000797 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000798 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000799 return true;
800 }
801
802 return false;
803}
804
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000805// Performs a semantic analysis on the call to built-in Pipe
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000806// Query Functions.
807// \param S Reference to the semantic analyzer.
808// \param Call The call to the builtin function to be analyzed.
809// \return True if a semantic error was found, false otherwise.
810static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
811 if (checkArgCount(S, Call, 1))
812 return true;
813
814 if (!Call->getArg(0)->getType()->isPipeType()) {
815 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000816 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000817 return true;
818 }
819
820 return false;
821}
Eugene Zelenko11a7ef82017-11-15 22:00:04 +0000822
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000823// OpenCL v2.0 s6.13.9 - Address space qualifier functions.
824// Performs semantic analysis for the to_global/local/private call.
Yaxun Liuf7449a12016-05-20 19:54:38 +0000825// \param S Reference to the semantic analyzer.
826// \param BuiltinID ID of the builtin function.
827// \param Call A pointer to the builtin call.
828// \return True if a semantic error has been found, false otherwise.
829static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
830 CallExpr *Call) {
Yaxun Liuf7449a12016-05-20 19:54:38 +0000831 if (Call->getNumArgs() != 1) {
832 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
833 << Call->getDirectCallee() << Call->getSourceRange();
834 return true;
835 }
836
837 auto RT = Call->getArg(0)->getType();
838 if (!RT->isPointerType() || RT->getPointeeType()
839 .getAddressSpace() == LangAS::opencl_constant) {
840 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
841 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
842 return true;
843 }
844
845 RT = RT->getPointeeType();
846 auto Qual = RT.getQualifiers();
847 switch (BuiltinID) {
848 case Builtin::BIto_global:
849 Qual.setAddressSpace(LangAS::opencl_global);
850 break;
851 case Builtin::BIto_local:
852 Qual.setAddressSpace(LangAS::opencl_local);
853 break;
Yaxun Liub7318e02017-10-13 03:37:48 +0000854 case Builtin::BIto_private:
855 Qual.setAddressSpace(LangAS::opencl_private);
856 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +0000857 default:
Yaxun Liub7318e02017-10-13 03:37:48 +0000858 llvm_unreachable("Invalid builtin function");
Yaxun Liuf7449a12016-05-20 19:54:38 +0000859 }
860 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
861 RT.getUnqualifiedType(), Qual)));
862
863 return false;
864}
865
Reid Kleckneraa46ed92018-06-07 21:39:04 +0000866// Emit an error and return true if the current architecture is not in the list
867// of supported architectures.
868static bool
869CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
870 ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
871 llvm::Triple::ArchType CurArch =
872 S.getASTContext().getTargetInfo().getTriple().getArch();
873 if (llvm::is_contained(SupportedArchs, CurArch))
874 return false;
875 S.Diag(TheCall->getLocStart(), diag::err_builtin_target_unsupported)
876 << TheCall->getSourceRange();
877 return true;
878}
879
John McCalldadc5752010-08-24 06:29:42 +0000880ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000881Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
882 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000883 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000884
Chris Lattner3be167f2010-10-01 23:23:24 +0000885 // Find out if any arguments are required to be integer constant expressions.
886 unsigned ICEArguments = 0;
887 ASTContext::GetBuiltinTypeError Error;
888 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
889 if (Error != ASTContext::GE_None)
890 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
891
892 // If any arguments are required to be ICE's, check and diagnose.
893 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
894 // Skip arguments not required to be ICE's.
895 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
896
897 llvm::APSInt Result;
898 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
899 return true;
900 ICEArguments &= ~(1 << ArgNo);
901 }
902
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000903 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000904 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000905 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000906 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000907 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000908 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000909 break;
Martin Storsjo022e7822017-07-17 20:49:45 +0000910 case Builtin::BI__builtin_ms_va_start:
Ted Kremeneka174c522008-07-09 17:58:53 +0000911 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000912 case Builtin::BI__builtin_va_start:
Reid Kleckner2b0fa122017-05-02 20:10:03 +0000913 if (SemaBuiltinVAStart(BuiltinID, TheCall))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000914 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000915 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000916 case Builtin::BI__va_start: {
917 switch (Context.getTargetInfo().getTriple().getArch()) {
918 case llvm::Triple::arm:
919 case llvm::Triple::thumb:
Saleem Abdulrasool3450aa72017-09-26 20:12:04 +0000920 if (SemaBuiltinVAStartARMMicrosoft(TheCall))
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000921 return ExprError();
922 break;
923 default:
Reid Kleckner2b0fa122017-05-02 20:10:03 +0000924 if (SemaBuiltinVAStart(BuiltinID, TheCall))
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000925 return ExprError();
926 break;
927 }
928 break;
929 }
Reid Kleckneraa46ed92018-06-07 21:39:04 +0000930
931 // The acquire, release, and no fence variants are ARM and AArch64 only.
932 case Builtin::BI_interlockedbittestandset_acq:
933 case Builtin::BI_interlockedbittestandset_rel:
934 case Builtin::BI_interlockedbittestandset_nf:
935 case Builtin::BI_interlockedbittestandreset_acq:
936 case Builtin::BI_interlockedbittestandreset_rel:
937 case Builtin::BI_interlockedbittestandreset_nf:
938 if (CheckBuiltinTargetSupport(
939 *this, BuiltinID, TheCall,
940 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
941 return ExprError();
942 break;
943
944 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
945 case Builtin::BI_bittest64:
946 case Builtin::BI_bittestandcomplement64:
947 case Builtin::BI_bittestandreset64:
948 case Builtin::BI_bittestandset64:
949 case Builtin::BI_interlockedbittestandreset64:
950 case Builtin::BI_interlockedbittestandset64:
951 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
952 {llvm::Triple::x86_64, llvm::Triple::arm,
953 llvm::Triple::thumb, llvm::Triple::aarch64}))
954 return ExprError();
955 break;
956
Chris Lattner2da14fb2007-12-20 00:26:33 +0000957 case Builtin::BI__builtin_isgreater:
958 case Builtin::BI__builtin_isgreaterequal:
959 case Builtin::BI__builtin_isless:
960 case Builtin::BI__builtin_islessequal:
961 case Builtin::BI__builtin_islessgreater:
962 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000963 if (SemaBuiltinUnorderedCompare(TheCall))
964 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000965 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000966 case Builtin::BI__builtin_fpclassify:
967 if (SemaBuiltinFPClassification(TheCall, 6))
968 return ExprError();
969 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000970 case Builtin::BI__builtin_isfinite:
971 case Builtin::BI__builtin_isinf:
972 case Builtin::BI__builtin_isinf_sign:
973 case Builtin::BI__builtin_isnan:
974 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000975 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000976 return ExprError();
977 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000978 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000979 return SemaBuiltinShuffleVector(TheCall);
980 // TheCall will be freed by the smart pointer here, but that's fine, since
981 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000982 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000983 if (SemaBuiltinPrefetch(TheCall))
984 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000985 break;
David Majnemer51169932016-10-31 05:37:48 +0000986 case Builtin::BI__builtin_alloca_with_align:
987 if (SemaBuiltinAllocaWithAlign(TheCall))
988 return ExprError();
989 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000990 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000991 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000992 if (SemaBuiltinAssume(TheCall))
993 return ExprError();
994 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000995 case Builtin::BI__builtin_assume_aligned:
996 if (SemaBuiltinAssumeAligned(TheCall))
997 return ExprError();
998 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000999 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +00001000 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001001 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001002 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +00001003 case Builtin::BI__builtin_longjmp:
1004 if (SemaBuiltinLongjmp(TheCall))
1005 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001006 break;
Joerg Sonnenberger27173282015-03-11 23:46:32 +00001007 case Builtin::BI__builtin_setjmp:
1008 if (SemaBuiltinSetjmp(TheCall))
1009 return ExprError();
1010 break;
David Majnemerc403a1c2015-03-20 17:03:35 +00001011 case Builtin::BI_setjmp:
1012 case Builtin::BI_setjmpex:
1013 if (checkArgCount(*this, TheCall, 1))
1014 return true;
1015 break;
John McCallbebede42011-02-26 05:39:39 +00001016 case Builtin::BI__builtin_classify_type:
1017 if (checkArgCount(*this, TheCall, 1)) return true;
1018 TheCall->setType(Context.IntTy);
1019 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +00001020 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +00001021 if (checkArgCount(*this, TheCall, 1)) return true;
1022 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +00001023 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00001024 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +00001025 case Builtin::BI__sync_fetch_and_add_1:
1026 case Builtin::BI__sync_fetch_and_add_2:
1027 case Builtin::BI__sync_fetch_and_add_4:
1028 case Builtin::BI__sync_fetch_and_add_8:
1029 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001030 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +00001031 case Builtin::BI__sync_fetch_and_sub_1:
1032 case Builtin::BI__sync_fetch_and_sub_2:
1033 case Builtin::BI__sync_fetch_and_sub_4:
1034 case Builtin::BI__sync_fetch_and_sub_8:
1035 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001036 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +00001037 case Builtin::BI__sync_fetch_and_or_1:
1038 case Builtin::BI__sync_fetch_and_or_2:
1039 case Builtin::BI__sync_fetch_and_or_4:
1040 case Builtin::BI__sync_fetch_and_or_8:
1041 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001042 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +00001043 case Builtin::BI__sync_fetch_and_and_1:
1044 case Builtin::BI__sync_fetch_and_and_2:
1045 case Builtin::BI__sync_fetch_and_and_4:
1046 case Builtin::BI__sync_fetch_and_and_8:
1047 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001048 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +00001049 case Builtin::BI__sync_fetch_and_xor_1:
1050 case Builtin::BI__sync_fetch_and_xor_2:
1051 case Builtin::BI__sync_fetch_and_xor_4:
1052 case Builtin::BI__sync_fetch_and_xor_8:
1053 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001054 case Builtin::BI__sync_fetch_and_nand:
1055 case Builtin::BI__sync_fetch_and_nand_1:
1056 case Builtin::BI__sync_fetch_and_nand_2:
1057 case Builtin::BI__sync_fetch_and_nand_4:
1058 case Builtin::BI__sync_fetch_and_nand_8:
1059 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001060 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001061 case Builtin::BI__sync_add_and_fetch_1:
1062 case Builtin::BI__sync_add_and_fetch_2:
1063 case Builtin::BI__sync_add_and_fetch_4:
1064 case Builtin::BI__sync_add_and_fetch_8:
1065 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001066 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001067 case Builtin::BI__sync_sub_and_fetch_1:
1068 case Builtin::BI__sync_sub_and_fetch_2:
1069 case Builtin::BI__sync_sub_and_fetch_4:
1070 case Builtin::BI__sync_sub_and_fetch_8:
1071 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001072 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001073 case Builtin::BI__sync_and_and_fetch_1:
1074 case Builtin::BI__sync_and_and_fetch_2:
1075 case Builtin::BI__sync_and_and_fetch_4:
1076 case Builtin::BI__sync_and_and_fetch_8:
1077 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001078 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001079 case Builtin::BI__sync_or_and_fetch_1:
1080 case Builtin::BI__sync_or_and_fetch_2:
1081 case Builtin::BI__sync_or_and_fetch_4:
1082 case Builtin::BI__sync_or_and_fetch_8:
1083 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001084 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001085 case Builtin::BI__sync_xor_and_fetch_1:
1086 case Builtin::BI__sync_xor_and_fetch_2:
1087 case Builtin::BI__sync_xor_and_fetch_4:
1088 case Builtin::BI__sync_xor_and_fetch_8:
1089 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001090 case Builtin::BI__sync_nand_and_fetch:
1091 case Builtin::BI__sync_nand_and_fetch_1:
1092 case Builtin::BI__sync_nand_and_fetch_2:
1093 case Builtin::BI__sync_nand_and_fetch_4:
1094 case Builtin::BI__sync_nand_and_fetch_8:
1095 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001096 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001097 case Builtin::BI__sync_val_compare_and_swap_1:
1098 case Builtin::BI__sync_val_compare_and_swap_2:
1099 case Builtin::BI__sync_val_compare_and_swap_4:
1100 case Builtin::BI__sync_val_compare_and_swap_8:
1101 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001102 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001103 case Builtin::BI__sync_bool_compare_and_swap_1:
1104 case Builtin::BI__sync_bool_compare_and_swap_2:
1105 case Builtin::BI__sync_bool_compare_and_swap_4:
1106 case Builtin::BI__sync_bool_compare_and_swap_8:
1107 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001108 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +00001109 case Builtin::BI__sync_lock_test_and_set_1:
1110 case Builtin::BI__sync_lock_test_and_set_2:
1111 case Builtin::BI__sync_lock_test_and_set_4:
1112 case Builtin::BI__sync_lock_test_and_set_8:
1113 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001114 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001115 case Builtin::BI__sync_lock_release_1:
1116 case Builtin::BI__sync_lock_release_2:
1117 case Builtin::BI__sync_lock_release_4:
1118 case Builtin::BI__sync_lock_release_8:
1119 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001120 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001121 case Builtin::BI__sync_swap_1:
1122 case Builtin::BI__sync_swap_2:
1123 case Builtin::BI__sync_swap_4:
1124 case Builtin::BI__sync_swap_8:
1125 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001126 return SemaBuiltinAtomicOverloaded(TheCallResult);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001127 case Builtin::BI__builtin_nontemporal_load:
1128 case Builtin::BI__builtin_nontemporal_store:
1129 return SemaBuiltinNontemporalOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +00001130#define BUILTIN(ID, TYPE, ATTRS)
1131#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1132 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001133 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +00001134#include "clang/Basic/Builtins.def"
Reid Kleckner30701ed2017-09-05 20:27:35 +00001135 case Builtin::BI__annotation:
1136 if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1137 return ExprError();
1138 break;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001139 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +00001140 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001141 return ExprError();
1142 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +00001143 case Builtin::BI__builtin_addressof:
1144 if (SemaBuiltinAddressof(*this, TheCall))
1145 return ExprError();
1146 break;
John McCall03107a42015-10-29 20:48:01 +00001147 case Builtin::BI__builtin_add_overflow:
1148 case Builtin::BI__builtin_sub_overflow:
1149 case Builtin::BI__builtin_mul_overflow:
Craig Toppera86e70d2015-11-07 06:16:14 +00001150 if (SemaBuiltinOverflow(*this, TheCall))
1151 return ExprError();
1152 break;
Richard Smith760520b2014-06-03 23:27:44 +00001153 case Builtin::BI__builtin_operator_new:
Eric Fiselierfa752f22018-03-21 19:19:48 +00001154 case Builtin::BI__builtin_operator_delete: {
1155 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1156 ExprResult Res =
1157 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1158 if (Res.isInvalid())
1159 CorrectDelayedTyposInExpr(TheCallResult.get());
1160 return Res;
1161 }
Aaron Ballman06525342018-04-10 21:58:13 +00001162 case Builtin::BI__builtin_dump_struct: {
1163 // We first want to ensure we are called with 2 arguments
1164 if (checkArgCount(*this, TheCall, 2))
1165 return ExprError();
1166 // Ensure that the first argument is of type 'struct XX *'
1167 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1168 const QualType PtrArgType = PtrArg->getType();
1169 if (!PtrArgType->isPointerType() ||
1170 !PtrArgType->getPointeeType()->isRecordType()) {
1171 Diag(PtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1172 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1173 << "structure pointer";
1174 return ExprError();
1175 }
1176
1177 // Ensure that the second argument is of type 'FunctionType'
1178 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1179 const QualType FnPtrArgType = FnPtrArg->getType();
1180 if (!FnPtrArgType->isPointerType()) {
1181 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1182 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1183 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1184 return ExprError();
1185 }
1186
1187 const auto *FuncType =
1188 FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1189
1190 if (!FuncType) {
1191 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1192 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1193 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1194 return ExprError();
1195 }
1196
1197 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1198 if (!FT->getNumParams()) {
1199 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1200 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1201 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1202 return ExprError();
1203 }
1204 QualType PT = FT->getParamType(0);
1205 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1206 !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1207 !PT->getPointeeType().isConstQualified()) {
1208 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1209 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1210 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1211 return ExprError();
1212 }
1213 }
1214
1215 TheCall->setType(Context.IntTy);
1216 break;
1217 }
1218
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001219 // check secure string manipulation functions where overflows
1220 // are detectable at compile time
1221 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001222 case Builtin::BI__builtin___memmove_chk:
1223 case Builtin::BI__builtin___memset_chk:
1224 case Builtin::BI__builtin___strlcat_chk:
1225 case Builtin::BI__builtin___strlcpy_chk:
1226 case Builtin::BI__builtin___strncat_chk:
1227 case Builtin::BI__builtin___strncpy_chk:
1228 case Builtin::BI__builtin___stpncpy_chk:
1229 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
1230 break;
Steven Wu566c14e2014-09-24 04:37:33 +00001231 case Builtin::BI__builtin___memccpy_chk:
1232 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
1233 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001234 case Builtin::BI__builtin___snprintf_chk:
1235 case Builtin::BI__builtin___vsnprintf_chk:
1236 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
1237 break;
Peter Collingbournef7706832014-12-12 23:41:25 +00001238 case Builtin::BI__builtin_call_with_static_chain:
1239 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1240 return ExprError();
1241 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001242 case Builtin::BI__exception_code:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001243 case Builtin::BI_exception_code:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001244 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1245 diag::err_seh___except_block))
1246 return ExprError();
1247 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001248 case Builtin::BI__exception_info:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001249 case Builtin::BI_exception_info:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001250 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1251 diag::err_seh___except_filter))
1252 return ExprError();
1253 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +00001254 case Builtin::BI__GetExceptionInfo:
1255 if (checkArgCount(*this, TheCall, 1))
1256 return ExprError();
1257
1258 if (CheckCXXThrowOperand(
1259 TheCall->getLocStart(),
1260 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1261 TheCall))
1262 return ExprError();
1263
1264 TheCall->setType(Context.VoidPtrTy);
1265 break;
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +00001266 // OpenCL v2.0, s6.13.16 - Pipe functions
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001267 case Builtin::BIread_pipe:
1268 case Builtin::BIwrite_pipe:
1269 // Since those two functions are declared with var args, we need a semantic
1270 // check for the argument.
1271 if (SemaBuiltinRWPipe(*this, TheCall))
1272 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001273 TheCall->setType(Context.IntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001274 break;
1275 case Builtin::BIreserve_read_pipe:
1276 case Builtin::BIreserve_write_pipe:
1277 case Builtin::BIwork_group_reserve_read_pipe:
1278 case Builtin::BIwork_group_reserve_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001279 if (SemaBuiltinReserveRWPipe(*this, TheCall))
1280 return ExprError();
Joey Gouly84ae3362017-07-31 15:15:59 +00001281 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001282 case Builtin::BIsub_group_reserve_read_pipe:
1283 case Builtin::BIsub_group_reserve_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001284 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1285 SemaBuiltinReserveRWPipe(*this, TheCall))
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001286 return ExprError();
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001287 break;
1288 case Builtin::BIcommit_read_pipe:
1289 case Builtin::BIcommit_write_pipe:
1290 case Builtin::BIwork_group_commit_read_pipe:
1291 case Builtin::BIwork_group_commit_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001292 if (SemaBuiltinCommitRWPipe(*this, TheCall))
1293 return ExprError();
1294 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001295 case Builtin::BIsub_group_commit_read_pipe:
1296 case Builtin::BIsub_group_commit_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001297 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1298 SemaBuiltinCommitRWPipe(*this, TheCall))
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001299 return ExprError();
1300 break;
1301 case Builtin::BIget_pipe_num_packets:
1302 case Builtin::BIget_pipe_max_packets:
1303 if (SemaBuiltinPipePackets(*this, TheCall))
1304 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001305 TheCall->setType(Context.UnsignedIntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001306 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +00001307 case Builtin::BIto_global:
1308 case Builtin::BIto_local:
1309 case Builtin::BIto_private:
1310 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1311 return ExprError();
1312 break;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001313 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1314 case Builtin::BIenqueue_kernel:
1315 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1316 return ExprError();
1317 break;
1318 case Builtin::BIget_kernel_work_group_size:
1319 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1320 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1321 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001322 break;
Joey Goulyfa76b492017-08-01 13:27:09 +00001323 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1324 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1325 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1326 return ExprError();
1327 break;
Mehdi Amini06d367c2016-10-24 20:39:34 +00001328 case Builtin::BI__builtin_os_log_format:
1329 case Builtin::BI__builtin_os_log_format_buffer_size:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00001330 if (SemaBuiltinOSLogFormat(TheCall))
Mehdi Amini06d367c2016-10-24 20:39:34 +00001331 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001332 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001333 }
Richard Smith760520b2014-06-03 23:27:44 +00001334
Nate Begeman4904e322010-06-08 02:47:44 +00001335 // Since the target specific builtins for each arch overlap, only check those
1336 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +00001337 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001338 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +00001339 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001340 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001341 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001342 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001343 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1344 return ExprError();
1345 break;
Tim Northover25e8a672014-05-24 12:51:25 +00001346 case llvm::Triple::aarch64:
1347 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +00001348 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +00001349 return ExprError();
1350 break;
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00001351 case llvm::Triple::hexagon:
1352 if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall))
1353 return ExprError();
1354 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001355 case llvm::Triple::mips:
1356 case llvm::Triple::mipsel:
1357 case llvm::Triple::mips64:
1358 case llvm::Triple::mips64el:
1359 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1360 return ExprError();
1361 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001362 case llvm::Triple::systemz:
1363 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1364 return ExprError();
1365 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001366 case llvm::Triple::x86:
1367 case llvm::Triple::x86_64:
1368 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1369 return ExprError();
1370 break;
Kit Bartone50adcb2015-03-30 19:40:59 +00001371 case llvm::Triple::ppc:
1372 case llvm::Triple::ppc64:
1373 case llvm::Triple::ppc64le:
1374 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1375 return ExprError();
1376 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001377 default:
1378 break;
1379 }
1380 }
1381
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001382 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +00001383}
1384
Nate Begeman91e1fea2010-06-14 05:21:25 +00001385// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +00001386static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +00001387 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +00001388 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +00001389 switch (Type.getEltType()) {
1390 case NeonTypeFlags::Int8:
1391 case NeonTypeFlags::Poly8:
1392 return shift ? 7 : (8 << IsQuad) - 1;
1393 case NeonTypeFlags::Int16:
1394 case NeonTypeFlags::Poly16:
1395 return shift ? 15 : (4 << IsQuad) - 1;
1396 case NeonTypeFlags::Int32:
1397 return shift ? 31 : (2 << IsQuad) - 1;
1398 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +00001399 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +00001400 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001401 case NeonTypeFlags::Poly128:
1402 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +00001403 case NeonTypeFlags::Float16:
1404 assert(!shift && "cannot shift float types!");
1405 return (4 << IsQuad) - 1;
1406 case NeonTypeFlags::Float32:
1407 assert(!shift && "cannot shift float types!");
1408 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001409 case NeonTypeFlags::Float64:
1410 assert(!shift && "cannot shift float types!");
1411 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +00001412 }
David Blaikie8a40f702012-01-17 06:56:22 +00001413 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +00001414}
1415
Bob Wilsone4d77232011-11-08 05:04:11 +00001416/// getNeonEltType - Return the QualType corresponding to the elements of
1417/// the vector type specified by the NeonTypeFlags. This is used to check
1418/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +00001419static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +00001420 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +00001421 switch (Flags.getEltType()) {
1422 case NeonTypeFlags::Int8:
1423 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1424 case NeonTypeFlags::Int16:
1425 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1426 case NeonTypeFlags::Int32:
1427 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1428 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +00001429 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +00001430 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1431 else
1432 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1433 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001434 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +00001435 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001436 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +00001437 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +00001438 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +00001439 if (IsInt64Long)
1440 return Context.UnsignedLongTy;
1441 else
1442 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001443 case NeonTypeFlags::Poly128:
1444 break;
Bob Wilsone4d77232011-11-08 05:04:11 +00001445 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +00001446 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001447 case NeonTypeFlags::Float32:
1448 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +00001449 case NeonTypeFlags::Float64:
1450 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001451 }
David Blaikie8a40f702012-01-17 06:56:22 +00001452 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +00001453}
1454
Tim Northover12670412014-02-19 10:37:05 +00001455bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +00001456 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +00001457 uint64_t mask = 0;
1458 unsigned TV = 0;
1459 int PtrArgNum = -1;
1460 bool HasConstPtr = false;
1461 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +00001462#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001463#include "clang/Basic/arm_neon.inc"
Abderrazek Zaafranice8746d2018-01-19 23:11:18 +00001464#include "clang/Basic/arm_fp16.inc"
Tim Northover12670412014-02-19 10:37:05 +00001465#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001466 }
1467
1468 // For NEON intrinsics which are overloaded on vector element type, validate
1469 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +00001470 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001471 if (mask) {
1472 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1473 return true;
1474
1475 TV = Result.getLimitedValue(64);
1476 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1477 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +00001478 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +00001479 }
1480
1481 if (PtrArgNum >= 0) {
1482 // Check that pointer arguments have the specified type.
1483 Expr *Arg = TheCall->getArg(PtrArgNum);
1484 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1485 Arg = ICE->getSubExpr();
1486 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1487 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +00001488
Tim Northovera2ee4332014-03-29 15:09:45 +00001489 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Joerg Sonnenberger47006c52017-01-09 11:40:41 +00001490 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1491 Arch == llvm::Triple::aarch64_be;
Tim Northovera2ee4332014-03-29 15:09:45 +00001492 bool IsInt64Long =
1493 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1494 QualType EltTy =
1495 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +00001496 if (HasConstPtr)
1497 EltTy = EltTy.withConst();
1498 QualType LHSTy = Context.getPointerType(EltTy);
1499 AssignConvertType ConvTy;
1500 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1501 if (RHS.isInvalid())
1502 return true;
1503 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1504 RHS.get(), AA_Assigning))
1505 return true;
1506 }
1507
1508 // For NEON intrinsics which take an immediate value as part of the
1509 // instruction, range check them here.
1510 unsigned i = 0, l = 0, u = 0;
1511 switch (BuiltinID) {
1512 default:
1513 return false;
Luke Geesondc54b372018-06-12 09:54:27 +00001514 #define GET_NEON_IMMEDIATE_CHECK
1515 #include "clang/Basic/arm_neon.inc"
1516 #include "clang/Basic/arm_fp16.inc"
1517 #undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001518 }
Tim Northover2fe823a2013-08-01 09:23:19 +00001519
Richard Sandiford28940af2014-04-16 08:47:51 +00001520 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +00001521}
1522
Tim Northovera2ee4332014-03-29 15:09:45 +00001523bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1524 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +00001525 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001526 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +00001527 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001528 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +00001529 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001530 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1531 BuiltinID == AArch64::BI__builtin_arm_strex ||
1532 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +00001533 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +00001534 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001535 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1536 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1537 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +00001538
1539 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1540
1541 // Ensure that we have the proper number of arguments.
1542 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1543 return true;
1544
1545 // Inspect the pointer argument of the atomic builtin. This should always be
1546 // a pointer type, whose element is an integral scalar or pointer type.
1547 // Because it is a pointer type, we don't have to worry about any implicit
1548 // casts here.
1549 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1550 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1551 if (PointerArgRes.isInvalid())
1552 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001553 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001554
1555 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1556 if (!pointerType) {
1557 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1558 << PointerArg->getType() << PointerArg->getSourceRange();
1559 return true;
1560 }
1561
1562 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1563 // task is to insert the appropriate casts into the AST. First work out just
1564 // what the appropriate type is.
1565 QualType ValType = pointerType->getPointeeType();
1566 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1567 if (IsLdrex)
1568 AddrType.addConst();
1569
1570 // Issue a warning if the cast is dodgy.
1571 CastKind CastNeeded = CK_NoOp;
1572 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1573 CastNeeded = CK_BitCast;
1574 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1575 << PointerArg->getType()
1576 << Context.getPointerType(AddrType)
1577 << AA_Passing << PointerArg->getSourceRange();
1578 }
1579
1580 // Finally, do the cast and replace the argument with the corrected version.
1581 AddrType = Context.getPointerType(AddrType);
1582 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1583 if (PointerArgRes.isInvalid())
1584 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001585 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001586
1587 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1588
1589 // In general, we allow ints, floats and pointers to be loaded and stored.
1590 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1591 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1592 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1593 << PointerArg->getType() << PointerArg->getSourceRange();
1594 return true;
1595 }
1596
1597 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001598 if (Context.getTypeSize(ValType) > MaxWidth) {
1599 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +00001600 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1601 << PointerArg->getType() << PointerArg->getSourceRange();
1602 return true;
1603 }
1604
1605 switch (ValType.getObjCLifetime()) {
1606 case Qualifiers::OCL_None:
1607 case Qualifiers::OCL_ExplicitNone:
1608 // okay
1609 break;
1610
1611 case Qualifiers::OCL_Weak:
1612 case Qualifiers::OCL_Strong:
1613 case Qualifiers::OCL_Autoreleasing:
1614 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1615 << ValType << PointerArg->getSourceRange();
1616 return true;
1617 }
1618
Tim Northover6aacd492013-07-16 09:47:53 +00001619 if (IsLdrex) {
1620 TheCall->setType(ValType);
1621 return false;
1622 }
1623
1624 // Initialize the argument to be stored.
1625 ExprResult ValArg = TheCall->getArg(0);
1626 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1627 Context, ValType, /*consume*/ false);
1628 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1629 if (ValArg.isInvalid())
1630 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001631 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001632
1633 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1634 // but the custom checker bypasses all default analysis.
1635 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001636 return false;
1637}
1638
Nate Begeman4904e322010-06-08 02:47:44 +00001639bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover6aacd492013-07-16 09:47:53 +00001640 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001641 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1642 BuiltinID == ARM::BI__builtin_arm_strex ||
1643 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001644 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001645 }
1646
Yi Kong26d104a2014-08-13 19:18:14 +00001647 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1648 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1649 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1650 }
1651
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001652 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1653 BuiltinID == ARM::BI__builtin_arm_wsr64)
1654 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1655
1656 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1657 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1658 BuiltinID == ARM::BI__builtin_arm_wsr ||
1659 BuiltinID == ARM::BI__builtin_arm_wsrp)
1660 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1661
Tim Northover12670412014-02-19 10:37:05 +00001662 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1663 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001664
Yi Kong4efadfb2014-07-03 16:01:25 +00001665 // For intrinsics which take an immediate value as part of the instruction,
1666 // range check them here.
Sjoerd Meijer293da702017-12-07 09:54:39 +00001667 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begemand773fe62010-06-13 04:47:52 +00001668 switch (BuiltinID) {
1669 default: return false;
Sjoerd Meijer293da702017-12-07 09:54:39 +00001670 case ARM::BI__builtin_arm_ssat:
1671 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
1672 case ARM::BI__builtin_arm_usat:
1673 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
1674 case ARM::BI__builtin_arm_ssat16:
1675 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
1676 case ARM::BI__builtin_arm_usat16:
1677 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
Nate Begemanf568b072010-08-03 21:32:34 +00001678 case ARM::BI__builtin_arm_vcvtr_f:
Sjoerd Meijer293da702017-12-07 09:54:39 +00001679 case ARM::BI__builtin_arm_vcvtr_d:
1680 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
Weiming Zhao87bb4922013-11-12 21:42:50 +00001681 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001682 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001683 case ARM::BI__builtin_arm_isb:
Sjoerd Meijer293da702017-12-07 09:54:39 +00001684 case ARM::BI__builtin_arm_dbg:
1685 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
Richard Sandiford28940af2014-04-16 08:47:51 +00001686 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001687}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001688
Tim Northover573cbee2014-05-24 12:52:07 +00001689bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001690 CallExpr *TheCall) {
Tim Northover573cbee2014-05-24 12:52:07 +00001691 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001692 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1693 BuiltinID == AArch64::BI__builtin_arm_strex ||
1694 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001695 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1696 }
1697
Yi Konga5548432014-08-13 19:18:20 +00001698 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1699 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1700 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1701 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1702 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1703 }
1704
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001705 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1706 BuiltinID == AArch64::BI__builtin_arm_wsr64)
Tim Northover54e50002016-04-13 17:08:55 +00001707 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001708
1709 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1710 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1711 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1712 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1713 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1714
Tim Northovera2ee4332014-03-29 15:09:45 +00001715 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1716 return true;
1717
Yi Kong19a29ac2014-07-17 10:52:06 +00001718 // For intrinsics which take an immediate value as part of the instruction,
1719 // range check them here.
1720 unsigned i = 0, l = 0, u = 0;
1721 switch (BuiltinID) {
1722 default: return false;
1723 case AArch64::BI__builtin_arm_dmb:
1724 case AArch64::BI__builtin_arm_dsb:
1725 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1726 }
1727
Yi Kong19a29ac2014-07-17 10:52:06 +00001728 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001729}
1730
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00001731bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
1732 CallExpr *TheCall) {
1733 struct ArgInfo {
1734 ArgInfo(unsigned O, bool S, unsigned W, unsigned A)
1735 : OpNum(O), IsSigned(S), BitWidth(W), Align(A) {}
1736 unsigned OpNum = 0;
1737 bool IsSigned = false;
1738 unsigned BitWidth = 0;
1739 unsigned Align = 0;
1740 };
1741
1742 static const std::map<unsigned, std::vector<ArgInfo>> Infos = {
1743 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} },
1744 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} },
1745 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} },
1746 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 0 }} },
1747 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} },
1748 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} },
1749 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} },
1750 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} },
1751 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} },
1752 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} },
1753 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} },
1754
1755 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} },
1756 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} },
1757 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} },
1758 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} },
1759 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} },
1760 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} },
1761 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} },
1762 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} },
1763 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} },
1764 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} },
1765 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} },
1766
1767 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} },
1768 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} },
1769 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} },
1770 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} },
1771 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} },
1772 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} },
1773 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} },
1774 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} },
1775 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} },
1776 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} },
1777 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} },
1778 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} },
1779 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} },
1780 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} },
1781 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} },
1782 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} },
1783 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} },
1784 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} },
1785 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} },
1786 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} },
1787 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} },
1788 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} },
1789 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} },
1790 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} },
1791 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} },
1792 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} },
1793 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} },
1794 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} },
1795 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} },
1796 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} },
1797 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} },
1798 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} },
1799 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} },
1800 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} },
1801 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} },
1802 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} },
1803 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} },
1804 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} },
1805 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} },
1806 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} },
1807 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} },
1808 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} },
1809 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} },
1810 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} },
1811 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} },
1812 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} },
1813 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} },
1814 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} },
1815 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} },
1816 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} },
1817 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} },
1818 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
1819 {{ 1, false, 6, 0 }} },
1820 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} },
1821 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} },
1822 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} },
1823 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} },
1824 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} },
1825 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} },
1826 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
1827 {{ 1, false, 5, 0 }} },
1828 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} },
1829 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} },
1830 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} },
1831 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} },
1832 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} },
1833 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 },
1834 { 2, false, 5, 0 }} },
1835 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 },
1836 { 2, false, 6, 0 }} },
1837 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 },
1838 { 3, false, 5, 0 }} },
1839 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 },
1840 { 3, false, 6, 0 }} },
1841 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} },
1842 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} },
1843 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} },
1844 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} },
1845 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} },
1846 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} },
1847 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} },
1848 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} },
1849 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} },
1850 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} },
1851 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} },
1852 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} },
1853 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} },
1854 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} },
1855 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} },
1856 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
1857 {{ 2, false, 4, 0 },
1858 { 3, false, 5, 0 }} },
1859 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
1860 {{ 2, false, 4, 0 },
1861 { 3, false, 5, 0 }} },
1862 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
1863 {{ 2, false, 4, 0 },
1864 { 3, false, 5, 0 }} },
1865 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
1866 {{ 2, false, 4, 0 },
1867 { 3, false, 5, 0 }} },
1868 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} },
1869 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} },
1870 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} },
1871 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} },
1872 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} },
1873 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} },
1874 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} },
1875 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} },
1876 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} },
1877 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} },
1878 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 },
1879 { 2, false, 5, 0 }} },
1880 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 },
1881 { 2, false, 6, 0 }} },
1882 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} },
1883 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} },
1884 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} },
1885 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} },
1886 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} },
1887 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} },
1888 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} },
1889 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} },
1890 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
1891 {{ 1, false, 4, 0 }} },
1892 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} },
1893 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
1894 {{ 1, false, 4, 0 }} },
1895 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} },
1896 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} },
1897 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} },
1898 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} },
1899 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} },
1900 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} },
1901 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} },
1902 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} },
1903 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} },
1904 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} },
1905 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} },
1906 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} },
1907 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} },
1908 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} },
1909 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} },
1910 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} },
1911 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} },
1912 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} },
1913 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} },
1914 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
1915 {{ 3, false, 1, 0 }} },
1916 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} },
1917 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} },
1918 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} },
1919 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
1920 {{ 3, false, 1, 0 }} },
1921 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} },
1922 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} },
1923 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} },
1924 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
1925 {{ 3, false, 1, 0 }} },
1926 };
1927
1928 auto F = Infos.find(BuiltinID);
1929 if (F == Infos.end())
1930 return false;
1931
1932 bool Error = false;
1933
1934 for (const ArgInfo &A : F->second) {
1935 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth-1)) : 0;
1936 int32_t Max = (1 << (A.IsSigned ? A.BitWidth-1 : A.BitWidth)) - 1;
1937 if (!A.Align) {
1938 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
1939 } else {
1940 unsigned M = 1 << A.Align;
1941 Min *= M;
1942 Max *= M;
1943 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
1944 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
1945 }
1946 }
1947 return Error;
1948}
1949
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001950// CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1951// intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1952// ordering for DSP is unspecified. MSA is ordered by the data format used
1953// by the underlying instruction i.e., df/m, df/n and then by size.
1954//
1955// FIXME: The size tests here should instead be tablegen'd along with the
1956// definitions from include/clang/Basic/BuiltinsMips.def.
1957// FIXME: GCC is strict on signedness for some of these intrinsics, we should
1958// be too.
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001959bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001960 unsigned i = 0, l = 0, u = 0, m = 0;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001961 switch (BuiltinID) {
1962 default: return false;
1963 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1964 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00001965 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1966 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1967 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1968 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1969 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001970 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1971 // df/m field.
1972 // These intrinsics take an unsigned 3 bit immediate.
1973 case Mips::BI__builtin_msa_bclri_b:
1974 case Mips::BI__builtin_msa_bnegi_b:
1975 case Mips::BI__builtin_msa_bseti_b:
1976 case Mips::BI__builtin_msa_sat_s_b:
1977 case Mips::BI__builtin_msa_sat_u_b:
1978 case Mips::BI__builtin_msa_slli_b:
1979 case Mips::BI__builtin_msa_srai_b:
1980 case Mips::BI__builtin_msa_srari_b:
1981 case Mips::BI__builtin_msa_srli_b:
1982 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1983 case Mips::BI__builtin_msa_binsli_b:
1984 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1985 // These intrinsics take an unsigned 4 bit immediate.
1986 case Mips::BI__builtin_msa_bclri_h:
1987 case Mips::BI__builtin_msa_bnegi_h:
1988 case Mips::BI__builtin_msa_bseti_h:
1989 case Mips::BI__builtin_msa_sat_s_h:
1990 case Mips::BI__builtin_msa_sat_u_h:
1991 case Mips::BI__builtin_msa_slli_h:
1992 case Mips::BI__builtin_msa_srai_h:
1993 case Mips::BI__builtin_msa_srari_h:
1994 case Mips::BI__builtin_msa_srli_h:
1995 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1996 case Mips::BI__builtin_msa_binsli_h:
1997 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00001998 // These intrinsics take an unsigned 5 bit immediate.
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001999 // The first block of intrinsics actually have an unsigned 5 bit field,
2000 // not a df/n field.
2001 case Mips::BI__builtin_msa_clei_u_b:
2002 case Mips::BI__builtin_msa_clei_u_h:
2003 case Mips::BI__builtin_msa_clei_u_w:
2004 case Mips::BI__builtin_msa_clei_u_d:
2005 case Mips::BI__builtin_msa_clti_u_b:
2006 case Mips::BI__builtin_msa_clti_u_h:
2007 case Mips::BI__builtin_msa_clti_u_w:
2008 case Mips::BI__builtin_msa_clti_u_d:
2009 case Mips::BI__builtin_msa_maxi_u_b:
2010 case Mips::BI__builtin_msa_maxi_u_h:
2011 case Mips::BI__builtin_msa_maxi_u_w:
2012 case Mips::BI__builtin_msa_maxi_u_d:
2013 case Mips::BI__builtin_msa_mini_u_b:
2014 case Mips::BI__builtin_msa_mini_u_h:
2015 case Mips::BI__builtin_msa_mini_u_w:
2016 case Mips::BI__builtin_msa_mini_u_d:
2017 case Mips::BI__builtin_msa_addvi_b:
2018 case Mips::BI__builtin_msa_addvi_h:
2019 case Mips::BI__builtin_msa_addvi_w:
2020 case Mips::BI__builtin_msa_addvi_d:
2021 case Mips::BI__builtin_msa_bclri_w:
2022 case Mips::BI__builtin_msa_bnegi_w:
2023 case Mips::BI__builtin_msa_bseti_w:
2024 case Mips::BI__builtin_msa_sat_s_w:
2025 case Mips::BI__builtin_msa_sat_u_w:
2026 case Mips::BI__builtin_msa_slli_w:
2027 case Mips::BI__builtin_msa_srai_w:
2028 case Mips::BI__builtin_msa_srari_w:
2029 case Mips::BI__builtin_msa_srli_w:
2030 case Mips::BI__builtin_msa_srlri_w:
2031 case Mips::BI__builtin_msa_subvi_b:
2032 case Mips::BI__builtin_msa_subvi_h:
2033 case Mips::BI__builtin_msa_subvi_w:
2034 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
2035 case Mips::BI__builtin_msa_binsli_w:
2036 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
2037 // These intrinsics take an unsigned 6 bit immediate.
2038 case Mips::BI__builtin_msa_bclri_d:
2039 case Mips::BI__builtin_msa_bnegi_d:
2040 case Mips::BI__builtin_msa_bseti_d:
2041 case Mips::BI__builtin_msa_sat_s_d:
2042 case Mips::BI__builtin_msa_sat_u_d:
2043 case Mips::BI__builtin_msa_slli_d:
2044 case Mips::BI__builtin_msa_srai_d:
2045 case Mips::BI__builtin_msa_srari_d:
2046 case Mips::BI__builtin_msa_srli_d:
2047 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
2048 case Mips::BI__builtin_msa_binsli_d:
2049 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
2050 // These intrinsics take a signed 5 bit immediate.
2051 case Mips::BI__builtin_msa_ceqi_b:
2052 case Mips::BI__builtin_msa_ceqi_h:
2053 case Mips::BI__builtin_msa_ceqi_w:
2054 case Mips::BI__builtin_msa_ceqi_d:
2055 case Mips::BI__builtin_msa_clti_s_b:
2056 case Mips::BI__builtin_msa_clti_s_h:
2057 case Mips::BI__builtin_msa_clti_s_w:
2058 case Mips::BI__builtin_msa_clti_s_d:
2059 case Mips::BI__builtin_msa_clei_s_b:
2060 case Mips::BI__builtin_msa_clei_s_h:
2061 case Mips::BI__builtin_msa_clei_s_w:
2062 case Mips::BI__builtin_msa_clei_s_d:
2063 case Mips::BI__builtin_msa_maxi_s_b:
2064 case Mips::BI__builtin_msa_maxi_s_h:
2065 case Mips::BI__builtin_msa_maxi_s_w:
2066 case Mips::BI__builtin_msa_maxi_s_d:
2067 case Mips::BI__builtin_msa_mini_s_b:
2068 case Mips::BI__builtin_msa_mini_s_h:
2069 case Mips::BI__builtin_msa_mini_s_w:
2070 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
2071 // These intrinsics take an unsigned 8 bit immediate.
2072 case Mips::BI__builtin_msa_andi_b:
2073 case Mips::BI__builtin_msa_nori_b:
2074 case Mips::BI__builtin_msa_ori_b:
2075 case Mips::BI__builtin_msa_shf_b:
2076 case Mips::BI__builtin_msa_shf_h:
2077 case Mips::BI__builtin_msa_shf_w:
2078 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
2079 case Mips::BI__builtin_msa_bseli_b:
2080 case Mips::BI__builtin_msa_bmnzi_b:
2081 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
2082 // df/n format
2083 // These intrinsics take an unsigned 4 bit immediate.
2084 case Mips::BI__builtin_msa_copy_s_b:
2085 case Mips::BI__builtin_msa_copy_u_b:
2086 case Mips::BI__builtin_msa_insve_b:
2087 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002088 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
2089 // These intrinsics take an unsigned 3 bit immediate.
2090 case Mips::BI__builtin_msa_copy_s_h:
2091 case Mips::BI__builtin_msa_copy_u_h:
2092 case Mips::BI__builtin_msa_insve_h:
2093 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002094 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
2095 // These intrinsics take an unsigned 2 bit immediate.
2096 case Mips::BI__builtin_msa_copy_s_w:
2097 case Mips::BI__builtin_msa_copy_u_w:
2098 case Mips::BI__builtin_msa_insve_w:
2099 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002100 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
2101 // These intrinsics take an unsigned 1 bit immediate.
2102 case Mips::BI__builtin_msa_copy_s_d:
2103 case Mips::BI__builtin_msa_copy_u_d:
2104 case Mips::BI__builtin_msa_insve_d:
2105 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002106 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
2107 // Memory offsets and immediate loads.
2108 // These intrinsics take a signed 10 bit immediate.
Petar Jovanovic9b8b9e82017-03-31 16:16:43 +00002109 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002110 case Mips::BI__builtin_msa_ldi_h:
2111 case Mips::BI__builtin_msa_ldi_w:
2112 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
2113 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
2114 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
2115 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
2116 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
2117 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
2118 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
2119 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
2120 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00002121 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00002122
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002123 if (!m)
2124 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2125
2126 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
2127 SemaBuiltinConstantArgMultiple(TheCall, i, m);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00002128}
2129
Kit Bartone50adcb2015-03-30 19:40:59 +00002130bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2131 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00002132 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
2133 BuiltinID == PPC::BI__builtin_divdeu ||
2134 BuiltinID == PPC::BI__builtin_bpermd;
2135 bool IsTarget64Bit = Context.getTargetInfo()
2136 .getTypeWidth(Context
2137 .getTargetInfo()
2138 .getIntPtrType()) == 64;
2139 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
2140 BuiltinID == PPC::BI__builtin_divweu ||
2141 BuiltinID == PPC::BI__builtin_divde ||
2142 BuiltinID == PPC::BI__builtin_divdeu;
2143
2144 if (Is64BitBltin && !IsTarget64Bit)
2145 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
2146 << TheCall->getSourceRange();
2147
2148 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
2149 (BuiltinID == PPC::BI__builtin_bpermd &&
2150 !Context.getTargetInfo().hasFeature("bpermd")))
2151 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
2152 << TheCall->getSourceRange();
2153
Kit Bartone50adcb2015-03-30 19:40:59 +00002154 switch (BuiltinID) {
2155 default: return false;
2156 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
2157 case PPC::BI__builtin_altivec_crypto_vshasigmad:
2158 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2159 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
2160 case PPC::BI__builtin_tbegin:
2161 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
2162 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
2163 case PPC::BI__builtin_tabortwc:
2164 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
2165 case PPC::BI__builtin_tabortwci:
2166 case PPC::BI__builtin_tabortdci:
2167 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
2168 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
Tony Jiangbbc48e92017-05-24 15:13:32 +00002169 case PPC::BI__builtin_vsx_xxpermdi:
Tony Jiang9aa2c032017-05-24 15:54:13 +00002170 case PPC::BI__builtin_vsx_xxsldwi:
Tony Jiangbbc48e92017-05-24 15:13:32 +00002171 return SemaBuiltinVSX(TheCall);
Kit Bartone50adcb2015-03-30 19:40:59 +00002172 }
2173 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2174}
2175
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00002176bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
2177 CallExpr *TheCall) {
2178 if (BuiltinID == SystemZ::BI__builtin_tabort) {
2179 Expr *Arg = TheCall->getArg(0);
2180 llvm::APSInt AbortCode(32);
2181 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
2182 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
2183 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
2184 << Arg->getSourceRange();
2185 }
2186
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00002187 // For intrinsics which take an immediate value as part of the instruction,
2188 // range check them here.
2189 unsigned i = 0, l = 0, u = 0;
2190 switch (BuiltinID) {
2191 default: return false;
2192 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
2193 case SystemZ::BI__builtin_s390_verimb:
2194 case SystemZ::BI__builtin_s390_verimh:
2195 case SystemZ::BI__builtin_s390_verimf:
2196 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
2197 case SystemZ::BI__builtin_s390_vfaeb:
2198 case SystemZ::BI__builtin_s390_vfaeh:
2199 case SystemZ::BI__builtin_s390_vfaef:
2200 case SystemZ::BI__builtin_s390_vfaebs:
2201 case SystemZ::BI__builtin_s390_vfaehs:
2202 case SystemZ::BI__builtin_s390_vfaefs:
2203 case SystemZ::BI__builtin_s390_vfaezb:
2204 case SystemZ::BI__builtin_s390_vfaezh:
2205 case SystemZ::BI__builtin_s390_vfaezf:
2206 case SystemZ::BI__builtin_s390_vfaezbs:
2207 case SystemZ::BI__builtin_s390_vfaezhs:
2208 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00002209 case SystemZ::BI__builtin_s390_vfisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00002210 case SystemZ::BI__builtin_s390_vfidb:
2211 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
2212 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00002213 case SystemZ::BI__builtin_s390_vftcisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00002214 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
2215 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
2216 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
2217 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
2218 case SystemZ::BI__builtin_s390_vstrcb:
2219 case SystemZ::BI__builtin_s390_vstrch:
2220 case SystemZ::BI__builtin_s390_vstrcf:
2221 case SystemZ::BI__builtin_s390_vstrczb:
2222 case SystemZ::BI__builtin_s390_vstrczh:
2223 case SystemZ::BI__builtin_s390_vstrczf:
2224 case SystemZ::BI__builtin_s390_vstrcbs:
2225 case SystemZ::BI__builtin_s390_vstrchs:
2226 case SystemZ::BI__builtin_s390_vstrcfs:
2227 case SystemZ::BI__builtin_s390_vstrczbs:
2228 case SystemZ::BI__builtin_s390_vstrczhs:
2229 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00002230 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
2231 case SystemZ::BI__builtin_s390_vfminsb:
2232 case SystemZ::BI__builtin_s390_vfmaxsb:
2233 case SystemZ::BI__builtin_s390_vfmindb:
2234 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00002235 }
2236 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00002237}
2238
Craig Topper5ba2c502015-11-07 08:08:31 +00002239/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
2240/// This checks that the target supports __builtin_cpu_supports and
2241/// that the string argument is constant and valid.
2242static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
2243 Expr *Arg = TheCall->getArg(0);
2244
2245 // Check if the argument is a string literal.
2246 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
2247 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
2248 << Arg->getSourceRange();
2249
2250 // Check the contents of the string.
2251 StringRef Feature =
2252 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
2253 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
2254 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
2255 << Arg->getSourceRange();
2256 return false;
2257}
2258
Craig Topper699ae0c2017-08-10 20:28:30 +00002259/// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
2260/// This checks that the target supports __builtin_cpu_is and
2261/// that the string argument is constant and valid.
2262static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
2263 Expr *Arg = TheCall->getArg(0);
2264
2265 // Check if the argument is a string literal.
2266 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
2267 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
2268 << Arg->getSourceRange();
2269
2270 // Check the contents of the string.
2271 StringRef Feature =
2272 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
2273 if (!S.Context.getTargetInfo().validateCpuIs(Feature))
2274 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is)
2275 << Arg->getSourceRange();
2276 return false;
2277}
2278
Craig Toppera7e253e2016-09-23 04:48:31 +00002279// Check if the rounding mode is legal.
2280bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
2281 // Indicates if this instruction has rounding control or just SAE.
2282 bool HasRC = false;
2283
2284 unsigned ArgNum = 0;
2285 switch (BuiltinID) {
2286 default:
2287 return false;
2288 case X86::BI__builtin_ia32_vcvttsd2si32:
2289 case X86::BI__builtin_ia32_vcvttsd2si64:
2290 case X86::BI__builtin_ia32_vcvttsd2usi32:
2291 case X86::BI__builtin_ia32_vcvttsd2usi64:
2292 case X86::BI__builtin_ia32_vcvttss2si32:
2293 case X86::BI__builtin_ia32_vcvttss2si64:
2294 case X86::BI__builtin_ia32_vcvttss2usi32:
2295 case X86::BI__builtin_ia32_vcvttss2usi64:
2296 ArgNum = 1;
2297 break;
2298 case X86::BI__builtin_ia32_cvtps2pd512_mask:
2299 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
2300 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
2301 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
2302 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
2303 case X86::BI__builtin_ia32_cvttps2dq512_mask:
2304 case X86::BI__builtin_ia32_cvttps2qq512_mask:
2305 case X86::BI__builtin_ia32_cvttps2udq512_mask:
2306 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
2307 case X86::BI__builtin_ia32_exp2pd_mask:
2308 case X86::BI__builtin_ia32_exp2ps_mask:
2309 case X86::BI__builtin_ia32_getexppd512_mask:
2310 case X86::BI__builtin_ia32_getexpps512_mask:
2311 case X86::BI__builtin_ia32_rcp28pd_mask:
2312 case X86::BI__builtin_ia32_rcp28ps_mask:
2313 case X86::BI__builtin_ia32_rsqrt28pd_mask:
2314 case X86::BI__builtin_ia32_rsqrt28ps_mask:
2315 case X86::BI__builtin_ia32_vcomisd:
2316 case X86::BI__builtin_ia32_vcomiss:
2317 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
2318 ArgNum = 3;
2319 break;
2320 case X86::BI__builtin_ia32_cmppd512_mask:
2321 case X86::BI__builtin_ia32_cmpps512_mask:
2322 case X86::BI__builtin_ia32_cmpsd_mask:
2323 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002324 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00002325 case X86::BI__builtin_ia32_getexpsd128_round_mask:
2326 case X86::BI__builtin_ia32_getexpss128_round_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002327 case X86::BI__builtin_ia32_maxpd512_mask:
2328 case X86::BI__builtin_ia32_maxps512_mask:
2329 case X86::BI__builtin_ia32_maxsd_round_mask:
2330 case X86::BI__builtin_ia32_maxss_round_mask:
2331 case X86::BI__builtin_ia32_minpd512_mask:
2332 case X86::BI__builtin_ia32_minps512_mask:
2333 case X86::BI__builtin_ia32_minsd_round_mask:
2334 case X86::BI__builtin_ia32_minss_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00002335 case X86::BI__builtin_ia32_rcp28sd_round_mask:
2336 case X86::BI__builtin_ia32_rcp28ss_round_mask:
2337 case X86::BI__builtin_ia32_reducepd512_mask:
2338 case X86::BI__builtin_ia32_reduceps512_mask:
2339 case X86::BI__builtin_ia32_rndscalepd_mask:
2340 case X86::BI__builtin_ia32_rndscaleps_mask:
2341 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
2342 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
2343 ArgNum = 4;
2344 break;
2345 case X86::BI__builtin_ia32_fixupimmpd512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002346 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002347 case X86::BI__builtin_ia32_fixupimmps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002348 case X86::BI__builtin_ia32_fixupimmps512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002349 case X86::BI__builtin_ia32_fixupimmsd_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002350 case X86::BI__builtin_ia32_fixupimmsd_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002351 case X86::BI__builtin_ia32_fixupimmss_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002352 case X86::BI__builtin_ia32_fixupimmss_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002353 case X86::BI__builtin_ia32_rangepd512_mask:
2354 case X86::BI__builtin_ia32_rangeps512_mask:
2355 case X86::BI__builtin_ia32_rangesd128_round_mask:
2356 case X86::BI__builtin_ia32_rangess128_round_mask:
2357 case X86::BI__builtin_ia32_reducesd_mask:
2358 case X86::BI__builtin_ia32_reducess_mask:
2359 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2360 case X86::BI__builtin_ia32_rndscaless_round_mask:
2361 ArgNum = 5;
2362 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00002363 case X86::BI__builtin_ia32_vcvtsd2si64:
2364 case X86::BI__builtin_ia32_vcvtsd2si32:
2365 case X86::BI__builtin_ia32_vcvtsd2usi32:
2366 case X86::BI__builtin_ia32_vcvtsd2usi64:
2367 case X86::BI__builtin_ia32_vcvtss2si32:
2368 case X86::BI__builtin_ia32_vcvtss2si64:
2369 case X86::BI__builtin_ia32_vcvtss2usi32:
2370 case X86::BI__builtin_ia32_vcvtss2usi64:
2371 ArgNum = 1;
2372 HasRC = true;
2373 break;
Craig Topper3614b412018-06-10 06:01:42 +00002374 case X86::BI__builtin_ia32_addpd512:
2375 case X86::BI__builtin_ia32_addps512:
2376 case X86::BI__builtin_ia32_divpd512:
2377 case X86::BI__builtin_ia32_divps512:
2378 case X86::BI__builtin_ia32_mulpd512:
2379 case X86::BI__builtin_ia32_mulps512:
2380 case X86::BI__builtin_ia32_subpd512:
2381 case X86::BI__builtin_ia32_subps512:
Craig Topper8e066312016-11-07 07:01:09 +00002382 case X86::BI__builtin_ia32_cvtsi2sd64:
2383 case X86::BI__builtin_ia32_cvtsi2ss32:
2384 case X86::BI__builtin_ia32_cvtsi2ss64:
Craig Topper7609f1c2016-10-01 21:03:50 +00002385 case X86::BI__builtin_ia32_cvtusi2sd64:
2386 case X86::BI__builtin_ia32_cvtusi2ss32:
2387 case X86::BI__builtin_ia32_cvtusi2ss64:
2388 ArgNum = 2;
2389 HasRC = true;
2390 break;
2391 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
2392 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
2393 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
2394 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
2395 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
2396 case X86::BI__builtin_ia32_cvtps2qq512_mask:
2397 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
2398 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
2399 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
2400 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
2401 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002402 case X86::BI__builtin_ia32_sqrtpd512_mask:
2403 case X86::BI__builtin_ia32_sqrtps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002404 ArgNum = 3;
2405 HasRC = true;
2406 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00002407 case X86::BI__builtin_ia32_addss_round_mask:
2408 case X86::BI__builtin_ia32_addsd_round_mask:
2409 case X86::BI__builtin_ia32_divss_round_mask:
2410 case X86::BI__builtin_ia32_divsd_round_mask:
2411 case X86::BI__builtin_ia32_mulss_round_mask:
2412 case X86::BI__builtin_ia32_mulsd_round_mask:
2413 case X86::BI__builtin_ia32_subss_round_mask:
2414 case X86::BI__builtin_ia32_subsd_round_mask:
2415 case X86::BI__builtin_ia32_scalefpd512_mask:
2416 case X86::BI__builtin_ia32_scalefps512_mask:
2417 case X86::BI__builtin_ia32_scalefsd_round_mask:
2418 case X86::BI__builtin_ia32_scalefss_round_mask:
2419 case X86::BI__builtin_ia32_getmantpd512_mask:
2420 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002421 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
2422 case X86::BI__builtin_ia32_sqrtsd_round_mask:
2423 case X86::BI__builtin_ia32_sqrtss_round_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002424 case X86::BI__builtin_ia32_vfmaddsd3_mask:
2425 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
2426 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
2427 case X86::BI__builtin_ia32_vfmaddss3_mask:
2428 case X86::BI__builtin_ia32_vfmaddss3_maskz:
2429 case X86::BI__builtin_ia32_vfmaddss3_mask3:
Craig Topperb92c77d2018-06-07 02:46:02 +00002430 case X86::BI__builtin_ia32_vfmaddpd512_mask:
2431 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
2432 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
2433 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
2434 case X86::BI__builtin_ia32_vfmaddps512_mask:
2435 case X86::BI__builtin_ia32_vfmaddps512_maskz:
2436 case X86::BI__builtin_ia32_vfmaddps512_mask3:
2437 case X86::BI__builtin_ia32_vfmsubps512_mask3:
2438 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
2439 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
2440 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
2441 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
2442 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
2443 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
2444 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
2445 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
Craig Topper7609f1c2016-10-01 21:03:50 +00002446 ArgNum = 4;
2447 HasRC = true;
2448 break;
2449 case X86::BI__builtin_ia32_getmantsd_round_mask:
2450 case X86::BI__builtin_ia32_getmantss_round_mask:
2451 ArgNum = 5;
2452 HasRC = true;
2453 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00002454 }
2455
2456 llvm::APSInt Result;
2457
2458 // We can't check the value of a dependent argument.
2459 Expr *Arg = TheCall->getArg(ArgNum);
2460 if (Arg->isTypeDependent() || Arg->isValueDependent())
2461 return false;
2462
2463 // Check constant-ness first.
2464 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2465 return true;
2466
2467 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
2468 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
2469 // combined with ROUND_NO_EXC.
2470 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
2471 Result == 8/*ROUND_NO_EXC*/ ||
2472 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
2473 return false;
2474
2475 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
2476 << Arg->getSourceRange();
2477}
2478
Craig Topperdf5beb22017-03-13 17:16:50 +00002479// Check if the gather/scatter scale is legal.
2480bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
2481 CallExpr *TheCall) {
2482 unsigned ArgNum = 0;
2483 switch (BuiltinID) {
2484 default:
2485 return false;
2486 case X86::BI__builtin_ia32_gatherpfdpd:
2487 case X86::BI__builtin_ia32_gatherpfdps:
2488 case X86::BI__builtin_ia32_gatherpfqpd:
2489 case X86::BI__builtin_ia32_gatherpfqps:
2490 case X86::BI__builtin_ia32_scatterpfdpd:
2491 case X86::BI__builtin_ia32_scatterpfdps:
2492 case X86::BI__builtin_ia32_scatterpfqpd:
2493 case X86::BI__builtin_ia32_scatterpfqps:
2494 ArgNum = 3;
2495 break;
2496 case X86::BI__builtin_ia32_gatherd_pd:
2497 case X86::BI__builtin_ia32_gatherd_pd256:
2498 case X86::BI__builtin_ia32_gatherq_pd:
2499 case X86::BI__builtin_ia32_gatherq_pd256:
2500 case X86::BI__builtin_ia32_gatherd_ps:
2501 case X86::BI__builtin_ia32_gatherd_ps256:
2502 case X86::BI__builtin_ia32_gatherq_ps:
2503 case X86::BI__builtin_ia32_gatherq_ps256:
2504 case X86::BI__builtin_ia32_gatherd_q:
2505 case X86::BI__builtin_ia32_gatherd_q256:
2506 case X86::BI__builtin_ia32_gatherq_q:
2507 case X86::BI__builtin_ia32_gatherq_q256:
2508 case X86::BI__builtin_ia32_gatherd_d:
2509 case X86::BI__builtin_ia32_gatherd_d256:
2510 case X86::BI__builtin_ia32_gatherq_d:
2511 case X86::BI__builtin_ia32_gatherq_d256:
2512 case X86::BI__builtin_ia32_gather3div2df:
2513 case X86::BI__builtin_ia32_gather3div2di:
2514 case X86::BI__builtin_ia32_gather3div4df:
2515 case X86::BI__builtin_ia32_gather3div4di:
2516 case X86::BI__builtin_ia32_gather3div4sf:
2517 case X86::BI__builtin_ia32_gather3div4si:
2518 case X86::BI__builtin_ia32_gather3div8sf:
2519 case X86::BI__builtin_ia32_gather3div8si:
2520 case X86::BI__builtin_ia32_gather3siv2df:
2521 case X86::BI__builtin_ia32_gather3siv2di:
2522 case X86::BI__builtin_ia32_gather3siv4df:
2523 case X86::BI__builtin_ia32_gather3siv4di:
2524 case X86::BI__builtin_ia32_gather3siv4sf:
2525 case X86::BI__builtin_ia32_gather3siv4si:
2526 case X86::BI__builtin_ia32_gather3siv8sf:
2527 case X86::BI__builtin_ia32_gather3siv8si:
2528 case X86::BI__builtin_ia32_gathersiv8df:
2529 case X86::BI__builtin_ia32_gathersiv16sf:
2530 case X86::BI__builtin_ia32_gatherdiv8df:
2531 case X86::BI__builtin_ia32_gatherdiv16sf:
2532 case X86::BI__builtin_ia32_gathersiv8di:
2533 case X86::BI__builtin_ia32_gathersiv16si:
2534 case X86::BI__builtin_ia32_gatherdiv8di:
2535 case X86::BI__builtin_ia32_gatherdiv16si:
2536 case X86::BI__builtin_ia32_scatterdiv2df:
2537 case X86::BI__builtin_ia32_scatterdiv2di:
2538 case X86::BI__builtin_ia32_scatterdiv4df:
2539 case X86::BI__builtin_ia32_scatterdiv4di:
2540 case X86::BI__builtin_ia32_scatterdiv4sf:
2541 case X86::BI__builtin_ia32_scatterdiv4si:
2542 case X86::BI__builtin_ia32_scatterdiv8sf:
2543 case X86::BI__builtin_ia32_scatterdiv8si:
2544 case X86::BI__builtin_ia32_scattersiv2df:
2545 case X86::BI__builtin_ia32_scattersiv2di:
2546 case X86::BI__builtin_ia32_scattersiv4df:
2547 case X86::BI__builtin_ia32_scattersiv4di:
2548 case X86::BI__builtin_ia32_scattersiv4sf:
2549 case X86::BI__builtin_ia32_scattersiv4si:
2550 case X86::BI__builtin_ia32_scattersiv8sf:
2551 case X86::BI__builtin_ia32_scattersiv8si:
2552 case X86::BI__builtin_ia32_scattersiv8df:
2553 case X86::BI__builtin_ia32_scattersiv16sf:
2554 case X86::BI__builtin_ia32_scatterdiv8df:
2555 case X86::BI__builtin_ia32_scatterdiv16sf:
2556 case X86::BI__builtin_ia32_scattersiv8di:
2557 case X86::BI__builtin_ia32_scattersiv16si:
2558 case X86::BI__builtin_ia32_scatterdiv8di:
2559 case X86::BI__builtin_ia32_scatterdiv16si:
2560 ArgNum = 4;
2561 break;
2562 }
2563
2564 llvm::APSInt Result;
2565
2566 // We can't check the value of a dependent argument.
2567 Expr *Arg = TheCall->getArg(ArgNum);
2568 if (Arg->isTypeDependent() || Arg->isValueDependent())
2569 return false;
2570
2571 // Check constant-ness first.
2572 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2573 return true;
2574
2575 if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
2576 return false;
2577
2578 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
2579 << Arg->getSourceRange();
2580}
2581
Craig Topper51738f82018-04-26 20:14:46 +00002582static bool isX86_32Builtin(unsigned BuiltinID) {
2583 // These builtins only work on x86-32 targets.
2584 switch (BuiltinID) {
2585 case X86::BI__builtin_ia32_readeflags_u32:
2586 case X86::BI__builtin_ia32_writeeflags_u32:
2587 return true;
2588 }
2589
2590 return false;
2591}
2592
Craig Topperf0ddc892016-09-23 04:48:27 +00002593bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2594 if (BuiltinID == X86::BI__builtin_cpu_supports)
2595 return SemaBuiltinCpuSupports(*this, TheCall);
2596
Craig Topper699ae0c2017-08-10 20:28:30 +00002597 if (BuiltinID == X86::BI__builtin_cpu_is)
2598 return SemaBuiltinCpuIs(*this, TheCall);
2599
Craig Topper51738f82018-04-26 20:14:46 +00002600 // Check for 32-bit only builtins on a 64-bit target.
2601 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
2602 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
2603 return Diag(TheCall->getCallee()->getLocStart(),
2604 diag::err_32_bit_builtin_64_bit_tgt);
2605
Craig Toppera7e253e2016-09-23 04:48:31 +00002606 // If the intrinsic has rounding or SAE make sure its valid.
2607 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2608 return true;
2609
Craig Topperdf5beb22017-03-13 17:16:50 +00002610 // If the intrinsic has a gather/scatter scale immediate make sure its valid.
2611 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
2612 return true;
2613
Craig Topperf0ddc892016-09-23 04:48:27 +00002614 // For intrinsics which take an immediate value as part of the instruction,
2615 // range check them here.
2616 int i = 0, l = 0, u = 0;
2617 switch (BuiltinID) {
2618 default:
2619 return false;
Craig Topper11899b02018-06-05 21:54:35 +00002620 case X86::BI__builtin_ia32_vec_ext_v2si:
Craig Topperf3914b72018-06-06 00:24:55 +00002621 case X86::BI__builtin_ia32_vec_ext_v2di:
Craig Topper3428bee2018-06-08 03:24:47 +00002622 case X86::BI__builtin_ia32_vextractf128_pd256:
2623 case X86::BI__builtin_ia32_vextractf128_ps256:
2624 case X86::BI__builtin_ia32_vextractf128_si256:
2625 case X86::BI__builtin_ia32_extract128i256:
Craig Topper5f50f3382018-06-08 21:50:07 +00002626 case X86::BI__builtin_ia32_extractf64x4_mask:
2627 case X86::BI__builtin_ia32_extracti64x4_mask:
2628 case X86::BI__builtin_ia32_extractf32x8_mask:
2629 case X86::BI__builtin_ia32_extracti32x8_mask:
2630 case X86::BI__builtin_ia32_extractf64x2_256_mask:
2631 case X86::BI__builtin_ia32_extracti64x2_256_mask:
2632 case X86::BI__builtin_ia32_extractf32x4_256_mask:
2633 case X86::BI__builtin_ia32_extracti32x4_256_mask:
Craig Topper11899b02018-06-05 21:54:35 +00002634 i = 1; l = 0; u = 1;
2635 break;
Craig Topperf3914b72018-06-06 00:24:55 +00002636 case X86::BI__builtin_ia32_vec_set_v2di:
Craig Topper3428bee2018-06-08 03:24:47 +00002637 case X86::BI__builtin_ia32_vinsertf128_pd256:
2638 case X86::BI__builtin_ia32_vinsertf128_ps256:
2639 case X86::BI__builtin_ia32_vinsertf128_si256:
2640 case X86::BI__builtin_ia32_insert128i256:
2641 case X86::BI__builtin_ia32_insertf32x8:
2642 case X86::BI__builtin_ia32_inserti32x8:
2643 case X86::BI__builtin_ia32_insertf64x4:
2644 case X86::BI__builtin_ia32_inserti64x4:
2645 case X86::BI__builtin_ia32_insertf64x2_256:
2646 case X86::BI__builtin_ia32_inserti64x2_256:
2647 case X86::BI__builtin_ia32_insertf32x4_256:
2648 case X86::BI__builtin_ia32_inserti32x4_256:
Craig Topperf3914b72018-06-06 00:24:55 +00002649 i = 2; l = 0; u = 1;
2650 break;
Craig Topperacf56012018-06-08 00:59:27 +00002651 case X86::BI__builtin_ia32_vpermilpd:
Craig Topper11899b02018-06-05 21:54:35 +00002652 case X86::BI__builtin_ia32_vec_ext_v4hi:
Craig Topperf3914b72018-06-06 00:24:55 +00002653 case X86::BI__builtin_ia32_vec_ext_v4si:
2654 case X86::BI__builtin_ia32_vec_ext_v4sf:
2655 case X86::BI__builtin_ia32_vec_ext_v4di:
Craig Topper5f50f3382018-06-08 21:50:07 +00002656 case X86::BI__builtin_ia32_extractf32x4_mask:
2657 case X86::BI__builtin_ia32_extracti32x4_mask:
2658 case X86::BI__builtin_ia32_extractf64x2_512_mask:
2659 case X86::BI__builtin_ia32_extracti64x2_512_mask:
Craig Topper11899b02018-06-05 21:54:35 +00002660 i = 1; l = 0; u = 3;
2661 break;
Craig Topperf3914b72018-06-06 00:24:55 +00002662 case X86::BI_mm_prefetch:
2663 case X86::BI__builtin_ia32_vec_ext_v8hi:
2664 case X86::BI__builtin_ia32_vec_ext_v8si:
2665 i = 1; l = 0; u = 7;
2666 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00002667 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper7d17d722018-06-08 00:00:21 +00002668 case X86::BI__builtin_ia32_blendpd:
Craig Topper422a1bb2018-06-08 07:18:33 +00002669 case X86::BI__builtin_ia32_shufpd:
Craig Topper11899b02018-06-05 21:54:35 +00002670 case X86::BI__builtin_ia32_vec_set_v4hi:
Craig Topperf3914b72018-06-06 00:24:55 +00002671 case X86::BI__builtin_ia32_vec_set_v4si:
2672 case X86::BI__builtin_ia32_vec_set_v4di:
Craig Topper93921362018-06-07 23:03:08 +00002673 case X86::BI__builtin_ia32_shuf_f32x4_256:
2674 case X86::BI__builtin_ia32_shuf_f64x2_256:
2675 case X86::BI__builtin_ia32_shuf_i32x4_256:
2676 case X86::BI__builtin_ia32_shuf_i64x2_256:
Craig Topper3428bee2018-06-08 03:24:47 +00002677 case X86::BI__builtin_ia32_insertf64x2_512:
2678 case X86::BI__builtin_ia32_inserti64x2_512:
2679 case X86::BI__builtin_ia32_insertf32x4:
2680 case X86::BI__builtin_ia32_inserti32x4:
Craig Topper39c87102016-05-18 03:18:12 +00002681 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002682 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00002683 case X86::BI__builtin_ia32_vpermil2pd:
2684 case X86::BI__builtin_ia32_vpermil2pd256:
2685 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00002686 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00002687 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002688 break;
Craig Topper95b0d732015-01-25 23:30:05 +00002689 case X86::BI__builtin_ia32_cmpb128_mask:
2690 case X86::BI__builtin_ia32_cmpw128_mask:
2691 case X86::BI__builtin_ia32_cmpd128_mask:
2692 case X86::BI__builtin_ia32_cmpq128_mask:
2693 case X86::BI__builtin_ia32_cmpb256_mask:
2694 case X86::BI__builtin_ia32_cmpw256_mask:
2695 case X86::BI__builtin_ia32_cmpd256_mask:
2696 case X86::BI__builtin_ia32_cmpq256_mask:
2697 case X86::BI__builtin_ia32_cmpb512_mask:
2698 case X86::BI__builtin_ia32_cmpw512_mask:
2699 case X86::BI__builtin_ia32_cmpd512_mask:
2700 case X86::BI__builtin_ia32_cmpq512_mask:
2701 case X86::BI__builtin_ia32_ucmpb128_mask:
2702 case X86::BI__builtin_ia32_ucmpw128_mask:
2703 case X86::BI__builtin_ia32_ucmpd128_mask:
2704 case X86::BI__builtin_ia32_ucmpq128_mask:
2705 case X86::BI__builtin_ia32_ucmpb256_mask:
2706 case X86::BI__builtin_ia32_ucmpw256_mask:
2707 case X86::BI__builtin_ia32_ucmpd256_mask:
2708 case X86::BI__builtin_ia32_ucmpq256_mask:
2709 case X86::BI__builtin_ia32_ucmpb512_mask:
2710 case X86::BI__builtin_ia32_ucmpw512_mask:
2711 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00002712 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00002713 case X86::BI__builtin_ia32_vpcomub:
2714 case X86::BI__builtin_ia32_vpcomuw:
2715 case X86::BI__builtin_ia32_vpcomud:
2716 case X86::BI__builtin_ia32_vpcomuq:
2717 case X86::BI__builtin_ia32_vpcomb:
2718 case X86::BI__builtin_ia32_vpcomw:
2719 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00002720 case X86::BI__builtin_ia32_vpcomq:
Craig Topperf3914b72018-06-06 00:24:55 +00002721 case X86::BI__builtin_ia32_vec_set_v8hi:
2722 case X86::BI__builtin_ia32_vec_set_v8si:
Craig Topper39c87102016-05-18 03:18:12 +00002723 i = 2; l = 0; u = 7;
2724 break;
Craig Topperacf56012018-06-08 00:59:27 +00002725 case X86::BI__builtin_ia32_vpermilpd256:
Craig Topper39c87102016-05-18 03:18:12 +00002726 case X86::BI__builtin_ia32_roundps:
2727 case X86::BI__builtin_ia32_roundpd:
2728 case X86::BI__builtin_ia32_roundps256:
2729 case X86::BI__builtin_ia32_roundpd256:
Craig Topper03a1d482018-06-15 17:03:32 +00002730 case X86::BI__builtin_ia32_getmantpd128_mask:
2731 case X86::BI__builtin_ia32_getmantpd256_mask:
2732 case X86::BI__builtin_ia32_getmantps128_mask:
2733 case X86::BI__builtin_ia32_getmantps256_mask:
2734 case X86::BI__builtin_ia32_getmantpd512_mask:
2735 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topperf3914b72018-06-06 00:24:55 +00002736 case X86::BI__builtin_ia32_vec_ext_v16qi:
2737 case X86::BI__builtin_ia32_vec_ext_v16hi:
Craig Topper39c87102016-05-18 03:18:12 +00002738 i = 1; l = 0; u = 15;
2739 break;
Craig Topper7d17d722018-06-08 00:00:21 +00002740 case X86::BI__builtin_ia32_pblendd128:
2741 case X86::BI__builtin_ia32_blendps:
2742 case X86::BI__builtin_ia32_blendpd256:
Craig Topper422a1bb2018-06-08 07:18:33 +00002743 case X86::BI__builtin_ia32_shufpd256:
Craig Topper39c87102016-05-18 03:18:12 +00002744 case X86::BI__builtin_ia32_roundss:
2745 case X86::BI__builtin_ia32_roundsd:
2746 case X86::BI__builtin_ia32_rangepd128_mask:
2747 case X86::BI__builtin_ia32_rangepd256_mask:
2748 case X86::BI__builtin_ia32_rangepd512_mask:
2749 case X86::BI__builtin_ia32_rangeps128_mask:
2750 case X86::BI__builtin_ia32_rangeps256_mask:
2751 case X86::BI__builtin_ia32_rangeps512_mask:
2752 case X86::BI__builtin_ia32_getmantsd_round_mask:
2753 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topperf3914b72018-06-06 00:24:55 +00002754 case X86::BI__builtin_ia32_vec_set_v16qi:
2755 case X86::BI__builtin_ia32_vec_set_v16hi:
Craig Topper39c87102016-05-18 03:18:12 +00002756 i = 2; l = 0; u = 15;
2757 break;
Craig Topperf3914b72018-06-06 00:24:55 +00002758 case X86::BI__builtin_ia32_vec_ext_v32qi:
2759 i = 1; l = 0; u = 31;
2760 break;
Craig Topper39c87102016-05-18 03:18:12 +00002761 case X86::BI__builtin_ia32_cmpps:
2762 case X86::BI__builtin_ia32_cmpss:
2763 case X86::BI__builtin_ia32_cmppd:
2764 case X86::BI__builtin_ia32_cmpsd:
2765 case X86::BI__builtin_ia32_cmpps256:
2766 case X86::BI__builtin_ia32_cmppd256:
2767 case X86::BI__builtin_ia32_cmpps128_mask:
2768 case X86::BI__builtin_ia32_cmppd128_mask:
2769 case X86::BI__builtin_ia32_cmpps256_mask:
2770 case X86::BI__builtin_ia32_cmppd256_mask:
2771 case X86::BI__builtin_ia32_cmpps512_mask:
2772 case X86::BI__builtin_ia32_cmppd512_mask:
2773 case X86::BI__builtin_ia32_cmpsd_mask:
2774 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topperf3914b72018-06-06 00:24:55 +00002775 case X86::BI__builtin_ia32_vec_set_v32qi:
Craig Topper39c87102016-05-18 03:18:12 +00002776 i = 2; l = 0; u = 31;
2777 break;
Craig Topper03f4f042018-06-08 18:00:25 +00002778 case X86::BI__builtin_ia32_permdf256:
2779 case X86::BI__builtin_ia32_permdi256:
2780 case X86::BI__builtin_ia32_permdf512:
2781 case X86::BI__builtin_ia32_permdi512:
Craig Topperacf56012018-06-08 00:59:27 +00002782 case X86::BI__builtin_ia32_vpermilps:
2783 case X86::BI__builtin_ia32_vpermilps256:
2784 case X86::BI__builtin_ia32_vpermilpd512:
2785 case X86::BI__builtin_ia32_vpermilps512:
Craig Topper03de1662018-06-08 06:13:16 +00002786 case X86::BI__builtin_ia32_pshufd:
2787 case X86::BI__builtin_ia32_pshufd256:
2788 case X86::BI__builtin_ia32_pshufd512:
2789 case X86::BI__builtin_ia32_pshufhw:
2790 case X86::BI__builtin_ia32_pshufhw256:
2791 case X86::BI__builtin_ia32_pshufhw512:
2792 case X86::BI__builtin_ia32_pshuflw:
2793 case X86::BI__builtin_ia32_pshuflw256:
2794 case X86::BI__builtin_ia32_pshuflw512:
Craig Topper39c87102016-05-18 03:18:12 +00002795 case X86::BI__builtin_ia32_vcvtps2ph:
Craig Topper23a30222017-11-08 04:54:26 +00002796 case X86::BI__builtin_ia32_vcvtps2ph_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002797 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper23a30222017-11-08 04:54:26 +00002798 case X86::BI__builtin_ia32_vcvtps2ph256_mask:
2799 case X86::BI__builtin_ia32_vcvtps2ph512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002800 case X86::BI__builtin_ia32_rndscaleps_128_mask:
2801 case X86::BI__builtin_ia32_rndscalepd_128_mask:
2802 case X86::BI__builtin_ia32_rndscaleps_256_mask:
2803 case X86::BI__builtin_ia32_rndscalepd_256_mask:
2804 case X86::BI__builtin_ia32_rndscaleps_mask:
2805 case X86::BI__builtin_ia32_rndscalepd_mask:
2806 case X86::BI__builtin_ia32_reducepd128_mask:
2807 case X86::BI__builtin_ia32_reducepd256_mask:
2808 case X86::BI__builtin_ia32_reducepd512_mask:
2809 case X86::BI__builtin_ia32_reduceps128_mask:
2810 case X86::BI__builtin_ia32_reduceps256_mask:
2811 case X86::BI__builtin_ia32_reduceps512_mask:
2812 case X86::BI__builtin_ia32_prold512_mask:
2813 case X86::BI__builtin_ia32_prolq512_mask:
2814 case X86::BI__builtin_ia32_prold128_mask:
2815 case X86::BI__builtin_ia32_prold256_mask:
2816 case X86::BI__builtin_ia32_prolq128_mask:
2817 case X86::BI__builtin_ia32_prolq256_mask:
Craig Topper4217d172018-06-15 17:40:37 +00002818 case X86::BI__builtin_ia32_prord512_mask:
2819 case X86::BI__builtin_ia32_prorq512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002820 case X86::BI__builtin_ia32_prord128_mask:
2821 case X86::BI__builtin_ia32_prord256_mask:
2822 case X86::BI__builtin_ia32_prorq128_mask:
2823 case X86::BI__builtin_ia32_prorq256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002824 case X86::BI__builtin_ia32_fpclasspd128_mask:
2825 case X86::BI__builtin_ia32_fpclasspd256_mask:
2826 case X86::BI__builtin_ia32_fpclassps128_mask:
2827 case X86::BI__builtin_ia32_fpclassps256_mask:
2828 case X86::BI__builtin_ia32_fpclassps512_mask:
2829 case X86::BI__builtin_ia32_fpclasspd512_mask:
2830 case X86::BI__builtin_ia32_fpclasssd_mask:
2831 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper31730ae2018-06-14 22:02:35 +00002832 case X86::BI__builtin_ia32_pslldqi128_byteshift:
2833 case X86::BI__builtin_ia32_pslldqi256_byteshift:
2834 case X86::BI__builtin_ia32_pslldqi512_byteshift:
2835 case X86::BI__builtin_ia32_psrldqi128_byteshift:
2836 case X86::BI__builtin_ia32_psrldqi256_byteshift:
2837 case X86::BI__builtin_ia32_psrldqi512_byteshift:
Craig Topper39c87102016-05-18 03:18:12 +00002838 i = 1; l = 0; u = 255;
2839 break;
Craig Topper9d3962f2018-06-08 18:00:22 +00002840 case X86::BI__builtin_ia32_vperm2f128_pd256:
2841 case X86::BI__builtin_ia32_vperm2f128_ps256:
2842 case X86::BI__builtin_ia32_vperm2f128_si256:
2843 case X86::BI__builtin_ia32_permti256:
Craig Topper7d17d722018-06-08 00:00:21 +00002844 case X86::BI__builtin_ia32_pblendw128:
2845 case X86::BI__builtin_ia32_pblendw256:
2846 case X86::BI__builtin_ia32_blendps256:
2847 case X86::BI__builtin_ia32_pblendd256:
Craig Topper39c87102016-05-18 03:18:12 +00002848 case X86::BI__builtin_ia32_palignr128:
2849 case X86::BI__builtin_ia32_palignr256:
Craig Topper8e3689c2018-05-22 20:48:24 +00002850 case X86::BI__builtin_ia32_palignr512:
Craig Toppere56819e2018-06-07 21:27:41 +00002851 case X86::BI__builtin_ia32_alignq512:
2852 case X86::BI__builtin_ia32_alignd512:
2853 case X86::BI__builtin_ia32_alignd128:
2854 case X86::BI__builtin_ia32_alignd256:
2855 case X86::BI__builtin_ia32_alignq128:
2856 case X86::BI__builtin_ia32_alignq256:
Craig Topper39c87102016-05-18 03:18:12 +00002857 case X86::BI__builtin_ia32_vcomisd:
2858 case X86::BI__builtin_ia32_vcomiss:
Craig Topper93921362018-06-07 23:03:08 +00002859 case X86::BI__builtin_ia32_shuf_f32x4:
2860 case X86::BI__builtin_ia32_shuf_f64x2:
2861 case X86::BI__builtin_ia32_shuf_i32x4:
2862 case X86::BI__builtin_ia32_shuf_i64x2:
Craig Topper422a1bb2018-06-08 07:18:33 +00002863 case X86::BI__builtin_ia32_shufpd512:
2864 case X86::BI__builtin_ia32_shufps:
2865 case X86::BI__builtin_ia32_shufps256:
2866 case X86::BI__builtin_ia32_shufps512:
Craig Topper91bbe982018-06-11 06:18:29 +00002867 case X86::BI__builtin_ia32_dbpsadbw128:
2868 case X86::BI__builtin_ia32_dbpsadbw256:
2869 case X86::BI__builtin_ia32_dbpsadbw512:
Craig Topper2527c372018-06-13 07:19:28 +00002870 case X86::BI__builtin_ia32_vpshldd128:
2871 case X86::BI__builtin_ia32_vpshldd256:
2872 case X86::BI__builtin_ia32_vpshldd512:
2873 case X86::BI__builtin_ia32_vpshldq128:
2874 case X86::BI__builtin_ia32_vpshldq256:
2875 case X86::BI__builtin_ia32_vpshldq512:
2876 case X86::BI__builtin_ia32_vpshldw128:
2877 case X86::BI__builtin_ia32_vpshldw256:
2878 case X86::BI__builtin_ia32_vpshldw512:
2879 case X86::BI__builtin_ia32_vpshrdd128:
2880 case X86::BI__builtin_ia32_vpshrdd256:
2881 case X86::BI__builtin_ia32_vpshrdd512:
2882 case X86::BI__builtin_ia32_vpshrdq128:
2883 case X86::BI__builtin_ia32_vpshrdq256:
2884 case X86::BI__builtin_ia32_vpshrdq512:
2885 case X86::BI__builtin_ia32_vpshrdw128:
2886 case X86::BI__builtin_ia32_vpshrdw256:
2887 case X86::BI__builtin_ia32_vpshrdw512:
Craig Topper39c87102016-05-18 03:18:12 +00002888 i = 2; l = 0; u = 255;
2889 break;
2890 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2891 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2892 case X86::BI__builtin_ia32_fixupimmps512_mask:
2893 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2894 case X86::BI__builtin_ia32_fixupimmsd_mask:
2895 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2896 case X86::BI__builtin_ia32_fixupimmss_mask:
2897 case X86::BI__builtin_ia32_fixupimmss_maskz:
2898 case X86::BI__builtin_ia32_fixupimmpd128_mask:
2899 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2900 case X86::BI__builtin_ia32_fixupimmpd256_mask:
2901 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2902 case X86::BI__builtin_ia32_fixupimmps128_mask:
2903 case X86::BI__builtin_ia32_fixupimmps128_maskz:
2904 case X86::BI__builtin_ia32_fixupimmps256_mask:
2905 case X86::BI__builtin_ia32_fixupimmps256_maskz:
2906 case X86::BI__builtin_ia32_pternlogd512_mask:
2907 case X86::BI__builtin_ia32_pternlogd512_maskz:
2908 case X86::BI__builtin_ia32_pternlogq512_mask:
2909 case X86::BI__builtin_ia32_pternlogq512_maskz:
2910 case X86::BI__builtin_ia32_pternlogd128_mask:
2911 case X86::BI__builtin_ia32_pternlogd128_maskz:
2912 case X86::BI__builtin_ia32_pternlogd256_mask:
2913 case X86::BI__builtin_ia32_pternlogd256_maskz:
2914 case X86::BI__builtin_ia32_pternlogq128_mask:
2915 case X86::BI__builtin_ia32_pternlogq128_maskz:
2916 case X86::BI__builtin_ia32_pternlogq256_mask:
2917 case X86::BI__builtin_ia32_pternlogq256_maskz:
2918 i = 3; l = 0; u = 255;
2919 break;
Craig Topper9625db02017-03-12 22:19:10 +00002920 case X86::BI__builtin_ia32_gatherpfdpd:
2921 case X86::BI__builtin_ia32_gatherpfdps:
2922 case X86::BI__builtin_ia32_gatherpfqpd:
2923 case X86::BI__builtin_ia32_gatherpfqps:
2924 case X86::BI__builtin_ia32_scatterpfdpd:
2925 case X86::BI__builtin_ia32_scatterpfdps:
2926 case X86::BI__builtin_ia32_scatterpfqpd:
2927 case X86::BI__builtin_ia32_scatterpfqps:
Craig Topperf771f79b2017-03-31 17:22:30 +00002928 i = 4; l = 2; u = 3;
Craig Topper9625db02017-03-12 22:19:10 +00002929 break;
Craig Topper39c87102016-05-18 03:18:12 +00002930 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2931 case X86::BI__builtin_ia32_rndscaless_round_mask:
2932 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00002933 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002934 }
Craig Topperdd84ec52014-12-27 07:00:08 +00002935 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002936}
2937
Richard Smith55ce3522012-06-25 20:30:08 +00002938/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2939/// parameter with the FormatAttr's correct format_idx and firstDataArg.
2940/// Returns true when the format fits the function and the FormatStringInfo has
2941/// been populated.
2942bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2943 FormatStringInfo *FSI) {
2944 FSI->HasVAListArg = Format->getFirstArg() == 0;
2945 FSI->FormatIdx = Format->getFormatIdx() - 1;
2946 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002947
Richard Smith55ce3522012-06-25 20:30:08 +00002948 // The way the format attribute works in GCC, the implicit this argument
2949 // of member functions is counted. However, it doesn't appear in our own
2950 // lists, so decrement format_idx in that case.
2951 if (IsCXXMember) {
2952 if(FSI->FormatIdx == 0)
2953 return false;
2954 --FSI->FormatIdx;
2955 if (FSI->FirstDataArg != 0)
2956 --FSI->FirstDataArg;
2957 }
2958 return true;
2959}
Mike Stump11289f42009-09-09 15:08:12 +00002960
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002961/// Checks if a the given expression evaluates to null.
2962///
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002963/// Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00002964static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002965 // If the expression has non-null type, it doesn't evaluate to null.
2966 if (auto nullability
2967 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2968 if (*nullability == NullabilityKind::NonNull)
2969 return false;
2970 }
2971
Ted Kremeneka146db32014-01-17 06:24:47 +00002972 // As a special case, transparent unions initialized with zero are
2973 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002974 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00002975 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2976 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002977 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00002978 if (const InitListExpr *ILE =
2979 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002980 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00002981 }
2982
2983 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00002984 return (!Expr->isValueDependent() &&
2985 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2986 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002987}
2988
2989static void CheckNonNullArgument(Sema &S,
2990 const Expr *ArgExpr,
2991 SourceLocation CallSiteLoc) {
2992 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00002993 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2994 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00002995}
2996
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002997bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2998 FormatStringInfo FSI;
2999 if ((GetFormatStringType(Format) == FST_NSString) &&
3000 getFormatStringInfo(Format, false, &FSI)) {
3001 Idx = FSI.FormatIdx;
3002 return true;
3003 }
3004 return false;
3005}
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003006
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003007/// Diagnose use of %s directive in an NSString which is being passed
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00003008/// as formatting string to formatting method.
3009static void
3010DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
3011 const NamedDecl *FDecl,
3012 Expr **Args,
3013 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00003014 unsigned Idx = 0;
3015 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00003016 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
3017 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00003018 Idx = 2;
3019 Format = true;
3020 }
3021 else
3022 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
3023 if (S.GetFormatNSStringIdx(I, Idx)) {
3024 Format = true;
3025 break;
3026 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00003027 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00003028 if (!Format || NumArgs <= Idx)
3029 return;
3030 const Expr *FormatExpr = Args[Idx];
3031 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
3032 FormatExpr = CSCE->getSubExpr();
3033 const StringLiteral *FormatString;
3034 if (const ObjCStringLiteral *OSL =
3035 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
3036 FormatString = OSL->getString();
3037 else
3038 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
3039 if (!FormatString)
3040 return;
3041 if (S.FormatStringHasSArg(FormatString)) {
3042 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
3043 << "%s" << 1 << 1;
3044 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
3045 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00003046 }
3047}
3048
Douglas Gregorb4866e82015-06-19 18:13:19 +00003049/// Determine whether the given type has a non-null nullability annotation.
3050static bool isNonNullType(ASTContext &ctx, QualType type) {
3051 if (auto nullability = type->getNullability(ctx))
3052 return *nullability == NullabilityKind::NonNull;
3053
3054 return false;
3055}
3056
Ted Kremenek2bc73332014-01-17 06:24:43 +00003057static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00003058 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00003059 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00003060 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00003061 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00003062 assert((FDecl || Proto) && "Need a function declaration or prototype");
3063
Ted Kremenek9aedc152014-01-17 06:24:56 +00003064 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00003065 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00003066 if (FDecl) {
3067 // Handle the nonnull attribute on the function/method declaration itself.
3068 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
3069 if (!NonNull->args_size()) {
3070 // Easy case: all pointer arguments are nonnull.
3071 for (const auto *Arg : Args)
3072 if (S.isValidPointerAttrType(Arg->getType()))
3073 CheckNonNullArgument(S, Arg, CallSiteLoc);
3074 return;
3075 }
Richard Smith588bd9b2014-08-27 04:59:42 +00003076
Joel E. Denny81508102018-03-13 14:51:22 +00003077 for (const ParamIdx &Idx : NonNull->args()) {
3078 unsigned IdxAST = Idx.getASTIndex();
3079 if (IdxAST >= Args.size())
Douglas Gregorb4866e82015-06-19 18:13:19 +00003080 continue;
3081 if (NonNullArgs.empty())
3082 NonNullArgs.resize(Args.size());
Joel E. Denny81508102018-03-13 14:51:22 +00003083 NonNullArgs.set(IdxAST);
Douglas Gregorb4866e82015-06-19 18:13:19 +00003084 }
Richard Smith588bd9b2014-08-27 04:59:42 +00003085 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00003086 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00003087
Douglas Gregorb4866e82015-06-19 18:13:19 +00003088 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
3089 // Handle the nonnull attribute on the parameters of the
3090 // function/method.
3091 ArrayRef<ParmVarDecl*> parms;
3092 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
3093 parms = FD->parameters();
3094 else
3095 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
3096
3097 unsigned ParamIndex = 0;
3098 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
3099 I != E; ++I, ++ParamIndex) {
3100 const ParmVarDecl *PVD = *I;
3101 if (PVD->hasAttr<NonNullAttr>() ||
3102 isNonNullType(S.Context, PVD->getType())) {
3103 if (NonNullArgs.empty())
3104 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00003105
Douglas Gregorb4866e82015-06-19 18:13:19 +00003106 NonNullArgs.set(ParamIndex);
3107 }
3108 }
3109 } else {
3110 // If we have a non-function, non-method declaration but no
3111 // function prototype, try to dig out the function prototype.
3112 if (!Proto) {
3113 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
3114 QualType type = VD->getType().getNonReferenceType();
3115 if (auto pointerType = type->getAs<PointerType>())
3116 type = pointerType->getPointeeType();
3117 else if (auto blockType = type->getAs<BlockPointerType>())
3118 type = blockType->getPointeeType();
3119 // FIXME: data member pointers?
3120
3121 // Dig out the function prototype, if there is one.
3122 Proto = type->getAs<FunctionProtoType>();
3123 }
3124 }
3125
3126 // Fill in non-null argument information from the nullability
3127 // information on the parameter types (if we have them).
3128 if (Proto) {
3129 unsigned Index = 0;
3130 for (auto paramType : Proto->getParamTypes()) {
3131 if (isNonNullType(S.Context, paramType)) {
3132 if (NonNullArgs.empty())
3133 NonNullArgs.resize(Args.size());
3134
3135 NonNullArgs.set(Index);
3136 }
3137
3138 ++Index;
3139 }
3140 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00003141 }
Richard Smith588bd9b2014-08-27 04:59:42 +00003142
Douglas Gregorb4866e82015-06-19 18:13:19 +00003143 // Check for non-null arguments.
3144 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
3145 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00003146 if (NonNullArgs[ArgIndex])
3147 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00003148 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00003149}
3150
Richard Smith55ce3522012-06-25 20:30:08 +00003151/// Handles the checks for format strings, non-POD arguments to vararg
George Burgess IVce6284b2017-01-28 02:19:40 +00003152/// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
3153/// attributes.
Douglas Gregorb4866e82015-06-19 18:13:19 +00003154void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
George Burgess IVce6284b2017-01-28 02:19:40 +00003155 const Expr *ThisArg, ArrayRef<const Expr *> Args,
3156 bool IsMemberFunction, SourceLocation Loc,
3157 SourceRange Range, VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00003158 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00003159 if (CurContext->isDependentContext())
3160 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00003161
Ted Kremenekb8176da2010-09-09 04:33:05 +00003162 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00003163 llvm::SmallBitVector CheckedVarArgs;
3164 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003165 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00003166 // Only create vector if there are format attributes.
3167 CheckedVarArgs.resize(Args.size());
3168
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003169 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00003170 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00003171 }
Richard Smithd7293d72013-08-05 18:49:43 +00003172 }
Richard Smith55ce3522012-06-25 20:30:08 +00003173
3174 // Refuse POD arguments that weren't caught by the format string
3175 // checks above.
Richard Smith836de6b2016-12-19 23:59:34 +00003176 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
3177 if (CallType != VariadicDoesNotApply &&
3178 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00003179 unsigned NumParams = Proto ? Proto->getNumParams()
3180 : FDecl && isa<FunctionDecl>(FDecl)
3181 ? cast<FunctionDecl>(FDecl)->getNumParams()
3182 : FDecl && isa<ObjCMethodDecl>(FDecl)
3183 ? cast<ObjCMethodDecl>(FDecl)->param_size()
3184 : 0;
3185
Alp Toker9cacbab2014-01-20 20:26:09 +00003186 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00003187 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00003188 if (const Expr *Arg = Args[ArgIdx]) {
3189 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
3190 checkVariadicArgument(Arg, CallType);
3191 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00003192 }
Richard Smithd7293d72013-08-05 18:49:43 +00003193 }
Mike Stump11289f42009-09-09 15:08:12 +00003194
Douglas Gregorb4866e82015-06-19 18:13:19 +00003195 if (FDecl || Proto) {
3196 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00003197
Richard Trieu41bc0992013-06-22 00:20:41 +00003198 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00003199 if (FDecl) {
3200 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +00003201 CheckArgumentWithTypeTag(I, Args, Loc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00003202 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00003203 }
George Burgess IVce6284b2017-01-28 02:19:40 +00003204
3205 if (FD)
3206 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
Richard Smith55ce3522012-06-25 20:30:08 +00003207}
3208
3209/// CheckConstructorCall - Check a constructor call for correctness and safety
3210/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003211void Sema::CheckConstructorCall(FunctionDecl *FDecl,
3212 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003213 const FunctionProtoType *Proto,
3214 SourceLocation Loc) {
3215 VariadicCallType CallType =
3216 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
George Burgess IVce6284b2017-01-28 02:19:40 +00003217 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
3218 Loc, SourceRange(), CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00003219}
3220
3221/// CheckFunctionCall - Check a direct function call for various correctness
3222/// and safety properties not strictly enforced by the C type system.
3223bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
3224 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00003225 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
3226 isa<CXXMethodDecl>(FDecl);
3227 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
3228 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00003229 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
3230 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00003231 Expr** Args = TheCall->getArgs();
3232 unsigned NumArgs = TheCall->getNumArgs();
George Burgess IVce6284b2017-01-28 02:19:40 +00003233
3234 Expr *ImplicitThis = nullptr;
Eli Friedmanadf42182012-10-11 00:34:15 +00003235 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00003236 // If this is a call to a member operator, hide the first argument
3237 // from checkCall.
3238 // FIXME: Our choice of AST representation here is less than ideal.
George Burgess IVce6284b2017-01-28 02:19:40 +00003239 ImplicitThis = Args[0];
Eli Friedman726d11c2012-10-11 00:30:58 +00003240 ++Args;
3241 --NumArgs;
George Burgess IVce6284b2017-01-28 02:19:40 +00003242 } else if (IsMemberFunction)
3243 ImplicitThis =
3244 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
3245
3246 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00003247 IsMemberFunction, TheCall->getRParenLoc(),
3248 TheCall->getCallee()->getSourceRange(), CallType);
3249
3250 IdentifierInfo *FnInfo = FDecl->getIdentifier();
3251 // None of the checks below are needed for functions that don't have
3252 // simple names (e.g., C++ conversion functions).
3253 if (!FnInfo)
3254 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003255
Richard Trieua7f30b12016-12-06 01:42:28 +00003256 CheckAbsoluteValueFunction(TheCall, FDecl);
3257 CheckMaxUnsignedZero(TheCall, FDecl);
Richard Trieu67c00712016-12-05 23:41:46 +00003258
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00003259 if (getLangOpts().ObjC1)
3260 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003261
Anna Zaks22122702012-01-17 00:37:07 +00003262 unsigned CMId = FDecl->getMemoryFunctionKind();
3263 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00003264 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00003265
Anna Zaks201d4892012-01-13 21:52:01 +00003266 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00003267 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00003268 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00003269 else if (CMId == Builtin::BIstrncat)
3270 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00003271 else
Anna Zaks22122702012-01-17 00:37:07 +00003272 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003273
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003274 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00003275}
3276
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003277bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00003278 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00003279 VariadicCallType CallType =
3280 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003281
George Burgess IVce6284b2017-01-28 02:19:40 +00003282 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
3283 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
Douglas Gregorb4866e82015-06-19 18:13:19 +00003284 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003285
3286 return false;
3287}
3288
Richard Trieu664c4c62013-06-20 21:03:13 +00003289bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
3290 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00003291 QualType Ty;
3292 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00003293 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00003294 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00003295 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00003296 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003297 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003298
Douglas Gregorb4866e82015-06-19 18:13:19 +00003299 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
3300 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003301 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003302
Richard Trieu664c4c62013-06-20 21:03:13 +00003303 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00003304 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00003305 CallType = VariadicDoesNotApply;
3306 } else if (Ty->isBlockPointerType()) {
3307 CallType = VariadicBlock;
3308 } else { // Ty->isFunctionPointerType()
3309 CallType = VariadicFunction;
3310 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003311
George Burgess IVce6284b2017-01-28 02:19:40 +00003312 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
Douglas Gregorb4866e82015-06-19 18:13:19 +00003313 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
3314 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00003315 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00003316
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003317 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00003318}
3319
Richard Trieu41bc0992013-06-22 00:20:41 +00003320/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
3321/// such as function pointers returned from functions.
3322bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003323 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00003324 TheCall->getCallee());
George Burgess IVce6284b2017-01-28 02:19:40 +00003325 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00003326 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00003327 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00003328 TheCall->getCallee()->getSourceRange(), CallType);
3329
3330 return false;
3331}
3332
Tim Northovere94a34c2014-03-11 10:49:14 +00003333static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00003334 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00003335 return false;
3336
JF Bastiendda2cb12016-04-18 18:01:49 +00003337 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00003338 switch (Op) {
3339 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00003340 case AtomicExpr::AO__opencl_atomic_init:
Tim Northovere94a34c2014-03-11 10:49:14 +00003341 llvm_unreachable("There is no ordering argument for an init");
3342
3343 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00003344 case AtomicExpr::AO__opencl_atomic_load:
Tim Northovere94a34c2014-03-11 10:49:14 +00003345 case AtomicExpr::AO__atomic_load_n:
3346 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00003347 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
3348 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00003349
3350 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00003351 case AtomicExpr::AO__opencl_atomic_store:
Tim Northovere94a34c2014-03-11 10:49:14 +00003352 case AtomicExpr::AO__atomic_store:
3353 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00003354 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
3355 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
3356 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00003357
3358 default:
3359 return true;
3360 }
3361}
3362
Richard Smithfeea8832012-04-12 05:08:17 +00003363ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
3364 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003365 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3366 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003367
Yaxun Liu39195062017-08-04 18:16:31 +00003368 // All the non-OpenCL operations take one of the following forms.
3369 // The OpenCL operations take the __c11 forms with one extra argument for
3370 // synchronization scope.
Richard Smithfeea8832012-04-12 05:08:17 +00003371 enum {
3372 // C __c11_atomic_init(A *, C)
3373 Init,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003374
Richard Smithfeea8832012-04-12 05:08:17 +00003375 // C __c11_atomic_load(A *, int)
3376 Load,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003377
Richard Smithfeea8832012-04-12 05:08:17 +00003378 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00003379 LoadCopy,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003380
Eric Fiselier8d662442016-03-30 23:39:56 +00003381 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00003382 Copy,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003383
Richard Smithfeea8832012-04-12 05:08:17 +00003384 // C __c11_atomic_add(A *, M, int)
3385 Arithmetic,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003386
Richard Smithfeea8832012-04-12 05:08:17 +00003387 // C __atomic_exchange_n(A *, CP, int)
3388 Xchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003389
Richard Smithfeea8832012-04-12 05:08:17 +00003390 // void __atomic_exchange(A *, C *, CP, int)
3391 GNUXchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003392
Richard Smithfeea8832012-04-12 05:08:17 +00003393 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
3394 C11CmpXchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003395
Richard Smithfeea8832012-04-12 05:08:17 +00003396 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
3397 GNUCmpXchg
3398 } Form = Init;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003399
Yaxun Liu39195062017-08-04 18:16:31 +00003400 const unsigned NumForm = GNUCmpXchg + 1;
Eric Fiselier8d662442016-03-30 23:39:56 +00003401 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
3402 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00003403 // where:
3404 // C is an appropriate type,
3405 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
3406 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
3407 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
3408 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003409
Yaxun Liu39195062017-08-04 18:16:31 +00003410 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
3411 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
3412 "need to update code for modified forms");
Gabor Horvath98bd0982015-03-16 09:59:54 +00003413 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
3414 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
3415 AtomicExpr::AO__atomic_load,
3416 "need to update code for modified C11 atomics");
Yaxun Liu39195062017-08-04 18:16:31 +00003417 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
3418 Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
3419 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
3420 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
3421 IsOpenCL;
Richard Smithfeea8832012-04-12 05:08:17 +00003422 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
3423 Op == AtomicExpr::AO__atomic_store_n ||
3424 Op == AtomicExpr::AO__atomic_exchange_n ||
3425 Op == AtomicExpr::AO__atomic_compare_exchange_n;
3426 bool IsAddSub = false;
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00003427 bool IsMinMax = false;
Richard Smithfeea8832012-04-12 05:08:17 +00003428
3429 switch (Op) {
3430 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00003431 case AtomicExpr::AO__opencl_atomic_init:
Richard Smithfeea8832012-04-12 05:08:17 +00003432 Form = Init;
3433 break;
3434
3435 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00003436 case AtomicExpr::AO__opencl_atomic_load:
Richard Smithfeea8832012-04-12 05:08:17 +00003437 case AtomicExpr::AO__atomic_load_n:
3438 Form = Load;
3439 break;
3440
Richard Smithfeea8832012-04-12 05:08:17 +00003441 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00003442 Form = LoadCopy;
3443 break;
3444
3445 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00003446 case AtomicExpr::AO__opencl_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00003447 case AtomicExpr::AO__atomic_store:
3448 case AtomicExpr::AO__atomic_store_n:
3449 Form = Copy;
3450 break;
3451
3452 case AtomicExpr::AO__c11_atomic_fetch_add:
3453 case AtomicExpr::AO__c11_atomic_fetch_sub:
Yaxun Liu39195062017-08-04 18:16:31 +00003454 case AtomicExpr::AO__opencl_atomic_fetch_add:
3455 case AtomicExpr::AO__opencl_atomic_fetch_sub:
3456 case AtomicExpr::AO__opencl_atomic_fetch_min:
3457 case AtomicExpr::AO__opencl_atomic_fetch_max:
Richard Smithfeea8832012-04-12 05:08:17 +00003458 case AtomicExpr::AO__atomic_fetch_add:
3459 case AtomicExpr::AO__atomic_fetch_sub:
3460 case AtomicExpr::AO__atomic_add_fetch:
3461 case AtomicExpr::AO__atomic_sub_fetch:
3462 IsAddSub = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00003463 LLVM_FALLTHROUGH;
Richard Smithfeea8832012-04-12 05:08:17 +00003464 case AtomicExpr::AO__c11_atomic_fetch_and:
3465 case AtomicExpr::AO__c11_atomic_fetch_or:
3466 case AtomicExpr::AO__c11_atomic_fetch_xor:
Yaxun Liu39195062017-08-04 18:16:31 +00003467 case AtomicExpr::AO__opencl_atomic_fetch_and:
3468 case AtomicExpr::AO__opencl_atomic_fetch_or:
3469 case AtomicExpr::AO__opencl_atomic_fetch_xor:
Richard Smithfeea8832012-04-12 05:08:17 +00003470 case AtomicExpr::AO__atomic_fetch_and:
3471 case AtomicExpr::AO__atomic_fetch_or:
3472 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00003473 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00003474 case AtomicExpr::AO__atomic_and_fetch:
3475 case AtomicExpr::AO__atomic_or_fetch:
3476 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00003477 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00003478 Form = Arithmetic;
3479 break;
3480
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00003481 case AtomicExpr::AO__atomic_fetch_min:
3482 case AtomicExpr::AO__atomic_fetch_max:
3483 IsMinMax = true;
3484 Form = Arithmetic;
3485 break;
3486
Richard Smithfeea8832012-04-12 05:08:17 +00003487 case AtomicExpr::AO__c11_atomic_exchange:
Yaxun Liu39195062017-08-04 18:16:31 +00003488 case AtomicExpr::AO__opencl_atomic_exchange:
Richard Smithfeea8832012-04-12 05:08:17 +00003489 case AtomicExpr::AO__atomic_exchange_n:
3490 Form = Xchg;
3491 break;
3492
3493 case AtomicExpr::AO__atomic_exchange:
3494 Form = GNUXchg;
3495 break;
3496
3497 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3498 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
Yaxun Liu39195062017-08-04 18:16:31 +00003499 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
3500 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
Richard Smithfeea8832012-04-12 05:08:17 +00003501 Form = C11CmpXchg;
3502 break;
3503
3504 case AtomicExpr::AO__atomic_compare_exchange:
3505 case AtomicExpr::AO__atomic_compare_exchange_n:
3506 Form = GNUCmpXchg;
3507 break;
3508 }
3509
Yaxun Liu39195062017-08-04 18:16:31 +00003510 unsigned AdjustedNumArgs = NumArgs[Form];
3511 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
3512 ++AdjustedNumArgs;
Richard Smithfeea8832012-04-12 05:08:17 +00003513 // Check we have the right number of arguments.
Yaxun Liu39195062017-08-04 18:16:31 +00003514 if (TheCall->getNumArgs() < AdjustedNumArgs) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003515 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Yaxun Liu39195062017-08-04 18:16:31 +00003516 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003517 << TheCall->getCallee()->getSourceRange();
3518 return ExprError();
Yaxun Liu39195062017-08-04 18:16:31 +00003519 } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
3520 Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003521 diag::err_typecheck_call_too_many_args)
Yaxun Liu39195062017-08-04 18:16:31 +00003522 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003523 << TheCall->getCallee()->getSourceRange();
3524 return ExprError();
3525 }
3526
Richard Smithfeea8832012-04-12 05:08:17 +00003527 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003528 Expr *Ptr = TheCall->getArg(0);
George Burgess IV92b43a42016-07-21 03:28:13 +00003529 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
3530 if (ConvertedPtr.isInvalid())
3531 return ExprError();
3532
3533 Ptr = ConvertedPtr.get();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003534 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
3535 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00003536 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003537 << Ptr->getType() << Ptr->getSourceRange();
3538 return ExprError();
3539 }
3540
Richard Smithfeea8832012-04-12 05:08:17 +00003541 // For a __c11 builtin, this should be a pointer to an _Atomic type.
3542 QualType AtomTy = pointerType->getPointeeType(); // 'A'
3543 QualType ValType = AtomTy; // 'C'
3544 if (IsC11) {
3545 if (!AtomTy->isAtomicType()) {
3546 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
3547 << Ptr->getType() << Ptr->getSourceRange();
3548 return ExprError();
3549 }
Yaxun Liu39195062017-08-04 18:16:31 +00003550 if (AtomTy.isConstQualified() ||
3551 AtomTy.getAddressSpace() == LangAS::opencl_constant) {
Richard Smithe00921a2012-09-15 06:09:58 +00003552 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
Yaxun Liu39195062017-08-04 18:16:31 +00003553 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
3554 << Ptr->getSourceRange();
Richard Smithe00921a2012-09-15 06:09:58 +00003555 return ExprError();
3556 }
Richard Smithfeea8832012-04-12 05:08:17 +00003557 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00003558 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00003559 if (ValType.isConstQualified()) {
3560 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
3561 << Ptr->getType() << Ptr->getSourceRange();
3562 return ExprError();
3563 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003564 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003565
Richard Smithfeea8832012-04-12 05:08:17 +00003566 // For an arithmetic operation, the implied arithmetic must be well-formed.
3567 if (Form == Arithmetic) {
3568 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00003569 if (IsAddSub && !ValType->isIntegerType()
3570 && !ValType->isPointerType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00003571 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3572 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3573 return ExprError();
3574 }
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00003575 if (IsMinMax) {
3576 const BuiltinType *BT = ValType->getAs<BuiltinType>();
3577 if (!BT || (BT->getKind() != BuiltinType::Int &&
3578 BT->getKind() != BuiltinType::UInt)) {
3579 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_int32_or_ptr);
3580 return ExprError();
3581 }
3582 }
3583 if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00003584 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
3585 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3586 return ExprError();
3587 }
David Majnemere85cff82015-01-28 05:48:06 +00003588 if (IsC11 && ValType->isPointerType() &&
3589 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
3590 diag::err_incomplete_type)) {
3591 return ExprError();
3592 }
Richard Smithfeea8832012-04-12 05:08:17 +00003593 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
3594 // For __atomic_*_n operations, the value type must be a scalar integral or
3595 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003596 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00003597 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3598 return ExprError();
3599 }
3600
Eli Friedmanaa769812013-09-11 03:49:34 +00003601 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
3602 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00003603 // For GNU atomics, require a trivially-copyable type. This is not part of
3604 // the GNU atomics specification, but we enforce it for sanity.
3605 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003606 << Ptr->getType() << Ptr->getSourceRange();
3607 return ExprError();
3608 }
3609
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003610 switch (ValType.getObjCLifetime()) {
3611 case Qualifiers::OCL_None:
3612 case Qualifiers::OCL_ExplicitNone:
3613 // okay
3614 break;
3615
3616 case Qualifiers::OCL_Weak:
3617 case Qualifiers::OCL_Strong:
3618 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00003619 // FIXME: Can this happen? By this point, ValType should be known
3620 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003621 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3622 << ValType << Ptr->getSourceRange();
3623 return ExprError();
3624 }
3625
JF Bastien7f0a05a2018-05-25 00:07:09 +00003626 // All atomic operations have an overload which takes a pointer to a volatile
3627 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
3628 // into the result or the other operands. Similarly atomic_load takes a
3629 // pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00003630 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00003631 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003632 QualType ResultType = ValType;
Yaxun Liu39195062017-08-04 18:16:31 +00003633 if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
3634 Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003635 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00003636 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003637 ResultType = Context.BoolTy;
3638
Richard Smithfeea8832012-04-12 05:08:17 +00003639 // The type of a parameter passed 'by value'. In the GNU atomics, such
3640 // arguments are actually passed as pointers.
3641 QualType ByValType = ValType; // 'CP'
JF Bastien7f0a05a2018-05-25 00:07:09 +00003642 bool IsPassedByAddress = false;
3643 if (!IsC11 && !IsN) {
Richard Smithfeea8832012-04-12 05:08:17 +00003644 ByValType = Ptr->getType();
JF Bastien7f0a05a2018-05-25 00:07:09 +00003645 IsPassedByAddress = true;
3646 }
Richard Smithfeea8832012-04-12 05:08:17 +00003647
JF Bastien7f0a05a2018-05-25 00:07:09 +00003648 // The first argument's non-CV pointer type is used to deduce the type of
3649 // subsequent arguments, except for:
3650 // - weak flag (always converted to bool)
3651 // - memory order (always converted to int)
3652 // - scope (always converted to int)
3653 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003654 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00003655 if (i < NumVals[Form] + 1) {
3656 switch (i) {
JF Bastien7f0a05a2018-05-25 00:07:09 +00003657 case 0:
3658 // The first argument is always a pointer. It has a fixed type.
3659 // It is always dereferenced, a nullptr is undefined.
3660 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart());
3661 // Nothing else to do: we already know all we want about this pointer.
3662 continue;
Richard Smithfeea8832012-04-12 05:08:17 +00003663 case 1:
3664 // The second argument is the non-atomic operand. For arithmetic, this
3665 // is always passed by value, and for a compare_exchange it is always
3666 // passed by address. For the rest, GNU uses by-address and C11 uses
3667 // by-value.
3668 assert(Form != Load);
3669 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
3670 Ty = ValType;
JF Bastien7f0a05a2018-05-25 00:07:09 +00003671 else if (Form == Copy || Form == Xchg) {
3672 if (IsPassedByAddress)
3673 // The value pointer is always dereferenced, a nullptr is undefined.
3674 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart());
Richard Smithfeea8832012-04-12 05:08:17 +00003675 Ty = ByValType;
JF Bastien7f0a05a2018-05-25 00:07:09 +00003676 } else if (Form == Arithmetic)
Richard Smithfeea8832012-04-12 05:08:17 +00003677 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003678 else {
3679 Expr *ValArg = TheCall->getArg(i);
JF Bastien7f0a05a2018-05-25 00:07:09 +00003680 // The value pointer is always dereferenced, a nullptr is undefined.
Alex Lorenz67522152016-11-23 16:57:03 +00003681 CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
Alexander Richardson6d989432017-10-15 18:48:14 +00003682 LangAS AS = LangAS::Default;
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003683 // Keep address space of non-atomic pointer type.
3684 if (const PointerType *PtrTy =
3685 ValArg->getType()->getAs<PointerType>()) {
3686 AS = PtrTy->getPointeeType().getAddressSpace();
3687 }
3688 Ty = Context.getPointerType(
3689 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
3690 }
Richard Smithfeea8832012-04-12 05:08:17 +00003691 break;
3692 case 2:
JF Bastien7f0a05a2018-05-25 00:07:09 +00003693 // The third argument to compare_exchange / GNU exchange is the desired
JF Bastien7853d5f2018-05-25 17:36:49 +00003694 // value, either by-value (for the C11 and *_n variant) or as a pointer.
3695 if (IsPassedByAddress)
JF Bastien7f0a05a2018-05-25 00:07:09 +00003696 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart());
Richard Smithfeea8832012-04-12 05:08:17 +00003697 Ty = ByValType;
3698 break;
3699 case 3:
3700 // The fourth argument to GNU compare_exchange is a 'weak' flag.
3701 Ty = Context.BoolTy;
3702 break;
3703 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003704 } else {
Yaxun Liu39195062017-08-04 18:16:31 +00003705 // The order(s) and scope are always converted to int.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003706 Ty = Context.IntTy;
3707 }
Richard Smithfeea8832012-04-12 05:08:17 +00003708
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003709 InitializedEntity Entity =
3710 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00003711 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003712 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3713 if (Arg.isInvalid())
3714 return true;
3715 TheCall->setArg(i, Arg.get());
3716 }
3717
Richard Smithfeea8832012-04-12 05:08:17 +00003718 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003719 SmallVector<Expr*, 5> SubExprs;
3720 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00003721 switch (Form) {
3722 case Init:
3723 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00003724 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003725 break;
3726 case Load:
3727 SubExprs.push_back(TheCall->getArg(1)); // Order
3728 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00003729 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00003730 case Copy:
3731 case Arithmetic:
3732 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003733 SubExprs.push_back(TheCall->getArg(2)); // Order
3734 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003735 break;
3736 case GNUXchg:
3737 // Note, AtomicExpr::getVal2() has a special case for this atomic.
3738 SubExprs.push_back(TheCall->getArg(3)); // Order
3739 SubExprs.push_back(TheCall->getArg(1)); // Val1
3740 SubExprs.push_back(TheCall->getArg(2)); // Val2
3741 break;
3742 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003743 SubExprs.push_back(TheCall->getArg(3)); // Order
3744 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003745 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00003746 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00003747 break;
3748 case GNUCmpXchg:
3749 SubExprs.push_back(TheCall->getArg(4)); // Order
3750 SubExprs.push_back(TheCall->getArg(1)); // Val1
3751 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
3752 SubExprs.push_back(TheCall->getArg(2)); // Val2
3753 SubExprs.push_back(TheCall->getArg(3)); // Weak
3754 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003755 }
Tim Northovere94a34c2014-03-11 10:49:14 +00003756
3757 if (SubExprs.size() >= 2 && Form != Init) {
3758 llvm::APSInt Result(32);
3759 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
3760 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00003761 Diag(SubExprs[1]->getLocStart(),
3762 diag::warn_atomic_op_has_invalid_memory_order)
3763 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00003764 }
3765
Yaxun Liu30d652a2017-08-15 16:02:49 +00003766 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
3767 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
3768 llvm::APSInt Result(32);
3769 if (Scope->isIntegerConstantExpr(Result, Context) &&
3770 !ScopeModel->isValid(Result.getZExtValue())) {
3771 Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope)
3772 << Scope->getSourceRange();
3773 }
3774 SubExprs.push_back(Scope);
3775 }
3776
Fariborz Jahanian615de762013-05-28 17:37:39 +00003777 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
3778 SubExprs, ResultType, Op,
3779 TheCall->getRParenLoc());
3780
3781 if ((Op == AtomicExpr::AO__c11_atomic_load ||
Yaxun Liu39195062017-08-04 18:16:31 +00003782 Op == AtomicExpr::AO__c11_atomic_store ||
3783 Op == AtomicExpr::AO__opencl_atomic_load ||
3784 Op == AtomicExpr::AO__opencl_atomic_store ) &&
Fariborz Jahanian615de762013-05-28 17:37:39 +00003785 Context.AtomicUsesUnsupportedLibcall(AE))
Yaxun Liu39195062017-08-04 18:16:31 +00003786 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib)
3787 << ((Op == AtomicExpr::AO__c11_atomic_load ||
3788 Op == AtomicExpr::AO__opencl_atomic_load)
3789 ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003790
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003791 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003792}
3793
John McCall29ad95b2011-08-27 01:09:30 +00003794/// checkBuiltinArgument - Given a call to a builtin function, perform
3795/// normal type-checking on the given argument, updating the call in
3796/// place. This is useful when a builtin function requires custom
3797/// type-checking for some of its arguments but not necessarily all of
3798/// them.
3799///
3800/// Returns true on error.
3801static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
3802 FunctionDecl *Fn = E->getDirectCallee();
3803 assert(Fn && "builtin call without direct callee!");
3804
3805 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
3806 InitializedEntity Entity =
3807 InitializedEntity::InitializeParameter(S.Context, Param);
3808
3809 ExprResult Arg = E->getArg(0);
3810 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3811 if (Arg.isInvalid())
3812 return true;
3813
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003814 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00003815 return false;
3816}
3817
Chris Lattnerdc046542009-05-08 06:58:22 +00003818/// SemaBuiltinAtomicOverloaded - We have a call to a function like
3819/// __sync_fetch_and_add, which is an overloaded function based on the pointer
3820/// type of its first argument. The main ActOnCallExpr routines have already
3821/// promoted the types of arguments because all of these calls are prototyped as
3822/// void(...).
3823///
3824/// This function goes through and does final semantic checking for these
3825/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00003826ExprResult
3827Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003828 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00003829 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3830 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3831
3832 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003833 if (TheCall->getNumArgs() < 1) {
3834 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3835 << 0 << 1 << TheCall->getNumArgs()
3836 << TheCall->getCallee()->getSourceRange();
3837 return ExprError();
3838 }
Mike Stump11289f42009-09-09 15:08:12 +00003839
Chris Lattnerdc046542009-05-08 06:58:22 +00003840 // Inspect the first argument of the atomic builtin. This should always be
3841 // a pointer type, whose element is an integral scalar or pointer type.
3842 // Because it is a pointer type, we don't have to worry about any implicit
3843 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003844 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00003845 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00003846 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3847 if (FirstArgResult.isInvalid())
3848 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003849 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00003850 TheCall->setArg(0, FirstArg);
3851
John McCall31168b02011-06-15 23:02:42 +00003852 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3853 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003854 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3855 << FirstArg->getType() << FirstArg->getSourceRange();
3856 return ExprError();
3857 }
Mike Stump11289f42009-09-09 15:08:12 +00003858
John McCall31168b02011-06-15 23:02:42 +00003859 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00003860 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003861 !ValType->isBlockPointerType()) {
3862 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3863 << FirstArg->getType() << FirstArg->getSourceRange();
3864 return ExprError();
3865 }
Chris Lattnerdc046542009-05-08 06:58:22 +00003866
Aaron Ballmana383c942018-05-05 17:38:42 +00003867 if (ValType.isConstQualified()) {
3868 Diag(DRE->getLocStart(), diag::err_atomic_builtin_cannot_be_const)
3869 << FirstArg->getType() << FirstArg->getSourceRange();
3870 return ExprError();
3871 }
3872
John McCall31168b02011-06-15 23:02:42 +00003873 switch (ValType.getObjCLifetime()) {
3874 case Qualifiers::OCL_None:
3875 case Qualifiers::OCL_ExplicitNone:
3876 // okay
3877 break;
3878
3879 case Qualifiers::OCL_Weak:
3880 case Qualifiers::OCL_Strong:
3881 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00003882 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00003883 << ValType << FirstArg->getSourceRange();
3884 return ExprError();
3885 }
3886
John McCallb50451a2011-10-05 07:41:44 +00003887 // Strip any qualifiers off ValType.
3888 ValType = ValType.getUnqualifiedType();
3889
Chandler Carruth3973af72010-07-18 20:54:12 +00003890 // The majority of builtins return a value, but a few have special return
3891 // types, so allow them to override appropriately below.
3892 QualType ResultType = ValType;
3893
Chris Lattnerdc046542009-05-08 06:58:22 +00003894 // We need to figure out which concrete builtin this maps onto. For example,
3895 // __sync_fetch_and_add with a 2 byte object turns into
3896 // __sync_fetch_and_add_2.
3897#define BUILTIN_ROW(x) \
3898 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3899 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00003900
Chris Lattnerdc046542009-05-08 06:58:22 +00003901 static const unsigned BuiltinIndices[][5] = {
3902 BUILTIN_ROW(__sync_fetch_and_add),
3903 BUILTIN_ROW(__sync_fetch_and_sub),
3904 BUILTIN_ROW(__sync_fetch_and_or),
3905 BUILTIN_ROW(__sync_fetch_and_and),
3906 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00003907 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00003908
Chris Lattnerdc046542009-05-08 06:58:22 +00003909 BUILTIN_ROW(__sync_add_and_fetch),
3910 BUILTIN_ROW(__sync_sub_and_fetch),
3911 BUILTIN_ROW(__sync_and_and_fetch),
3912 BUILTIN_ROW(__sync_or_and_fetch),
3913 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00003914 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00003915
Chris Lattnerdc046542009-05-08 06:58:22 +00003916 BUILTIN_ROW(__sync_val_compare_and_swap),
3917 BUILTIN_ROW(__sync_bool_compare_and_swap),
3918 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00003919 BUILTIN_ROW(__sync_lock_release),
3920 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00003921 };
Mike Stump11289f42009-09-09 15:08:12 +00003922#undef BUILTIN_ROW
3923
Chris Lattnerdc046542009-05-08 06:58:22 +00003924 // Determine the index of the size.
3925 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00003926 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00003927 case 1: SizeIndex = 0; break;
3928 case 2: SizeIndex = 1; break;
3929 case 4: SizeIndex = 2; break;
3930 case 8: SizeIndex = 3; break;
3931 case 16: SizeIndex = 4; break;
3932 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003933 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3934 << FirstArg->getType() << FirstArg->getSourceRange();
3935 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00003936 }
Mike Stump11289f42009-09-09 15:08:12 +00003937
Chris Lattnerdc046542009-05-08 06:58:22 +00003938 // Each of these builtins has one pointer argument, followed by some number of
3939 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3940 // that we ignore. Find out which row of BuiltinIndices to read from as well
3941 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00003942 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00003943 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00003944 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00003945 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00003946 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00003947 case Builtin::BI__sync_fetch_and_add:
3948 case Builtin::BI__sync_fetch_and_add_1:
3949 case Builtin::BI__sync_fetch_and_add_2:
3950 case Builtin::BI__sync_fetch_and_add_4:
3951 case Builtin::BI__sync_fetch_and_add_8:
3952 case Builtin::BI__sync_fetch_and_add_16:
3953 BuiltinIndex = 0;
3954 break;
3955
3956 case Builtin::BI__sync_fetch_and_sub:
3957 case Builtin::BI__sync_fetch_and_sub_1:
3958 case Builtin::BI__sync_fetch_and_sub_2:
3959 case Builtin::BI__sync_fetch_and_sub_4:
3960 case Builtin::BI__sync_fetch_and_sub_8:
3961 case Builtin::BI__sync_fetch_and_sub_16:
3962 BuiltinIndex = 1;
3963 break;
3964
3965 case Builtin::BI__sync_fetch_and_or:
3966 case Builtin::BI__sync_fetch_and_or_1:
3967 case Builtin::BI__sync_fetch_and_or_2:
3968 case Builtin::BI__sync_fetch_and_or_4:
3969 case Builtin::BI__sync_fetch_and_or_8:
3970 case Builtin::BI__sync_fetch_and_or_16:
3971 BuiltinIndex = 2;
3972 break;
3973
3974 case Builtin::BI__sync_fetch_and_and:
3975 case Builtin::BI__sync_fetch_and_and_1:
3976 case Builtin::BI__sync_fetch_and_and_2:
3977 case Builtin::BI__sync_fetch_and_and_4:
3978 case Builtin::BI__sync_fetch_and_and_8:
3979 case Builtin::BI__sync_fetch_and_and_16:
3980 BuiltinIndex = 3;
3981 break;
Mike Stump11289f42009-09-09 15:08:12 +00003982
Douglas Gregor73722482011-11-28 16:30:08 +00003983 case Builtin::BI__sync_fetch_and_xor:
3984 case Builtin::BI__sync_fetch_and_xor_1:
3985 case Builtin::BI__sync_fetch_and_xor_2:
3986 case Builtin::BI__sync_fetch_and_xor_4:
3987 case Builtin::BI__sync_fetch_and_xor_8:
3988 case Builtin::BI__sync_fetch_and_xor_16:
3989 BuiltinIndex = 4;
3990 break;
3991
Hal Finkeld2208b52014-10-02 20:53:50 +00003992 case Builtin::BI__sync_fetch_and_nand:
3993 case Builtin::BI__sync_fetch_and_nand_1:
3994 case Builtin::BI__sync_fetch_and_nand_2:
3995 case Builtin::BI__sync_fetch_and_nand_4:
3996 case Builtin::BI__sync_fetch_and_nand_8:
3997 case Builtin::BI__sync_fetch_and_nand_16:
3998 BuiltinIndex = 5;
3999 WarnAboutSemanticsChange = true;
4000 break;
4001
Douglas Gregor73722482011-11-28 16:30:08 +00004002 case Builtin::BI__sync_add_and_fetch:
4003 case Builtin::BI__sync_add_and_fetch_1:
4004 case Builtin::BI__sync_add_and_fetch_2:
4005 case Builtin::BI__sync_add_and_fetch_4:
4006 case Builtin::BI__sync_add_and_fetch_8:
4007 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004008 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00004009 break;
4010
4011 case Builtin::BI__sync_sub_and_fetch:
4012 case Builtin::BI__sync_sub_and_fetch_1:
4013 case Builtin::BI__sync_sub_and_fetch_2:
4014 case Builtin::BI__sync_sub_and_fetch_4:
4015 case Builtin::BI__sync_sub_and_fetch_8:
4016 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004017 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00004018 break;
4019
4020 case Builtin::BI__sync_and_and_fetch:
4021 case Builtin::BI__sync_and_and_fetch_1:
4022 case Builtin::BI__sync_and_and_fetch_2:
4023 case Builtin::BI__sync_and_and_fetch_4:
4024 case Builtin::BI__sync_and_and_fetch_8:
4025 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004026 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00004027 break;
4028
4029 case Builtin::BI__sync_or_and_fetch:
4030 case Builtin::BI__sync_or_and_fetch_1:
4031 case Builtin::BI__sync_or_and_fetch_2:
4032 case Builtin::BI__sync_or_and_fetch_4:
4033 case Builtin::BI__sync_or_and_fetch_8:
4034 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004035 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00004036 break;
4037
4038 case Builtin::BI__sync_xor_and_fetch:
4039 case Builtin::BI__sync_xor_and_fetch_1:
4040 case Builtin::BI__sync_xor_and_fetch_2:
4041 case Builtin::BI__sync_xor_and_fetch_4:
4042 case Builtin::BI__sync_xor_and_fetch_8:
4043 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004044 BuiltinIndex = 10;
4045 break;
4046
4047 case Builtin::BI__sync_nand_and_fetch:
4048 case Builtin::BI__sync_nand_and_fetch_1:
4049 case Builtin::BI__sync_nand_and_fetch_2:
4050 case Builtin::BI__sync_nand_and_fetch_4:
4051 case Builtin::BI__sync_nand_and_fetch_8:
4052 case Builtin::BI__sync_nand_and_fetch_16:
4053 BuiltinIndex = 11;
4054 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00004055 break;
Mike Stump11289f42009-09-09 15:08:12 +00004056
Chris Lattnerdc046542009-05-08 06:58:22 +00004057 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00004058 case Builtin::BI__sync_val_compare_and_swap_1:
4059 case Builtin::BI__sync_val_compare_and_swap_2:
4060 case Builtin::BI__sync_val_compare_and_swap_4:
4061 case Builtin::BI__sync_val_compare_and_swap_8:
4062 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004063 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00004064 NumFixed = 2;
4065 break;
Douglas Gregor73722482011-11-28 16:30:08 +00004066
Chris Lattnerdc046542009-05-08 06:58:22 +00004067 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00004068 case Builtin::BI__sync_bool_compare_and_swap_1:
4069 case Builtin::BI__sync_bool_compare_and_swap_2:
4070 case Builtin::BI__sync_bool_compare_and_swap_4:
4071 case Builtin::BI__sync_bool_compare_and_swap_8:
4072 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004073 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00004074 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00004075 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00004076 break;
Douglas Gregor73722482011-11-28 16:30:08 +00004077
JF Bastien7f0a05a2018-05-25 00:07:09 +00004078 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +00004079 case Builtin::BI__sync_lock_test_and_set_1:
4080 case Builtin::BI__sync_lock_test_and_set_2:
4081 case Builtin::BI__sync_lock_test_and_set_4:
4082 case Builtin::BI__sync_lock_test_and_set_8:
4083 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004084 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00004085 break;
4086
Chris Lattnerdc046542009-05-08 06:58:22 +00004087 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00004088 case Builtin::BI__sync_lock_release_1:
4089 case Builtin::BI__sync_lock_release_2:
4090 case Builtin::BI__sync_lock_release_4:
4091 case Builtin::BI__sync_lock_release_8:
4092 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004093 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00004094 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00004095 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00004096 break;
Douglas Gregor73722482011-11-28 16:30:08 +00004097
4098 case Builtin::BI__sync_swap:
4099 case Builtin::BI__sync_swap_1:
4100 case Builtin::BI__sync_swap_2:
4101 case Builtin::BI__sync_swap_4:
4102 case Builtin::BI__sync_swap_8:
4103 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004104 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00004105 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00004106 }
Mike Stump11289f42009-09-09 15:08:12 +00004107
Chris Lattnerdc046542009-05-08 06:58:22 +00004108 // Now that we know how many fixed arguments we expect, first check that we
4109 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004110 if (TheCall->getNumArgs() < 1+NumFixed) {
4111 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
4112 << 0 << 1+NumFixed << TheCall->getNumArgs()
4113 << TheCall->getCallee()->getSourceRange();
4114 return ExprError();
4115 }
Mike Stump11289f42009-09-09 15:08:12 +00004116
Hal Finkeld2208b52014-10-02 20:53:50 +00004117 if (WarnAboutSemanticsChange) {
4118 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
4119 << TheCall->getCallee()->getSourceRange();
4120 }
4121
Chris Lattner5b9241b2009-05-08 15:36:58 +00004122 // Get the decl for the concrete builtin from this, we can tell what the
4123 // concrete integer type we should convert to is.
4124 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Mehdi Amini7186a432016-10-11 19:04:24 +00004125 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00004126 FunctionDecl *NewBuiltinDecl;
4127 if (NewBuiltinID == BuiltinID)
4128 NewBuiltinDecl = FDecl;
4129 else {
4130 // Perform builtin lookup to avoid redeclaring it.
4131 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
4132 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
4133 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
4134 assert(Res.getFoundDecl());
4135 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00004136 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00004137 return ExprError();
4138 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004139
John McCallcf142162010-08-07 06:22:56 +00004140 // The first argument --- the pointer --- has a fixed type; we
4141 // deduce the types of the rest of the arguments accordingly. Walk
4142 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00004143 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00004144 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00004145
Chris Lattnerdc046542009-05-08 06:58:22 +00004146 // GCC does an implicit conversion to the pointer or integer ValType. This
4147 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00004148 // Initialize the argument.
4149 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4150 ValType, /*consume*/ false);
4151 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00004152 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004153 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004154
Chris Lattnerdc046542009-05-08 06:58:22 +00004155 // Okay, we have something that *can* be converted to the right type. Check
4156 // to see if there is a potentially weird extension going on here. This can
4157 // happen when you do an atomic operation on something like an char* and
4158 // pass in 42. The 42 gets converted to char. This is even more strange
4159 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00004160 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004161 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00004162 }
Mike Stump11289f42009-09-09 15:08:12 +00004163
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00004164 ASTContext& Context = this->getASTContext();
4165
4166 // Create a new DeclRefExpr to refer to the new decl.
4167 DeclRefExpr* NewDRE = DeclRefExpr::Create(
4168 Context,
4169 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00004170 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00004171 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00004172 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00004173 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00004174 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00004175 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00004176
Chris Lattnerdc046542009-05-08 06:58:22 +00004177 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00004178 // FIXME: This loses syntactic information.
4179 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
4180 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
4181 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004182 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00004183
Chandler Carruthbc8cab12010-07-18 07:23:17 +00004184 // Change the result type of the call to match the original value type. This
4185 // is arbitrary, but the codegen for these builtins ins design to handle it
4186 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00004187 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004188
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004189 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00004190}
4191
Michael Zolotukhin84df1232015-09-08 23:52:33 +00004192/// SemaBuiltinNontemporalOverloaded - We have a call to
4193/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
4194/// overloaded function based on the pointer type of its last argument.
4195///
4196/// This function goes through and does final semantic checking for these
4197/// builtins.
4198ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
4199 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
4200 DeclRefExpr *DRE =
4201 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4202 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4203 unsigned BuiltinID = FDecl->getBuiltinID();
4204 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
4205 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
4206 "Unexpected nontemporal load/store builtin!");
4207 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
4208 unsigned numArgs = isStore ? 2 : 1;
4209
4210 // Ensure that we have the proper number of arguments.
4211 if (checkArgCount(*this, TheCall, numArgs))
4212 return ExprError();
4213
4214 // Inspect the last argument of the nontemporal builtin. This should always
4215 // be a pointer type, from which we imply the type of the memory access.
4216 // Because it is a pointer type, we don't have to worry about any implicit
4217 // casts here.
4218 Expr *PointerArg = TheCall->getArg(numArgs - 1);
4219 ExprResult PointerArgResult =
4220 DefaultFunctionArrayLvalueConversion(PointerArg);
4221
4222 if (PointerArgResult.isInvalid())
4223 return ExprError();
4224 PointerArg = PointerArgResult.get();
4225 TheCall->setArg(numArgs - 1, PointerArg);
4226
4227 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
4228 if (!pointerType) {
4229 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
4230 << PointerArg->getType() << PointerArg->getSourceRange();
4231 return ExprError();
4232 }
4233
4234 QualType ValType = pointerType->getPointeeType();
4235
4236 // Strip any qualifiers off ValType.
4237 ValType = ValType.getUnqualifiedType();
4238 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4239 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
4240 !ValType->isVectorType()) {
4241 Diag(DRE->getLocStart(),
4242 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
4243 << PointerArg->getType() << PointerArg->getSourceRange();
4244 return ExprError();
4245 }
4246
4247 if (!isStore) {
4248 TheCall->setType(ValType);
4249 return TheCallResult;
4250 }
4251
4252 ExprResult ValArg = TheCall->getArg(0);
4253 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4254 Context, ValType, /*consume*/ false);
4255 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
4256 if (ValArg.isInvalid())
4257 return ExprError();
4258
4259 TheCall->setArg(0, ValArg.get());
4260 TheCall->setType(Context.VoidTy);
4261 return TheCallResult;
4262}
4263
Chris Lattner6436fb62009-02-18 06:01:06 +00004264/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00004265/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00004266/// Note: It might also make sense to do the UTF-16 conversion here (would
4267/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00004268bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00004269 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00004270 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
4271
Douglas Gregorfb65e592011-07-27 05:40:30 +00004272 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00004273 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
4274 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00004275 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00004276 }
Mike Stump11289f42009-09-09 15:08:12 +00004277
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00004278 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004279 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00004280 unsigned NumBytes = String.size();
Justin Lebar90910552016-09-30 00:38:45 +00004281 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
4282 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
4283 llvm::UTF16 *ToPtr = &ToBuf[0];
4284
4285 llvm::ConversionResult Result =
4286 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
4287 ToPtr + NumBytes, llvm::strictConversion);
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00004288 // Check for conversion failure.
Justin Lebar90910552016-09-30 00:38:45 +00004289 if (Result != llvm::conversionOK)
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00004290 Diag(Arg->getLocStart(),
4291 diag::warn_cfstring_truncated) << Arg->getSourceRange();
4292 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00004293 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004294}
4295
Mehdi Amini06d367c2016-10-24 20:39:34 +00004296/// CheckObjCString - Checks that the format string argument to the os_log()
4297/// and os_trace() functions is correct, and converts it to const char *.
4298ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
4299 Arg = Arg->IgnoreParenCasts();
4300 auto *Literal = dyn_cast<StringLiteral>(Arg);
4301 if (!Literal) {
4302 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
4303 Literal = ObjcLiteral->getString();
4304 }
4305 }
4306
4307 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
4308 return ExprError(
4309 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
4310 << Arg->getSourceRange());
4311 }
4312
4313 ExprResult Result(Literal);
4314 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
4315 InitializedEntity Entity =
4316 InitializedEntity::InitializeParameter(Context, ResultTy, false);
4317 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
4318 return Result;
4319}
4320
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004321/// Check that the user is calling the appropriate va_start builtin for the
4322/// target and calling convention.
4323static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
4324 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
4325 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
Martin Storsjo022e7822017-07-17 20:49:45 +00004326 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004327 bool IsWindows = TT.isOSWindows();
Martin Storsjo022e7822017-07-17 20:49:45 +00004328 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
4329 if (IsX64 || IsAArch64) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004330 CallingConv CC = CC_C;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004331 if (const FunctionDecl *FD = S.getCurFunctionDecl())
4332 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
4333 if (IsMSVAStart) {
4334 // Don't allow this in System V ABI functions.
Martin Storsjo022e7822017-07-17 20:49:45 +00004335 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004336 return S.Diag(Fn->getLocStart(),
4337 diag::err_ms_va_start_used_in_sysv_function);
4338 } else {
Martin Storsjo022e7822017-07-17 20:49:45 +00004339 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004340 // On x64 Windows, don't allow this in System V ABI functions.
4341 // (Yes, that means there's no corresponding way to support variadic
4342 // System V ABI functions on Windows.)
4343 if ((IsWindows && CC == CC_X86_64SysV) ||
Martin Storsjo022e7822017-07-17 20:49:45 +00004344 (!IsWindows && CC == CC_Win64))
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004345 return S.Diag(Fn->getLocStart(),
4346 diag::err_va_start_used_in_wrong_abi_function)
4347 << !IsWindows;
4348 }
4349 return false;
4350 }
4351
4352 if (IsMSVAStart)
Martin Storsjo022e7822017-07-17 20:49:45 +00004353 return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004354 return false;
4355}
4356
4357static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
4358 ParmVarDecl **LastParam = nullptr) {
4359 // Determine whether the current function, block, or obj-c method is variadic
4360 // and get its parameter list.
4361 bool IsVariadic = false;
4362 ArrayRef<ParmVarDecl *> Params;
Reid Klecknerf1deb832017-05-04 19:51:05 +00004363 DeclContext *Caller = S.CurContext;
4364 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
4365 IsVariadic = Block->isVariadic();
4366 Params = Block->parameters();
4367 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004368 IsVariadic = FD->isVariadic();
4369 Params = FD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00004370 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004371 IsVariadic = MD->isVariadic();
4372 // FIXME: This isn't correct for methods (results in bogus warning).
4373 Params = MD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00004374 } else if (isa<CapturedDecl>(Caller)) {
4375 // We don't support va_start in a CapturedDecl.
4376 S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
4377 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004378 } else {
Reid Klecknerf1deb832017-05-04 19:51:05 +00004379 // This must be some other declcontext that parses exprs.
4380 S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
4381 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004382 }
4383
4384 if (!IsVariadic) {
Reid Klecknerf1deb832017-05-04 19:51:05 +00004385 S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004386 return true;
4387 }
4388
4389 if (LastParam)
4390 *LastParam = Params.empty() ? nullptr : Params.back();
4391
4392 return false;
4393}
4394
Charles Davisc7d5c942015-09-17 20:55:33 +00004395/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
4396/// for validity. Emit an error and return true on failure; return false
4397/// on success.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004398bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00004399 Expr *Fn = TheCall->getCallee();
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004400
4401 if (checkVAStartABI(*this, BuiltinID, Fn))
4402 return true;
4403
Chris Lattner08464942007-12-28 05:29:59 +00004404 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00004405 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004406 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004407 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4408 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00004409 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004410 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00004411 return true;
4412 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00004413
4414 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00004415 return Diag(TheCall->getLocEnd(),
4416 diag::err_typecheck_call_too_few_args_at_least)
4417 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00004418 }
4419
John McCall29ad95b2011-08-27 01:09:30 +00004420 // Type-check the first argument normally.
4421 if (checkBuiltinArgument(*this, TheCall, 0))
4422 return true;
4423
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004424 // Check that the current function is variadic, and get its last parameter.
4425 ParmVarDecl *LastParam;
4426 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
Chris Lattner43be2e62007-12-19 23:59:04 +00004427 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004428
Chris Lattner43be2e62007-12-19 23:59:04 +00004429 // Verify that the second argument to the builtin is the last argument of the
4430 // current function or method.
4431 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00004432 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00004433
Nico Weber9eea7642013-05-24 23:31:57 +00004434 // These are valid if SecondArgIsLastNamedArgument is false after the next
4435 // block.
4436 QualType Type;
4437 SourceLocation ParamLoc;
Aaron Ballman1de59c52016-04-24 13:30:21 +00004438 bool IsCRegister = false;
Nico Weber9eea7642013-05-24 23:31:57 +00004439
Anders Carlsson6a8350b2008-02-11 04:20:54 +00004440 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
4441 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004442 SecondArgIsLastNamedArgument = PV == LastParam;
Nico Weber9eea7642013-05-24 23:31:57 +00004443
4444 Type = PV->getType();
4445 ParamLoc = PV->getLocation();
Aaron Ballman1de59c52016-04-24 13:30:21 +00004446 IsCRegister =
4447 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
Chris Lattner43be2e62007-12-19 23:59:04 +00004448 }
4449 }
Mike Stump11289f42009-09-09 15:08:12 +00004450
Chris Lattner43be2e62007-12-19 23:59:04 +00004451 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00004452 Diag(TheCall->getArg(1)->getLocStart(),
Aaron Ballman05164812016-04-18 18:10:53 +00004453 diag::warn_second_arg_of_va_start_not_last_named_param);
Aaron Ballman1de59c52016-04-24 13:30:21 +00004454 else if (IsCRegister || Type->isReferenceType() ||
Aaron Ballmana4f597f2016-09-15 18:07:51 +00004455 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
4456 // Promotable integers are UB, but enumerations need a bit of
4457 // extra checking to see what their promotable type actually is.
4458 if (!Type->isPromotableIntegerType())
4459 return false;
4460 if (!Type->isEnumeralType())
4461 return true;
4462 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
4463 return !(ED &&
4464 Context.typesAreCompatible(ED->getPromotionType(), Type));
4465 }()) {
Aaron Ballman1de59c52016-04-24 13:30:21 +00004466 unsigned Reason = 0;
4467 if (Type->isReferenceType()) Reason = 1;
4468 else if (IsCRegister) Reason = 2;
4469 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
Nico Weber9eea7642013-05-24 23:31:57 +00004470 Diag(ParamLoc, diag::note_parameter_type) << Type;
4471 }
4472
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00004473 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00004474 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00004475}
Chris Lattner43be2e62007-12-19 23:59:04 +00004476
Saleem Abdulrasool3450aa72017-09-26 20:12:04 +00004477bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004478 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
4479 // const char *named_addr);
4480
4481 Expr *Func = Call->getCallee();
4482
4483 if (Call->getNumArgs() < 3)
4484 return Diag(Call->getLocEnd(),
4485 diag::err_typecheck_call_too_few_args_at_least)
4486 << 0 /*function call*/ << 3 << Call->getNumArgs();
4487
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004488 // Type-check the first argument normally.
4489 if (checkBuiltinArgument(*this, Call, 0))
4490 return true;
4491
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004492 // Check that the current function is variadic.
4493 if (checkVAStartIsInVariadicFunction(*this, Func))
4494 return true;
4495
Saleem Abdulrasool448e8ad2017-09-26 17:44:10 +00004496 // __va_start on Windows does not validate the parameter qualifiers
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004497
Saleem Abdulrasool448e8ad2017-09-26 17:44:10 +00004498 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
4499 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
4500
4501 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
4502 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
4503
4504 const QualType &ConstCharPtrTy =
4505 Context.getPointerType(Context.CharTy.withConst());
4506 if (!Arg1Ty->isPointerType() ||
4507 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
4508 Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible)
4509 << Arg1->getType() << ConstCharPtrTy
4510 << 1 /* different class */
4511 << 0 /* qualifier difference */
4512 << 3 /* parameter mismatch */
4513 << 2 << Arg1->getType() << ConstCharPtrTy;
4514
4515 const QualType SizeTy = Context.getSizeType();
4516 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
4517 Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible)
4518 << Arg2->getType() << SizeTy
4519 << 1 /* different class */
4520 << 0 /* qualifier difference */
4521 << 3 /* parameter mismatch */
4522 << 3 << Arg2->getType() << SizeTy;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004523
4524 return false;
4525}
4526
Chris Lattner2da14fb2007-12-20 00:26:33 +00004527/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
4528/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00004529bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
4530 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00004531 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00004532 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00004533 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00004534 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004535 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004536 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00004537 << SourceRange(TheCall->getArg(2)->getLocStart(),
4538 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00004539
John Wiegley01296292011-04-08 18:41:53 +00004540 ExprResult OrigArg0 = TheCall->getArg(0);
4541 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00004542
Chris Lattner2da14fb2007-12-20 00:26:33 +00004543 // Do standard promotions between the two arguments, returning their common
4544 // type.
Chris Lattner08464942007-12-28 05:29:59 +00004545 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00004546 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
4547 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00004548
4549 // Make sure any conversions are pushed back into the call; this is
4550 // type safe since unordered compare builtins are declared as "_Bool
4551 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00004552 TheCall->setArg(0, OrigArg0.get());
4553 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00004554
John Wiegley01296292011-04-08 18:41:53 +00004555 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00004556 return false;
4557
Chris Lattner2da14fb2007-12-20 00:26:33 +00004558 // If the common type isn't a real floating type, then the arguments were
4559 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00004560 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00004561 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004562 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00004563 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
4564 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00004565
Chris Lattner2da14fb2007-12-20 00:26:33 +00004566 return false;
4567}
4568
Benjamin Kramer634fc102010-02-15 22:42:31 +00004569/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
4570/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00004571/// to check everything. We expect the last argument to be a floating point
4572/// value.
4573bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
4574 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00004575 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00004576 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00004577 if (TheCall->getNumArgs() > NumArgs)
4578 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004579 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004580 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00004581 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004582 (*(TheCall->arg_end()-1))->getLocEnd());
4583
Benjamin Kramer64aae502010-02-16 10:07:31 +00004584 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00004585
Eli Friedman7e4faac2009-08-31 20:06:00 +00004586 if (OrigArg->isTypeDependent())
4587 return false;
4588
Chris Lattner68784ef2010-05-06 05:50:07 +00004589 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00004590 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00004591 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004592 diag::err_typecheck_call_invalid_unary_fp)
4593 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004594
Neil Hickey88c0fac2016-12-13 16:22:50 +00004595 // If this is an implicit conversion from float -> float or double, remove it.
Chris Lattner68784ef2010-05-06 05:50:07 +00004596 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
Neil Hickey7b5ddab2016-12-14 13:18:48 +00004597 // Only remove standard FloatCasts, leaving other casts inplace
4598 if (Cast->getCastKind() == CK_FloatingCast) {
4599 Expr *CastArg = Cast->getSubExpr();
4600 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
4601 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
4602 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
4603 "promotion from float to either float or double is the only expected cast here");
4604 Cast->setSubExpr(nullptr);
4605 TheCall->setArg(NumArgs-1, CastArg);
4606 }
Chris Lattner68784ef2010-05-06 05:50:07 +00004607 }
4608 }
4609
Eli Friedman7e4faac2009-08-31 20:06:00 +00004610 return false;
4611}
4612
Tony Jiangbbc48e92017-05-24 15:13:32 +00004613// Customized Sema Checking for VSX builtins that have the following signature:
4614// vector [...] builtinName(vector [...], vector [...], const int);
4615// Which takes the same type of vectors (any legal vector type) for the first
4616// two arguments and takes compile time constant for the third argument.
4617// Example builtins are :
4618// vector double vec_xxpermdi(vector double, vector double, int);
4619// vector short vec_xxsldwi(vector short, vector short, int);
4620bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
4621 unsigned ExpectedNumArgs = 3;
4622 if (TheCall->getNumArgs() < ExpectedNumArgs)
4623 return Diag(TheCall->getLocEnd(),
4624 diag::err_typecheck_call_too_few_args_at_least)
4625 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4626 << TheCall->getSourceRange();
4627
4628 if (TheCall->getNumArgs() > ExpectedNumArgs)
4629 return Diag(TheCall->getLocEnd(),
4630 diag::err_typecheck_call_too_many_args_at_most)
4631 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4632 << TheCall->getSourceRange();
4633
4634 // Check the third argument is a compile time constant
4635 llvm::APSInt Value;
4636 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
4637 return Diag(TheCall->getLocStart(),
4638 diag::err_vsx_builtin_nonconstant_argument)
4639 << 3 /* argument index */ << TheCall->getDirectCallee()
4640 << SourceRange(TheCall->getArg(2)->getLocStart(),
4641 TheCall->getArg(2)->getLocEnd());
4642
4643 QualType Arg1Ty = TheCall->getArg(0)->getType();
4644 QualType Arg2Ty = TheCall->getArg(1)->getType();
4645
4646 // Check the type of argument 1 and argument 2 are vectors.
4647 SourceLocation BuiltinLoc = TheCall->getLocStart();
4648 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
4649 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
4650 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
4651 << TheCall->getDirectCallee()
4652 << SourceRange(TheCall->getArg(0)->getLocStart(),
4653 TheCall->getArg(1)->getLocEnd());
4654 }
4655
4656 // Check the first two arguments are the same type.
4657 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
4658 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
4659 << TheCall->getDirectCallee()
4660 << SourceRange(TheCall->getArg(0)->getLocStart(),
4661 TheCall->getArg(1)->getLocEnd());
4662 }
4663
4664 // When default clang type checking is turned off and the customized type
4665 // checking is used, the returning type of the function must be explicitly
4666 // set. Otherwise it is _Bool by default.
4667 TheCall->setType(Arg1Ty);
4668
4669 return false;
4670}
4671
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004672/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
4673// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00004674ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00004675 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004676 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00004677 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00004678 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4679 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004680
Nate Begemana0110022010-06-08 00:16:34 +00004681 // Determine which of the following types of shufflevector we're checking:
4682 // 1) unary, vector mask: (lhs, mask)
Craig Topperb3174a82016-05-18 04:11:25 +00004683 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
Nate Begemana0110022010-06-08 00:16:34 +00004684 QualType resType = TheCall->getArg(0)->getType();
4685 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00004686
Douglas Gregorc25f7662009-05-19 22:10:17 +00004687 if (!TheCall->getArg(0)->isTypeDependent() &&
4688 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00004689 QualType LHSType = TheCall->getArg(0)->getType();
4690 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00004691
Craig Topperbaca3892013-07-29 06:47:04 +00004692 if (!LHSType->isVectorType() || !RHSType->isVectorType())
4693 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004694 diag::err_vec_builtin_non_vector)
4695 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004696 << SourceRange(TheCall->getArg(0)->getLocStart(),
4697 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00004698
Nate Begemana0110022010-06-08 00:16:34 +00004699 numElements = LHSType->getAs<VectorType>()->getNumElements();
4700 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00004701
Nate Begemana0110022010-06-08 00:16:34 +00004702 // Check to see if we have a call with 2 vector arguments, the unary shuffle
4703 // with mask. If so, verify that RHS is an integer vector type with the
4704 // same number of elts as lhs.
4705 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00004706 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00004707 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00004708 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004709 diag::err_vec_builtin_incompatible_vector)
4710 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004711 << SourceRange(TheCall->getArg(1)->getLocStart(),
4712 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00004713 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00004714 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004715 diag::err_vec_builtin_incompatible_vector)
4716 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004717 << SourceRange(TheCall->getArg(0)->getLocStart(),
4718 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00004719 } else if (numElements != numResElements) {
4720 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00004721 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00004722 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00004723 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004724 }
4725
4726 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00004727 if (TheCall->getArg(i)->isTypeDependent() ||
4728 TheCall->getArg(i)->isValueDependent())
4729 continue;
4730
Nate Begemana0110022010-06-08 00:16:34 +00004731 llvm::APSInt Result(32);
4732 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
4733 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004734 diag::err_shufflevector_nonconstant_argument)
4735 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004736
Craig Topper50ad5b72013-08-03 17:40:38 +00004737 // Allow -1 which will be translated to undef in the IR.
4738 if (Result.isSigned() && Result.isAllOnesValue())
4739 continue;
4740
Chris Lattner7ab824e2008-08-10 02:05:13 +00004741 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004742 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004743 diag::err_shufflevector_argument_too_large)
4744 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004745 }
4746
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004747 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004748
Chris Lattner7ab824e2008-08-10 02:05:13 +00004749 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004750 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00004751 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004752 }
4753
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004754 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
4755 TheCall->getCallee()->getLocStart(),
4756 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004757}
Chris Lattner43be2e62007-12-19 23:59:04 +00004758
Hal Finkelc4d7c822013-09-18 03:29:45 +00004759/// SemaConvertVectorExpr - Handle __builtin_convertvector
4760ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
4761 SourceLocation BuiltinLoc,
4762 SourceLocation RParenLoc) {
4763 ExprValueKind VK = VK_RValue;
4764 ExprObjectKind OK = OK_Ordinary;
4765 QualType DstTy = TInfo->getType();
4766 QualType SrcTy = E->getType();
4767
4768 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
4769 return ExprError(Diag(BuiltinLoc,
4770 diag::err_convertvector_non_vector)
4771 << E->getSourceRange());
4772 if (!DstTy->isVectorType() && !DstTy->isDependentType())
4773 return ExprError(Diag(BuiltinLoc,
4774 diag::err_convertvector_non_vector_type));
4775
4776 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
4777 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
4778 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
4779 if (SrcElts != DstElts)
4780 return ExprError(Diag(BuiltinLoc,
4781 diag::err_convertvector_incompatible_vector)
4782 << E->getSourceRange());
4783 }
4784
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004785 return new (Context)
4786 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00004787}
4788
Daniel Dunbarb7257262008-07-21 22:59:13 +00004789/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
4790// This is declared to take (const void*, ...) and can take two
4791// optional constant int args.
4792bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00004793 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004794
Chris Lattner3b054132008-11-19 05:08:23 +00004795 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004796 return Diag(TheCall->getLocEnd(),
4797 diag::err_typecheck_call_too_many_args_at_most)
4798 << 0 /*function call*/ << 3 << NumArgs
4799 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004800
4801 // Argument 0 is checked for us and the remaining arguments must be
4802 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00004803 for (unsigned i = 1; i != NumArgs; ++i)
4804 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004805 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004806
Warren Hunt20e4a5d2014-02-21 23:08:53 +00004807 return false;
4808}
4809
Hal Finkelf0417332014-07-17 14:25:55 +00004810/// SemaBuiltinAssume - Handle __assume (MS Extension).
4811// __assume does not evaluate its arguments, and should warn if its argument
4812// has side effects.
4813bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
4814 Expr *Arg = TheCall->getArg(0);
4815 if (Arg->isInstantiationDependent()) return false;
4816
4817 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00004818 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00004819 << Arg->getSourceRange()
4820 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
4821
4822 return false;
4823}
4824
David Majnemer86b1bfa2016-10-31 18:07:57 +00004825/// Handle __builtin_alloca_with_align. This is declared
David Majnemer51169932016-10-31 05:37:48 +00004826/// as (size_t, size_t) where the second size_t must be a power of 2 greater
4827/// than 8.
4828bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
4829 // The alignment must be a constant integer.
4830 Expr *Arg = TheCall->getArg(1);
4831
4832 // We can't check the value of a dependent argument.
4833 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
David Majnemer86b1bfa2016-10-31 18:07:57 +00004834 if (const auto *UE =
4835 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
4836 if (UE->getKind() == UETT_AlignOf)
4837 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
4838 << Arg->getSourceRange();
4839
David Majnemer51169932016-10-31 05:37:48 +00004840 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
4841
4842 if (!Result.isPowerOf2())
4843 return Diag(TheCall->getLocStart(),
4844 diag::err_alignment_not_power_of_two)
4845 << Arg->getSourceRange();
4846
4847 if (Result < Context.getCharWidth())
4848 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
4849 << (unsigned)Context.getCharWidth()
4850 << Arg->getSourceRange();
4851
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004852 if (Result > std::numeric_limits<int32_t>::max())
David Majnemer51169932016-10-31 05:37:48 +00004853 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004854 << std::numeric_limits<int32_t>::max()
David Majnemer51169932016-10-31 05:37:48 +00004855 << Arg->getSourceRange();
4856 }
4857
4858 return false;
4859}
4860
4861/// Handle __builtin_assume_aligned. This is declared
Hal Finkelbcc06082014-09-07 22:58:14 +00004862/// as (const void*, size_t, ...) and can take one optional constant int arg.
4863bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
4864 unsigned NumArgs = TheCall->getNumArgs();
4865
4866 if (NumArgs > 3)
4867 return Diag(TheCall->getLocEnd(),
4868 diag::err_typecheck_call_too_many_args_at_most)
4869 << 0 /*function call*/ << 3 << NumArgs
4870 << TheCall->getSourceRange();
4871
4872 // The alignment must be a constant integer.
4873 Expr *Arg = TheCall->getArg(1);
4874
4875 // We can't check the value of a dependent argument.
4876 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4877 llvm::APSInt Result;
4878 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4879 return true;
4880
4881 if (!Result.isPowerOf2())
4882 return Diag(TheCall->getLocStart(),
4883 diag::err_alignment_not_power_of_two)
4884 << Arg->getSourceRange();
4885 }
4886
4887 if (NumArgs > 2) {
4888 ExprResult Arg(TheCall->getArg(2));
4889 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4890 Context.getSizeType(), false);
4891 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4892 if (Arg.isInvalid()) return true;
4893 TheCall->setArg(2, Arg.get());
4894 }
Hal Finkelf0417332014-07-17 14:25:55 +00004895
4896 return false;
4897}
4898
Mehdi Amini06d367c2016-10-24 20:39:34 +00004899bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4900 unsigned BuiltinID =
4901 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4902 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4903
4904 unsigned NumArgs = TheCall->getNumArgs();
4905 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4906 if (NumArgs < NumRequiredArgs) {
4907 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4908 << 0 /* function call */ << NumRequiredArgs << NumArgs
4909 << TheCall->getSourceRange();
4910 }
4911 if (NumArgs >= NumRequiredArgs + 0x100) {
4912 return Diag(TheCall->getLocEnd(),
4913 diag::err_typecheck_call_too_many_args_at_most)
4914 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4915 << TheCall->getSourceRange();
4916 }
4917 unsigned i = 0;
4918
4919 // For formatting call, check buffer arg.
4920 if (!IsSizeCall) {
4921 ExprResult Arg(TheCall->getArg(i));
4922 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4923 Context, Context.VoidPtrTy, false);
4924 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4925 if (Arg.isInvalid())
4926 return true;
4927 TheCall->setArg(i, Arg.get());
4928 i++;
4929 }
4930
4931 // Check string literal arg.
4932 unsigned FormatIdx = i;
4933 {
4934 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4935 if (Arg.isInvalid())
4936 return true;
4937 TheCall->setArg(i, Arg.get());
4938 i++;
4939 }
4940
4941 // Make sure variadic args are scalar.
4942 unsigned FirstDataArg = i;
4943 while (i < NumArgs) {
4944 ExprResult Arg = DefaultVariadicArgumentPromotion(
4945 TheCall->getArg(i), VariadicFunction, nullptr);
4946 if (Arg.isInvalid())
4947 return true;
4948 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4949 if (ArgSize.getQuantity() >= 0x100) {
4950 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4951 << i << (int)ArgSize.getQuantity() << 0xff
4952 << TheCall->getSourceRange();
4953 }
4954 TheCall->setArg(i, Arg.get());
4955 i++;
4956 }
4957
4958 // Check formatting specifiers. NOTE: We're only doing this for the non-size
4959 // call to avoid duplicate diagnostics.
4960 if (!IsSizeCall) {
4961 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4962 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4963 bool Success = CheckFormatArguments(
4964 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4965 VariadicFunction, TheCall->getLocStart(), SourceRange(),
4966 CheckedVarArgs);
4967 if (!Success)
4968 return true;
4969 }
4970
4971 if (IsSizeCall) {
4972 TheCall->setType(Context.getSizeType());
4973 } else {
4974 TheCall->setType(Context.VoidPtrTy);
4975 }
4976 return false;
4977}
4978
Eric Christopher8d0c6212010-04-17 02:26:23 +00004979/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4980/// TheCall is a constant expression.
4981bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4982 llvm::APSInt &Result) {
4983 Expr *Arg = TheCall->getArg(ArgNum);
4984 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4985 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4986
4987 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4988
4989 if (!Arg->isIntegerConstantExpr(Result, Context))
4990 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00004991 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00004992
Chris Lattnerd545ad12009-09-23 06:06:36 +00004993 return false;
4994}
4995
Richard Sandiford28940af2014-04-16 08:47:51 +00004996/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4997/// TheCall is a constant expression in the range [Low, High].
4998bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4999 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00005000 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00005001
5002 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00005003 Expr *Arg = TheCall->getArg(ArgNum);
5004 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00005005 return false;
5006
Eric Christopher8d0c6212010-04-17 02:26:23 +00005007 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00005008 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00005009 return true;
5010
Richard Sandiford28940af2014-04-16 08:47:51 +00005011 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00005012 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00005013 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00005014
5015 return false;
5016}
5017
Simon Dardis1f90f2d2016-10-19 17:50:52 +00005018/// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
5019/// TheCall is a constant expression is a multiple of Num..
5020bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
5021 unsigned Num) {
5022 llvm::APSInt Result;
5023
5024 // We can't check the value of a dependent argument.
5025 Expr *Arg = TheCall->getArg(ArgNum);
5026 if (Arg->isTypeDependent() || Arg->isValueDependent())
5027 return false;
5028
5029 // Check constant-ness first.
5030 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
5031 return true;
5032
5033 if (Result.getSExtValue() % Num != 0)
5034 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
5035 << Num << Arg->getSourceRange();
5036
5037 return false;
5038}
5039
Luke Cheeseman59b2d832015-06-15 17:51:01 +00005040/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
5041/// TheCall is an ARM/AArch64 special register string literal.
5042bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
5043 int ArgNum, unsigned ExpectedFieldNum,
5044 bool AllowName) {
5045 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
5046 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
5047 BuiltinID == ARM::BI__builtin_arm_rsr ||
5048 BuiltinID == ARM::BI__builtin_arm_rsrp ||
5049 BuiltinID == ARM::BI__builtin_arm_wsr ||
5050 BuiltinID == ARM::BI__builtin_arm_wsrp;
5051 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
5052 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
5053 BuiltinID == AArch64::BI__builtin_arm_rsr ||
5054 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
5055 BuiltinID == AArch64::BI__builtin_arm_wsr ||
5056 BuiltinID == AArch64::BI__builtin_arm_wsrp;
5057 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
5058
5059 // We can't check the value of a dependent argument.
5060 Expr *Arg = TheCall->getArg(ArgNum);
5061 if (Arg->isTypeDependent() || Arg->isValueDependent())
5062 return false;
5063
5064 // Check if the argument is a string literal.
5065 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
5066 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
5067 << Arg->getSourceRange();
5068
5069 // Check the type of special register given.
5070 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
5071 SmallVector<StringRef, 6> Fields;
5072 Reg.split(Fields, ":");
5073
5074 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
5075 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
5076 << Arg->getSourceRange();
5077
5078 // If the string is the name of a register then we cannot check that it is
5079 // valid here but if the string is of one the forms described in ACLE then we
5080 // can check that the supplied fields are integers and within the valid
5081 // ranges.
5082 if (Fields.size() > 1) {
5083 bool FiveFields = Fields.size() == 5;
5084
5085 bool ValidString = true;
5086 if (IsARMBuiltin) {
5087 ValidString &= Fields[0].startswith_lower("cp") ||
5088 Fields[0].startswith_lower("p");
5089 if (ValidString)
5090 Fields[0] =
5091 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
5092
5093 ValidString &= Fields[2].startswith_lower("c");
5094 if (ValidString)
5095 Fields[2] = Fields[2].drop_front(1);
5096
5097 if (FiveFields) {
5098 ValidString &= Fields[3].startswith_lower("c");
5099 if (ValidString)
5100 Fields[3] = Fields[3].drop_front(1);
5101 }
5102 }
5103
5104 SmallVector<int, 5> Ranges;
5105 if (FiveFields)
Oleg Ranevskyy85d93a82016-11-18 21:00:08 +00005106 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
Luke Cheeseman59b2d832015-06-15 17:51:01 +00005107 else
5108 Ranges.append({15, 7, 15});
5109
5110 for (unsigned i=0; i<Fields.size(); ++i) {
5111 int IntField;
5112 ValidString &= !Fields[i].getAsInteger(10, IntField);
5113 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
5114 }
5115
5116 if (!ValidString)
5117 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
5118 << Arg->getSourceRange();
Luke Cheeseman59b2d832015-06-15 17:51:01 +00005119 } else if (IsAArch64Builtin && Fields.size() == 1) {
5120 // If the register name is one of those that appear in the condition below
5121 // and the special register builtin being used is one of the write builtins,
5122 // then we require that the argument provided for writing to the register
5123 // is an integer constant expression. This is because it will be lowered to
5124 // an MSR (immediate) instruction, so we need to know the immediate at
5125 // compile time.
5126 if (TheCall->getNumArgs() != 2)
5127 return false;
5128
5129 std::string RegLower = Reg.lower();
5130 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
5131 RegLower != "pan" && RegLower != "uao")
5132 return false;
5133
5134 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
5135 }
5136
5137 return false;
5138}
5139
Eli Friedmanc97d0142009-05-03 06:04:26 +00005140/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00005141/// This checks that the target supports __builtin_longjmp and
5142/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00005143bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00005144 if (!Context.getTargetInfo().hasSjLjLowering())
5145 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
5146 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
5147
Eli Friedmaneed8ad22009-05-03 04:46:36 +00005148 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00005149 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00005150
Eric Christopher8d0c6212010-04-17 02:26:23 +00005151 // TODO: This is less than ideal. Overload this to take a value.
5152 if (SemaBuiltinConstantArg(TheCall, 1, Result))
5153 return true;
5154
5155 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00005156 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
5157 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
5158
5159 return false;
5160}
5161
Joerg Sonnenberger27173282015-03-11 23:46:32 +00005162/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
5163/// This checks that the target supports __builtin_setjmp.
5164bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
5165 if (!Context.getTargetInfo().hasSjLjLowering())
5166 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
5167 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
5168 return false;
5169}
5170
Richard Smithd7293d72013-08-05 18:49:43 +00005171namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005172
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005173class UncoveredArgHandler {
5174 enum { Unknown = -1, AllCovered = -2 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005175
5176 signed FirstUncoveredArg = Unknown;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005177 SmallVector<const Expr *, 4> DiagnosticExprs;
5178
5179public:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005180 UncoveredArgHandler() = default;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005181
5182 bool hasUncoveredArg() const {
5183 return (FirstUncoveredArg >= 0);
5184 }
5185
5186 unsigned getUncoveredArg() const {
5187 assert(hasUncoveredArg() && "no uncovered argument");
5188 return FirstUncoveredArg;
5189 }
5190
5191 void setAllCovered() {
5192 // A string has been found with all arguments covered, so clear out
5193 // the diagnostics.
5194 DiagnosticExprs.clear();
5195 FirstUncoveredArg = AllCovered;
5196 }
5197
5198 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
5199 assert(NewFirstUncoveredArg >= 0 && "Outside range");
5200
5201 // Don't update if a previous string covers all arguments.
5202 if (FirstUncoveredArg == AllCovered)
5203 return;
5204
5205 // UncoveredArgHandler tracks the highest uncovered argument index
5206 // and with it all the strings that match this index.
5207 if (NewFirstUncoveredArg == FirstUncoveredArg)
5208 DiagnosticExprs.push_back(StrExpr);
5209 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
5210 DiagnosticExprs.clear();
5211 DiagnosticExprs.push_back(StrExpr);
5212 FirstUncoveredArg = NewFirstUncoveredArg;
5213 }
5214 }
5215
5216 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
5217};
5218
Richard Smithd7293d72013-08-05 18:49:43 +00005219enum StringLiteralCheckType {
5220 SLCT_NotALiteral,
5221 SLCT_UncheckedLiteral,
5222 SLCT_CheckedLiteral
5223};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005224
5225} // namespace
Richard Smithd7293d72013-08-05 18:49:43 +00005226
Stephen Hines648c3692016-09-16 01:07:04 +00005227static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
5228 BinaryOperatorKind BinOpKind,
5229 bool AddendIsRight) {
5230 unsigned BitWidth = Offset.getBitWidth();
5231 unsigned AddendBitWidth = Addend.getBitWidth();
5232 // There might be negative interim results.
5233 if (Addend.isUnsigned()) {
5234 Addend = Addend.zext(++AddendBitWidth);
5235 Addend.setIsSigned(true);
5236 }
5237 // Adjust the bit width of the APSInts.
5238 if (AddendBitWidth > BitWidth) {
5239 Offset = Offset.sext(AddendBitWidth);
5240 BitWidth = AddendBitWidth;
5241 } else if (BitWidth > AddendBitWidth) {
5242 Addend = Addend.sext(BitWidth);
5243 }
5244
5245 bool Ov = false;
5246 llvm::APSInt ResOffset = Offset;
5247 if (BinOpKind == BO_Add)
5248 ResOffset = Offset.sadd_ov(Addend, Ov);
5249 else {
5250 assert(AddendIsRight && BinOpKind == BO_Sub &&
5251 "operator must be add or sub with addend on the right");
5252 ResOffset = Offset.ssub_ov(Addend, Ov);
5253 }
5254
5255 // We add an offset to a pointer here so we should support an offset as big as
5256 // possible.
5257 if (Ov) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005258 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
5259 "index (intermediate) result too big");
Stephen Hinesfec73ad2016-09-16 07:21:24 +00005260 Offset = Offset.sext(2 * BitWidth);
Stephen Hines648c3692016-09-16 01:07:04 +00005261 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
5262 return;
5263 }
5264
5265 Offset = ResOffset;
5266}
5267
5268namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005269
Stephen Hines648c3692016-09-16 01:07:04 +00005270// This is a wrapper class around StringLiteral to support offsetted string
5271// literals as format strings. It takes the offset into account when returning
5272// the string and its length or the source locations to display notes correctly.
5273class FormatStringLiteral {
5274 const StringLiteral *FExpr;
5275 int64_t Offset;
5276
5277 public:
5278 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
5279 : FExpr(fexpr), Offset(Offset) {}
5280
5281 StringRef getString() const {
5282 return FExpr->getString().drop_front(Offset);
5283 }
5284
5285 unsigned getByteLength() const {
5286 return FExpr->getByteLength() - getCharByteWidth() * Offset;
5287 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005288
Stephen Hines648c3692016-09-16 01:07:04 +00005289 unsigned getLength() const { return FExpr->getLength() - Offset; }
5290 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
5291
5292 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
5293
5294 QualType getType() const { return FExpr->getType(); }
5295
5296 bool isAscii() const { return FExpr->isAscii(); }
5297 bool isWide() const { return FExpr->isWide(); }
5298 bool isUTF8() const { return FExpr->isUTF8(); }
5299 bool isUTF16() const { return FExpr->isUTF16(); }
5300 bool isUTF32() const { return FExpr->isUTF32(); }
5301 bool isPascal() const { return FExpr->isPascal(); }
5302
5303 SourceLocation getLocationOfByte(
5304 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
5305 const TargetInfo &Target, unsigned *StartToken = nullptr,
5306 unsigned *StartTokenByteOffset = nullptr) const {
5307 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
5308 StartToken, StartTokenByteOffset);
5309 }
5310
5311 SourceLocation getLocStart() const LLVM_READONLY {
5312 return FExpr->getLocStart().getLocWithOffset(Offset);
5313 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005314
Stephen Hines648c3692016-09-16 01:07:04 +00005315 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
5316};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005317
5318} // namespace
Stephen Hines648c3692016-09-16 01:07:04 +00005319
5320static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005321 const Expr *OrigFormatExpr,
5322 ArrayRef<const Expr *> Args,
5323 bool HasVAListArg, unsigned format_idx,
5324 unsigned firstDataArg,
5325 Sema::FormatStringType Type,
5326 bool inFunctionCall,
5327 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005328 llvm::SmallBitVector &CheckedVarArgs,
5329 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005330
Richard Smith55ce3522012-06-25 20:30:08 +00005331// Determine if an expression is a string literal or constant string.
5332// If this function returns false on the arguments to a function expecting a
5333// format string, we will usually need to emit a warning.
5334// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00005335static StringLiteralCheckType
5336checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
5337 bool HasVAListArg, unsigned format_idx,
5338 unsigned firstDataArg, Sema::FormatStringType Type,
5339 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005340 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00005341 UncoveredArgHandler &UncoveredArg,
5342 llvm::APSInt Offset) {
Ted Kremenek808829352010-09-09 03:51:39 +00005343 tryAgain:
Stephen Hines648c3692016-09-16 01:07:04 +00005344 assert(Offset.isSigned() && "invalid offset");
5345
Douglas Gregorc25f7662009-05-19 22:10:17 +00005346 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00005347 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005348
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005349 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00005350
Richard Smithd7293d72013-08-05 18:49:43 +00005351 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00005352 // Technically -Wformat-nonliteral does not warn about this case.
5353 // The behavior of printf and friends in this case is implementation
5354 // dependent. Ideally if the format string cannot be null then
5355 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00005356 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00005357
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005358 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00005359 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005360 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00005361 // The expression is a literal if both sub-expressions were, and it was
5362 // completely checked only if both sub-expressions were checked.
5363 const AbstractConditionalOperator *C =
5364 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005365
5366 // Determine whether it is necessary to check both sub-expressions, for
5367 // example, because the condition expression is a constant that can be
5368 // evaluated at compile time.
5369 bool CheckLeft = true, CheckRight = true;
5370
5371 bool Cond;
5372 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
5373 if (Cond)
5374 CheckRight = false;
5375 else
5376 CheckLeft = false;
5377 }
5378
Stephen Hines648c3692016-09-16 01:07:04 +00005379 // We need to maintain the offsets for the right and the left hand side
5380 // separately to check if every possible indexed expression is a valid
5381 // string literal. They might have different offsets for different string
5382 // literals in the end.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005383 StringLiteralCheckType Left;
5384 if (!CheckLeft)
5385 Left = SLCT_UncheckedLiteral;
5386 else {
5387 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
5388 HasVAListArg, format_idx, firstDataArg,
5389 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00005390 CheckedVarArgs, UncoveredArg, Offset);
5391 if (Left == SLCT_NotALiteral || !CheckRight) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005392 return Left;
Stephen Hines648c3692016-09-16 01:07:04 +00005393 }
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005394 }
5395
Richard Smith55ce3522012-06-25 20:30:08 +00005396 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00005397 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005398 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005399 Type, CallType, InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00005400 UncoveredArg, Offset);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005401
5402 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005403 }
5404
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005405 case Stmt::ImplicitCastExprClass:
Ted Kremenek808829352010-09-09 03:51:39 +00005406 E = cast<ImplicitCastExpr>(E)->getSubExpr();
5407 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005408
John McCallc07a0c72011-02-17 10:25:35 +00005409 case Stmt::OpaqueValueExprClass:
5410 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
5411 E = src;
5412 goto tryAgain;
5413 }
Richard Smith55ce3522012-06-25 20:30:08 +00005414 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00005415
Ted Kremeneka8890832011-02-24 23:03:04 +00005416 case Stmt::PredefinedExprClass:
5417 // While __func__, etc., are technically not string literals, they
5418 // cannot contain format specifiers and thus are not a security
5419 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00005420 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00005421
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005422 case Stmt::DeclRefExprClass: {
5423 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005424
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005425 // As an exception, do not flag errors for variables binding to
5426 // const string literals.
5427 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
5428 bool isConstant = false;
5429 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005430
Richard Smithd7293d72013-08-05 18:49:43 +00005431 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
5432 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00005433 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00005434 isConstant = T.isConstant(S.Context) &&
5435 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00005436 } else if (T->isObjCObjectPointerType()) {
5437 // In ObjC, there is usually no "const ObjectPointer" type,
5438 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00005439 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005440 }
Mike Stump11289f42009-09-09 15:08:12 +00005441
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005442 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00005443 if (const Expr *Init = VD->getAnyInitializer()) {
5444 // Look through initializers like const char c[] = { "foo" }
5445 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
5446 if (InitList->isStringLiteralInit())
5447 Init = InitList->getInit(0)->IgnoreParenImpCasts();
5448 }
Richard Smithd7293d72013-08-05 18:49:43 +00005449 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005450 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005451 firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00005452 /*InFunctionCall*/ false, CheckedVarArgs,
5453 UncoveredArg, Offset);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00005454 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005455 }
Mike Stump11289f42009-09-09 15:08:12 +00005456
Anders Carlssonb012ca92009-06-28 19:55:58 +00005457 // For vprintf* functions (i.e., HasVAListArg==true), we add a
5458 // special check to see if the format string is a function parameter
5459 // of the function calling the printf function. If the function
5460 // has an attribute indicating it is a printf-like function, then we
5461 // should suppress warnings concerning non-literals being used in a call
5462 // to a vprintf function. For example:
5463 //
5464 // void
5465 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
5466 // va_list ap;
5467 // va_start(ap, fmt);
5468 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
5469 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00005470 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00005471 if (HasVAListArg) {
5472 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
5473 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
5474 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00005475 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00005476 // adjust for implicit parameter
5477 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5478 if (MD->isInstance())
5479 ++PVIndex;
5480 // We also check if the formats are compatible.
5481 // We can't pass a 'scanf' string to a 'printf' function.
5482 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00005483 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00005484 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00005485 }
5486 }
5487 }
5488 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005489 }
Mike Stump11289f42009-09-09 15:08:12 +00005490
Richard Smith55ce3522012-06-25 20:30:08 +00005491 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005492 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005493
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00005494 case Stmt::CallExprClass:
5495 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005496 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00005497 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
5498 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
Joel E. Denny81508102018-03-13 14:51:22 +00005499 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
Richard Smithd7293d72013-08-05 18:49:43 +00005500 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005501 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00005502 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00005503 CheckedVarArgs, UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005504 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5505 unsigned BuiltinID = FD->getBuiltinID();
5506 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
5507 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
5508 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00005509 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005510 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005511 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005512 InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00005513 UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005514 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005515 }
5516 }
Mike Stump11289f42009-09-09 15:08:12 +00005517
Richard Smith55ce3522012-06-25 20:30:08 +00005518 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005519 }
Alex Lorenzd9007142016-10-24 09:42:34 +00005520 case Stmt::ObjCMessageExprClass: {
5521 const auto *ME = cast<ObjCMessageExpr>(E);
5522 if (const auto *ND = ME->getMethodDecl()) {
5523 if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
Joel E. Denny81508102018-03-13 14:51:22 +00005524 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
Alex Lorenzd9007142016-10-24 09:42:34 +00005525 return checkFormatStringExpr(
5526 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
5527 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
5528 }
5529 }
5530
5531 return SLCT_NotALiteral;
5532 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005533 case Stmt::ObjCStringLiteralClass:
5534 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00005535 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005536
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005537 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005538 StrE = ObjCFExpr->getString();
5539 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005540 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005541
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005542 if (StrE) {
Stephen Hines648c3692016-09-16 01:07:04 +00005543 if (Offset.isNegative() || Offset > StrE->getLength()) {
5544 // TODO: It would be better to have an explicit warning for out of
5545 // bounds literals.
5546 return SLCT_NotALiteral;
5547 }
5548 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
5549 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005550 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005551 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00005552 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005553 }
Mike Stump11289f42009-09-09 15:08:12 +00005554
Richard Smith55ce3522012-06-25 20:30:08 +00005555 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005556 }
Stephen Hines648c3692016-09-16 01:07:04 +00005557 case Stmt::BinaryOperatorClass: {
5558 llvm::APSInt LResult;
5559 llvm::APSInt RResult;
5560
5561 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
5562
5563 // A string literal + an int offset is still a string literal.
5564 if (BinOp->isAdditiveOp()) {
5565 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
5566 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
5567
5568 if (LIsInt != RIsInt) {
5569 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
5570
5571 if (LIsInt) {
5572 if (BinOpKind == BO_Add) {
5573 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
5574 E = BinOp->getRHS();
5575 goto tryAgain;
5576 }
5577 } else {
5578 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
5579 E = BinOp->getLHS();
5580 goto tryAgain;
5581 }
5582 }
Stephen Hines648c3692016-09-16 01:07:04 +00005583 }
George Burgess IVd273aab2016-09-22 00:00:26 +00005584
5585 return SLCT_NotALiteral;
Stephen Hines648c3692016-09-16 01:07:04 +00005586 }
5587 case Stmt::UnaryOperatorClass: {
5588 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
5589 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005590 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
Stephen Hines648c3692016-09-16 01:07:04 +00005591 llvm::APSInt IndexResult;
5592 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
5593 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
5594 E = ASE->getBase();
5595 goto tryAgain;
5596 }
5597 }
5598
5599 return SLCT_NotALiteral;
5600 }
Mike Stump11289f42009-09-09 15:08:12 +00005601
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005602 default:
Richard Smith55ce3522012-06-25 20:30:08 +00005603 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005604 }
5605}
5606
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005607Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00005608 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Mehdi Amini06d367c2016-10-24 20:39:34 +00005609 .Case("scanf", FST_Scanf)
5610 .Cases("printf", "printf0", FST_Printf)
5611 .Cases("NSString", "CFString", FST_NSString)
5612 .Case("strftime", FST_Strftime)
5613 .Case("strfmon", FST_Strfmon)
5614 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
5615 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
5616 .Case("os_trace", FST_OSLog)
5617 .Case("os_log", FST_OSLog)
5618 .Default(FST_Unknown);
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005619}
5620
Jordan Rose3e0ec582012-07-19 18:10:23 +00005621/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00005622/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00005623/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005624bool Sema::CheckFormatArguments(const FormatAttr *Format,
5625 ArrayRef<const Expr *> Args,
5626 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005627 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00005628 SourceLocation Loc, SourceRange Range,
5629 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00005630 FormatStringInfo FSI;
5631 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005632 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00005633 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00005634 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00005635 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005636}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00005637
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005638bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005639 bool HasVAListArg, unsigned format_idx,
5640 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005641 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00005642 SourceLocation Loc, SourceRange Range,
5643 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00005644 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005645 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005646 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00005647 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005648 }
Mike Stump11289f42009-09-09 15:08:12 +00005649
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005650 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00005651
Chris Lattnerb87b1b32007-08-10 20:18:51 +00005652 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00005653 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005654 // Dynamically generated format strings are difficult to
5655 // automatically vet at compile time. Requiring that format strings
5656 // are string literals: (1) permits the checking of format strings by
5657 // the compiler and thereby (2) can practically remove the source of
5658 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00005659
Mike Stump11289f42009-09-09 15:08:12 +00005660 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00005661 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00005662 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00005663 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005664 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00005665 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00005666 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
5667 format_idx, firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00005668 /*IsFunctionCall*/ true, CheckedVarArgs,
5669 UncoveredArg,
5670 /*no string offset*/ llvm::APSInt(64, false) = 0);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005671
5672 // Generate a diagnostic where an uncovered argument is detected.
5673 if (UncoveredArg.hasUncoveredArg()) {
5674 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
5675 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
5676 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
5677 }
5678
Richard Smith55ce3522012-06-25 20:30:08 +00005679 if (CT != SLCT_NotALiteral)
5680 // Literal format string found, check done!
5681 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00005682
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00005683 // Strftime is particular as it always uses a single 'time' argument,
5684 // so it is safe to pass a non-literal string.
5685 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00005686 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00005687
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00005688 // Do not emit diag when the string param is a macro expansion and the
5689 // format is either NSString or CFString. This is a hack to prevent
5690 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
5691 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005692 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
5693 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00005694 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00005695
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005696 // If there are no arguments specified, warn with -Wformat-security, otherwise
5697 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005698 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00005699 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
5700 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005701 switch (Type) {
5702 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005703 break;
5704 case FST_Kprintf:
5705 case FST_FreeBSDKPrintf:
5706 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00005707 Diag(FormatLoc, diag::note_format_security_fixit)
5708 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005709 break;
5710 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00005711 Diag(FormatLoc, diag::note_format_security_fixit)
5712 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005713 break;
5714 }
5715 } else {
5716 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005717 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005718 }
Richard Smith55ce3522012-06-25 20:30:08 +00005719 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005720}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005721
Ted Kremenekab278de2010-01-28 23:39:18 +00005722namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005723
Ted Kremenek02087932010-07-16 02:11:22 +00005724class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
5725protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00005726 Sema &S;
Stephen Hines648c3692016-09-16 01:07:04 +00005727 const FormatStringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00005728 const Expr *OrigFormatExpr;
Mehdi Amini06d367c2016-10-24 20:39:34 +00005729 const Sema::FormatStringType FSType;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00005730 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00005731 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00005732 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00005733 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005734 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00005735 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00005736 llvm::SmallBitVector CoveredArgs;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005737 bool usesPositionalArgs = false;
5738 bool atFirstArg = true;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005739 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00005740 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00005741 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005742 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005743
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005744public:
Stephen Hines648c3692016-09-16 01:07:04 +00005745 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005746 const Expr *origFormatExpr,
5747 const Sema::FormatStringType type, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005748 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005749 ArrayRef<const Expr *> Args, unsigned formatIdx,
5750 bool inFunctionCall, Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005751 llvm::SmallBitVector &CheckedVarArgs,
5752 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005753 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
5754 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
5755 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
Mehdi Amini06d367c2016-10-24 20:39:34 +00005756 inFunctionCall(inFunctionCall), CallType(callType),
5757 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00005758 CoveredArgs.resize(numDataArgs);
5759 CoveredArgs.reset();
5760 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005761
Ted Kremenek019d2242010-01-29 01:50:07 +00005762 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005763
Ted Kremenek02087932010-07-16 02:11:22 +00005764 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005765 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005766
Jordan Rose92303592012-09-08 04:00:03 +00005767 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005768 const analyze_format_string::FormatSpecifier &FS,
5769 const analyze_format_string::ConversionSpecifier &CS,
5770 const char *startSpecifier, unsigned specifierLen,
5771 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00005772
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005773 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005774 const analyze_format_string::FormatSpecifier &FS,
5775 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005776
5777 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005778 const analyze_format_string::ConversionSpecifier &CS,
5779 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005780
Craig Toppere14c0f82014-03-12 04:55:44 +00005781 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005782
Craig Toppere14c0f82014-03-12 04:55:44 +00005783 void HandleInvalidPosition(const char *startSpecifier,
5784 unsigned specifierLen,
5785 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005786
Craig Toppere14c0f82014-03-12 04:55:44 +00005787 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005788
Craig Toppere14c0f82014-03-12 04:55:44 +00005789 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005790
Richard Trieu03cf7b72011-10-28 00:41:25 +00005791 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00005792 static void
5793 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
5794 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
5795 bool IsStringLocation, Range StringRange,
5796 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005797
Ted Kremenek02087932010-07-16 02:11:22 +00005798protected:
Ted Kremenekce815422010-07-19 21:25:57 +00005799 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
5800 const char *startSpec,
5801 unsigned specifierLen,
5802 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005803
5804 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
5805 const char *startSpec,
5806 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00005807
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005808 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00005809 CharSourceRange getSpecifierRange(const char *startSpecifier,
5810 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00005811 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005812
Ted Kremenek5739de72010-01-29 01:06:55 +00005813 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005814
5815 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
5816 const analyze_format_string::ConversionSpecifier &CS,
5817 const char *startSpecifier, unsigned specifierLen,
5818 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005819
5820 template <typename Range>
5821 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5822 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00005823 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00005824};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005825
5826} // namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00005827
Ted Kremenek02087932010-07-16 02:11:22 +00005828SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00005829 return OrigFormatExpr->getSourceRange();
5830}
5831
Ted Kremenek02087932010-07-16 02:11:22 +00005832CharSourceRange CheckFormatHandler::
5833getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00005834 SourceLocation Start = getLocationOfByte(startSpecifier);
5835 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
5836
5837 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00005838 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00005839
5840 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005841}
5842
Ted Kremenek02087932010-07-16 02:11:22 +00005843SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines648c3692016-09-16 01:07:04 +00005844 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
5845 S.getLangOpts(), S.Context.getTargetInfo());
Ted Kremenekab278de2010-01-28 23:39:18 +00005846}
5847
Ted Kremenek02087932010-07-16 02:11:22 +00005848void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
5849 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00005850 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
5851 getLocationOfByte(startSpecifier),
5852 /*IsStringLocation*/true,
5853 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00005854}
5855
Jordan Rose92303592012-09-08 04:00:03 +00005856void CheckFormatHandler::HandleInvalidLengthModifier(
5857 const analyze_format_string::FormatSpecifier &FS,
5858 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00005859 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00005860 using namespace analyze_format_string;
5861
5862 const LengthModifier &LM = FS.getLengthModifier();
5863 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5864
5865 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005866 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00005867 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005868 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005869 getLocationOfByte(LM.getStart()),
5870 /*IsStringLocation*/true,
5871 getSpecifierRange(startSpecifier, specifierLen));
5872
5873 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5874 << FixedLM->toString()
5875 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5876
5877 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005878 FixItHint Hint;
5879 if (DiagID == diag::warn_format_nonsensical_length)
5880 Hint = FixItHint::CreateRemoval(LMRange);
5881
5882 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005883 getLocationOfByte(LM.getStart()),
5884 /*IsStringLocation*/true,
5885 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00005886 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00005887 }
5888}
5889
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005890void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00005891 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005892 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005893 using namespace analyze_format_string;
5894
5895 const LengthModifier &LM = FS.getLengthModifier();
5896 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5897
5898 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005899 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00005900 if (FixedLM) {
5901 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5902 << LM.toString() << 0,
5903 getLocationOfByte(LM.getStart()),
5904 /*IsStringLocation*/true,
5905 getSpecifierRange(startSpecifier, specifierLen));
5906
5907 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5908 << FixedLM->toString()
5909 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5910
5911 } else {
5912 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5913 << LM.toString() << 0,
5914 getLocationOfByte(LM.getStart()),
5915 /*IsStringLocation*/true,
5916 getSpecifierRange(startSpecifier, specifierLen));
5917 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005918}
5919
5920void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5921 const analyze_format_string::ConversionSpecifier &CS,
5922 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00005923 using namespace analyze_format_string;
5924
5925 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00005926 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00005927 if (FixedCS) {
5928 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5929 << CS.toString() << /*conversion specifier*/1,
5930 getLocationOfByte(CS.getStart()),
5931 /*IsStringLocation*/true,
5932 getSpecifierRange(startSpecifier, specifierLen));
5933
5934 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5935 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5936 << FixedCS->toString()
5937 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5938 } else {
5939 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5940 << CS.toString() << /*conversion specifier*/1,
5941 getLocationOfByte(CS.getStart()),
5942 /*IsStringLocation*/true,
5943 getSpecifierRange(startSpecifier, specifierLen));
5944 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005945}
5946
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005947void CheckFormatHandler::HandlePosition(const char *startPos,
5948 unsigned posLen) {
5949 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5950 getLocationOfByte(startPos),
5951 /*IsStringLocation*/true,
5952 getSpecifierRange(startPos, posLen));
5953}
5954
Ted Kremenekd1668192010-02-27 01:41:03 +00005955void
Ted Kremenek02087932010-07-16 02:11:22 +00005956CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5957 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005958 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5959 << (unsigned) p,
5960 getLocationOfByte(startPos), /*IsStringLocation*/true,
5961 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005962}
5963
Ted Kremenek02087932010-07-16 02:11:22 +00005964void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00005965 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005966 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5967 getLocationOfByte(startPos),
5968 /*IsStringLocation*/true,
5969 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005970}
5971
Ted Kremenek02087932010-07-16 02:11:22 +00005972void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005973 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005974 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005975 EmitFormatDiagnostic(
5976 S.PDiag(diag::warn_printf_format_string_contains_null_char),
5977 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5978 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005979 }
Ted Kremenek02087932010-07-16 02:11:22 +00005980}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005981
Jordan Rose58bbe422012-07-19 18:10:08 +00005982// Note that this may return NULL if there was an error parsing or building
5983// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00005984const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005985 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00005986}
5987
5988void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005989 // Does the number of data arguments exceed the number of
5990 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00005991 if (!HasVAListArg) {
5992 // Find any arguments that weren't covered.
5993 CoveredArgs.flip();
5994 signed notCoveredArg = CoveredArgs.find_first();
5995 if (notCoveredArg >= 0) {
5996 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005997 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5998 } else {
5999 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00006000 }
6001 }
6002}
6003
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006004void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
6005 const Expr *ArgExpr) {
6006 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
6007 "Invalid state");
6008
6009 if (!ArgExpr)
6010 return;
6011
6012 SourceLocation Loc = ArgExpr->getLocStart();
6013
6014 if (S.getSourceManager().isInSystemMacro(Loc))
6015 return;
6016
6017 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
6018 for (auto E : DiagnosticExprs)
6019 PDiag << E->getSourceRange();
6020
6021 CheckFormatHandler::EmitFormatDiagnostic(
6022 S, IsFunctionCall, DiagnosticExprs[0],
6023 PDiag, Loc, /*IsStringLocation*/false,
6024 DiagnosticExprs[0]->getSourceRange());
6025}
6026
Ted Kremenekce815422010-07-19 21:25:57 +00006027bool
6028CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
6029 SourceLocation Loc,
6030 const char *startSpec,
6031 unsigned specifierLen,
6032 const char *csStart,
6033 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00006034 bool keepGoing = true;
6035 if (argIndex < NumDataArgs) {
6036 // Consider the argument coverered, even though the specifier doesn't
6037 // make sense.
6038 CoveredArgs.set(argIndex);
6039 }
6040 else {
6041 // If argIndex exceeds the number of data arguments we
6042 // don't issue a warning because that is just a cascade of warnings (and
6043 // they may have intended '%%' anyway). We don't want to continue processing
6044 // the format string after this point, however, as we will like just get
6045 // gibberish when trying to match arguments.
6046 keepGoing = false;
6047 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00006048
6049 StringRef Specifier(csStart, csLen);
6050
6051 // If the specifier in non-printable, it could be the first byte of a UTF-8
6052 // sequence. In that case, print the UTF-8 code point. If not, print the byte
6053 // hex value.
6054 std::string CodePointStr;
6055 if (!llvm::sys::locale::isPrint(*csStart)) {
Justin Lebar90910552016-09-30 00:38:45 +00006056 llvm::UTF32 CodePoint;
6057 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
6058 const llvm::UTF8 *E =
6059 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
6060 llvm::ConversionResult Result =
6061 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00006062
Justin Lebar90910552016-09-30 00:38:45 +00006063 if (Result != llvm::conversionOK) {
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00006064 unsigned char FirstChar = *csStart;
Justin Lebar90910552016-09-30 00:38:45 +00006065 CodePoint = (llvm::UTF32)FirstChar;
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00006066 }
6067
6068 llvm::raw_string_ostream OS(CodePointStr);
6069 if (CodePoint < 256)
6070 OS << "\\x" << llvm::format("%02x", CodePoint);
6071 else if (CodePoint <= 0xFFFF)
6072 OS << "\\u" << llvm::format("%04x", CodePoint);
6073 else
6074 OS << "\\U" << llvm::format("%08x", CodePoint);
6075 OS.flush();
6076 Specifier = CodePointStr;
6077 }
6078
6079 EmitFormatDiagnostic(
6080 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
6081 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
6082
Ted Kremenekce815422010-07-19 21:25:57 +00006083 return keepGoing;
6084}
6085
Richard Trieu03cf7b72011-10-28 00:41:25 +00006086void
6087CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
6088 const char *startSpec,
6089 unsigned specifierLen) {
6090 EmitFormatDiagnostic(
6091 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
6092 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
6093}
6094
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006095bool
6096CheckFormatHandler::CheckNumArgs(
6097 const analyze_format_string::FormatSpecifier &FS,
6098 const analyze_format_string::ConversionSpecifier &CS,
6099 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
6100
6101 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006102 PartialDiagnostic PDiag = FS.usesPositionalArg()
6103 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
6104 << (argIndex+1) << NumDataArgs)
6105 : S.PDiag(diag::warn_printf_insufficient_data_args);
6106 EmitFormatDiagnostic(
6107 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
6108 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006109
6110 // Since more arguments than conversion tokens are given, by extension
6111 // all arguments are covered, so mark this as so.
6112 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006113 return false;
6114 }
6115 return true;
6116}
6117
Richard Trieu03cf7b72011-10-28 00:41:25 +00006118template<typename Range>
6119void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
6120 SourceLocation Loc,
6121 bool IsStringLocation,
6122 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00006123 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00006124 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00006125 Loc, IsStringLocation, StringRange, FixIt);
6126}
6127
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006128/// If the format string is not within the function call, emit a note
Richard Trieu03cf7b72011-10-28 00:41:25 +00006129/// so that the function call and string are in diagnostic messages.
6130///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00006131/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00006132/// call and only one diagnostic message will be produced. Otherwise, an
6133/// extra note will be emitted pointing to location of the format string.
6134///
6135/// \param ArgumentExpr the expression that is passed as the format string
6136/// argument in the function call. Used for getting locations when two
6137/// diagnostics are emitted.
6138///
6139/// \param PDiag the callee should already have provided any strings for the
6140/// diagnostic message. This function only adds locations and fixits
6141/// to diagnostics.
6142///
6143/// \param Loc primary location for diagnostic. If two diagnostics are
6144/// required, one will be at Loc and a new SourceLocation will be created for
6145/// the other one.
6146///
6147/// \param IsStringLocation if true, Loc points to the format string should be
6148/// used for the note. Otherwise, Loc points to the argument list and will
6149/// be used with PDiag.
6150///
6151/// \param StringRange some or all of the string to highlight. This is
6152/// templated so it can accept either a CharSourceRange or a SourceRange.
6153///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00006154/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00006155template <typename Range>
6156void CheckFormatHandler::EmitFormatDiagnostic(
6157 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
6158 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
6159 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00006160 if (InFunctionCall) {
6161 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
6162 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00006163 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00006164 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006165 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
6166 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00006167
6168 const Sema::SemaDiagnosticBuilder &Note =
6169 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
6170 diag::note_format_string_defined);
6171
6172 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00006173 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00006174 }
6175}
6176
Ted Kremenek02087932010-07-16 02:11:22 +00006177//===--- CHECK: Printf format string checking ------------------------------===//
6178
6179namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006180
Ted Kremenek02087932010-07-16 02:11:22 +00006181class CheckPrintfHandler : public CheckFormatHandler {
6182public:
Stephen Hines648c3692016-09-16 01:07:04 +00006183 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006184 const Expr *origFormatExpr,
6185 const Sema::FormatStringType type, unsigned firstDataArg,
6186 unsigned numDataArgs, bool isObjC, const char *beg,
6187 bool hasVAListArg, ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00006188 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00006189 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006190 llvm::SmallBitVector &CheckedVarArgs,
6191 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006192 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6193 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6194 inFunctionCall, CallType, CheckedVarArgs,
6195 UncoveredArg) {}
6196
6197 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
6198
6199 /// Returns true if '%@' specifiers are allowed in the format string.
6200 bool allowsObjCArg() const {
6201 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
6202 FSType == Sema::FST_OSTrace;
6203 }
Jordan Rose3e0ec582012-07-19 18:10:23 +00006204
Ted Kremenek02087932010-07-16 02:11:22 +00006205 bool HandleInvalidPrintfConversionSpecifier(
6206 const analyze_printf::PrintfSpecifier &FS,
6207 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006208 unsigned specifierLen) override;
6209
Ted Kremenek02087932010-07-16 02:11:22 +00006210 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
6211 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006212 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00006213 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6214 const char *StartSpecifier,
6215 unsigned SpecifierLen,
6216 const Expr *E);
6217
Ted Kremenek02087932010-07-16 02:11:22 +00006218 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
6219 const char *startSpecifier, unsigned specifierLen);
6220 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
6221 const analyze_printf::OptionalAmount &Amt,
6222 unsigned type,
6223 const char *startSpecifier, unsigned specifierLen);
6224 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
6225 const analyze_printf::OptionalFlag &flag,
6226 const char *startSpecifier, unsigned specifierLen);
6227 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
6228 const analyze_printf::OptionalFlag &ignoredFlag,
6229 const analyze_printf::OptionalFlag &flag,
6230 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006231 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00006232 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00006233
6234 void HandleEmptyObjCModifierFlag(const char *startFlag,
6235 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00006236
Ted Kremenek2b417712015-07-02 05:39:16 +00006237 void HandleInvalidObjCModifierFlag(const char *startFlag,
6238 unsigned flagLen) override;
6239
6240 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
6241 const char *flagsEnd,
6242 const char *conversionPosition)
6243 override;
6244};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006245
6246} // namespace
Ted Kremenek02087932010-07-16 02:11:22 +00006247
6248bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
6249 const analyze_printf::PrintfSpecifier &FS,
6250 const char *startSpecifier,
6251 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006252 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00006253 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00006254
Ted Kremenekce815422010-07-19 21:25:57 +00006255 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6256 getLocationOfByte(CS.getStart()),
6257 startSpecifier, specifierLen,
6258 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00006259}
6260
Ted Kremenek02087932010-07-16 02:11:22 +00006261bool CheckPrintfHandler::HandleAmount(
6262 const analyze_format_string::OptionalAmount &Amt,
6263 unsigned k, const char *startSpecifier,
6264 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00006265 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00006266 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00006267 unsigned argIndex = Amt.getArgIndex();
6268 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006269 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
6270 << k,
6271 getLocationOfByte(Amt.getStart()),
6272 /*IsStringLocation*/true,
6273 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00006274 // Don't do any more checking. We will just emit
6275 // spurious errors.
6276 return false;
6277 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006278
Ted Kremenek5739de72010-01-29 01:06:55 +00006279 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00006280 // Although not in conformance with C99, we also allow the argument to be
6281 // an 'unsigned int' as that is a reasonably safe case. GCC also
6282 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00006283 CoveredArgs.set(argIndex);
6284 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00006285 if (!Arg)
6286 return false;
6287
Ted Kremenek5739de72010-01-29 01:06:55 +00006288 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006289
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006290 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
6291 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006292
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006293 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006294 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006295 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00006296 << T << Arg->getSourceRange(),
6297 getLocationOfByte(Amt.getStart()),
6298 /*IsStringLocation*/true,
6299 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00006300 // Don't do any more checking. We will just emit
6301 // spurious errors.
6302 return false;
6303 }
6304 }
6305 }
6306 return true;
6307}
Ted Kremenek5739de72010-01-29 01:06:55 +00006308
Tom Careb49ec692010-06-17 19:00:27 +00006309void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00006310 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00006311 const analyze_printf::OptionalAmount &Amt,
6312 unsigned type,
6313 const char *startSpecifier,
6314 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006315 const analyze_printf::PrintfConversionSpecifier &CS =
6316 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00006317
Richard Trieu03cf7b72011-10-28 00:41:25 +00006318 FixItHint fixit =
6319 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
6320 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
6321 Amt.getConstantLength()))
6322 : FixItHint();
6323
6324 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
6325 << type << CS.toString(),
6326 getLocationOfByte(Amt.getStart()),
6327 /*IsStringLocation*/true,
6328 getSpecifierRange(startSpecifier, specifierLen),
6329 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00006330}
6331
Ted Kremenek02087932010-07-16 02:11:22 +00006332void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00006333 const analyze_printf::OptionalFlag &flag,
6334 const char *startSpecifier,
6335 unsigned specifierLen) {
6336 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006337 const analyze_printf::PrintfConversionSpecifier &CS =
6338 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00006339 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
6340 << flag.toString() << CS.toString(),
6341 getLocationOfByte(flag.getPosition()),
6342 /*IsStringLocation*/true,
6343 getSpecifierRange(startSpecifier, specifierLen),
6344 FixItHint::CreateRemoval(
6345 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00006346}
6347
6348void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00006349 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00006350 const analyze_printf::OptionalFlag &ignoredFlag,
6351 const analyze_printf::OptionalFlag &flag,
6352 const char *startSpecifier,
6353 unsigned specifierLen) {
6354 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00006355 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
6356 << ignoredFlag.toString() << flag.toString(),
6357 getLocationOfByte(ignoredFlag.getPosition()),
6358 /*IsStringLocation*/true,
6359 getSpecifierRange(startSpecifier, specifierLen),
6360 FixItHint::CreateRemoval(
6361 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00006362}
6363
Ted Kremenek2b417712015-07-02 05:39:16 +00006364void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
6365 unsigned flagLen) {
6366 // Warn about an empty flag.
6367 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
6368 getLocationOfByte(startFlag),
6369 /*IsStringLocation*/true,
6370 getSpecifierRange(startFlag, flagLen));
6371}
6372
6373void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
6374 unsigned flagLen) {
6375 // Warn about an invalid flag.
6376 auto Range = getSpecifierRange(startFlag, flagLen);
6377 StringRef flag(startFlag, flagLen);
6378 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
6379 getLocationOfByte(startFlag),
6380 /*IsStringLocation*/true,
6381 Range, FixItHint::CreateRemoval(Range));
6382}
6383
6384void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
6385 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
6386 // Warn about using '[...]' without a '@' conversion.
6387 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
6388 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
6389 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
6390 getLocationOfByte(conversionPosition),
6391 /*IsStringLocation*/true,
6392 Range, FixItHint::CreateRemoval(Range));
6393}
6394
Richard Smith55ce3522012-06-25 20:30:08 +00006395// Determines if the specified is a C++ class or struct containing
6396// a member with the specified name and kind (e.g. a CXXMethodDecl named
6397// "c_str()").
6398template<typename MemberKind>
6399static llvm::SmallPtrSet<MemberKind*, 1>
6400CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
6401 const RecordType *RT = Ty->getAs<RecordType>();
6402 llvm::SmallPtrSet<MemberKind*, 1> Results;
6403
6404 if (!RT)
6405 return Results;
6406 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00006407 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00006408 return Results;
6409
Alp Tokerb6cc5922014-05-03 03:45:55 +00006410 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00006411 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00006412 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00006413
6414 // We just need to include all members of the right kind turned up by the
6415 // filter, at this point.
6416 if (S.LookupQualifiedName(R, RT->getDecl()))
6417 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6418 NamedDecl *decl = (*I)->getUnderlyingDecl();
6419 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
6420 Results.insert(FK);
6421 }
6422 return Results;
6423}
6424
Richard Smith2868a732014-02-28 01:36:39 +00006425/// Check if we could call '.c_str()' on an object.
6426///
6427/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
6428/// allow the call, or if it would be ambiguous).
6429bool Sema::hasCStrMethod(const Expr *E) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006430 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
6431
Richard Smith2868a732014-02-28 01:36:39 +00006432 MethodSet Results =
6433 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
6434 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
6435 MI != ME; ++MI)
6436 if ((*MI)->getMinRequiredArguments() == 0)
6437 return true;
6438 return false;
6439}
6440
Richard Smith55ce3522012-06-25 20:30:08 +00006441// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006442// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00006443// Returns true when a c_str() conversion method is found.
6444bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00006445 const analyze_printf::ArgType &AT, const Expr *E) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006446 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
Richard Smith55ce3522012-06-25 20:30:08 +00006447
6448 MethodSet Results =
6449 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
6450
6451 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
6452 MI != ME; ++MI) {
6453 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00006454 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00006455 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00006456 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00006457 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00006458 S.Diag(E->getLocStart(), diag::note_printf_c_str)
6459 << "c_str()"
6460 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
6461 return true;
6462 }
6463 }
6464
6465 return false;
6466}
6467
Ted Kremenekab278de2010-01-28 23:39:18 +00006468bool
Ted Kremenek02087932010-07-16 02:11:22 +00006469CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00006470 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00006471 const char *startSpecifier,
6472 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006473 using namespace analyze_format_string;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006474 using namespace analyze_printf;
6475
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006476 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00006477
Ted Kremenek6cd69422010-07-19 22:01:06 +00006478 if (FS.consumesDataArgument()) {
6479 if (atFirstArg) {
6480 atFirstArg = false;
6481 usesPositionalArgs = FS.usesPositionalArg();
6482 }
6483 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006484 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6485 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00006486 return false;
6487 }
Ted Kremenek5739de72010-01-29 01:06:55 +00006488 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006489
Ted Kremenekd1668192010-02-27 01:41:03 +00006490 // First check if the field width, precision, and conversion specifier
6491 // have matching data arguments.
6492 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
6493 startSpecifier, specifierLen)) {
6494 return false;
6495 }
6496
6497 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
6498 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00006499 return false;
6500 }
6501
Ted Kremenek8d9842d2010-01-29 20:55:36 +00006502 if (!CS.consumesDataArgument()) {
6503 // FIXME: Technically specifying a precision or field width here
6504 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00006505 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00006506 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006507
Ted Kremenek4a49d982010-02-26 19:18:41 +00006508 // Consume the argument.
6509 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00006510 if (argIndex < NumDataArgs) {
6511 // The check to see if the argIndex is valid will come later.
6512 // We set the bit here because we may exit early from this
6513 // function if we encounter some other error.
6514 CoveredArgs.set(argIndex);
6515 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00006516
Dimitry Andric6b5ed342015-02-19 22:32:33 +00006517 // FreeBSD kernel extensions.
6518 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
6519 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
6520 // We need at least two arguments.
6521 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
6522 return false;
6523
6524 // Claim the second argument.
6525 CoveredArgs.set(argIndex + 1);
6526
6527 // Type check the first argument (int for %b, pointer for %D)
6528 const Expr *Ex = getDataArg(argIndex);
6529 const analyze_printf::ArgType &AT =
6530 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
6531 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
6532 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
6533 EmitFormatDiagnostic(
6534 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6535 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
6536 << false << Ex->getSourceRange(),
6537 Ex->getLocStart(), /*IsStringLocation*/false,
6538 getSpecifierRange(startSpecifier, specifierLen));
6539
6540 // Type check the second argument (char * for both %b and %D)
6541 Ex = getDataArg(argIndex + 1);
6542 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
6543 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
6544 EmitFormatDiagnostic(
6545 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6546 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
6547 << false << Ex->getSourceRange(),
6548 Ex->getLocStart(), /*IsStringLocation*/false,
6549 getSpecifierRange(startSpecifier, specifierLen));
6550
6551 return true;
6552 }
6553
Ted Kremenek4a49d982010-02-26 19:18:41 +00006554 // Check for using an Objective-C specific conversion specifier
6555 // in a non-ObjC literal.
Mehdi Amini06d367c2016-10-24 20:39:34 +00006556 if (!allowsObjCArg() && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00006557 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6558 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00006559 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006560
Mehdi Amini06d367c2016-10-24 20:39:34 +00006561 // %P can only be used with os_log.
6562 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
6563 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6564 specifierLen);
6565 }
6566
6567 // %n is not allowed with os_log.
6568 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
6569 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
6570 getLocationOfByte(CS.getStart()),
6571 /*IsStringLocation*/ false,
6572 getSpecifierRange(startSpecifier, specifierLen));
6573
6574 return true;
6575 }
6576
6577 // Only scalars are allowed for os_trace.
6578 if (FSType == Sema::FST_OSTrace &&
6579 (CS.getKind() == ConversionSpecifier::PArg ||
6580 CS.getKind() == ConversionSpecifier::sArg ||
6581 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
6582 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6583 specifierLen);
6584 }
6585
6586 // Check for use of public/private annotation outside of os_log().
6587 if (FSType != Sema::FST_OSLog) {
6588 if (FS.isPublic().isSet()) {
6589 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6590 << "public",
6591 getLocationOfByte(FS.isPublic().getPosition()),
6592 /*IsStringLocation*/ false,
6593 getSpecifierRange(startSpecifier, specifierLen));
6594 }
6595 if (FS.isPrivate().isSet()) {
6596 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6597 << "private",
6598 getLocationOfByte(FS.isPrivate().getPosition()),
6599 /*IsStringLocation*/ false,
6600 getSpecifierRange(startSpecifier, specifierLen));
6601 }
6602 }
6603
Tom Careb49ec692010-06-17 19:00:27 +00006604 // Check for invalid use of field width
6605 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00006606 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00006607 startSpecifier, specifierLen);
6608 }
6609
6610 // Check for invalid use of precision
6611 if (!FS.hasValidPrecision()) {
6612 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
6613 startSpecifier, specifierLen);
6614 }
6615
Mehdi Amini06d367c2016-10-24 20:39:34 +00006616 // Precision is mandatory for %P specifier.
6617 if (CS.getKind() == ConversionSpecifier::PArg &&
6618 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
6619 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
6620 getLocationOfByte(startSpecifier),
6621 /*IsStringLocation*/ false,
6622 getSpecifierRange(startSpecifier, specifierLen));
6623 }
6624
Tom Careb49ec692010-06-17 19:00:27 +00006625 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00006626 if (!FS.hasValidThousandsGroupingPrefix())
6627 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006628 if (!FS.hasValidLeadingZeros())
6629 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
6630 if (!FS.hasValidPlusPrefix())
6631 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00006632 if (!FS.hasValidSpacePrefix())
6633 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006634 if (!FS.hasValidAlternativeForm())
6635 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
6636 if (!FS.hasValidLeftJustified())
6637 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
6638
6639 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00006640 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
6641 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
6642 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006643 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
6644 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
6645 startSpecifier, specifierLen);
6646
6647 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006648 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006649 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6650 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006651 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006652 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006653 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006654 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6655 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00006656
Jordan Rose92303592012-09-08 04:00:03 +00006657 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6658 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6659
Ted Kremenek9fcd8302010-01-29 01:43:31 +00006660 // The remaining checks depend on the data arguments.
6661 if (HasVAListArg)
6662 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006663
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006664 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00006665 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006666
Jordan Rose58bbe422012-07-19 18:10:08 +00006667 const Expr *Arg = getDataArg(argIndex);
6668 if (!Arg)
6669 return true;
6670
6671 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00006672}
6673
Jordan Roseaee34382012-09-05 22:56:26 +00006674static bool requiresParensToAddCast(const Expr *E) {
6675 // FIXME: We should have a general way to reason about operator
6676 // precedence and whether parens are actually needed here.
6677 // Take care of a few common cases where they aren't.
6678 const Expr *Inside = E->IgnoreImpCasts();
6679 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
6680 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
6681
6682 switch (Inside->getStmtClass()) {
6683 case Stmt::ArraySubscriptExprClass:
6684 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006685 case Stmt::CharacterLiteralClass:
6686 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006687 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006688 case Stmt::FloatingLiteralClass:
6689 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006690 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006691 case Stmt::ObjCArrayLiteralClass:
6692 case Stmt::ObjCBoolLiteralExprClass:
6693 case Stmt::ObjCBoxedExprClass:
6694 case Stmt::ObjCDictionaryLiteralClass:
6695 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006696 case Stmt::ObjCIvarRefExprClass:
6697 case Stmt::ObjCMessageExprClass:
6698 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006699 case Stmt::ObjCStringLiteralClass:
6700 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006701 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006702 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006703 case Stmt::UnaryOperatorClass:
6704 return false;
6705 default:
6706 return true;
6707 }
6708}
6709
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006710static std::pair<QualType, StringRef>
6711shouldNotPrintDirectly(const ASTContext &Context,
6712 QualType IntendedTy,
6713 const Expr *E) {
6714 // Use a 'while' to peel off layers of typedefs.
6715 QualType TyTy = IntendedTy;
6716 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
6717 StringRef Name = UserTy->getDecl()->getName();
6718 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Saleem Abdulrasoola01ed932017-10-17 17:39:32 +00006719 .Case("CFIndex", Context.getNSIntegerType())
6720 .Case("NSInteger", Context.getNSIntegerType())
6721 .Case("NSUInteger", Context.getNSUIntegerType())
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006722 .Case("SInt32", Context.IntTy)
6723 .Case("UInt32", Context.UnsignedIntTy)
6724 .Default(QualType());
6725
6726 if (!CastTy.isNull())
6727 return std::make_pair(CastTy, Name);
6728
6729 TyTy = UserTy->desugar();
6730 }
6731
6732 // Strip parens if necessary.
6733 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
6734 return shouldNotPrintDirectly(Context,
6735 PE->getSubExpr()->getType(),
6736 PE->getSubExpr());
6737
6738 // If this is a conditional expression, then its result type is constructed
6739 // via usual arithmetic conversions and thus there might be no necessary
6740 // typedef sugar there. Recurse to operands to check for NSInteger &
6741 // Co. usage condition.
6742 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6743 QualType TrueTy, FalseTy;
6744 StringRef TrueName, FalseName;
6745
6746 std::tie(TrueTy, TrueName) =
6747 shouldNotPrintDirectly(Context,
6748 CO->getTrueExpr()->getType(),
6749 CO->getTrueExpr());
6750 std::tie(FalseTy, FalseName) =
6751 shouldNotPrintDirectly(Context,
6752 CO->getFalseExpr()->getType(),
6753 CO->getFalseExpr());
6754
6755 if (TrueTy == FalseTy)
6756 return std::make_pair(TrueTy, TrueName);
6757 else if (TrueTy.isNull())
6758 return std::make_pair(FalseTy, FalseName);
6759 else if (FalseTy.isNull())
6760 return std::make_pair(TrueTy, TrueName);
6761 }
6762
6763 return std::make_pair(QualType(), StringRef());
6764}
6765
Richard Smith55ce3522012-06-25 20:30:08 +00006766bool
6767CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6768 const char *StartSpecifier,
6769 unsigned SpecifierLen,
6770 const Expr *E) {
6771 using namespace analyze_format_string;
6772 using namespace analyze_printf;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006773
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006774 // Now type check the data expression that matches the
6775 // format specifier.
Mehdi Amini06d367c2016-10-24 20:39:34 +00006776 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
Jordan Rose22b74712012-09-05 22:56:19 +00006777 if (!AT.isValid())
6778 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00006779
Jordan Rose598ec092012-12-05 18:44:40 +00006780 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00006781 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
6782 ExprTy = TET->getUnderlyingExpr()->getType();
6783 }
6784
Seth Cantrellb4802962015-03-04 03:12:10 +00006785 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
6786
6787 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00006788 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006789 }
Jordan Rose98709982012-06-04 22:48:57 +00006790
Jordan Rose22b74712012-09-05 22:56:19 +00006791 // Look through argument promotions for our error message's reported type.
6792 // This includes the integral and floating promotions, but excludes array
6793 // and function pointer decay; seeing that an argument intended to be a
6794 // string has type 'char [6]' is probably more confusing than 'char *'.
6795 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6796 if (ICE->getCastKind() == CK_IntegralCast ||
6797 ICE->getCastKind() == CK_FloatingCast) {
6798 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00006799 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00006800
6801 // Check if we didn't match because of an implicit cast from a 'char'
6802 // or 'short' to an 'int'. This is done because printf is a varargs
6803 // function.
6804 if (ICE->getType() == S.Context.IntTy ||
6805 ICE->getType() == S.Context.UnsignedIntTy) {
6806 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00006807 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00006808 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00006809 }
Jordan Rose98709982012-06-04 22:48:57 +00006810 }
Jordan Rose598ec092012-12-05 18:44:40 +00006811 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
6812 // Special case for 'a', which has type 'int' in C.
6813 // Note, however, that we do /not/ want to treat multibyte constants like
6814 // 'MooV' as characters! This form is deprecated but still exists.
6815 if (ExprTy == S.Context.IntTy)
6816 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6817 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00006818 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006819
Jordan Rosebc53ed12014-05-31 04:12:14 +00006820 // Look through enums to their underlying type.
6821 bool IsEnum = false;
6822 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
6823 ExprTy = EnumTy->getDecl()->getIntegerType();
6824 IsEnum = true;
6825 }
6826
Jordan Rose0e5badd2012-12-05 18:44:49 +00006827 // %C in an Objective-C context prints a unichar, not a wchar_t.
6828 // If the argument is an integer of some kind, believe the %C and suggest
6829 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00006830 QualType IntendedTy = ExprTy;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006831 if (isObjCContext() &&
Jordan Rose0e5badd2012-12-05 18:44:49 +00006832 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
6833 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6834 !ExprTy->isCharType()) {
6835 // 'unichar' is defined as a typedef of unsigned short, but we should
6836 // prefer using the typedef if it is visible.
6837 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00006838
6839 // While we are here, check if the value is an IntegerLiteral that happens
6840 // to be within the valid range.
6841 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
6842 const llvm::APInt &V = IL->getValue();
6843 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6844 return true;
6845 }
6846
Jordan Rose0e5badd2012-12-05 18:44:49 +00006847 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
6848 Sema::LookupOrdinaryName);
6849 if (S.LookupName(Result, S.getCurScope())) {
6850 NamedDecl *ND = Result.getFoundDecl();
6851 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
6852 if (TD->getUnderlyingType() == IntendedTy)
6853 IntendedTy = S.Context.getTypedefType(TD);
6854 }
6855 }
6856 }
6857
6858 // Special-case some of Darwin's platform-independence types by suggesting
6859 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006860 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00006861 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006862 QualType CastTy;
6863 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
6864 if (!CastTy.isNull()) {
6865 IntendedTy = CastTy;
6866 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00006867 }
6868 }
6869
Jordan Rose22b74712012-09-05 22:56:19 +00006870 // We may be able to offer a FixItHint if it is a supported type.
6871 PrintfSpecifier fixedFS = FS;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006872 bool success =
6873 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006874
Jordan Rose22b74712012-09-05 22:56:19 +00006875 if (success) {
6876 // Get the fix string from the fixed format specifier
6877 SmallString<16> buf;
6878 llvm::raw_svector_ostream os(buf);
6879 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006880
Jordan Roseaee34382012-09-05 22:56:26 +00006881 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6882
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006883 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00006884 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6885 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6886 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6887 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00006888 // In this case, the specifier is wrong and should be changed to match
6889 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00006890 EmitFormatDiagnostic(S.PDiag(diag)
6891 << AT.getRepresentativeTypeName(S.Context)
6892 << IntendedTy << IsEnum << E->getSourceRange(),
6893 E->getLocStart(),
6894 /*IsStringLocation*/ false, SpecRange,
6895 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00006896 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00006897 // The canonical type for formatting this value is different from the
6898 // actual type of the expression. (This occurs, for example, with Darwin's
6899 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6900 // should be printed as 'long' for 64-bit compatibility.)
6901 // Rather than emitting a normal format/argument mismatch, we want to
6902 // add a cast to the recommended type (and correct the format string
6903 // if necessary).
6904 SmallString<16> CastBuf;
6905 llvm::raw_svector_ostream CastFix(CastBuf);
6906 CastFix << "(";
6907 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6908 CastFix << ")";
6909
6910 SmallVector<FixItHint,4> Hints;
Alexander Shaposhnikov1788a9b2017-09-22 18:36:06 +00006911 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
Jordan Roseaee34382012-09-05 22:56:26 +00006912 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6913
6914 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6915 // If there's already a cast present, just replace it.
6916 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6917 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6918
6919 } else if (!requiresParensToAddCast(E)) {
6920 // If the expression has high enough precedence,
6921 // just write the C-style cast.
6922 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6923 CastFix.str()));
6924 } else {
6925 // Otherwise, add parens around the expression as well as the cast.
6926 CastFix << "(";
6927 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6928 CastFix.str()));
6929
Alp Tokerb6cc5922014-05-03 03:45:55 +00006930 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00006931 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6932 }
6933
Jordan Rose0e5badd2012-12-05 18:44:49 +00006934 if (ShouldNotPrintDirectly) {
6935 // The expression has a type that should not be printed directly.
6936 // We extract the name from the typedef because we don't want to show
6937 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006938 StringRef Name;
6939 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6940 Name = TypedefTy->getDecl()->getName();
6941 else
6942 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00006943 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00006944 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006945 << E->getSourceRange(),
6946 E->getLocStart(), /*IsStringLocation=*/false,
6947 SpecRange, Hints);
6948 } else {
6949 // In this case, the expression could be printed using a different
6950 // specifier, but we've decided that the specifier is probably correct
6951 // and we should cast instead. Just use the normal warning message.
6952 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00006953 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6954 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006955 << E->getSourceRange(),
6956 E->getLocStart(), /*IsStringLocation*/false,
6957 SpecRange, Hints);
6958 }
Jordan Roseaee34382012-09-05 22:56:26 +00006959 }
Jordan Rose22b74712012-09-05 22:56:19 +00006960 } else {
6961 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6962 SpecifierLen);
6963 // Since the warning for passing non-POD types to variadic functions
6964 // was deferred until now, we emit a warning for non-POD
6965 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00006966 switch (S.isValidVarArgType(ExprTy)) {
6967 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00006968 case Sema::VAK_ValidInCXX11: {
6969 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6970 if (match == analyze_printf::ArgType::NoMatchPedantic) {
6971 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6972 }
Richard Smithd7293d72013-08-05 18:49:43 +00006973
Seth Cantrellb4802962015-03-04 03:12:10 +00006974 EmitFormatDiagnostic(
6975 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6976 << IsEnum << CSR << E->getSourceRange(),
6977 E->getLocStart(), /*IsStringLocation*/ false, CSR);
6978 break;
6979 }
Richard Smithd7293d72013-08-05 18:49:43 +00006980 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00006981 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00006982 EmitFormatDiagnostic(
6983 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006984 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00006985 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00006986 << CallType
6987 << AT.getRepresentativeTypeName(S.Context)
6988 << CSR
6989 << E->getSourceRange(),
6990 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00006991 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00006992 break;
6993
6994 case Sema::VAK_Invalid:
6995 if (ExprTy->isObjCObjectType())
6996 EmitFormatDiagnostic(
6997 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6998 << S.getLangOpts().CPlusPlus11
6999 << ExprTy
7000 << CallType
7001 << AT.getRepresentativeTypeName(S.Context)
7002 << CSR
7003 << E->getSourceRange(),
7004 E->getLocStart(), /*IsStringLocation*/false, CSR);
7005 else
7006 // FIXME: If this is an initializer list, suggest removing the braces
7007 // or inserting a cast to the target type.
7008 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
7009 << isa<InitListExpr>(E) << ExprTy << CallType
7010 << AT.getRepresentativeTypeName(S.Context)
7011 << E->getSourceRange();
7012 break;
7013 }
7014
7015 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
7016 "format string specifier index out of range");
7017 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00007018 }
7019
Ted Kremenekab278de2010-01-28 23:39:18 +00007020 return true;
7021}
7022
Ted Kremenek02087932010-07-16 02:11:22 +00007023//===--- CHECK: Scanf format string checking ------------------------------===//
7024
7025namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007026
Ted Kremenek02087932010-07-16 02:11:22 +00007027class CheckScanfHandler : public CheckFormatHandler {
7028public:
Stephen Hines648c3692016-09-16 01:07:04 +00007029 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00007030 const Expr *origFormatExpr, Sema::FormatStringType type,
7031 unsigned firstDataArg, unsigned numDataArgs,
7032 const char *beg, bool hasVAListArg,
7033 ArrayRef<const Expr *> Args, unsigned formatIdx,
7034 bool inFunctionCall, Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007035 llvm::SmallBitVector &CheckedVarArgs,
7036 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00007037 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7038 numDataArgs, beg, hasVAListArg, Args, formatIdx,
7039 inFunctionCall, CallType, CheckedVarArgs,
7040 UncoveredArg) {}
7041
Ted Kremenek02087932010-07-16 02:11:22 +00007042 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
7043 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00007044 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00007045
7046 bool HandleInvalidScanfConversionSpecifier(
7047 const analyze_scanf::ScanfSpecifier &FS,
7048 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00007049 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00007050
Craig Toppere14c0f82014-03-12 04:55:44 +00007051 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00007052};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007053
7054} // namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00007055
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00007056void CheckScanfHandler::HandleIncompleteScanList(const char *start,
7057 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007058 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
7059 getLocationOfByte(end), /*IsStringLocation*/true,
7060 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00007061}
7062
Ted Kremenekce815422010-07-19 21:25:57 +00007063bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
7064 const analyze_scanf::ScanfSpecifier &FS,
7065 const char *startSpecifier,
7066 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00007067 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00007068 FS.getConversionSpecifier();
7069
7070 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7071 getLocationOfByte(CS.getStart()),
7072 startSpecifier, specifierLen,
7073 CS.getStart(), CS.getLength());
7074}
7075
Ted Kremenek02087932010-07-16 02:11:22 +00007076bool CheckScanfHandler::HandleScanfSpecifier(
7077 const analyze_scanf::ScanfSpecifier &FS,
7078 const char *startSpecifier,
7079 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00007080 using namespace analyze_scanf;
7081 using namespace analyze_format_string;
7082
Ted Kremenekf03e6d852010-07-20 20:04:27 +00007083 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00007084
Ted Kremenek6cd69422010-07-19 22:01:06 +00007085 // Handle case where '%' and '*' don't consume an argument. These shouldn't
7086 // be used to decide if we are using positional arguments consistently.
7087 if (FS.consumesDataArgument()) {
7088 if (atFirstArg) {
7089 atFirstArg = false;
7090 usesPositionalArgs = FS.usesPositionalArg();
7091 }
7092 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007093 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7094 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00007095 return false;
7096 }
Ted Kremenek02087932010-07-16 02:11:22 +00007097 }
7098
7099 // Check if the field with is non-zero.
7100 const OptionalAmount &Amt = FS.getFieldWidth();
7101 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
7102 if (Amt.getConstantAmount() == 0) {
7103 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
7104 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00007105 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
7106 getLocationOfByte(Amt.getStart()),
7107 /*IsStringLocation*/true, R,
7108 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00007109 }
7110 }
Seth Cantrellb4802962015-03-04 03:12:10 +00007111
Ted Kremenek02087932010-07-16 02:11:22 +00007112 if (!FS.consumesDataArgument()) {
7113 // FIXME: Technically specifying a precision or field width here
7114 // makes no sense. Worth issuing a warning at some point.
7115 return true;
7116 }
Seth Cantrellb4802962015-03-04 03:12:10 +00007117
Ted Kremenek02087932010-07-16 02:11:22 +00007118 // Consume the argument.
7119 unsigned argIndex = FS.getArgIndex();
7120 if (argIndex < NumDataArgs) {
7121 // The check to see if the argIndex is valid will come later.
7122 // We set the bit here because we may exit early from this
7123 // function if we encounter some other error.
7124 CoveredArgs.set(argIndex);
7125 }
Seth Cantrellb4802962015-03-04 03:12:10 +00007126
Ted Kremenek4407ea42010-07-20 20:04:47 +00007127 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00007128 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00007129 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7130 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00007131 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00007132 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00007133 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00007134 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7135 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00007136
Jordan Rose92303592012-09-08 04:00:03 +00007137 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
7138 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
7139
Ted Kremenek02087932010-07-16 02:11:22 +00007140 // The remaining checks depend on the data arguments.
7141 if (HasVAListArg)
7142 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00007143
Ted Kremenek6adb7e32010-07-26 19:45:42 +00007144 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00007145 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00007146
Hans Wennborgb1a5e092011-12-10 13:20:11 +00007147 // Check that the argument type matches the format specifier.
7148 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00007149 if (!Ex)
7150 return true;
7151
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00007152 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00007153
7154 if (!AT.isValid()) {
7155 return true;
7156 }
7157
Seth Cantrellb4802962015-03-04 03:12:10 +00007158 analyze_format_string::ArgType::MatchKind match =
7159 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00007160 if (match == analyze_format_string::ArgType::Match) {
7161 return true;
7162 }
Seth Cantrellb4802962015-03-04 03:12:10 +00007163
Seth Cantrell79340072015-03-04 05:58:08 +00007164 ScanfSpecifier fixedFS = FS;
7165 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
7166 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00007167
Seth Cantrell79340072015-03-04 05:58:08 +00007168 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
7169 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
7170 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
7171 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00007172
Seth Cantrell79340072015-03-04 05:58:08 +00007173 if (success) {
7174 // Get the fix string from the fixed format specifier.
7175 SmallString<128> buf;
7176 llvm::raw_svector_ostream os(buf);
7177 fixedFS.toString(os);
7178
7179 EmitFormatDiagnostic(
7180 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
7181 << Ex->getType() << false << Ex->getSourceRange(),
7182 Ex->getLocStart(),
7183 /*IsStringLocation*/ false,
7184 getSpecifierRange(startSpecifier, specifierLen),
7185 FixItHint::CreateReplacement(
7186 getSpecifierRange(startSpecifier, specifierLen), os.str()));
7187 } else {
7188 EmitFormatDiagnostic(S.PDiag(diag)
7189 << AT.getRepresentativeTypeName(S.Context)
7190 << Ex->getType() << false << Ex->getSourceRange(),
7191 Ex->getLocStart(),
7192 /*IsStringLocation*/ false,
7193 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00007194 }
7195
Ted Kremenek02087932010-07-16 02:11:22 +00007196 return true;
7197}
7198
Stephen Hines648c3692016-09-16 01:07:04 +00007199static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007200 const Expr *OrigFormatExpr,
7201 ArrayRef<const Expr *> Args,
7202 bool HasVAListArg, unsigned format_idx,
7203 unsigned firstDataArg,
7204 Sema::FormatStringType Type,
7205 bool inFunctionCall,
7206 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007207 llvm::SmallBitVector &CheckedVarArgs,
7208 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00007209 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00007210 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007211 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007212 S, inFunctionCall, Args[format_idx],
7213 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00007214 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00007215 return;
7216 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007217
Ted Kremenekab278de2010-01-28 23:39:18 +00007218 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007219 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00007220 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00007221 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007222 const ConstantArrayType *T =
7223 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00007224 assert(T && "String literal not of constant array type!");
7225 size_t TypeSize = T->getSize().getZExtValue();
7226 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00007227 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00007228
7229 // Emit a warning if the string literal is truncated and does not contain an
7230 // embedded null character.
7231 if (TypeSize <= StrRef.size() &&
7232 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
7233 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007234 S, inFunctionCall, Args[format_idx],
7235 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00007236 FExpr->getLocStart(),
7237 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
7238 return;
7239 }
7240
Ted Kremenekab278de2010-01-28 23:39:18 +00007241 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00007242 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007243 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007244 S, inFunctionCall, Args[format_idx],
7245 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00007246 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00007247 return;
7248 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007249
7250 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
Mehdi Amini06d367c2016-10-24 20:39:34 +00007251 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
7252 Type == Sema::FST_OSTrace) {
7253 CheckPrintfHandler H(
7254 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
7255 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
7256 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
7257 CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007258
Hans Wennborg23926bd2011-12-15 10:25:47 +00007259 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007260 S.getLangOpts(),
7261 S.Context.getTargetInfo(),
7262 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00007263 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007264 } else if (Type == Sema::FST_Scanf) {
Mehdi Amini06d367c2016-10-24 20:39:34 +00007265 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
7266 numDataArgs, Str, HasVAListArg, Args, format_idx,
7267 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007268
Hans Wennborg23926bd2011-12-15 10:25:47 +00007269 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007270 S.getLangOpts(),
7271 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00007272 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00007273 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00007274}
7275
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00007276bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
7277 // Str - The format string. NOTE: this is NOT null-terminated!
7278 StringRef StrRef = FExpr->getString();
7279 const char *Str = StrRef.data();
7280 // Account for cases where the string literal is truncated in a declaration.
7281 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
7282 assert(T && "String literal not of constant array type!");
7283 size_t TypeSize = T->getSize().getZExtValue();
7284 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
7285 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
7286 getLangOpts(),
7287 Context.getTargetInfo());
7288}
7289
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007290//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
7291
7292// Returns the related absolute value function that is larger, of 0 if one
7293// does not exist.
7294static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
7295 switch (AbsFunction) {
7296 default:
7297 return 0;
7298
7299 case Builtin::BI__builtin_abs:
7300 return Builtin::BI__builtin_labs;
7301 case Builtin::BI__builtin_labs:
7302 return Builtin::BI__builtin_llabs;
7303 case Builtin::BI__builtin_llabs:
7304 return 0;
7305
7306 case Builtin::BI__builtin_fabsf:
7307 return Builtin::BI__builtin_fabs;
7308 case Builtin::BI__builtin_fabs:
7309 return Builtin::BI__builtin_fabsl;
7310 case Builtin::BI__builtin_fabsl:
7311 return 0;
7312
7313 case Builtin::BI__builtin_cabsf:
7314 return Builtin::BI__builtin_cabs;
7315 case Builtin::BI__builtin_cabs:
7316 return Builtin::BI__builtin_cabsl;
7317 case Builtin::BI__builtin_cabsl:
7318 return 0;
7319
7320 case Builtin::BIabs:
7321 return Builtin::BIlabs;
7322 case Builtin::BIlabs:
7323 return Builtin::BIllabs;
7324 case Builtin::BIllabs:
7325 return 0;
7326
7327 case Builtin::BIfabsf:
7328 return Builtin::BIfabs;
7329 case Builtin::BIfabs:
7330 return Builtin::BIfabsl;
7331 case Builtin::BIfabsl:
7332 return 0;
7333
7334 case Builtin::BIcabsf:
7335 return Builtin::BIcabs;
7336 case Builtin::BIcabs:
7337 return Builtin::BIcabsl;
7338 case Builtin::BIcabsl:
7339 return 0;
7340 }
7341}
7342
7343// Returns the argument type of the absolute value function.
7344static QualType getAbsoluteValueArgumentType(ASTContext &Context,
7345 unsigned AbsType) {
7346 if (AbsType == 0)
7347 return QualType();
7348
7349 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
7350 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
7351 if (Error != ASTContext::GE_None)
7352 return QualType();
7353
7354 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
7355 if (!FT)
7356 return QualType();
7357
7358 if (FT->getNumParams() != 1)
7359 return QualType();
7360
7361 return FT->getParamType(0);
7362}
7363
7364// Returns the best absolute value function, or zero, based on type and
7365// current absolute value function.
7366static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
7367 unsigned AbsFunctionKind) {
7368 unsigned BestKind = 0;
7369 uint64_t ArgSize = Context.getTypeSize(ArgType);
7370 for (unsigned Kind = AbsFunctionKind; Kind != 0;
7371 Kind = getLargerAbsoluteValueFunction(Kind)) {
7372 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
7373 if (Context.getTypeSize(ParamType) >= ArgSize) {
7374 if (BestKind == 0)
7375 BestKind = Kind;
7376 else if (Context.hasSameType(ParamType, ArgType)) {
7377 BestKind = Kind;
7378 break;
7379 }
7380 }
7381 }
7382 return BestKind;
7383}
7384
7385enum AbsoluteValueKind {
7386 AVK_Integer,
7387 AVK_Floating,
7388 AVK_Complex
7389};
7390
7391static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
7392 if (T->isIntegralOrEnumerationType())
7393 return AVK_Integer;
7394 if (T->isRealFloatingType())
7395 return AVK_Floating;
7396 if (T->isAnyComplexType())
7397 return AVK_Complex;
7398
7399 llvm_unreachable("Type not integer, floating, or complex");
7400}
7401
7402// Changes the absolute value function to a different type. Preserves whether
7403// the function is a builtin.
7404static unsigned changeAbsFunction(unsigned AbsKind,
7405 AbsoluteValueKind ValueKind) {
7406 switch (ValueKind) {
7407 case AVK_Integer:
7408 switch (AbsKind) {
7409 default:
7410 return 0;
7411 case Builtin::BI__builtin_fabsf:
7412 case Builtin::BI__builtin_fabs:
7413 case Builtin::BI__builtin_fabsl:
7414 case Builtin::BI__builtin_cabsf:
7415 case Builtin::BI__builtin_cabs:
7416 case Builtin::BI__builtin_cabsl:
7417 return Builtin::BI__builtin_abs;
7418 case Builtin::BIfabsf:
7419 case Builtin::BIfabs:
7420 case Builtin::BIfabsl:
7421 case Builtin::BIcabsf:
7422 case Builtin::BIcabs:
7423 case Builtin::BIcabsl:
7424 return Builtin::BIabs;
7425 }
7426 case AVK_Floating:
7427 switch (AbsKind) {
7428 default:
7429 return 0;
7430 case Builtin::BI__builtin_abs:
7431 case Builtin::BI__builtin_labs:
7432 case Builtin::BI__builtin_llabs:
7433 case Builtin::BI__builtin_cabsf:
7434 case Builtin::BI__builtin_cabs:
7435 case Builtin::BI__builtin_cabsl:
7436 return Builtin::BI__builtin_fabsf;
7437 case Builtin::BIabs:
7438 case Builtin::BIlabs:
7439 case Builtin::BIllabs:
7440 case Builtin::BIcabsf:
7441 case Builtin::BIcabs:
7442 case Builtin::BIcabsl:
7443 return Builtin::BIfabsf;
7444 }
7445 case AVK_Complex:
7446 switch (AbsKind) {
7447 default:
7448 return 0;
7449 case Builtin::BI__builtin_abs:
7450 case Builtin::BI__builtin_labs:
7451 case Builtin::BI__builtin_llabs:
7452 case Builtin::BI__builtin_fabsf:
7453 case Builtin::BI__builtin_fabs:
7454 case Builtin::BI__builtin_fabsl:
7455 return Builtin::BI__builtin_cabsf;
7456 case Builtin::BIabs:
7457 case Builtin::BIlabs:
7458 case Builtin::BIllabs:
7459 case Builtin::BIfabsf:
7460 case Builtin::BIfabs:
7461 case Builtin::BIfabsl:
7462 return Builtin::BIcabsf;
7463 }
7464 }
7465 llvm_unreachable("Unable to convert function");
7466}
7467
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00007468static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007469 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
7470 if (!FnInfo)
7471 return 0;
7472
7473 switch (FDecl->getBuiltinID()) {
7474 default:
7475 return 0;
7476 case Builtin::BI__builtin_abs:
7477 case Builtin::BI__builtin_fabs:
7478 case Builtin::BI__builtin_fabsf:
7479 case Builtin::BI__builtin_fabsl:
7480 case Builtin::BI__builtin_labs:
7481 case Builtin::BI__builtin_llabs:
7482 case Builtin::BI__builtin_cabs:
7483 case Builtin::BI__builtin_cabsf:
7484 case Builtin::BI__builtin_cabsl:
7485 case Builtin::BIabs:
7486 case Builtin::BIlabs:
7487 case Builtin::BIllabs:
7488 case Builtin::BIfabs:
7489 case Builtin::BIfabsf:
7490 case Builtin::BIfabsl:
7491 case Builtin::BIcabs:
7492 case Builtin::BIcabsf:
7493 case Builtin::BIcabsl:
7494 return FDecl->getBuiltinID();
7495 }
7496 llvm_unreachable("Unknown Builtin type");
7497}
7498
7499// If the replacement is valid, emit a note with replacement function.
7500// Additionally, suggest including the proper header if not already included.
7501static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00007502 unsigned AbsKind, QualType ArgType) {
7503 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00007504 const char *HeaderName = nullptr;
Mehdi Amini7186a432016-10-11 19:04:24 +00007505 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00007506 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
7507 FunctionName = "std::abs";
7508 if (ArgType->isIntegralOrEnumerationType()) {
7509 HeaderName = "cstdlib";
7510 } else if (ArgType->isRealFloatingType()) {
7511 HeaderName = "cmath";
7512 } else {
7513 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007514 }
Richard Trieubeffb832014-04-15 23:47:53 +00007515
7516 // Lookup all std::abs
7517 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00007518 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00007519 R.suppressDiagnostics();
7520 S.LookupQualifiedName(R, Std);
7521
7522 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007523 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00007524 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
7525 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
7526 } else {
7527 FDecl = dyn_cast<FunctionDecl>(I);
7528 }
7529 if (!FDecl)
7530 continue;
7531
7532 // Found std::abs(), check that they are the right ones.
7533 if (FDecl->getNumParams() != 1)
7534 continue;
7535
7536 // Check that the parameter type can handle the argument.
7537 QualType ParamType = FDecl->getParamDecl(0)->getType();
7538 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
7539 S.Context.getTypeSize(ArgType) <=
7540 S.Context.getTypeSize(ParamType)) {
7541 // Found a function, don't need the header hint.
7542 EmitHeaderHint = false;
7543 break;
7544 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007545 }
Richard Trieubeffb832014-04-15 23:47:53 +00007546 }
7547 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00007548 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00007549 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
7550
7551 if (HeaderName) {
7552 DeclarationName DN(&S.Context.Idents.get(FunctionName));
7553 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
7554 R.suppressDiagnostics();
7555 S.LookupName(R, S.getCurScope());
7556
7557 if (R.isSingleResult()) {
7558 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
7559 if (FD && FD->getBuiltinID() == AbsKind) {
7560 EmitHeaderHint = false;
7561 } else {
7562 return;
7563 }
7564 } else if (!R.empty()) {
7565 return;
7566 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007567 }
7568 }
7569
7570 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00007571 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007572
Richard Trieubeffb832014-04-15 23:47:53 +00007573 if (!HeaderName)
7574 return;
7575
7576 if (!EmitHeaderHint)
7577 return;
7578
Alp Toker5d96e0a2014-07-11 20:53:51 +00007579 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
7580 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00007581}
7582
Richard Trieua7f30b12016-12-06 01:42:28 +00007583template <std::size_t StrLen>
7584static bool IsStdFunction(const FunctionDecl *FDecl,
7585 const char (&Str)[StrLen]) {
Richard Trieubeffb832014-04-15 23:47:53 +00007586 if (!FDecl)
7587 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00007588 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
Richard Trieubeffb832014-04-15 23:47:53 +00007589 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00007590 if (!FDecl->isInStdNamespace())
Richard Trieubeffb832014-04-15 23:47:53 +00007591 return false;
7592
7593 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007594}
7595
7596// Warn when using the wrong abs() function.
7597void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
Richard Trieua7f30b12016-12-06 01:42:28 +00007598 const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007599 if (Call->getNumArgs() != 1)
7600 return;
7601
7602 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieua7f30b12016-12-06 01:42:28 +00007603 bool IsStdAbs = IsStdFunction(FDecl, "abs");
Richard Trieubeffb832014-04-15 23:47:53 +00007604 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007605 return;
7606
7607 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7608 QualType ParamType = Call->getArg(0)->getType();
7609
Alp Toker5d96e0a2014-07-11 20:53:51 +00007610 // Unsigned types cannot be negative. Suggest removing the absolute value
7611 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007612 if (ArgType->isUnsignedIntegerType()) {
Mehdi Amini7186a432016-10-11 19:04:24 +00007613 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00007614 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007615 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
7616 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00007617 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007618 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
7619 return;
7620 }
7621
David Majnemer7f77eb92015-11-15 03:04:34 +00007622 // Taking the absolute value of a pointer is very suspicious, they probably
7623 // wanted to index into an array, dereference a pointer, call a function, etc.
7624 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
7625 unsigned DiagType = 0;
7626 if (ArgType->isFunctionType())
7627 DiagType = 1;
7628 else if (ArgType->isArrayType())
7629 DiagType = 2;
7630
7631 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
7632 return;
7633 }
7634
Richard Trieubeffb832014-04-15 23:47:53 +00007635 // std::abs has overloads which prevent most of the absolute value problems
7636 // from occurring.
7637 if (IsStdAbs)
7638 return;
7639
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007640 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
7641 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
7642
7643 // The argument and parameter are the same kind. Check if they are the right
7644 // size.
7645 if (ArgValueKind == ParamValueKind) {
7646 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
7647 return;
7648
7649 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
7650 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
7651 << FDecl << ArgType << ParamType;
7652
7653 if (NewAbsKind == 0)
7654 return;
7655
7656 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00007657 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007658 return;
7659 }
7660
7661 // ArgValueKind != ParamValueKind
7662 // The wrong type of absolute value function was used. Attempt to find the
7663 // proper one.
7664 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
7665 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
7666 if (NewAbsKind == 0)
7667 return;
7668
7669 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
7670 << FDecl << ParamValueKind << ArgValueKind;
7671
7672 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00007673 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007674}
7675
Richard Trieu67c00712016-12-05 23:41:46 +00007676//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
Richard Trieua7f30b12016-12-06 01:42:28 +00007677void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
7678 const FunctionDecl *FDecl) {
Richard Trieu67c00712016-12-05 23:41:46 +00007679 if (!Call || !FDecl) return;
7680
7681 // Ignore template specializations and macros.
Richard Smith51ec0cf2017-02-21 01:17:38 +00007682 if (inTemplateInstantiation()) return;
Richard Trieu67c00712016-12-05 23:41:46 +00007683 if (Call->getExprLoc().isMacroID()) return;
7684
7685 // Only care about the one template argument, two function parameter std::max
7686 if (Call->getNumArgs() != 2) return;
Richard Trieua7f30b12016-12-06 01:42:28 +00007687 if (!IsStdFunction(FDecl, "max")) return;
Richard Trieu67c00712016-12-05 23:41:46 +00007688 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
7689 if (!ArgList) return;
7690 if (ArgList->size() != 1) return;
7691
7692 // Check that template type argument is unsigned integer.
7693 const auto& TA = ArgList->get(0);
7694 if (TA.getKind() != TemplateArgument::Type) return;
7695 QualType ArgType = TA.getAsType();
7696 if (!ArgType->isUnsignedIntegerType()) return;
7697
7698 // See if either argument is a literal zero.
7699 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
7700 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
7701 if (!MTE) return false;
7702 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
7703 if (!Num) return false;
7704 if (Num->getValue() != 0) return false;
7705 return true;
7706 };
7707
7708 const Expr *FirstArg = Call->getArg(0);
7709 const Expr *SecondArg = Call->getArg(1);
7710 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
7711 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
7712
7713 // Only warn when exactly one argument is zero.
7714 if (IsFirstArgZero == IsSecondArgZero) return;
7715
7716 SourceRange FirstRange = FirstArg->getSourceRange();
7717 SourceRange SecondRange = SecondArg->getSourceRange();
7718
7719 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
7720
7721 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
7722 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
7723
7724 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
7725 SourceRange RemovalRange;
7726 if (IsFirstArgZero) {
7727 RemovalRange = SourceRange(FirstRange.getBegin(),
7728 SecondRange.getBegin().getLocWithOffset(-1));
7729 } else {
7730 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
7731 SecondRange.getEnd());
7732 }
7733
7734 Diag(Call->getExprLoc(), diag::note_remove_max_call)
7735 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
7736 << FixItHint::CreateRemoval(RemovalRange);
7737}
7738
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007739//===--- CHECK: Standard memory functions ---------------------------------===//
7740
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007741/// Takes the expression passed to the size_t parameter of functions
Nico Weber0e6daef2013-12-26 23:38:39 +00007742/// such as memcmp, strncat, etc and warns if it's a comparison.
7743///
7744/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
7745static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
7746 IdentifierInfo *FnName,
7747 SourceLocation FnLoc,
7748 SourceLocation RParenLoc) {
7749 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
7750 if (!Size)
7751 return false;
7752
Richard Smithc70f1d62017-12-14 15:16:18 +00007753 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
7754 if (!Size->isComparisonOp() && !Size->isLogicalOp())
Nico Weber0e6daef2013-12-26 23:38:39 +00007755 return false;
7756
Nico Weber0e6daef2013-12-26 23:38:39 +00007757 SourceRange SizeRange = Size->getSourceRange();
7758 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
7759 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00007760 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007761 << FnName << FixItHint::CreateInsertion(
7762 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00007763 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00007764 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00007765 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00007766 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
7767 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00007768
7769 return true;
7770}
7771
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007772/// Determine whether the given type is or contains a dynamic class type
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007773/// (e.g., whether it has a vtable).
7774static const CXXRecordDecl *getContainedDynamicClass(QualType T,
7775 bool &IsContained) {
7776 // Look through array types while ignoring qualifiers.
7777 const Type *Ty = T->getBaseElementTypeUnsafe();
7778 IsContained = false;
7779
7780 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
7781 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00007782 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007783 return nullptr;
7784
7785 if (RD->isDynamicClass())
7786 return RD;
7787
7788 // Check all the fields. If any bases were dynamic, the class is dynamic.
7789 // It's impossible for a class to transitively contain itself by value, so
7790 // infinite recursion is impossible.
7791 for (auto *FD : RD->fields()) {
7792 bool SubContained;
7793 if (const CXXRecordDecl *ContainedRD =
7794 getContainedDynamicClass(FD->getType(), SubContained)) {
7795 IsContained = true;
7796 return ContainedRD;
7797 }
7798 }
7799
7800 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00007801}
7802
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007803/// If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007804/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00007805static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00007806 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007807 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007808 if (SizeOf->getKind() == UETT_SizeOf && !SizeOf->isArgumentType())
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007809 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007810
Craig Topperc3ec1492014-05-26 06:22:03 +00007811 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007812}
7813
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007814/// If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00007815static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007816 if (const UnaryExprOrTypeTraitExpr *SizeOf =
7817 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007818 if (SizeOf->getKind() == UETT_SizeOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007819 return SizeOf->getTypeOfArgument();
7820
7821 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00007822}
7823
Akira Hatanaka2be04412018-04-17 19:13:41 +00007824namespace {
7825
7826struct SearchNonTrivialToInitializeField
7827 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
7828 using Super =
7829 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
7830
7831 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
7832
7833 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
7834 SourceLocation SL) {
7835 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
7836 asDerived().visitArray(PDIK, AT, SL);
7837 return;
7838 }
7839
7840 Super::visitWithKind(PDIK, FT, SL);
7841 }
7842
7843 void visitARCStrong(QualType FT, SourceLocation SL) {
7844 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
7845 }
7846 void visitARCWeak(QualType FT, SourceLocation SL) {
7847 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
7848 }
7849 void visitStruct(QualType FT, SourceLocation SL) {
7850 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
7851 visit(FD->getType(), FD->getLocation());
7852 }
7853 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
7854 const ArrayType *AT, SourceLocation SL) {
7855 visit(getContext().getBaseElementType(AT), SL);
7856 }
7857 void visitTrivial(QualType FT, SourceLocation SL) {}
7858
7859 static void diag(QualType RT, const Expr *E, Sema &S) {
7860 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
7861 }
7862
7863 ASTContext &getContext() { return S.getASTContext(); }
7864
7865 const Expr *E;
7866 Sema &S;
7867};
7868
7869struct SearchNonTrivialToCopyField
7870 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
7871 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
7872
7873 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
7874
7875 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
7876 SourceLocation SL) {
7877 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
7878 asDerived().visitArray(PCK, AT, SL);
7879 return;
7880 }
7881
7882 Super::visitWithKind(PCK, FT, SL);
7883 }
7884
7885 void visitARCStrong(QualType FT, SourceLocation SL) {
7886 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
7887 }
7888 void visitARCWeak(QualType FT, SourceLocation SL) {
7889 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
7890 }
7891 void visitStruct(QualType FT, SourceLocation SL) {
7892 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
7893 visit(FD->getType(), FD->getLocation());
7894 }
7895 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
7896 SourceLocation SL) {
7897 visit(getContext().getBaseElementType(AT), SL);
7898 }
7899 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
7900 SourceLocation SL) {}
7901 void visitTrivial(QualType FT, SourceLocation SL) {}
7902 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
7903
7904 static void diag(QualType RT, const Expr *E, Sema &S) {
7905 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
7906 }
7907
7908 ASTContext &getContext() { return S.getASTContext(); }
7909
7910 const Expr *E;
7911 Sema &S;
7912};
7913
7914}
7915
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007916/// Check for dangerous or invalid arguments to memset().
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007917///
Chandler Carruthac687262011-06-03 06:23:57 +00007918/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007919/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
7920/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007921///
7922/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007923void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00007924 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007925 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00007926 assert(BId != 0);
7927
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007928 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00007929 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007930 unsigned ExpectedNumArgs =
7931 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00007932 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007933 return;
7934
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007935 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00007936 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007937 unsigned LenArg =
7938 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00007939 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007940
Nico Weber0e6daef2013-12-26 23:38:39 +00007941 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
7942 Call->getLocStart(), Call->getRParenLoc()))
7943 return;
7944
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007945 // We have special checking when the length is a sizeof expression.
7946 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
7947 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
7948 llvm::FoldingSetNodeID SizeOfArgID;
7949
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00007950 // Although widely used, 'bzero' is not a standard function. Be more strict
7951 // with the argument types before allowing diagnostics and only allow the
7952 // form bzero(ptr, sizeof(...)).
7953 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7954 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
7955 return;
7956
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007957 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7958 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007959 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007960
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007961 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00007962 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007963 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00007964 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00007965
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007966 // Never warn about void type pointers. This can be used to suppress
7967 // false positives.
7968 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007969 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007970
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007971 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
7972 // actually comparing the expressions for equality. Because computing the
7973 // expression IDs can be expensive, we only do this if the diagnostic is
7974 // enabled.
7975 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007976 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
7977 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007978 // We only compute IDs for expressions if the warning is enabled, and
7979 // cache the sizeof arg's ID.
7980 if (SizeOfArgID == llvm::FoldingSetNodeID())
7981 SizeOfArg->Profile(SizeOfArgID, Context, true);
7982 llvm::FoldingSetNodeID DestID;
7983 Dest->Profile(DestID, Context, true);
7984 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00007985 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
7986 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007987 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00007988 StringRef ReadableName = FnName->getName();
7989
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007990 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00007991 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007992 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00007993 if (!PointeeTy->isIncompleteType() &&
7994 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007995 ActionIdx = 2; // If the pointee's size is sizeof(char),
7996 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00007997
7998 // If the function is defined as a builtin macro, do not show macro
7999 // expansion.
8000 SourceLocation SL = SizeOfArg->getExprLoc();
8001 SourceRange DSR = Dest->getSourceRange();
8002 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00008003 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00008004
8005 if (SM.isMacroArgExpansion(SL)) {
8006 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
8007 SL = SM.getSpellingLoc(SL);
8008 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
8009 SM.getSpellingLoc(DSR.getEnd()));
8010 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
8011 SM.getSpellingLoc(SSR.getEnd()));
8012 }
8013
Anna Zaksd08d9152012-05-30 23:14:52 +00008014 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00008015 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00008016 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00008017 << PointeeTy
8018 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00008019 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00008020 << SSR);
8021 DiagRuntimeBehavior(SL, SizeOfArg,
8022 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
8023 << ActionIdx
8024 << SSR);
8025
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00008026 break;
8027 }
8028 }
8029
8030 // Also check for cases where the sizeof argument is the exact same
8031 // type as the memory argument, and where it points to a user-defined
8032 // record type.
8033 if (SizeOfArgTy != QualType()) {
8034 if (PointeeTy->isRecordType() &&
8035 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
8036 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
8037 PDiag(diag::warn_sizeof_pointer_type_memaccess)
8038 << FnName << SizeOfArgTy << ArgIdx
8039 << PointeeTy << Dest->getSourceRange()
8040 << LenExpr->getSourceRange());
8041 break;
8042 }
Nico Weberc5e73862011-06-14 16:14:58 +00008043 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00008044 } else if (DestTy->isArrayType()) {
8045 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00008046 }
Nico Weberc5e73862011-06-14 16:14:58 +00008047
Nico Weberc44b35e2015-03-21 17:37:46 +00008048 if (PointeeTy == QualType())
8049 continue;
Anna Zaks22122702012-01-17 00:37:07 +00008050
Nico Weberc44b35e2015-03-21 17:37:46 +00008051 // Always complain about dynamic classes.
8052 bool IsContained;
8053 if (const CXXRecordDecl *ContainedRD =
8054 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00008055
Nico Weberc44b35e2015-03-21 17:37:46 +00008056 unsigned OperationType = 0;
8057 // "overwritten" if we're warning about the destination for any call
8058 // but memcmp; otherwise a verb appropriate to the call.
8059 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
8060 if (BId == Builtin::BImemcpy)
8061 OperationType = 1;
8062 else if(BId == Builtin::BImemmove)
8063 OperationType = 2;
8064 else if (BId == Builtin::BImemcmp)
8065 OperationType = 3;
8066 }
8067
John McCall31168b02011-06-15 23:02:42 +00008068 DiagRuntimeBehavior(
8069 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00008070 PDiag(diag::warn_dyn_class_memaccess)
8071 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
8072 << FnName << IsContained << ContainedRD << OperationType
8073 << Call->getCallee()->getSourceRange());
8074 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
8075 BId != Builtin::BImemset)
8076 DiagRuntimeBehavior(
8077 Dest->getExprLoc(), Dest,
8078 PDiag(diag::warn_arc_object_memaccess)
8079 << ArgIdx << FnName << PointeeTy
8080 << Call->getCallee()->getSourceRange());
Akira Hatanaka2be04412018-04-17 19:13:41 +00008081 else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
8082 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
8083 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
8084 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
8085 PDiag(diag::warn_cstruct_memaccess)
8086 << ArgIdx << FnName << PointeeTy << 0);
8087 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
8088 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
8089 RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
8090 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
8091 PDiag(diag::warn_cstruct_memaccess)
8092 << ArgIdx << FnName << PointeeTy << 1);
8093 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
8094 } else {
8095 continue;
8096 }
8097 } else
Nico Weberc44b35e2015-03-21 17:37:46 +00008098 continue;
8099
8100 DiagRuntimeBehavior(
8101 Dest->getExprLoc(), Dest,
8102 PDiag(diag::note_bad_memaccess_silence)
8103 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
8104 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00008105 }
8106}
8107
Ted Kremenek6865f772011-08-18 20:55:45 +00008108// A little helper routine: ignore addition and subtraction of integer literals.
8109// This intentionally does not ignore all integer constant expressions because
8110// we don't want to remove sizeof().
8111static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
8112 Ex = Ex->IgnoreParenCasts();
8113
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008114 while (true) {
Ted Kremenek6865f772011-08-18 20:55:45 +00008115 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
8116 if (!BO || !BO->isAdditiveOp())
8117 break;
8118
8119 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
8120 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
8121
8122 if (isa<IntegerLiteral>(RHS))
8123 Ex = LHS;
8124 else if (isa<IntegerLiteral>(LHS))
8125 Ex = RHS;
8126 else
8127 break;
8128 }
8129
8130 return Ex;
8131}
8132
Anna Zaks13b08572012-08-08 21:42:23 +00008133static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
8134 ASTContext &Context) {
8135 // Only handle constant-sized or VLAs, but not flexible members.
8136 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
8137 // Only issue the FIXIT for arrays of size > 1.
8138 if (CAT->getSize().getSExtValue() <= 1)
8139 return false;
8140 } else if (!Ty->isVariableArrayType()) {
8141 return false;
8142 }
8143 return true;
8144}
8145
Ted Kremenek6865f772011-08-18 20:55:45 +00008146// Warn if the user has made the 'size' argument to strlcpy or strlcat
8147// be the size of the source, instead of the destination.
8148void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
8149 IdentifierInfo *FnName) {
8150
8151 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00008152 unsigned NumArgs = Call->getNumArgs();
8153 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00008154 return;
8155
8156 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
8157 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00008158 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00008159
8160 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
8161 Call->getLocStart(), Call->getRParenLoc()))
8162 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00008163
8164 // Look for 'strlcpy(dst, x, sizeof(x))'
8165 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
8166 CompareWithSrc = Ex;
8167 else {
8168 // Look for 'strlcpy(dst, x, strlen(x))'
8169 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00008170 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
8171 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00008172 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
8173 }
8174 }
8175
8176 if (!CompareWithSrc)
8177 return;
8178
8179 // Determine if the argument to sizeof/strlen is equal to the source
8180 // argument. In principle there's all kinds of things you could do
8181 // here, for instance creating an == expression and evaluating it with
8182 // EvaluateAsBooleanCondition, but this uses a more direct technique:
8183 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
8184 if (!SrcArgDRE)
8185 return;
8186
8187 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
8188 if (!CompareWithSrcDRE ||
8189 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
8190 return;
8191
8192 const Expr *OriginalSizeArg = Call->getArg(2);
8193 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
8194 << OriginalSizeArg->getSourceRange() << FnName;
8195
8196 // Output a FIXIT hint if the destination is an array (rather than a
8197 // pointer to an array). This could be enhanced to handle some
8198 // pointers if we know the actual size, like if DstArg is 'array+2'
8199 // we could say 'sizeof(array)-2'.
8200 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00008201 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00008202 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00008203
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008204 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00008205 llvm::raw_svector_ostream OS(sizeString);
8206 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00008207 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00008208 OS << ")";
8209
8210 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
8211 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
8212 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00008213}
8214
Anna Zaks314cd092012-02-01 19:08:57 +00008215/// Check if two expressions refer to the same declaration.
8216static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
8217 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
8218 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
8219 return D1->getDecl() == D2->getDecl();
8220 return false;
8221}
8222
8223static const Expr *getStrlenExprArg(const Expr *E) {
8224 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8225 const FunctionDecl *FD = CE->getDirectCallee();
8226 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00008227 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00008228 return CE->getArg(0)->IgnoreParenCasts();
8229 }
Craig Topperc3ec1492014-05-26 06:22:03 +00008230 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00008231}
8232
8233// Warn on anti-patterns as the 'size' argument to strncat.
8234// The correct size argument should look like following:
8235// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
8236void Sema::CheckStrncatArguments(const CallExpr *CE,
8237 IdentifierInfo *FnName) {
8238 // Don't crash if the user has the wrong number of arguments.
8239 if (CE->getNumArgs() < 3)
8240 return;
8241 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
8242 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
8243 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
8244
Nico Weber0e6daef2013-12-26 23:38:39 +00008245 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
8246 CE->getRParenLoc()))
8247 return;
8248
Anna Zaks314cd092012-02-01 19:08:57 +00008249 // Identify common expressions, which are wrongly used as the size argument
8250 // to strncat and may lead to buffer overflows.
8251 unsigned PatternType = 0;
8252 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
8253 // - sizeof(dst)
8254 if (referToTheSameDecl(SizeOfArg, DstArg))
8255 PatternType = 1;
8256 // - sizeof(src)
8257 else if (referToTheSameDecl(SizeOfArg, SrcArg))
8258 PatternType = 2;
8259 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
8260 if (BE->getOpcode() == BO_Sub) {
8261 const Expr *L = BE->getLHS()->IgnoreParenCasts();
8262 const Expr *R = BE->getRHS()->IgnoreParenCasts();
8263 // - sizeof(dst) - strlen(dst)
8264 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
8265 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
8266 PatternType = 1;
8267 // - sizeof(src) - (anything)
8268 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
8269 PatternType = 2;
8270 }
8271 }
8272
8273 if (PatternType == 0)
8274 return;
8275
Anna Zaks5069aa32012-02-03 01:27:37 +00008276 // Generate the diagnostic.
8277 SourceLocation SL = LenArg->getLocStart();
8278 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00008279 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00008280
8281 // If the function is defined as a builtin macro, do not show macro expansion.
8282 if (SM.isMacroArgExpansion(SL)) {
8283 SL = SM.getSpellingLoc(SL);
8284 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
8285 SM.getSpellingLoc(SR.getEnd()));
8286 }
8287
Anna Zaks13b08572012-08-08 21:42:23 +00008288 // Check if the destination is an array (rather than a pointer to an array).
8289 QualType DstTy = DstArg->getType();
8290 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
8291 Context);
8292 if (!isKnownSizeArray) {
8293 if (PatternType == 1)
8294 Diag(SL, diag::warn_strncat_wrong_size) << SR;
8295 else
8296 Diag(SL, diag::warn_strncat_src_size) << SR;
8297 return;
8298 }
8299
Anna Zaks314cd092012-02-01 19:08:57 +00008300 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00008301 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00008302 else
Anna Zaks5069aa32012-02-03 01:27:37 +00008303 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00008304
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008305 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00008306 llvm::raw_svector_ostream OS(sizeString);
8307 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00008308 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00008309 OS << ") - ";
8310 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00008311 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00008312 OS << ") - 1";
8313
Anna Zaks5069aa32012-02-03 01:27:37 +00008314 Diag(SL, diag::note_strncat_wrong_size)
8315 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00008316}
8317
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008318//===--- CHECK: Return Address of Stack Variable --------------------------===//
8319
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008320static const Expr *EvalVal(const Expr *E,
8321 SmallVectorImpl<const DeclRefExpr *> &refVars,
8322 const Decl *ParentDecl);
8323static const Expr *EvalAddr(const Expr *E,
8324 SmallVectorImpl<const DeclRefExpr *> &refVars,
8325 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008326
8327/// CheckReturnStackAddr - Check if a return statement returns the address
8328/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008329static void
8330CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
8331 SourceLocation ReturnLoc) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008332 const Expr *stackE = nullptr;
8333 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008334
8335 // Perform checking for returned stack addresses, local blocks,
8336 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00008337 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008338 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008339 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00008340 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008341 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008342 }
8343
Craig Topperc3ec1492014-05-26 06:22:03 +00008344 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008345 return; // Nothing suspicious was found.
8346
Simon Pilgrim750bde62017-03-31 11:00:53 +00008347 // Parameters are initialized in the calling scope, so taking the address
Richard Trieu81b6c562016-08-05 23:24:47 +00008348 // of a parameter reference doesn't need a warning.
8349 for (auto *DRE : refVars)
8350 if (isa<ParmVarDecl>(DRE->getDecl()))
8351 return;
8352
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008353 SourceLocation diagLoc;
8354 SourceRange diagRange;
8355 if (refVars.empty()) {
8356 diagLoc = stackE->getLocStart();
8357 diagRange = stackE->getSourceRange();
8358 } else {
8359 // We followed through a reference variable. 'stackE' contains the
8360 // problematic expression but we will warn at the return statement pointing
8361 // at the reference variable. We will later display the "trail" of
8362 // reference variables using notes.
8363 diagLoc = refVars[0]->getLocStart();
8364 diagRange = refVars[0]->getSourceRange();
8365 }
8366
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008367 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
8368 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00008369 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008370 << DR->getDecl()->getDeclName() << diagRange;
8371 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008372 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008373 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008374 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008375 } else { // local temporary.
Richard Trieu81b6c562016-08-05 23:24:47 +00008376 // If there is an LValue->RValue conversion, then the value of the
8377 // reference type is used, not the reference.
8378 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
8379 if (ICE->getCastKind() == CK_LValueToRValue) {
8380 return;
8381 }
8382 }
Craig Topperda7b27f2015-11-17 05:40:09 +00008383 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
8384 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008385 }
8386
8387 // Display the "trail" of reference variables that we followed until we
8388 // found the problematic expression using notes.
8389 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008390 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008391 // If this var binds to another reference var, show the range of the next
8392 // var, otherwise the var binds to the problematic expression, in which case
8393 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008394 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
8395 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008396 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
8397 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008398 }
8399}
8400
8401/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
8402/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008403/// to a location on the stack, a local block, an address of a label, or a
8404/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008405/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008406/// encounter a subexpression that (1) clearly does not lead to one of the
8407/// above problematic expressions (2) is something we cannot determine leads to
8408/// a problematic expression based on such local checking.
8409///
8410/// Both EvalAddr and EvalVal follow through reference variables to evaluate
8411/// the expression that they point to. Such variables are added to the
8412/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008413///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00008414/// EvalAddr processes expressions that are pointers that are used as
8415/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008416/// At the base case of the recursion is a check for the above problematic
8417/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008418///
8419/// This implementation handles:
8420///
8421/// * pointer-to-pointer casts
8422/// * implicit conversions from array references to pointers
8423/// * taking the address of fields
8424/// * arbitrary interplay between "&" and "*" operators
8425/// * pointer arithmetic from an address of a stack variable
8426/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008427static const Expr *EvalAddr(const Expr *E,
8428 SmallVectorImpl<const DeclRefExpr *> &refVars,
8429 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008430 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00008431 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008432
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008433 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00008434 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00008435 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00008436 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00008437 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00008438
Peter Collingbourne91147592011-04-15 00:35:48 +00008439 E = E->IgnoreParens();
8440
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008441 // Our "symbolic interpreter" is just a dispatch off the currently
8442 // viewed AST node. We then recursively traverse the AST by calling
8443 // EvalAddr and EvalVal appropriately.
8444 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008445 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008446 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008447
Richard Smith40f08eb2014-01-30 22:05:38 +00008448 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00008449 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00008450 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00008451
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008452 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008453 // If this is a reference variable, follow through to the expression that
8454 // it points to.
8455 if (V->hasLocalStorage() &&
8456 V->getType()->isReferenceType() && V->hasInit()) {
8457 // Add the reference variable to the "trail".
8458 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008459 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008460 }
8461
Craig Topperc3ec1492014-05-26 06:22:03 +00008462 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008463 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008464
Chris Lattner934edb22007-12-28 05:31:15 +00008465 case Stmt::UnaryOperatorClass: {
8466 // The only unary operator that make sense to handle here
8467 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008468 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00008469
John McCalle3027922010-08-25 11:45:40 +00008470 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008471 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008472 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008473 }
Mike Stump11289f42009-09-09 15:08:12 +00008474
Chris Lattner934edb22007-12-28 05:31:15 +00008475 case Stmt::BinaryOperatorClass: {
8476 // Handle pointer arithmetic. All other binary operators are not valid
8477 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008478 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00008479 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00008480
John McCalle3027922010-08-25 11:45:40 +00008481 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00008482 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008483
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008484 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00008485
8486 // Determine which argument is the real pointer base. It could be
8487 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008488 if (!Base->getType()->isPointerType())
8489 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00008490
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008491 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008492 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00008493 }
Steve Naroff2752a172008-09-10 19:17:48 +00008494
Chris Lattner934edb22007-12-28 05:31:15 +00008495 // For conditional operators we need to see if either the LHS or RHS are
8496 // valid DeclRefExpr*s. If one of them is valid, we return it.
8497 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008498 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00008499
Chris Lattner934edb22007-12-28 05:31:15 +00008500 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008501 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008502 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008503 // In C++, we can have a throw-expression, which has 'void' type.
8504 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008505 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00008506 return LHS;
8507 }
Chris Lattner934edb22007-12-28 05:31:15 +00008508
Douglas Gregor270b2ef2010-10-21 16:21:08 +00008509 // In C++, we can have a throw-expression, which has 'void' type.
8510 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00008511 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00008512
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008513 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00008514 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008515
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008516 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00008517 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008518 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00008519 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008520
8521 case Stmt::AddrLabelExprClass:
8522 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00008523
John McCall28fc7092011-11-10 05:35:25 +00008524 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008525 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
8526 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00008527
Ted Kremenekc3b4c522008-08-07 00:49:01 +00008528 // For casts, we need to handle conversions from arrays to
8529 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00008530 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00008531 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00008532 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00008533 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00008534 case Stmt::CXXStaticCastExprClass:
8535 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00008536 case Stmt::CXXConstCastExprClass:
8537 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008538 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00008539 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00008540 case CK_LValueToRValue:
8541 case CK_NoOp:
8542 case CK_BaseToDerived:
8543 case CK_DerivedToBase:
8544 case CK_UncheckedDerivedToBase:
8545 case CK_Dynamic:
8546 case CK_CPointerToObjCPointerCast:
8547 case CK_BlockPointerToObjCPointerCast:
8548 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008549 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00008550
8551 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008552 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00008553
Richard Trieudadefde2014-07-02 04:39:38 +00008554 case CK_BitCast:
8555 if (SubExpr->getType()->isAnyPointerType() ||
8556 SubExpr->getType()->isBlockPointerType() ||
8557 SubExpr->getType()->isObjCQualifiedIdType())
8558 return EvalAddr(SubExpr, refVars, ParentDecl);
8559 else
8560 return nullptr;
8561
Eli Friedman8195ad72012-02-23 23:04:32 +00008562 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00008563 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00008564 }
Chris Lattner934edb22007-12-28 05:31:15 +00008565 }
Mike Stump11289f42009-09-09 15:08:12 +00008566
Douglas Gregorfe314812011-06-21 17:03:29 +00008567 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008568 if (const Expr *Result =
8569 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8570 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00008571 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00008572 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008573
Chris Lattner934edb22007-12-28 05:31:15 +00008574 // Everything else: we simply don't reason about them.
8575 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00008576 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00008577 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008578}
Mike Stump11289f42009-09-09 15:08:12 +00008579
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008580/// EvalVal - This function is complements EvalAddr in the mutual recursion.
8581/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008582static const Expr *EvalVal(const Expr *E,
8583 SmallVectorImpl<const DeclRefExpr *> &refVars,
8584 const Decl *ParentDecl) {
8585 do {
8586 // We should only be called for evaluating non-pointer expressions, or
8587 // expressions with a pointer type that are not used as references but
8588 // instead
8589 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00008590
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008591 // Our "symbolic interpreter" is just a dispatch off the currently
8592 // viewed AST node. We then recursively traverse the AST by calling
8593 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00008594
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008595 E = E->IgnoreParens();
8596 switch (E->getStmtClass()) {
8597 case Stmt::ImplicitCastExprClass: {
8598 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
8599 if (IE->getValueKind() == VK_LValue) {
8600 E = IE->getSubExpr();
8601 continue;
8602 }
Craig Topperc3ec1492014-05-26 06:22:03 +00008603 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008604 }
Richard Smith40f08eb2014-01-30 22:05:38 +00008605
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008606 case Stmt::ExprWithCleanupsClass:
8607 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
8608 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008609
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008610 case Stmt::DeclRefExprClass: {
8611 // When we hit a DeclRefExpr we are looking at code that refers to a
8612 // variable's name. If it's not a reference variable we check if it has
8613 // local storage within the function, and if so, return the expression.
8614 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
8615
8616 // If we leave the immediate function, the lifetime isn't about to end.
8617 if (DR->refersToEnclosingVariableOrCapture())
8618 return nullptr;
8619
8620 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
8621 // Check if it refers to itself, e.g. "int& i = i;".
8622 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008623 return DR;
8624
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008625 if (V->hasLocalStorage()) {
8626 if (!V->getType()->isReferenceType())
8627 return DR;
8628
8629 // Reference variable, follow through to the expression that
8630 // it points to.
8631 if (V->hasInit()) {
8632 // Add the reference variable to the "trail".
8633 refVars.push_back(DR);
8634 return EvalVal(V->getInit(), refVars, V);
8635 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008636 }
8637 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008638
8639 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008640 }
Mike Stump11289f42009-09-09 15:08:12 +00008641
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008642 case Stmt::UnaryOperatorClass: {
8643 // The only unary operator that make sense to handle here
8644 // is Deref. All others don't resolve to a "name." This includes
8645 // handling all sorts of rvalues passed to a unary operator.
8646 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00008647
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008648 if (U->getOpcode() == UO_Deref)
8649 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00008650
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008651 return nullptr;
8652 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008653
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008654 case Stmt::ArraySubscriptExprClass: {
8655 // Array subscripts are potential references to data on the stack. We
8656 // retrieve the DeclRefExpr* for the array variable if it indeed
8657 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00008658 const auto *ASE = cast<ArraySubscriptExpr>(E);
8659 if (ASE->isTypeDependent())
8660 return nullptr;
8661 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008662 }
Mike Stump11289f42009-09-09 15:08:12 +00008663
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008664 case Stmt::OMPArraySectionExprClass: {
8665 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
8666 ParentDecl);
8667 }
Mike Stump11289f42009-09-09 15:08:12 +00008668
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008669 case Stmt::ConditionalOperatorClass: {
8670 // For conditional operators we need to see if either the LHS or RHS are
8671 // non-NULL Expr's. If one is non-NULL, we return it.
8672 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00008673
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008674 // Handle the GNU extension for missing LHS.
8675 if (const Expr *LHSExpr = C->getLHS()) {
8676 // In C++, we can have a throw-expression, which has 'void' type.
8677 if (!LHSExpr->getType()->isVoidType())
8678 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
8679 return LHS;
8680 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008681
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008682 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008683 if (C->getRHS()->getType()->isVoidType())
8684 return nullptr;
8685
8686 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008687 }
8688
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008689 // Accesses to members are potential references to data on the stack.
8690 case Stmt::MemberExprClass: {
8691 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00008692
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008693 // Check for indirect access. We only want direct field accesses.
8694 if (M->isArrow())
8695 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008696
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008697 // Check whether the member type is itself a reference, in which case
8698 // we're not going to refer to the member, but to what the member refers
8699 // to.
8700 if (M->getMemberDecl()->getType()->isReferenceType())
8701 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008702
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008703 return EvalVal(M->getBase(), refVars, ParentDecl);
8704 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00008705
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008706 case Stmt::MaterializeTemporaryExprClass:
8707 if (const Expr *Result =
8708 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8709 refVars, ParentDecl))
8710 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008711 return E;
8712
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008713 default:
8714 // Check that we don't return or take the address of a reference to a
8715 // temporary. This is only useful in C++.
8716 if (!E->isTypeDependent() && E->isRValue())
8717 return E;
8718
8719 // Everything else: we simply don't reason about them.
8720 return nullptr;
8721 }
8722 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008723}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008724
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008725void
8726Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
8727 SourceLocation ReturnLoc,
8728 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00008729 const AttrVec *Attrs,
8730 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008731 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
8732
8733 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00008734 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
8735 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00008736 CheckNonNullExpr(*this, RetValExp))
8737 Diag(ReturnLoc, diag::warn_null_ret)
8738 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00008739
8740 // C++11 [basic.stc.dynamic.allocation]p4:
8741 // If an allocation function declared with a non-throwing
8742 // exception-specification fails to allocate storage, it shall return
8743 // a null pointer. Any other allocation function that fails to allocate
8744 // storage shall indicate failure only by throwing an exception [...]
8745 if (FD) {
8746 OverloadedOperatorKind Op = FD->getOverloadedOperator();
8747 if (Op == OO_New || Op == OO_Array_New) {
8748 const FunctionProtoType *Proto
8749 = FD->getType()->castAs<FunctionProtoType>();
Richard Smitheaf11ad2018-05-03 03:58:32 +00008750 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
Artyom Skrobov9f213442014-01-24 11:10:39 +00008751 CheckNonNullExpr(*this, RetValExp))
8752 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
8753 << FD << getLangOpts().CPlusPlus11;
8754 }
8755 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008756}
8757
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008758//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
8759
8760/// Check for comparisons of floating point operands using != and ==.
8761/// Issue a warning if these are no self-comparisons, as they are not likely
8762/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00008763void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00008764 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
8765 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008766
8767 // Special case: check for x == x (which is OK).
8768 // Do not emit warnings for such cases.
8769 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
8770 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
8771 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00008772 return;
Mike Stump11289f42009-09-09 15:08:12 +00008773
Ted Kremenekeda40e22007-11-29 00:59:04 +00008774 // Special case: check for comparisons against literals that can be exactly
8775 // represented by APFloat. In such cases, do not emit a warning. This
8776 // is a heuristic: often comparison against such literals are used to
8777 // detect if a value in a variable has not changed. This clearly can
8778 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00008779 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
8780 if (FLL->isExact())
8781 return;
8782 } else
8783 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
8784 if (FLR->isExact())
8785 return;
Mike Stump11289f42009-09-09 15:08:12 +00008786
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008787 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00008788 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00008789 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00008790 return;
Mike Stump11289f42009-09-09 15:08:12 +00008791
David Blaikie1f4ff152012-07-16 20:47:22 +00008792 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00008793 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00008794 return;
Mike Stump11289f42009-09-09 15:08:12 +00008795
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008796 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00008797 Diag(Loc, diag::warn_floatingpoint_eq)
8798 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008799}
John McCallca01b222010-01-04 23:21:16 +00008800
John McCall70aa5392010-01-06 05:24:50 +00008801//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
8802//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00008803
John McCall70aa5392010-01-06 05:24:50 +00008804namespace {
John McCallca01b222010-01-04 23:21:16 +00008805
John McCall70aa5392010-01-06 05:24:50 +00008806/// Structure recording the 'active' range of an integer-valued
8807/// expression.
8808struct IntRange {
8809 /// The number of bits active in the int.
8810 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00008811
John McCall70aa5392010-01-06 05:24:50 +00008812 /// True if the int is known not to have negative values.
8813 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00008814
John McCall70aa5392010-01-06 05:24:50 +00008815 IntRange(unsigned Width, bool NonNegative)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008816 : Width(Width), NonNegative(NonNegative) {}
John McCallca01b222010-01-04 23:21:16 +00008817
John McCall817d4af2010-11-10 23:38:19 +00008818 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00008819 static IntRange forBoolType() {
8820 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00008821 }
8822
John McCall817d4af2010-11-10 23:38:19 +00008823 /// Returns the range of an opaque value of the given integral type.
8824 static IntRange forValueOfType(ASTContext &C, QualType T) {
8825 return forValueOfCanonicalType(C,
8826 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00008827 }
8828
John McCall817d4af2010-11-10 23:38:19 +00008829 /// Returns the range of an opaque value of a canonical integral type.
8830 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00008831 assert(T->isCanonicalUnqualified());
8832
8833 if (const VectorType *VT = dyn_cast<VectorType>(T))
8834 T = VT->getElementType().getTypePtr();
8835 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8836 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008837 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8838 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00008839
Roman Lebedevca1aaac2017-10-21 16:44:03 +00008840 if (!C.getLangOpts().CPlusPlus) {
8841 // For enum types in C code, use the underlying datatype.
8842 if (const EnumType *ET = dyn_cast<EnumType>(T))
8843 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
8844 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
8845 // For enum types in C++, use the known bit width of the enumerators.
David Majnemer6a426652013-06-07 22:07:20 +00008846 EnumDecl *Enum = ET->getDecl();
Richard Smith371e9e8a2017-12-06 03:00:51 +00008847 // In C++11, enums can have a fixed underlying type. Use this type to
8848 // compute the range.
8849 if (Enum->isFixed()) {
Erich Keane69dbbb02017-09-21 19:58:55 +00008850 return IntRange(C.getIntWidth(QualType(T, 0)),
8851 !ET->isSignedIntegerOrEnumerationType());
Richard Smith371e9e8a2017-12-06 03:00:51 +00008852 }
John McCall18a2c2c2010-11-09 22:22:12 +00008853
David Majnemer6a426652013-06-07 22:07:20 +00008854 unsigned NumPositive = Enum->getNumPositiveBits();
8855 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00008856
David Majnemer6a426652013-06-07 22:07:20 +00008857 if (NumNegative == 0)
8858 return IntRange(NumPositive, true/*NonNegative*/);
8859 else
8860 return IntRange(std::max(NumPositive + 1, NumNegative),
8861 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00008862 }
John McCall70aa5392010-01-06 05:24:50 +00008863
8864 const BuiltinType *BT = cast<BuiltinType>(T);
8865 assert(BT->isInteger());
8866
8867 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8868 }
8869
John McCall817d4af2010-11-10 23:38:19 +00008870 /// Returns the "target" range of a canonical integral type, i.e.
8871 /// the range of values expressible in the type.
8872 ///
8873 /// This matches forValueOfCanonicalType except that enums have the
8874 /// full range of their type, not the range of their enumerators.
8875 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
8876 assert(T->isCanonicalUnqualified());
8877
8878 if (const VectorType *VT = dyn_cast<VectorType>(T))
8879 T = VT->getElementType().getTypePtr();
8880 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8881 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008882 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8883 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008884 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00008885 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008886
8887 const BuiltinType *BT = cast<BuiltinType>(T);
8888 assert(BT->isInteger());
8889
8890 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8891 }
8892
8893 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00008894 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00008895 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00008896 L.NonNegative && R.NonNegative);
8897 }
8898
John McCall817d4af2010-11-10 23:38:19 +00008899 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00008900 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00008901 return IntRange(std::min(L.Width, R.Width),
8902 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00008903 }
8904};
8905
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008906} // namespace
8907
8908static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
8909 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008910 if (value.isSigned() && value.isNegative())
8911 return IntRange(value.getMinSignedBits(), false);
8912
8913 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00008914 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008915
8916 // isNonNegative() just checks the sign bit without considering
8917 // signedness.
8918 return IntRange(value.getActiveBits(), true);
8919}
8920
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008921static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
8922 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008923 if (result.isInt())
8924 return GetValueRange(C, result.getInt(), MaxWidth);
8925
8926 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00008927 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
8928 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
8929 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
8930 R = IntRange::join(R, El);
8931 }
John McCall70aa5392010-01-06 05:24:50 +00008932 return R;
8933 }
8934
8935 if (result.isComplexInt()) {
8936 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
8937 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
8938 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00008939 }
8940
8941 // This can happen with lossless casts to intptr_t of "based" lvalues.
8942 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00008943 // FIXME: The only reason we need to pass the type in here is to get
8944 // the sign right on this one case. It would be nice if APValue
8945 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008946 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00008947 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00008948}
John McCall70aa5392010-01-06 05:24:50 +00008949
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008950static QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008951 QualType Ty = E->getType();
8952 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
8953 Ty = AtomicRHS->getValueType();
8954 return Ty;
8955}
8956
John McCall70aa5392010-01-06 05:24:50 +00008957/// Pseudo-evaluate the given integer expression, estimating the
8958/// range of values it might take.
8959///
8960/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008961static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008962 E = E->IgnoreParens();
8963
8964 // Try a full evaluation first.
8965 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00008966 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00008967 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008968
8969 // I think we only want to look through implicit casts here; if the
8970 // user has an explicit widening cast, we should treat the value as
8971 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008972 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00008973 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00008974 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
8975
Eli Friedmane6d33952013-07-08 20:20:06 +00008976 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00008977
George Burgess IVdf1ed002016-01-13 01:52:39 +00008978 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
8979 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00008980
John McCall70aa5392010-01-06 05:24:50 +00008981 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00008982 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00008983 return OutputTypeRange;
8984
8985 IntRange SubRange
8986 = GetExprRange(C, CE->getSubExpr(),
8987 std::min(MaxWidth, OutputTypeRange.Width));
8988
8989 // Bail out if the subexpr's range is as wide as the cast type.
8990 if (SubRange.Width >= OutputTypeRange.Width)
8991 return OutputTypeRange;
8992
8993 // Otherwise, we take the smaller width, and we're non-negative if
8994 // either the output type or the subexpr is.
8995 return IntRange(SubRange.Width,
8996 SubRange.NonNegative || OutputTypeRange.NonNegative);
8997 }
8998
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008999 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00009000 // If we can fold the condition, just take that operand.
9001 bool CondResult;
9002 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
9003 return GetExprRange(C, CondResult ? CO->getTrueExpr()
9004 : CO->getFalseExpr(),
9005 MaxWidth);
9006
9007 // Otherwise, conservatively merge.
9008 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
9009 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
9010 return IntRange::join(L, R);
9011 }
9012
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009013 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00009014 switch (BO->getOpcode()) {
Richard Smithc70f1d62017-12-14 15:16:18 +00009015 case BO_Cmp:
9016 llvm_unreachable("builtin <=> should have class type");
John McCall70aa5392010-01-06 05:24:50 +00009017
9018 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00009019 case BO_LAnd:
9020 case BO_LOr:
9021 case BO_LT:
9022 case BO_GT:
9023 case BO_LE:
9024 case BO_GE:
9025 case BO_EQ:
9026 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00009027 return IntRange::forBoolType();
9028
John McCallc3688382011-07-13 06:35:24 +00009029 // The type of the assignments is the type of the LHS, so the RHS
9030 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00009031 case BO_MulAssign:
9032 case BO_DivAssign:
9033 case BO_RemAssign:
9034 case BO_AddAssign:
9035 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00009036 case BO_XorAssign:
9037 case BO_OrAssign:
9038 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00009039 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00009040
John McCallc3688382011-07-13 06:35:24 +00009041 // Simple assignments just pass through the RHS, which will have
9042 // been coerced to the LHS type.
9043 case BO_Assign:
9044 // TODO: bitfields?
9045 return GetExprRange(C, BO->getRHS(), MaxWidth);
9046
John McCall70aa5392010-01-06 05:24:50 +00009047 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00009048 case BO_PtrMemD:
9049 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00009050 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00009051
John McCall2ce81ad2010-01-06 22:07:33 +00009052 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00009053 case BO_And:
9054 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00009055 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
9056 GetExprRange(C, BO->getRHS(), MaxWidth));
9057
John McCall70aa5392010-01-06 05:24:50 +00009058 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00009059 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00009060 // ...except that we want to treat '1 << (blah)' as logically
9061 // positive. It's an important idiom.
9062 if (IntegerLiteral *I
9063 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
9064 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00009065 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00009066 return IntRange(R.Width, /*NonNegative*/ true);
9067 }
9068 }
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00009069 LLVM_FALLTHROUGH;
John McCall1bff9932010-04-07 01:14:35 +00009070
John McCalle3027922010-08-25 11:45:40 +00009071 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00009072 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00009073
John McCall2ce81ad2010-01-06 22:07:33 +00009074 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00009075 case BO_Shr:
9076 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00009077 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
9078
9079 // If the shift amount is a positive constant, drop the width by
9080 // that much.
9081 llvm::APSInt shift;
9082 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
9083 shift.isNonNegative()) {
9084 unsigned zext = shift.getZExtValue();
9085 if (zext >= L.Width)
9086 L.Width = (L.NonNegative ? 0 : 1);
9087 else
9088 L.Width -= zext;
9089 }
9090
9091 return L;
9092 }
9093
9094 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00009095 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00009096 return GetExprRange(C, BO->getRHS(), MaxWidth);
9097
John McCall2ce81ad2010-01-06 22:07:33 +00009098 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00009099 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00009100 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00009101 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00009102 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00009103
John McCall51431812011-07-14 22:39:48 +00009104 // The width of a division result is mostly determined by the size
9105 // of the LHS.
9106 case BO_Div: {
9107 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00009108 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00009109 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
9110
9111 // If the divisor is constant, use that.
9112 llvm::APSInt divisor;
9113 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
9114 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
9115 if (log2 >= L.Width)
9116 L.Width = (L.NonNegative ? 0 : 1);
9117 else
9118 L.Width = std::min(L.Width - log2, MaxWidth);
9119 return L;
9120 }
9121
9122 // Otherwise, just use the LHS's width.
9123 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
9124 return IntRange(L.Width, L.NonNegative && R.NonNegative);
9125 }
9126
9127 // The result of a remainder can't be larger than the result of
9128 // either side.
9129 case BO_Rem: {
9130 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00009131 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00009132 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
9133 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
9134
9135 IntRange meet = IntRange::meet(L, R);
9136 meet.Width = std::min(meet.Width, MaxWidth);
9137 return meet;
9138 }
9139
9140 // The default behavior is okay for these.
9141 case BO_Mul:
9142 case BO_Add:
9143 case BO_Xor:
9144 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00009145 break;
9146 }
9147
John McCall51431812011-07-14 22:39:48 +00009148 // The default case is to treat the operation as if it were closed
9149 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00009150 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
9151 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
9152 return IntRange::join(L, R);
9153 }
9154
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009155 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00009156 switch (UO->getOpcode()) {
9157 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00009158 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00009159 return IntRange::forBoolType();
9160
9161 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00009162 case UO_Deref:
9163 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00009164 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00009165
9166 default:
9167 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
9168 }
9169 }
9170
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009171 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00009172 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
9173
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009174 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00009175 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00009176 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00009177
Eli Friedmane6d33952013-07-08 20:20:06 +00009178 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00009179}
John McCall263a48b2010-01-04 23:31:57 +00009180
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009181static IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00009182 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00009183}
9184
John McCall263a48b2010-01-04 23:31:57 +00009185/// Checks whether the given value, which currently has the given
9186/// source semantics, has the same value when coerced through the
9187/// target semantics.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009188static bool IsSameFloatAfterCast(const llvm::APFloat &value,
9189 const llvm::fltSemantics &Src,
9190 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00009191 llvm::APFloat truncated = value;
9192
9193 bool ignored;
9194 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
9195 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
9196
9197 return truncated.bitwiseIsEqual(value);
9198}
9199
9200/// Checks whether the given value, which currently has the given
9201/// source semantics, has the same value when coerced through the
9202/// target semantics.
9203///
9204/// The value might be a vector of floats (or a complex number).
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009205static bool IsSameFloatAfterCast(const APValue &value,
9206 const llvm::fltSemantics &Src,
9207 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00009208 if (value.isFloat())
9209 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
9210
9211 if (value.isVector()) {
9212 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
9213 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
9214 return false;
9215 return true;
9216 }
9217
9218 assert(value.isComplexFloat());
9219 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
9220 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
9221}
9222
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009223static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009224
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009225static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00009226 // Suppress cases where we are comparing against an enum constant.
9227 if (const DeclRefExpr *DR =
9228 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
9229 if (isa<EnumConstantDecl>(DR->getDecl()))
Roman Lebedev6de129e2017-10-15 20:13:17 +00009230 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +00009231
9232 // Suppress cases where the '0' value is expanded from a macro.
9233 if (E->getLocStart().isMacroID())
Roman Lebedev6de129e2017-10-15 20:13:17 +00009234 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +00009235
Roman Lebedev6de129e2017-10-15 20:13:17 +00009236 return false;
9237}
9238
Richard Smith692f66ab2017-12-06 19:23:19 +00009239static bool isKnownToHaveUnsignedValue(Expr *E) {
9240 return E->getType()->isIntegerType() &&
Roman Lebedev6de129e2017-10-15 20:13:17 +00009241 (!E->getType()->isSignedIntegerType() ||
9242 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
9243}
9244
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009245namespace {
Richard Smitha5370fb2017-12-08 22:57:11 +00009246/// The promoted range of values of a type. In general this has the
9247/// following structure:
9248///
9249/// |-----------| . . . |-----------|
9250/// ^ ^ ^ ^
9251/// Min HoleMin HoleMax Max
9252///
9253/// ... where there is only a hole if a signed type is promoted to unsigned
9254/// (in which case Min and Max are the smallest and largest representable
9255/// values).
9256struct PromotedRange {
9257 // Min, or HoleMax if there is a hole.
9258 llvm::APSInt PromotedMin;
9259 // Max, or HoleMin if there is a hole.
9260 llvm::APSInt PromotedMax;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009261
Richard Smitha5370fb2017-12-08 22:57:11 +00009262 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
9263 if (R.Width == 0)
9264 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
9265 else if (R.Width >= BitWidth && !Unsigned) {
9266 // Promotion made the type *narrower*. This happens when promoting
9267 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
9268 // Treat all values of 'signed int' as being in range for now.
9269 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
9270 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
9271 } else {
9272 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
9273 .extOrTrunc(BitWidth);
9274 PromotedMin.setIsUnsigned(Unsigned);
9275
9276 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
9277 .extOrTrunc(BitWidth);
9278 PromotedMax.setIsUnsigned(Unsigned);
9279 }
9280 }
9281
9282 // Determine whether this range is contiguous (has no hole).
9283 bool isContiguous() const { return PromotedMin <= PromotedMax; }
9284
9285 // Where a constant value is within the range.
9286 enum ComparisonResult {
9287 LT = 0x1,
9288 LE = 0x2,
9289 GT = 0x4,
9290 GE = 0x8,
9291 EQ = 0x10,
9292 NE = 0x20,
9293 InRangeFlag = 0x40,
9294
9295 Less = LE | LT | NE,
9296 Min = LE | InRangeFlag,
9297 InRange = InRangeFlag,
9298 Max = GE | InRangeFlag,
9299 Greater = GE | GT | NE,
9300
9301 OnlyValue = LE | GE | EQ | InRangeFlag,
9302 InHole = NE
9303 };
9304
9305 ComparisonResult compare(const llvm::APSInt &Value) const {
9306 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
9307 Value.isUnsigned() == PromotedMin.isUnsigned());
9308 if (!isContiguous()) {
9309 assert(Value.isUnsigned() && "discontiguous range for signed compare");
9310 if (Value.isMinValue()) return Min;
9311 if (Value.isMaxValue()) return Max;
9312 if (Value >= PromotedMin) return InRange;
9313 if (Value <= PromotedMax) return InRange;
9314 return InHole;
9315 }
9316
9317 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
9318 case -1: return Less;
9319 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
9320 case 1:
9321 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
9322 case -1: return InRange;
9323 case 0: return Max;
9324 case 1: return Greater;
9325 }
9326 }
9327
9328 llvm_unreachable("impossible compare result");
9329 }
9330
Richard Smithc70f1d62017-12-14 15:16:18 +00009331 static llvm::Optional<StringRef>
9332 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
9333 if (Op == BO_Cmp) {
9334 ComparisonResult LTFlag = LT, GTFlag = GT;
9335 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
9336
9337 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
9338 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
9339 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
9340 return llvm::None;
9341 }
9342
Richard Smitha5370fb2017-12-08 22:57:11 +00009343 ComparisonResult TrueFlag, FalseFlag;
9344 if (Op == BO_EQ) {
9345 TrueFlag = EQ;
9346 FalseFlag = NE;
9347 } else if (Op == BO_NE) {
9348 TrueFlag = NE;
9349 FalseFlag = EQ;
9350 } else {
9351 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
9352 TrueFlag = LT;
9353 FalseFlag = GE;
9354 } else {
9355 TrueFlag = GT;
9356 FalseFlag = LE;
9357 }
9358 if (Op == BO_GE || Op == BO_LE)
9359 std::swap(TrueFlag, FalseFlag);
9360 }
9361 if (R & TrueFlag)
Richard Smithc70f1d62017-12-14 15:16:18 +00009362 return StringRef("true");
Richard Smitha5370fb2017-12-08 22:57:11 +00009363 if (R & FalseFlag)
Richard Smithc70f1d62017-12-14 15:16:18 +00009364 return StringRef("false");
Richard Smitha5370fb2017-12-08 22:57:11 +00009365 return llvm::None;
9366 }
Roman Lebedev6de129e2017-10-15 20:13:17 +00009367};
John McCallcc7e5bf2010-05-06 08:58:33 +00009368}
9369
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009370static bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00009371 // Strip off implicit integral promotions.
9372 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00009373 if (ICE->getCastKind() != CK_IntegralCast &&
9374 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00009375 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00009376 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00009377 }
9378
9379 return E->getType()->isEnumeralType();
9380}
9381
Richard Smith692f66ab2017-12-06 19:23:19 +00009382static int classifyConstantValue(Expr *Constant) {
9383 // The values of this enumeration are used in the diagnostics
9384 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
9385 enum ConstantValueKind {
9386 Miscellaneous = 0,
9387 LiteralTrue,
9388 LiteralFalse
9389 };
9390 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
9391 return BL->getValue() ? ConstantValueKind::LiteralTrue
9392 : ConstantValueKind::LiteralFalse;
9393 return ConstantValueKind::Miscellaneous;
9394}
9395
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009396static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
9397 Expr *Constant, Expr *Other,
9398 const llvm::APSInt &Value,
9399 bool RhsConstant) {
Hans Wennborg5bb88e02017-12-08 05:19:12 +00009400 if (S.inTemplateInstantiation())
9401 return false;
9402
Richard Smitha5370fb2017-12-08 22:57:11 +00009403 Expr *OriginalOther = Other;
9404
Hans Wennborg5bb88e02017-12-08 05:19:12 +00009405 Constant = Constant->IgnoreParenImpCasts();
9406 Other = Other->IgnoreParenImpCasts();
9407
Richard Smitha5370fb2017-12-08 22:57:11 +00009408 // Suppress warnings on tautological comparisons between values of the same
9409 // enumeration type. There are only two ways we could warn on this:
9410 // - If the constant is outside the range of representable values of
9411 // the enumeration. In such a case, we should warn about the cast
9412 // to enumeration type, not about the comparison.
9413 // - If the constant is the maximum / minimum in-range value. For an
9414 // enumeratin type, such comparisons can be meaningful and useful.
9415 if (Constant->getType()->isEnumeralType() &&
9416 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
9417 return false;
9418
Hans Wennborg5bb88e02017-12-08 05:19:12 +00009419 // TODO: Investigate using GetExprRange() to get tighter bounds
9420 // on the bit ranges.
9421 QualType OtherT = Other->getType();
9422 if (const auto *AT = OtherT->getAs<AtomicType>())
9423 OtherT = AT->getValueType();
9424 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
9425
9426 // Whether we're treating Other as being a bool because of the form of
9427 // expression despite it having another type (typically 'int' in C).
9428 bool OtherIsBooleanDespiteType =
9429 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
9430 if (OtherIsBooleanDespiteType)
9431 OtherRange = IntRange::forBoolType();
9432
Richard Smitha5370fb2017-12-08 22:57:11 +00009433 // Determine the promoted range of the other type and see if a comparison of
9434 // the constant against that range is tautological.
9435 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
9436 Value.isUnsigned());
9437 auto Cmp = OtherPromotedRange.compare(Value);
9438 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
9439 if (!Result)
9440 return false;
Hans Wennborg5791ce72017-12-08 16:54:08 +00009441
Richard Smitha5370fb2017-12-08 22:57:11 +00009442 // Suppress the diagnostic for an in-range comparison if the constant comes
9443 // from a macro or enumerator. We don't want to diagnose
9444 //
9445 // some_long_value <= INT_MAX
9446 //
9447 // when sizeof(int) == sizeof(long).
9448 bool InRange = Cmp & PromotedRange::InRangeFlag;
9449 if (InRange && IsEnumConstOrFromMacro(S, Constant))
9450 return false;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00009451
9452 // If this is a comparison to an enum constant, include that
9453 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00009454 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00009455 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
9456 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
9457
Richard Smitha5370fb2017-12-08 22:57:11 +00009458 // Should be enough for uint128 (39 decimal digits)
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00009459 SmallString<64> PrettySourceValue;
9460 llvm::raw_svector_ostream OS(PrettySourceValue);
9461 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00009462 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00009463 else
9464 OS << Value;
9465
Richard Smitha5370fb2017-12-08 22:57:11 +00009466 // FIXME: We use a somewhat different formatting for the in-range cases and
9467 // cases involving boolean values for historical reasons. We should pick a
9468 // consistent way of presenting these diagnostics.
9469 if (!InRange || Other->isKnownToHaveBooleanValue()) {
9470 S.DiagRuntimeBehavior(
9471 E->getOperatorLoc(), E,
9472 S.PDiag(!InRange ? diag::warn_out_of_range_compare
9473 : diag::warn_tautological_bool_compare)
9474 << OS.str() << classifyConstantValue(Constant)
9475 << OtherT << OtherIsBooleanDespiteType << *Result
9476 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
9477 } else {
9478 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
9479 ? (HasEnumType(OriginalOther)
9480 ? diag::warn_unsigned_enum_always_true_comparison
9481 : diag::warn_unsigned_always_true_comparison)
9482 : diag::warn_tautological_constant_compare;
Roman Lebedev6de129e2017-10-15 20:13:17 +00009483
Richard Smitha5370fb2017-12-08 22:57:11 +00009484 S.Diag(E->getOperatorLoc(), Diag)
9485 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
9486 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
9487 }
9488
9489 return true;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00009490}
9491
John McCallcc7e5bf2010-05-06 08:58:33 +00009492/// Analyze the operands of the given comparison. Implements the
9493/// fallback case from AnalyzeComparison.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009494static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00009495 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9496 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00009497}
John McCall263a48b2010-01-04 23:31:57 +00009498
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009499/// Implements -Wsign-compare.
John McCallca01b222010-01-04 23:21:16 +00009500///
Richard Trieu82402a02011-09-15 21:56:47 +00009501/// \param E the binary operator to check for warnings
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009502static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009503 // The type the comparison is being performed in.
9504 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00009505
9506 // Only analyze comparison operators where both sides have been converted to
9507 // the same type.
9508 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
9509 return AnalyzeImpConvsInComparison(S, E);
9510
9511 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00009512 if (E->isValueDependent())
9513 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00009514
Roman Lebedev6de129e2017-10-15 20:13:17 +00009515 Expr *LHS = E->getLHS();
9516 Expr *RHS = E->getRHS();
9517
Fariborz Jahanianb1885422012-09-18 17:37:21 +00009518 if (T->isIntegralType(S.Context)) {
9519 llvm::APSInt RHSValue;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00009520 llvm::APSInt LHSValue;
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009521
Roman Lebedev6de129e2017-10-15 20:13:17 +00009522 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
9523 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
Roman Lebedevbd1fc222017-10-12 20:16:51 +00009524
Roman Lebedev6de129e2017-10-15 20:13:17 +00009525 // We don't care about expressions whose result is a constant.
9526 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
9527 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6f405db2017-10-12 22:03:20 +00009528
Roman Lebedev6de129e2017-10-15 20:13:17 +00009529 // We only care about expressions where just one side is literal
9530 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
9531 // Is the constant on the RHS or LHS?
9532 const bool RhsConstant = IsRHSIntegralLiteral;
9533 Expr *Const = RhsConstant ? RHS : LHS;
9534 Expr *Other = RhsConstant ? LHS : RHS;
9535 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
9536
9537 // Check whether an integer constant comparison results in a value
9538 // of 'true' or 'false'.
Roman Lebedev6de129e2017-10-15 20:13:17 +00009539 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
9540 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6de129e2017-10-15 20:13:17 +00009541 }
9542 }
9543
9544 if (!T->hasUnsignedIntegerRepresentation()) {
9545 // We don't do anything special if this isn't an unsigned integral
9546 // comparison: we're only interested in integral comparisons, and
9547 // signed comparisons only happen in cases we don't care to warn about.
Roman Lebedev6f405db2017-10-12 22:03:20 +00009548 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6de129e2017-10-15 20:13:17 +00009549 }
9550
9551 LHS = LHS->IgnoreParenImpCasts();
9552 RHS = RHS->IgnoreParenImpCasts();
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009553
Alex Lorenzb57409f2018-02-07 20:45:39 +00009554 if (!S.getLangOpts().CPlusPlus) {
9555 // Avoid warning about comparison of integers with different signs when
9556 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
9557 // the type of `E`.
9558 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
9559 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
9560 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
9561 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
9562 }
9563
John McCallcc7e5bf2010-05-06 08:58:33 +00009564 // Check to see if one of the (unmodified) operands is of different
9565 // signedness.
9566 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00009567 if (LHS->getType()->hasSignedIntegerRepresentation()) {
9568 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00009569 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00009570 signedOperand = LHS;
9571 unsignedOperand = RHS;
9572 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
9573 signedOperand = RHS;
9574 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00009575 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00009576 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00009577 }
9578
John McCallcc7e5bf2010-05-06 08:58:33 +00009579 // Otherwise, calculate the effective range of the signed operand.
9580 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00009581
John McCallcc7e5bf2010-05-06 08:58:33 +00009582 // Go ahead and analyze implicit conversions in the operands. Note
9583 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00009584 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
9585 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00009586
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009587 // If the signed range is non-negative, -Wsign-compare won't fire.
John McCallcc7e5bf2010-05-06 08:58:33 +00009588 if (signedRange.NonNegative)
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009589 return;
John McCallca01b222010-01-04 23:21:16 +00009590
9591 // For (in)equality comparisons, if the unsigned operand is a
9592 // constant which cannot collide with a overflowed signed operand,
9593 // then reinterpreting the signed operand as unsigned will not
9594 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00009595 if (E->isEqualityOp()) {
9596 unsigned comparisonWidth = S.Context.getIntWidth(T);
9597 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00009598
John McCallcc7e5bf2010-05-06 08:58:33 +00009599 // We should never be unable to prove that the unsigned operand is
9600 // non-negative.
9601 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
9602
9603 if (unsignedRange.Width < comparisonWidth)
9604 return;
9605 }
9606
Douglas Gregorbfb4a212012-05-01 01:53:49 +00009607 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
9608 S.PDiag(diag::warn_mixed_sign_comparison)
9609 << LHS->getType() << RHS->getType()
9610 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00009611}
9612
John McCall1f425642010-11-11 03:21:53 +00009613/// Analyzes an attempt to assign the given value to a bitfield.
9614///
9615/// Returns true if there was something fishy about the attempt.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009616static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
9617 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00009618 assert(Bitfield->isBitField());
9619 if (Bitfield->isInvalidDecl())
9620 return false;
9621
John McCalldeebbcf2010-11-11 05:33:51 +00009622 // White-list bool bitfields.
Reid Klecknerad425622016-11-16 23:40:00 +00009623 QualType BitfieldType = Bitfield->getType();
9624 if (BitfieldType->isBooleanType())
9625 return false;
9626
9627 if (BitfieldType->isEnumeralType()) {
9628 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
9629 // If the underlying enum type was not explicitly specified as an unsigned
9630 // type and the enum contain only positive values, MSVC++ will cause an
9631 // inconsistency by storing this as a signed type.
9632 if (S.getLangOpts().CPlusPlus11 &&
9633 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
9634 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
9635 BitfieldEnumDecl->getNumNegativeBits() == 0) {
9636 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
9637 << BitfieldEnumDecl->getNameAsString();
9638 }
9639 }
9640
John McCalldeebbcf2010-11-11 05:33:51 +00009641 if (Bitfield->getType()->isBooleanType())
9642 return false;
9643
Douglas Gregor789adec2011-02-04 13:09:01 +00009644 // Ignore value- or type-dependent expressions.
9645 if (Bitfield->getBitWidth()->isValueDependent() ||
9646 Bitfield->getBitWidth()->isTypeDependent() ||
9647 Init->isValueDependent() ||
9648 Init->isTypeDependent())
9649 return false;
9650
John McCall1f425642010-11-11 03:21:53 +00009651 Expr *OriginalInit = Init->IgnoreParenImpCasts();
Reid Kleckner329f24d2017-03-14 18:01:02 +00009652 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00009653
Richard Smith5fab0c92011-12-28 19:48:30 +00009654 llvm::APSInt Value;
Reid Kleckner329f24d2017-03-14 18:01:02 +00009655 if (!OriginalInit->EvaluateAsInt(Value, S.Context,
9656 Expr::SE_AllowSideEffects)) {
9657 // The RHS is not constant. If the RHS has an enum type, make sure the
9658 // bitfield is wide enough to hold all the values of the enum without
9659 // truncation.
9660 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
9661 EnumDecl *ED = EnumTy->getDecl();
9662 bool SignedBitfield = BitfieldType->isSignedIntegerType();
9663
9664 // Enum types are implicitly signed on Windows, so check if there are any
9665 // negative enumerators to see if the enum was intended to be signed or
9666 // not.
9667 bool SignedEnum = ED->getNumNegativeBits() > 0;
9668
9669 // Check for surprising sign changes when assigning enum values to a
9670 // bitfield of different signedness. If the bitfield is signed and we
9671 // have exactly the right number of bits to store this unsigned enum,
9672 // suggest changing the enum to an unsigned type. This typically happens
9673 // on Windows where unfixed enums always use an underlying type of 'int'.
9674 unsigned DiagID = 0;
9675 if (SignedEnum && !SignedBitfield) {
9676 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
9677 } else if (SignedBitfield && !SignedEnum &&
9678 ED->getNumPositiveBits() == FieldWidth) {
9679 DiagID = diag::warn_signed_bitfield_enum_conversion;
9680 }
9681
9682 if (DiagID) {
9683 S.Diag(InitLoc, DiagID) << Bitfield << ED;
9684 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
9685 SourceRange TypeRange =
9686 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
9687 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
9688 << SignedEnum << TypeRange;
9689 }
9690
9691 // Compute the required bitwidth. If the enum has negative values, we need
9692 // one more bit than the normal number of positive bits to represent the
9693 // sign bit.
9694 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
9695 ED->getNumNegativeBits())
9696 : ED->getNumPositiveBits();
9697
9698 // Check the bitwidth.
9699 if (BitsNeeded > FieldWidth) {
9700 Expr *WidthExpr = Bitfield->getBitWidth();
9701 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
9702 << Bitfield << ED;
9703 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
9704 << BitsNeeded << ED << WidthExpr->getSourceRange();
9705 }
9706 }
9707
John McCall1f425642010-11-11 03:21:53 +00009708 return false;
Reid Kleckner329f24d2017-03-14 18:01:02 +00009709 }
John McCall1f425642010-11-11 03:21:53 +00009710
John McCall1f425642010-11-11 03:21:53 +00009711 unsigned OriginalWidth = Value.getBitWidth();
John McCall1f425642010-11-11 03:21:53 +00009712
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00009713 if (!Value.isSigned() || Value.isNegative())
Richard Trieu7561ed02016-08-05 02:39:30 +00009714 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00009715 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
9716 OriginalWidth = Value.getMinSignedBits();
Richard Trieu7561ed02016-08-05 02:39:30 +00009717
John McCall1f425642010-11-11 03:21:53 +00009718 if (OriginalWidth <= FieldWidth)
9719 return false;
9720
Eli Friedmanc267a322012-01-26 23:11:39 +00009721 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00009722 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Reid Klecknerad425622016-11-16 23:40:00 +00009723 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00009724
Eli Friedmanc267a322012-01-26 23:11:39 +00009725 // Check whether the stored value is equal to the original value.
9726 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00009727 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00009728 return false;
9729
Eli Friedmanc267a322012-01-26 23:11:39 +00009730 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00009731 // therefore don't strictly fit into a signed bitfield of width 1.
9732 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00009733 return false;
9734
John McCall1f425642010-11-11 03:21:53 +00009735 std::string PrettyValue = Value.toString(10);
9736 std::string PrettyTrunc = TruncatedValue.toString(10);
9737
9738 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
9739 << PrettyValue << PrettyTrunc << OriginalInit->getType()
9740 << Init->getSourceRange();
9741
9742 return true;
9743}
9744
John McCalld2a53122010-11-09 23:24:47 +00009745/// Analyze the given simple or compound assignment for warning-worthy
9746/// operations.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009747static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00009748 // Just recurse on the LHS.
9749 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9750
9751 // We want to recurse on the RHS as normal unless we're assigning to
9752 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00009753 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009754 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00009755 E->getOperatorLoc())) {
9756 // Recurse, ignoring any implicit conversions on the RHS.
9757 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
9758 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00009759 }
9760 }
9761
9762 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9763}
9764
John McCall263a48b2010-01-04 23:31:57 +00009765/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009766static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
9767 SourceLocation CContext, unsigned diag,
9768 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00009769 if (pruneControlFlow) {
9770 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9771 S.PDiag(diag)
9772 << SourceType << T << E->getSourceRange()
9773 << SourceRange(CContext));
9774 return;
9775 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00009776 S.Diag(E->getExprLoc(), diag)
9777 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
9778}
9779
Chandler Carruth7f3654f2011-04-05 06:47:57 +00009780/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009781static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
9782 SourceLocation CContext,
9783 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00009784 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00009785}
9786
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +00009787/// Analyze the given compound assignment for the possible losing of
9788/// floating-point precision.
9789static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
9790 assert(isa<CompoundAssignOperator>(E) &&
9791 "Must be compound assignment operation");
9792 // Recurse on the LHS and RHS in here
9793 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9794 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9795
9796 // Now check the outermost expression
9797 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
9798 const auto *RBT = cast<CompoundAssignOperator>(E)
9799 ->getComputationResultType()
9800 ->getAs<BuiltinType>();
9801
9802 // If both source and target are floating points.
9803 if (ResultBT && ResultBT->isFloatingPoint() && RBT && RBT->isFloatingPoint())
9804 // Builtin FP kinds are ordered by increasing FP rank.
9805 if (ResultBT->getKind() < RBT->getKind())
9806 // We don't want to warn for system macro.
9807 if (!S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
9808 // warn about dropping FP rank.
9809 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(),
9810 E->getOperatorLoc(),
9811 diag::warn_impcast_float_result_precision);
9812}
Richard Trieube234c32016-04-21 21:04:55 +00009813
9814/// Diagnose an implicit cast from a floating point value to an integer value.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009815static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
9816 SourceLocation CContext) {
Richard Trieube234c32016-04-21 21:04:55 +00009817 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
Richard Smith51ec0cf2017-02-21 01:17:38 +00009818 const bool PruneWarnings = S.inTemplateInstantiation();
Richard Trieube234c32016-04-21 21:04:55 +00009819
9820 Expr *InnerE = E->IgnoreParenImpCasts();
9821 // We also want to warn on, e.g., "int i = -1.234"
9822 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
9823 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
9824 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
9825
9826 const bool IsLiteral =
9827 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
9828
9829 llvm::APFloat Value(0.0);
9830 bool IsConstant =
9831 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
9832 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00009833 return DiagnoseImpCast(S, E, T, CContext,
9834 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00009835 }
9836
Chandler Carruth016ef402011-04-10 08:36:24 +00009837 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00009838
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00009839 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
9840 T->hasUnsignedIntegerRepresentation());
Erich Keanea4c48c62018-05-08 21:26:21 +00009841 llvm::APFloat::opStatus Result = Value.convertToInteger(
9842 IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
9843
9844 if (Result == llvm::APFloat::opOK && isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00009845 if (IsLiteral) return;
9846 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
9847 PruneWarnings);
9848 }
9849
Erich Keanea4c48c62018-05-08 21:26:21 +00009850 // Conversion of a floating-point value to a non-bool integer where the
9851 // integral part cannot be represented by the integer type is undefined.
9852 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
9853 return DiagnoseImpCast(
9854 S, E, T, CContext,
9855 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
Richard Trieua2b8fe62018-05-14 23:21:48 +00009856 : diag::warn_impcast_float_to_integer_out_of_range,
9857 PruneWarnings);
Erich Keanea4c48c62018-05-08 21:26:21 +00009858
Richard Trieube234c32016-04-21 21:04:55 +00009859 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00009860 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00009861 // Warn on floating point literal to integer.
9862 DiagID = diag::warn_impcast_literal_float_to_integer;
9863 } else if (IntegerValue == 0) {
9864 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
9865 return DiagnoseImpCast(S, E, T, CContext,
9866 diag::warn_impcast_float_integer, PruneWarnings);
9867 }
9868 // Warn on non-zero to zero conversion.
9869 DiagID = diag::warn_impcast_float_to_integer_zero;
9870 } else {
9871 if (IntegerValue.isUnsigned()) {
9872 if (!IntegerValue.isMaxValue()) {
9873 return DiagnoseImpCast(S, E, T, CContext,
9874 diag::warn_impcast_float_integer, PruneWarnings);
9875 }
9876 } else { // IntegerValue.isSigned()
9877 if (!IntegerValue.isMaxSignedValue() &&
9878 !IntegerValue.isMinSignedValue()) {
9879 return DiagnoseImpCast(S, E, T, CContext,
9880 diag::warn_impcast_float_integer, PruneWarnings);
9881 }
9882 }
9883 // Warn on evaluatable floating point expression to integer conversion.
9884 DiagID = diag::warn_impcast_float_to_integer;
9885 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009886
Eli Friedman07185912013-08-29 23:44:43 +00009887 // FIXME: Force the precision of the source value down so we don't print
9888 // digits which are usually useless (we don't really care here if we
9889 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
9890 // would automatically print the shortest representation, but it's a bit
9891 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00009892 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00009893 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
9894 precision = (precision * 59 + 195) / 196;
9895 Value.toString(PrettySourceValue, precision);
9896
David Blaikie9b88cc02012-05-15 17:18:27 +00009897 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00009898 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00009899 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00009900 else
David Blaikie9b88cc02012-05-15 17:18:27 +00009901 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00009902
Richard Trieube234c32016-04-21 21:04:55 +00009903 if (PruneWarnings) {
9904 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9905 S.PDiag(DiagID)
9906 << E->getType() << T.getUnqualifiedType()
9907 << PrettySourceValue << PrettyTargetValue
9908 << E->getSourceRange() << SourceRange(CContext));
9909 } else {
9910 S.Diag(E->getExprLoc(), DiagID)
9911 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
9912 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
9913 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009914}
9915
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009916static std::string PrettyPrintInRange(const llvm::APSInt &Value,
9917 IntRange Range) {
John McCall18a2c2c2010-11-09 22:22:12 +00009918 if (!Range.Width) return "0";
9919
9920 llvm::APSInt ValueInRange = Value;
9921 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00009922 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00009923 return ValueInRange.toString(10);
9924}
9925
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009926static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009927 if (!isa<ImplicitCastExpr>(Ex))
9928 return false;
9929
9930 Expr *InnerE = Ex->IgnoreParenImpCasts();
9931 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
9932 const Type *Source =
9933 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
9934 if (Target->isDependentType())
9935 return false;
9936
9937 const BuiltinType *FloatCandidateBT =
9938 dyn_cast<BuiltinType>(ToBool ? Source : Target);
9939 const Type *BoolCandidateType = ToBool ? Target : Source;
9940
9941 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
9942 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
9943}
9944
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009945static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
9946 SourceLocation CC) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009947 unsigned NumArgs = TheCall->getNumArgs();
9948 for (unsigned i = 0; i < NumArgs; ++i) {
9949 Expr *CurrA = TheCall->getArg(i);
9950 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
9951 continue;
9952
9953 bool IsSwapped = ((i > 0) &&
9954 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
9955 IsSwapped |= ((i < (NumArgs - 1)) &&
9956 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
9957 if (IsSwapped) {
9958 // Warn on this floating-point to bool conversion.
9959 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
9960 CurrA->getType(), CC,
9961 diag::warn_impcast_floating_point_to_bool);
9962 }
9963 }
9964}
9965
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009966static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
9967 SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00009968 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
9969 E->getExprLoc()))
9970 return;
9971
Richard Trieu09d6b802016-01-08 23:35:06 +00009972 // Don't warn on functions which have return type nullptr_t.
9973 if (isa<CallExpr>(E))
9974 return;
9975
Richard Trieu5b993502014-10-15 03:42:06 +00009976 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
9977 const Expr::NullPointerConstantKind NullKind =
9978 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
9979 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
9980 return;
9981
9982 // Return if target type is a safe conversion.
9983 if (T->isAnyPointerType() || T->isBlockPointerType() ||
9984 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
9985 return;
9986
9987 SourceLocation Loc = E->getSourceRange().getBegin();
9988
Richard Trieu0a5e1662016-02-13 00:58:53 +00009989 // Venture through the macro stacks to get to the source of macro arguments.
9990 // The new location is a better location than the complete location that was
9991 // passed in.
George Karpenkov441e8fd2018-02-09 23:30:07 +00009992 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
9993 CC = S.SourceMgr.getTopMacroCallerLoc(CC);
Richard Trieu0a5e1662016-02-13 00:58:53 +00009994
Richard Trieu5b993502014-10-15 03:42:06 +00009995 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00009996 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
9997 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
9998 Loc, S.SourceMgr, S.getLangOpts());
9999 if (MacroName == "NULL")
Richard Smithb5f81712018-04-30 05:25:48 +000010000 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
Richard Trieu5b993502014-10-15 03:42:06 +000010001 }
10002
10003 // Only warn if the null and context location are in the same macro expansion.
10004 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
10005 return;
10006
10007 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010008 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
Richard Trieu5b993502014-10-15 03:42:06 +000010009 << FixItHint::CreateReplacement(Loc,
10010 S.getFixItZeroLiteralForType(T, Loc));
10011}
10012
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010013static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
10014 ObjCArrayLiteral *ArrayLiteral);
10015
10016static void
10017checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
10018 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +000010019
10020/// Check a single element within a collection literal against the
10021/// target element type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010022static void checkObjCCollectionLiteralElement(Sema &S,
10023 QualType TargetElementType,
10024 Expr *Element,
10025 unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +000010026 // Skip a bitcast to 'id' or qualified 'id'.
10027 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
10028 if (ICE->getCastKind() == CK_BitCast &&
10029 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
10030 Element = ICE->getSubExpr();
10031 }
10032
10033 QualType ElementType = Element->getType();
10034 ExprResult ElementResult(Element);
10035 if (ElementType->getAs<ObjCObjectPointerType>() &&
10036 S.CheckSingleAssignmentConstraints(TargetElementType,
10037 ElementResult,
10038 false, false)
10039 != Sema::Compatible) {
10040 S.Diag(Element->getLocStart(),
10041 diag::warn_objc_collection_literal_element)
10042 << ElementType << ElementKind << TargetElementType
10043 << Element->getSourceRange();
10044 }
10045
10046 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
10047 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
10048 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
10049 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
10050}
10051
10052/// Check an Objective-C array literal being converted to the given
10053/// target type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010054static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
10055 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +000010056 if (!S.NSArrayDecl)
10057 return;
10058
10059 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
10060 if (!TargetObjCPtr)
10061 return;
10062
10063 if (TargetObjCPtr->isUnspecialized() ||
10064 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
10065 != S.NSArrayDecl->getCanonicalDecl())
10066 return;
10067
10068 auto TypeArgs = TargetObjCPtr->getTypeArgs();
10069 if (TypeArgs.size() != 1)
10070 return;
10071
10072 QualType TargetElementType = TypeArgs[0];
10073 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
10074 checkObjCCollectionLiteralElement(S, TargetElementType,
10075 ArrayLiteral->getElement(I),
10076 0);
10077 }
10078}
10079
10080/// Check an Objective-C dictionary literal being converted to the given
10081/// target type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010082static void
10083checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
10084 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +000010085 if (!S.NSDictionaryDecl)
10086 return;
10087
10088 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
10089 if (!TargetObjCPtr)
10090 return;
10091
10092 if (TargetObjCPtr->isUnspecialized() ||
10093 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
10094 != S.NSDictionaryDecl->getCanonicalDecl())
10095 return;
10096
10097 auto TypeArgs = TargetObjCPtr->getTypeArgs();
10098 if (TypeArgs.size() != 2)
10099 return;
10100
10101 QualType TargetKeyType = TypeArgs[0];
10102 QualType TargetObjectType = TypeArgs[1];
10103 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
10104 auto Element = DictionaryLiteral->getKeyValueElement(I);
10105 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
10106 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
10107 }
10108}
10109
Richard Trieufc404c72016-02-05 23:02:38 +000010110// Helper function to filter out cases for constant width constant conversion.
10111// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010112static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
10113 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +000010114 // If initializing from a constant, and the constant starts with '0',
10115 // then it is a binary, octal, or hexadecimal. Allow these constants
10116 // to fill all the bits, even if there is a sign change.
10117 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
10118 const char FirstLiteralCharacter =
10119 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
10120 if (FirstLiteralCharacter == '0')
10121 return false;
10122 }
10123
10124 // If the CC location points to a '{', and the type is char, then assume
10125 // assume it is an array initialization.
10126 if (CC.isValid() && T->isCharType()) {
10127 const char FirstContextCharacter =
10128 S.getSourceManager().getCharacterData(CC)[0];
10129 if (FirstContextCharacter == '{')
10130 return false;
10131 }
10132
10133 return true;
10134}
10135
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010136static void
10137CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
10138 bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010139 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +000010140
John McCallcc7e5bf2010-05-06 08:58:33 +000010141 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
10142 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
10143 if (Source == Target) return;
10144 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +000010145
Chandler Carruthc22845a2011-07-26 05:40:03 +000010146 // If the conversion context location is invalid don't complain. We also
10147 // don't want to emit a warning if the issue occurs from the expansion of
10148 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
10149 // delay this check as long as possible. Once we detect we are in that
10150 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010151 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +000010152 return;
10153
Richard Trieu021baa32011-09-23 20:10:00 +000010154 // Diagnose implicit casts to bool.
10155 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
10156 if (isa<StringLiteral>(E))
10157 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +000010158 // and expressions, for instance, assert(0 && "error here"), are
10159 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +000010160 return DiagnoseImpCast(S, E, T, CC,
10161 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +000010162 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
10163 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
10164 // This covers the literal expressions that evaluate to Objective-C
10165 // objects.
10166 return DiagnoseImpCast(S, E, T, CC,
10167 diag::warn_impcast_objective_c_literal_to_bool);
10168 }
Richard Trieu3bb8b562014-02-26 02:36:06 +000010169 if (Source->isPointerType() || Source->canDecayToPointerType()) {
10170 // Warn on pointer to bool conversion that is always true.
10171 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
10172 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +000010173 }
Richard Trieu021baa32011-09-23 20:10:00 +000010174 }
John McCall263a48b2010-01-04 23:31:57 +000010175
Douglas Gregor5054cb02015-07-07 03:58:22 +000010176 // Check implicit casts from Objective-C collection literals to specialized
10177 // collection types, e.g., NSArray<NSString *> *.
10178 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
10179 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
10180 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
10181 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
10182
John McCall263a48b2010-01-04 23:31:57 +000010183 // Strip vector types.
10184 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010185 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010186 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010187 return;
John McCallacf0ee52010-10-08 02:01:28 +000010188 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010189 }
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000010190
Chris Lattneree7286f2011-06-14 04:51:15 +000010191 // If the vector cast is cast between two vectors of the same size, it is
10192 // a bitcast, not a conversion.
10193 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
10194 return;
John McCall263a48b2010-01-04 23:31:57 +000010195
10196 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
10197 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
10198 }
Stephen Canon3ba640d2014-04-03 10:33:25 +000010199 if (auto VecTy = dyn_cast<VectorType>(Target))
10200 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +000010201
10202 // Strip complex types.
10203 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010204 if (!isa<ComplexType>(Target)) {
Tim Northover02416372017-08-08 23:18:05 +000010205 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010206 return;
10207
Tim Northover02416372017-08-08 23:18:05 +000010208 return DiagnoseImpCast(S, E, T, CC,
10209 S.getLangOpts().CPlusPlus
10210 ? diag::err_impcast_complex_scalar
10211 : diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010212 }
John McCall263a48b2010-01-04 23:31:57 +000010213
10214 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
10215 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
10216 }
10217
10218 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
10219 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
10220
10221 // If the source is floating point...
10222 if (SourceBT && SourceBT->isFloatingPoint()) {
10223 // ...and the target is floating point...
10224 if (TargetBT && TargetBT->isFloatingPoint()) {
10225 // ...then warn if we're dropping FP rank.
10226
10227 // Builtin FP kinds are ordered by increasing FP rank.
10228 if (SourceBT->getKind() > TargetBT->getKind()) {
10229 // Don't warn about float constants that are precisely
10230 // representable in the target type.
10231 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +000010232 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +000010233 // Value might be a float, a float vector, or a float complex.
10234 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +000010235 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
10236 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +000010237 return;
10238 }
10239
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010240 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010241 return;
10242
John McCallacf0ee52010-10-08 02:01:28 +000010243 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +000010244 }
10245 // ... or possibly if we're increasing rank, too
10246 else if (TargetBT->getKind() > SourceBT->getKind()) {
10247 if (S.SourceMgr.isInSystemMacro(CC))
10248 return;
10249
10250 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +000010251 }
10252 return;
10253 }
10254
Richard Trieube234c32016-04-21 21:04:55 +000010255 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +000010256 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010257 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010258 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +000010259
Richard Trieube234c32016-04-21 21:04:55 +000010260 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +000010261 }
John McCall263a48b2010-01-04 23:31:57 +000010262
Richard Smith54894fd2015-12-30 01:06:52 +000010263 // Detect the case where a call result is converted from floating-point to
10264 // to bool, and the final argument to the call is converted from bool, to
10265 // discover this typo:
10266 //
10267 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
10268 //
10269 // FIXME: This is an incredibly special case; is there some more general
10270 // way to detect this class of misplaced-parentheses bug?
10271 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010272 // Check last argument of function call to see if it is an
10273 // implicit cast from a type matching the type the result
10274 // is being cast to.
10275 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +000010276 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010277 Expr *LastA = CEx->getArg(NumArgs - 1);
10278 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +000010279 if (isa<ImplicitCastExpr>(LastA) &&
10280 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010281 // Warn on this floating-point to bool conversion
10282 DiagnoseImpCast(S, E, T, CC,
10283 diag::warn_impcast_floating_point_to_bool);
10284 }
10285 }
10286 }
John McCall263a48b2010-01-04 23:31:57 +000010287 return;
10288 }
10289
Richard Trieu5b993502014-10-15 03:42:06 +000010290 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +000010291
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000010292 S.DiscardMisalignedMemberAddress(Target, E);
10293
David Blaikie9366d2b2012-06-19 21:19:06 +000010294 if (!Source->isIntegerType() || !Target->isIntegerType())
10295 return;
10296
David Blaikie7555b6a2012-05-15 16:56:36 +000010297 // TODO: remove this early return once the false positives for constant->bool
10298 // in templates, macros, etc, are reduced or removed.
10299 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
10300 return;
10301
John McCallcc7e5bf2010-05-06 08:58:33 +000010302 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +000010303 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +000010304
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010305 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +000010306 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010307 // TODO: this should happen for bitfield stores, too.
10308 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +000010309 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010310 if (S.SourceMgr.isInSystemMacro(CC))
10311 return;
10312
John McCall18a2c2c2010-11-09 22:22:12 +000010313 std::string PrettySourceValue = Value.toString(10);
10314 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010315
Ted Kremenek33ba9952011-10-22 02:37:33 +000010316 S.DiagRuntimeBehavior(E->getExprLoc(), E,
10317 S.PDiag(diag::warn_impcast_integer_precision_constant)
10318 << PrettySourceValue << PrettyTargetValue
10319 << E->getType() << T << E->getSourceRange()
10320 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +000010321 return;
10322 }
10323
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010324 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
10325 if (S.SourceMgr.isInSystemMacro(CC))
10326 return;
10327
David Blaikie9455da02012-04-12 22:40:54 +000010328 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +000010329 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
10330 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +000010331 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +000010332 }
10333
Richard Trieudcb55572016-01-29 23:51:16 +000010334 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
10335 SourceRange.NonNegative && Source->isSignedIntegerType()) {
10336 // Warn when doing a signed to signed conversion, warn if the positive
10337 // source value is exactly the width of the target type, which will
10338 // cause a negative value to be stored.
10339
10340 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +000010341 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
10342 !S.SourceMgr.isInSystemMacro(CC)) {
10343 if (isSameWidthConstantConversion(S, E, T, CC)) {
10344 std::string PrettySourceValue = Value.toString(10);
10345 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +000010346
Richard Trieufc404c72016-02-05 23:02:38 +000010347 S.DiagRuntimeBehavior(
10348 E->getExprLoc(), E,
10349 S.PDiag(diag::warn_impcast_integer_precision_constant)
10350 << PrettySourceValue << PrettyTargetValue << E->getType() << T
10351 << E->getSourceRange() << clang::SourceRange(CC));
10352 return;
Richard Trieudcb55572016-01-29 23:51:16 +000010353 }
10354 }
Richard Trieufc404c72016-02-05 23:02:38 +000010355
Richard Trieudcb55572016-01-29 23:51:16 +000010356 // Fall through for non-constants to give a sign conversion warning.
10357 }
10358
John McCallcc7e5bf2010-05-06 08:58:33 +000010359 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
10360 (!TargetRange.NonNegative && SourceRange.NonNegative &&
10361 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010362 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010363 return;
10364
John McCallcc7e5bf2010-05-06 08:58:33 +000010365 unsigned DiagID = diag::warn_impcast_integer_sign;
10366
10367 // Traditionally, gcc has warned about this under -Wsign-compare.
10368 // We also want to warn about it in -Wconversion.
10369 // So if -Wconversion is off, use a completely identical diagnostic
10370 // in the sign-compare group.
10371 // The conditional-checking code will
10372 if (ICContext) {
10373 DiagID = diag::warn_impcast_integer_sign_conditional;
10374 *ICContext = true;
10375 }
10376
John McCallacf0ee52010-10-08 02:01:28 +000010377 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +000010378 }
10379
Douglas Gregora78f1932011-02-22 02:45:07 +000010380 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +000010381 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
10382 // type, to give us better diagnostics.
10383 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +000010384 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +000010385 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10386 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
10387 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
10388 SourceType = S.Context.getTypeDeclType(Enum);
10389 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
10390 }
10391 }
10392
Douglas Gregora78f1932011-02-22 02:45:07 +000010393 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
10394 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +000010395 if (SourceEnum->getDecl()->hasNameForLinkage() &&
10396 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010397 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010398 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010399 return;
10400
Douglas Gregor364f7db2011-03-12 00:14:31 +000010401 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +000010402 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010403 }
John McCall263a48b2010-01-04 23:31:57 +000010404}
10405
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010406static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
10407 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +000010408
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010409static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
10410 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010411 E = E->IgnoreParenImpCasts();
10412
10413 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +000010414 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +000010415
John McCallacf0ee52010-10-08 02:01:28 +000010416 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010417 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +000010418 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +000010419}
10420
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010421static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
10422 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +000010423 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +000010424
10425 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +000010426 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
10427 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +000010428
10429 // If -Wconversion would have warned about either of the candidates
10430 // for a signedness conversion to the context type...
10431 if (!Suspicious) return;
10432
10433 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010434 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +000010435 return;
10436
John McCallcc7e5bf2010-05-06 08:58:33 +000010437 // ...then check whether it would have warned about either of the
10438 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +000010439 if (E->getType() == T) return;
10440
10441 Suspicious = false;
10442 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
10443 E->getType(), CC, &Suspicious);
10444 if (!Suspicious)
10445 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +000010446 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +000010447}
10448
Richard Trieu65724892014-11-15 06:37:39 +000010449/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10450/// Input argument E is a logical expression.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010451static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +000010452 if (S.getLangOpts().Bool)
10453 return;
10454 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
10455}
10456
John McCallcc7e5bf2010-05-06 08:58:33 +000010457/// AnalyzeImplicitConversions - Find and report any interesting
10458/// implicit conversions in the given expression. There are a couple
10459/// of competing diagnostics here, -Wconversion and -Wsign-compare.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010460static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
10461 SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +000010462 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +000010463 Expr *E = OrigE->IgnoreParenImpCasts();
10464
Douglas Gregor6e8da6a2011-10-10 17:38:18 +000010465 if (E->isTypeDependent() || E->isValueDependent())
10466 return;
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000010467
John McCallcc7e5bf2010-05-06 08:58:33 +000010468 // For conditional operators, we analyze the arguments as if they
10469 // were being fed directly into the output.
10470 if (isa<ConditionalOperator>(E)) {
10471 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +000010472 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +000010473 return;
10474 }
10475
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010476 // Check implicit argument conversions for function calls.
10477 if (CallExpr *Call = dyn_cast<CallExpr>(E))
10478 CheckImplicitArgumentConversions(S, Call, CC);
10479
John McCallcc7e5bf2010-05-06 08:58:33 +000010480 // Go ahead and check any implicit conversions we might have skipped.
10481 // The non-canonical typecheck is just an optimization;
10482 // CheckImplicitConversion will filter out dead implicit conversions.
10483 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +000010484 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010485
10486 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +000010487
10488 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
10489 // The bound subexpressions in a PseudoObjectExpr are not reachable
10490 // as transitive children.
10491 // FIXME: Use a more uniform representation for this.
10492 for (auto *SE : POE->semantics())
10493 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
10494 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +000010495 }
Richard Smithd7bed4d2015-11-22 02:57:17 +000010496
John McCallcc7e5bf2010-05-06 08:58:33 +000010497 // Skip past explicit casts.
10498 if (isa<ExplicitCastExpr>(E)) {
10499 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +000010500 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010501 }
10502
John McCalld2a53122010-11-09 23:24:47 +000010503 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10504 // Do a somewhat different check with comparison operators.
10505 if (BO->isComparisonOp())
10506 return AnalyzeComparison(S, BO);
10507
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010508 // And with simple assignments.
10509 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +000010510 return AnalyzeAssignment(S, BO);
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000010511 // And with compound assignments.
10512 if (BO->isAssignmentOp())
10513 return AnalyzeCompoundAssignment(S, BO);
John McCalld2a53122010-11-09 23:24:47 +000010514 }
John McCallcc7e5bf2010-05-06 08:58:33 +000010515
10516 // These break the otherwise-useful invariant below. Fortunately,
10517 // we don't really need to recurse into them, because any internal
10518 // expressions should have been analyzed already when they were
10519 // built into statements.
10520 if (isa<StmtExpr>(E)) return;
10521
10522 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +000010523 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +000010524
10525 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +000010526 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +000010527 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +000010528 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +000010529 for (Stmt *SubStmt : E->children()) {
10530 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +000010531 if (!ChildExpr)
10532 continue;
10533
Richard Trieu955231d2014-01-25 01:10:35 +000010534 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +000010535 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +000010536 // Ignore checking string literals that are in logical and operators.
10537 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +000010538 continue;
10539 AnalyzeImplicitConversions(S, ChildExpr, CC);
10540 }
Richard Trieu791b86e2014-11-19 06:08:18 +000010541
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000010542 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +000010543 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
10544 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +000010545 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +000010546
10547 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
10548 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +000010549 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000010550 }
Richard Trieu791b86e2014-11-19 06:08:18 +000010551
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000010552 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
10553 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +000010554 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010555}
10556
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +000010557/// Diagnose integer type and any valid implicit conversion to it.
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000010558static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
10559 // Taking into account implicit conversions,
10560 // allow any integer.
10561 if (!E->getType()->isIntegerType()) {
10562 S.Diag(E->getLocStart(),
10563 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
10564 return true;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010565 }
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000010566 // Potentially emit standard warnings for implicit conversions if enabled
10567 // using -Wconversion.
10568 CheckImplicitConversion(S, E, IntT, E->getLocStart());
10569 return false;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010570}
10571
Richard Trieuc1888e02014-06-28 23:25:37 +000010572// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
10573// Returns true when emitting a warning about taking the address of a reference.
10574static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +000010575 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +000010576 E = E->IgnoreParenImpCasts();
10577
10578 const FunctionDecl *FD = nullptr;
10579
10580 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10581 if (!DRE->getDecl()->getType()->isReferenceType())
10582 return false;
10583 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10584 if (!M->getMemberDecl()->getType()->isReferenceType())
10585 return false;
10586 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +000010587 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +000010588 return false;
10589 FD = Call->getDirectCallee();
10590 } else {
10591 return false;
10592 }
10593
10594 SemaRef.Diag(E->getExprLoc(), PD);
10595
10596 // If possible, point to location of function.
10597 if (FD) {
10598 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
10599 }
10600
10601 return true;
10602}
10603
Richard Trieu4cbff5c2014-08-08 22:41:43 +000010604// Returns true if the SourceLocation is expanded from any macro body.
10605// Returns false if the SourceLocation is invalid, is from not in a macro
10606// expansion, or is from expanded from a top-level macro argument.
10607static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
10608 if (Loc.isInvalid())
10609 return false;
10610
10611 while (Loc.isMacroID()) {
10612 if (SM.isMacroBodyExpansion(Loc))
10613 return true;
10614 Loc = SM.getImmediateMacroCallerLoc(Loc);
10615 }
10616
10617 return false;
10618}
10619
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010620/// Diagnose pointers that are always non-null.
Richard Trieu3bb8b562014-02-26 02:36:06 +000010621/// \param E the expression containing the pointer
10622/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
10623/// compared to a null pointer
10624/// \param IsEqual True when the comparison is equal to a null pointer
10625/// \param Range Extra SourceRange to highlight in the diagnostic
10626void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
10627 Expr::NullPointerConstantKind NullKind,
10628 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +000010629 if (!E)
10630 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010631
10632 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +000010633 if (E->getExprLoc().isMacroID()) {
10634 const SourceManager &SM = getSourceManager();
10635 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
10636 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +000010637 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +000010638 }
Richard Trieu3bb8b562014-02-26 02:36:06 +000010639 E = E->IgnoreImpCasts();
10640
10641 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
10642
Richard Trieuf7432752014-06-06 21:39:26 +000010643 if (isa<CXXThisExpr>(E)) {
10644 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
10645 : diag::warn_this_bool_conversion;
10646 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
10647 return;
10648 }
10649
Richard Trieu3bb8b562014-02-26 02:36:06 +000010650 bool IsAddressOf = false;
10651
10652 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10653 if (UO->getOpcode() != UO_AddrOf)
10654 return;
10655 IsAddressOf = true;
10656 E = UO->getSubExpr();
10657 }
10658
Richard Trieuc1888e02014-06-28 23:25:37 +000010659 if (IsAddressOf) {
10660 unsigned DiagID = IsCompare
10661 ? diag::warn_address_of_reference_null_compare
10662 : diag::warn_address_of_reference_bool_conversion;
10663 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
10664 << IsEqual;
10665 if (CheckForReference(*this, E, PD)) {
10666 return;
10667 }
10668 }
10669
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010670 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
10671 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +000010672 std::string Str;
10673 llvm::raw_string_ostream S(Str);
10674 E->printPretty(S, nullptr, getPrintingPolicy());
10675 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
10676 : diag::warn_cast_nonnull_to_bool;
10677 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
10678 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010679 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +000010680 };
10681
10682 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
10683 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
10684 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010685 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
10686 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000010687 return;
10688 }
10689 }
10690 }
10691
Richard Trieu3bb8b562014-02-26 02:36:06 +000010692 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +000010693 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010694 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
10695 D = R->getDecl();
10696 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10697 D = M->getMemberDecl();
10698 }
10699
10700 // Weak Decls can be null.
10701 if (!D || D->isWeak())
10702 return;
George Burgess IV850269a2015-12-08 22:02:00 +000010703
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010704 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +000010705 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
10706 if (getCurFunction() &&
10707 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010708 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
10709 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000010710 return;
10711 }
10712
10713 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +000010714 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +000010715 assert(ParamIter != FD->param_end());
10716 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
10717
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010718 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
10719 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010720 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +000010721 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010722 }
George Burgess IV850269a2015-12-08 22:02:00 +000010723
Joel E. Denny81508102018-03-13 14:51:22 +000010724 for (const ParamIdx &ArgNo : NonNull->args()) {
10725 if (ArgNo.getASTIndex() == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010726 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010727 return;
10728 }
George Burgess IV850269a2015-12-08 22:02:00 +000010729 }
10730 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010731 }
10732 }
George Burgess IV850269a2015-12-08 22:02:00 +000010733 }
10734
Richard Trieu3bb8b562014-02-26 02:36:06 +000010735 QualType T = D->getType();
10736 const bool IsArray = T->isArrayType();
10737 const bool IsFunction = T->isFunctionType();
10738
Richard Trieuc1888e02014-06-28 23:25:37 +000010739 // Address of function is used to silence the function warning.
10740 if (IsAddressOf && IsFunction) {
10741 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010742 }
10743
10744 // Found nothing.
10745 if (!IsAddressOf && !IsFunction && !IsArray)
10746 return;
10747
10748 // Pretty print the expression for the diagnostic.
10749 std::string Str;
10750 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +000010751 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +000010752
10753 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
10754 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +000010755 enum {
10756 AddressOf,
10757 FunctionPointer,
10758 ArrayPointer
10759 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010760 if (IsAddressOf)
10761 DiagType = AddressOf;
10762 else if (IsFunction)
10763 DiagType = FunctionPointer;
10764 else if (IsArray)
10765 DiagType = ArrayPointer;
10766 else
10767 llvm_unreachable("Could not determine diagnostic.");
10768 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
10769 << Range << IsEqual;
10770
10771 if (!IsFunction)
10772 return;
10773
10774 // Suggest '&' to silence the function warning.
10775 Diag(E->getExprLoc(), diag::note_function_warning_silence)
10776 << FixItHint::CreateInsertion(E->getLocStart(), "&");
10777
10778 // Check to see if '()' fixit should be emitted.
10779 QualType ReturnType;
10780 UnresolvedSet<4> NonTemplateOverloads;
10781 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
10782 if (ReturnType.isNull())
10783 return;
10784
10785 if (IsCompare) {
10786 // There are two cases here. If there is null constant, the only suggest
10787 // for a pointer return type. If the null is 0, then suggest if the return
10788 // type is a pointer or an integer type.
10789 if (!ReturnType->isPointerType()) {
10790 if (NullKind == Expr::NPCK_ZeroExpression ||
10791 NullKind == Expr::NPCK_ZeroLiteral) {
10792 if (!ReturnType->isIntegerType())
10793 return;
10794 } else {
10795 return;
10796 }
10797 }
10798 } else { // !IsCompare
10799 // For function to bool, only suggest if the function pointer has bool
10800 // return type.
10801 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
10802 return;
10803 }
10804 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +000010805 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +000010806}
10807
John McCallcc7e5bf2010-05-06 08:58:33 +000010808/// Diagnoses "dangerous" implicit conversions within the given
10809/// expression (which is a full expression). Implements -Wconversion
10810/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +000010811///
10812/// \param CC the "context" location of the implicit conversion, i.e.
10813/// the most location of the syntactic entity requiring the implicit
10814/// conversion
10815void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010816 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +000010817 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +000010818 return;
10819
10820 // Don't diagnose for value- or type-dependent expressions.
10821 if (E->isTypeDependent() || E->isValueDependent())
10822 return;
10823
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010824 // Check for array bounds violations in cases where the check isn't triggered
10825 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
10826 // ArraySubscriptExpr is on the RHS of a variable initialization.
10827 CheckArrayAccess(E);
10828
John McCallacf0ee52010-10-08 02:01:28 +000010829 // This is not the right CC for (e.g.) a variable initialization.
10830 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010831}
10832
Richard Trieu65724892014-11-15 06:37:39 +000010833/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10834/// Input argument E is a logical expression.
10835void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
10836 ::CheckBoolLikeConversion(*this, E, CC);
10837}
10838
Richard Smith9f7df0c2017-06-26 23:19:32 +000010839/// Diagnose when expression is an integer constant expression and its evaluation
10840/// results in integer overflow
10841void Sema::CheckForIntOverflow (Expr *E) {
10842 // Use a work list to deal with nested struct initializers.
10843 SmallVector<Expr *, 2> Exprs(1, E);
10844
10845 do {
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010846 Expr *OriginalE = Exprs.pop_back_val();
10847 Expr *E = OriginalE->IgnoreParenCasts();
Richard Smith9f7df0c2017-06-26 23:19:32 +000010848
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010849 if (isa<BinaryOperator>(E)) {
10850 E->EvaluateForOverflow(Context);
Richard Smith9f7df0c2017-06-26 23:19:32 +000010851 continue;
10852 }
10853
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010854 if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
Richard Smith9f7df0c2017-06-26 23:19:32 +000010855 Exprs.append(InitList->inits().begin(), InitList->inits().end());
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010856 else if (isa<ObjCBoxedExpr>(OriginalE))
10857 E->EvaluateForOverflow(Context);
10858 else if (auto Call = dyn_cast<CallExpr>(E))
10859 Exprs.append(Call->arg_begin(), Call->arg_end());
10860 else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
10861 Exprs.append(Message->arg_begin(), Message->arg_end());
Richard Smith9f7df0c2017-06-26 23:19:32 +000010862 } while (!Exprs.empty());
10863}
10864
Richard Smithc406cb72013-01-17 01:17:56 +000010865namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010866
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010867/// Visitor for expressions which looks for unsequenced operations on the
Richard Smithc406cb72013-01-17 01:17:56 +000010868/// same object.
10869class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010870 using Base = EvaluatedExprVisitor<SequenceChecker>;
Richard Smithe3dbfe02013-06-30 10:40:20 +000010871
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010872 /// A tree of sequenced regions within an expression. Two regions are
Richard Smithc406cb72013-01-17 01:17:56 +000010873 /// unsequenced if one is an ancestor or a descendent of the other. When we
10874 /// finish processing an expression with sequencing, such as a comma
10875 /// expression, we fold its tree nodes into its parent, since they are
10876 /// unsequenced with respect to nodes we will visit later.
10877 class SequenceTree {
10878 struct Value {
10879 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
10880 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +000010881 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +000010882 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010883 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +000010884
10885 public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010886 /// A region within an expression which may be sequenced with respect
Richard Smithc406cb72013-01-17 01:17:56 +000010887 /// to some other region.
10888 class Seq {
Richard Smithc406cb72013-01-17 01:17:56 +000010889 friend class SequenceTree;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010890
10891 unsigned Index = 0;
10892
10893 explicit Seq(unsigned N) : Index(N) {}
10894
Richard Smithc406cb72013-01-17 01:17:56 +000010895 public:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010896 Seq() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010897 };
10898
10899 SequenceTree() { Values.push_back(Value(0)); }
10900 Seq root() const { return Seq(0); }
10901
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010902 /// Create a new sequence of operations, which is an unsequenced
Richard Smithc406cb72013-01-17 01:17:56 +000010903 /// subset of \p Parent. This sequence of operations is sequenced with
10904 /// respect to other children of \p Parent.
10905 Seq allocate(Seq Parent) {
10906 Values.push_back(Value(Parent.Index));
10907 return Seq(Values.size() - 1);
10908 }
10909
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010910 /// Merge a sequence of operations into its parent.
Richard Smithc406cb72013-01-17 01:17:56 +000010911 void merge(Seq S) {
10912 Values[S.Index].Merged = true;
10913 }
10914
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010915 /// Determine whether two operations are unsequenced. This operation
Richard Smithc406cb72013-01-17 01:17:56 +000010916 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
10917 /// should have been merged into its parent as appropriate.
10918 bool isUnsequenced(Seq Cur, Seq Old) {
10919 unsigned C = representative(Cur.Index);
10920 unsigned Target = representative(Old.Index);
10921 while (C >= Target) {
10922 if (C == Target)
10923 return true;
10924 C = Values[C].Parent;
10925 }
10926 return false;
10927 }
10928
10929 private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010930 /// Pick a representative for a sequence.
Richard Smithc406cb72013-01-17 01:17:56 +000010931 unsigned representative(unsigned K) {
10932 if (Values[K].Merged)
10933 // Perform path compression as we go.
10934 return Values[K].Parent = representative(Values[K].Parent);
10935 return K;
10936 }
10937 };
10938
10939 /// An object for which we can track unsequenced uses.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010940 using Object = NamedDecl *;
Richard Smithc406cb72013-01-17 01:17:56 +000010941
10942 /// Different flavors of object usage which we track. We only track the
10943 /// least-sequenced usage of each kind.
10944 enum UsageKind {
10945 /// A read of an object. Multiple unsequenced reads are OK.
10946 UK_Use,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010947
Richard Smithc406cb72013-01-17 01:17:56 +000010948 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +000010949 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +000010950 UK_ModAsValue,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010951
Richard Smithc406cb72013-01-17 01:17:56 +000010952 /// A modification of an object which is not sequenced before the value
10953 /// computation of the expression, such as n++.
10954 UK_ModAsSideEffect,
10955
10956 UK_Count = UK_ModAsSideEffect + 1
10957 };
10958
10959 struct Usage {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010960 Expr *Use = nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000010961 SequenceTree::Seq Seq;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010962
10963 Usage() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010964 };
10965
10966 struct UsageInfo {
Richard Smithc406cb72013-01-17 01:17:56 +000010967 Usage Uses[UK_Count];
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010968
Richard Smithc406cb72013-01-17 01:17:56 +000010969 /// Have we issued a diagnostic for this variable already?
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010970 bool Diagnosed = false;
10971
10972 UsageInfo() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010973 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010974 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
Richard Smithc406cb72013-01-17 01:17:56 +000010975
10976 Sema &SemaRef;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010977
Richard Smithc406cb72013-01-17 01:17:56 +000010978 /// Sequenced regions within the expression.
10979 SequenceTree Tree;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010980
Richard Smithc406cb72013-01-17 01:17:56 +000010981 /// Declaration modifications and references which we have seen.
10982 UsageInfoMap UsageMap;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010983
Richard Smithc406cb72013-01-17 01:17:56 +000010984 /// The region we are currently within.
10985 SequenceTree::Seq Region;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010986
Richard Smithc406cb72013-01-17 01:17:56 +000010987 /// Filled in with declarations which were modified as a side-effect
10988 /// (that is, post-increment operations).
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010989 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
10990
Richard Smithd33f5202013-01-17 23:18:09 +000010991 /// Expressions to check later. We defer checking these to reduce
10992 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010993 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +000010994
10995 /// RAII object wrapping the visitation of a sequenced subexpression of an
10996 /// expression. At the end of this process, the side-effects of the evaluation
10997 /// become sequenced with respect to the value computation of the result, so
10998 /// we downgrade any UK_ModAsSideEffect within the evaluation to
10999 /// UK_ModAsValue.
11000 struct SequencedSubexpression {
11001 SequencedSubexpression(SequenceChecker &Self)
11002 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
11003 Self.ModAsSideEffect = &ModAsSideEffect;
11004 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011005
Richard Smithc406cb72013-01-17 01:17:56 +000011006 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +000011007 for (auto &M : llvm::reverse(ModAsSideEffect)) {
11008 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +000011009 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +000011010 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
11011 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +000011012 }
11013 Self.ModAsSideEffect = OldModAsSideEffect;
11014 }
11015
11016 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011017 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011018 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +000011019 };
11020
Richard Smith40238f02013-06-20 22:21:56 +000011021 /// RAII object wrapping the visitation of a subexpression which we might
11022 /// choose to evaluate as a constant. If any subexpression is evaluated and
11023 /// found to be non-constant, this allows us to suppress the evaluation of
11024 /// the outer expression.
11025 class EvaluationTracker {
11026 public:
11027 EvaluationTracker(SequenceChecker &Self)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011028 : Self(Self), Prev(Self.EvalTracker) {
Richard Smith40238f02013-06-20 22:21:56 +000011029 Self.EvalTracker = this;
11030 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011031
Richard Smith40238f02013-06-20 22:21:56 +000011032 ~EvaluationTracker() {
11033 Self.EvalTracker = Prev;
11034 if (Prev)
11035 Prev->EvalOK &= EvalOK;
11036 }
11037
11038 bool evaluate(const Expr *E, bool &Result) {
11039 if (!EvalOK || E->isValueDependent())
11040 return false;
11041 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
11042 return EvalOK;
11043 }
11044
11045 private:
11046 SequenceChecker &Self;
11047 EvaluationTracker *Prev;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011048 bool EvalOK = true;
11049 } *EvalTracker = nullptr;
Richard Smith40238f02013-06-20 22:21:56 +000011050
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011051 /// Find the object which is produced by the specified expression,
Richard Smithc406cb72013-01-17 01:17:56 +000011052 /// if any.
11053 Object getObject(Expr *E, bool Mod) const {
11054 E = E->IgnoreParenCasts();
11055 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
11056 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
11057 return getObject(UO->getSubExpr(), Mod);
11058 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11059 if (BO->getOpcode() == BO_Comma)
11060 return getObject(BO->getRHS(), Mod);
11061 if (Mod && BO->isAssignmentOp())
11062 return getObject(BO->getLHS(), Mod);
11063 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
11064 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
11065 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
11066 return ME->getMemberDecl();
11067 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11068 // FIXME: If this is a reference, map through to its value.
11069 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +000011070 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000011071 }
11072
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011073 /// Note that an object was modified or used by an expression.
Richard Smithc406cb72013-01-17 01:17:56 +000011074 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
11075 Usage &U = UI.Uses[UK];
11076 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
11077 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
11078 ModAsSideEffect->push_back(std::make_pair(O, U));
11079 U.Use = Ref;
11080 U.Seq = Region;
11081 }
11082 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011083
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011084 /// Check whether a modification or use conflicts with a prior usage.
Richard Smithc406cb72013-01-17 01:17:56 +000011085 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
11086 bool IsModMod) {
11087 if (UI.Diagnosed)
11088 return;
11089
11090 const Usage &U = UI.Uses[OtherKind];
11091 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
11092 return;
11093
11094 Expr *Mod = U.Use;
11095 Expr *ModOrUse = Ref;
11096 if (OtherKind == UK_Use)
11097 std::swap(Mod, ModOrUse);
11098
11099 SemaRef.Diag(Mod->getExprLoc(),
11100 IsModMod ? diag::warn_unsequenced_mod_mod
11101 : diag::warn_unsequenced_mod_use)
11102 << O << SourceRange(ModOrUse->getExprLoc());
11103 UI.Diagnosed = true;
11104 }
11105
11106 void notePreUse(Object O, Expr *Use) {
11107 UsageInfo &U = UsageMap[O];
11108 // Uses conflict with other modifications.
11109 checkUsage(O, U, Use, UK_ModAsValue, false);
11110 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011111
Richard Smithc406cb72013-01-17 01:17:56 +000011112 void notePostUse(Object O, Expr *Use) {
11113 UsageInfo &U = UsageMap[O];
11114 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
11115 addUsage(U, O, Use, UK_Use);
11116 }
11117
11118 void notePreMod(Object O, Expr *Mod) {
11119 UsageInfo &U = UsageMap[O];
11120 // Modifications conflict with other modifications and with uses.
11121 checkUsage(O, U, Mod, UK_ModAsValue, true);
11122 checkUsage(O, U, Mod, UK_Use, false);
11123 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011124
Richard Smithc406cb72013-01-17 01:17:56 +000011125 void notePostMod(Object O, Expr *Use, UsageKind UK) {
11126 UsageInfo &U = UsageMap[O];
11127 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
11128 addUsage(U, O, Use, UK);
11129 }
11130
11131public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011132 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011133 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
Richard Smithc406cb72013-01-17 01:17:56 +000011134 Visit(E);
11135 }
11136
11137 void VisitStmt(Stmt *S) {
11138 // Skip all statements which aren't expressions for now.
11139 }
11140
11141 void VisitExpr(Expr *E) {
11142 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +000011143 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +000011144 }
11145
11146 void VisitCastExpr(CastExpr *E) {
11147 Object O = Object();
11148 if (E->getCastKind() == CK_LValueToRValue)
11149 O = getObject(E->getSubExpr(), false);
11150
11151 if (O)
11152 notePreUse(O, E);
11153 VisitExpr(E);
11154 if (O)
11155 notePostUse(O, E);
11156 }
11157
11158 void VisitBinComma(BinaryOperator *BO) {
11159 // C++11 [expr.comma]p1:
11160 // Every value computation and side effect associated with the left
11161 // expression is sequenced before every value computation and side
11162 // effect associated with the right expression.
11163 SequenceTree::Seq LHS = Tree.allocate(Region);
11164 SequenceTree::Seq RHS = Tree.allocate(Region);
11165 SequenceTree::Seq OldRegion = Region;
11166
11167 {
11168 SequencedSubexpression SeqLHS(*this);
11169 Region = LHS;
11170 Visit(BO->getLHS());
11171 }
11172
11173 Region = RHS;
11174 Visit(BO->getRHS());
11175
11176 Region = OldRegion;
11177
11178 // Forget that LHS and RHS are sequenced. They are both unsequenced
11179 // with respect to other stuff.
11180 Tree.merge(LHS);
11181 Tree.merge(RHS);
11182 }
11183
11184 void VisitBinAssign(BinaryOperator *BO) {
11185 // The modification is sequenced after the value computation of the LHS
11186 // and RHS, so check it before inspecting the operands and update the
11187 // map afterwards.
11188 Object O = getObject(BO->getLHS(), true);
11189 if (!O)
11190 return VisitExpr(BO);
11191
11192 notePreMod(O, BO);
11193
11194 // C++11 [expr.ass]p7:
11195 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
11196 // only once.
11197 //
11198 // Therefore, for a compound assignment operator, O is considered used
11199 // everywhere except within the evaluation of E1 itself.
11200 if (isa<CompoundAssignOperator>(BO))
11201 notePreUse(O, BO);
11202
11203 Visit(BO->getLHS());
11204
11205 if (isa<CompoundAssignOperator>(BO))
11206 notePostUse(O, BO);
11207
11208 Visit(BO->getRHS());
11209
Richard Smith83e37bee2013-06-26 23:16:51 +000011210 // C++11 [expr.ass]p1:
11211 // the assignment is sequenced [...] before the value computation of the
11212 // assignment expression.
11213 // C11 6.5.16/3 has no such rule.
11214 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
11215 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000011216 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011217
Richard Smithc406cb72013-01-17 01:17:56 +000011218 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
11219 VisitBinAssign(CAO);
11220 }
11221
11222 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
11223 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
11224 void VisitUnaryPreIncDec(UnaryOperator *UO) {
11225 Object O = getObject(UO->getSubExpr(), true);
11226 if (!O)
11227 return VisitExpr(UO);
11228
11229 notePreMod(O, UO);
11230 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +000011231 // C++11 [expr.pre.incr]p1:
11232 // the expression ++x is equivalent to x+=1
11233 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
11234 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000011235 }
11236
11237 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
11238 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
11239 void VisitUnaryPostIncDec(UnaryOperator *UO) {
11240 Object O = getObject(UO->getSubExpr(), true);
11241 if (!O)
11242 return VisitExpr(UO);
11243
11244 notePreMod(O, UO);
11245 Visit(UO->getSubExpr());
11246 notePostMod(O, UO, UK_ModAsSideEffect);
11247 }
11248
11249 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
11250 void VisitBinLOr(BinaryOperator *BO) {
11251 // The side-effects of the LHS of an '&&' are sequenced before the
11252 // value computation of the RHS, and hence before the value computation
11253 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
11254 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +000011255 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000011256 {
11257 SequencedSubexpression Sequenced(*this);
11258 Visit(BO->getLHS());
11259 }
11260
11261 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000011262 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000011263 if (!Result)
11264 Visit(BO->getRHS());
11265 } else {
11266 // Check for unsequenced operations in the RHS, treating it as an
11267 // entirely separate evaluation.
11268 //
11269 // FIXME: If there are operations in the RHS which are unsequenced
11270 // with respect to operations outside the RHS, and those operations
11271 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +000011272 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000011273 }
Richard Smithc406cb72013-01-17 01:17:56 +000011274 }
11275 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +000011276 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000011277 {
11278 SequencedSubexpression Sequenced(*this);
11279 Visit(BO->getLHS());
11280 }
11281
11282 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000011283 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000011284 if (Result)
11285 Visit(BO->getRHS());
11286 } else {
Richard Smithd33f5202013-01-17 23:18:09 +000011287 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000011288 }
Richard Smithc406cb72013-01-17 01:17:56 +000011289 }
11290
11291 // Only visit the condition, unless we can be sure which subexpression will
11292 // be chosen.
11293 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +000011294 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +000011295 {
11296 SequencedSubexpression Sequenced(*this);
11297 Visit(CO->getCond());
11298 }
Richard Smithc406cb72013-01-17 01:17:56 +000011299
11300 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000011301 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +000011302 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000011303 else {
Richard Smithd33f5202013-01-17 23:18:09 +000011304 WorkList.push_back(CO->getTrueExpr());
11305 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000011306 }
Richard Smithc406cb72013-01-17 01:17:56 +000011307 }
11308
Richard Smithe3dbfe02013-06-30 10:40:20 +000011309 void VisitCallExpr(CallExpr *CE) {
11310 // C++11 [intro.execution]p15:
11311 // When calling a function [...], every value computation and side effect
11312 // associated with any argument expression, or with the postfix expression
11313 // designating the called function, is sequenced before execution of every
11314 // expression or statement in the body of the function [and thus before
11315 // the value computation of its result].
11316 SequencedSubexpression Sequenced(*this);
11317 Base::VisitCallExpr(CE);
11318
11319 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
11320 }
11321
Richard Smithc406cb72013-01-17 01:17:56 +000011322 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +000011323 // This is a call, so all subexpressions are sequenced before the result.
11324 SequencedSubexpression Sequenced(*this);
11325
Richard Smithc406cb72013-01-17 01:17:56 +000011326 if (!CCE->isListInitialization())
11327 return VisitExpr(CCE);
11328
11329 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011330 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000011331 SequenceTree::Seq Parent = Region;
11332 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
11333 E = CCE->arg_end();
11334 I != E; ++I) {
11335 Region = Tree.allocate(Parent);
11336 Elts.push_back(Region);
11337 Visit(*I);
11338 }
11339
11340 // Forget that the initializers are sequenced.
11341 Region = Parent;
11342 for (unsigned I = 0; I < Elts.size(); ++I)
11343 Tree.merge(Elts[I]);
11344 }
11345
11346 void VisitInitListExpr(InitListExpr *ILE) {
11347 if (!SemaRef.getLangOpts().CPlusPlus11)
11348 return VisitExpr(ILE);
11349
11350 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011351 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000011352 SequenceTree::Seq Parent = Region;
11353 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
11354 Expr *E = ILE->getInit(I);
11355 if (!E) continue;
11356 Region = Tree.allocate(Parent);
11357 Elts.push_back(Region);
11358 Visit(E);
11359 }
11360
11361 // Forget that the initializers are sequenced.
11362 Region = Parent;
11363 for (unsigned I = 0; I < Elts.size(); ++I)
11364 Tree.merge(Elts[I]);
11365 }
11366};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011367
11368} // namespace
Richard Smithc406cb72013-01-17 01:17:56 +000011369
11370void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011371 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +000011372 WorkList.push_back(E);
11373 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +000011374 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +000011375 SequenceChecker(*this, Item, WorkList);
11376 }
Richard Smithc406cb72013-01-17 01:17:56 +000011377}
11378
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011379void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
11380 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +000011381 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +000011382 if (!E->isInstantiationDependent())
11383 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011384 if (!IsConstexpr && !E->isValueDependent())
Richard Smith9f7df0c2017-06-26 23:19:32 +000011385 CheckForIntOverflow(E);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011386 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +000011387}
11388
John McCall1f425642010-11-11 03:21:53 +000011389void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
11390 FieldDecl *BitField,
11391 Expr *Init) {
11392 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
11393}
11394
David Majnemer61a5bbf2015-04-07 22:08:51 +000011395static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
11396 SourceLocation Loc) {
11397 if (!PType->isVariablyModifiedType())
11398 return;
11399 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
11400 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
11401 return;
11402 }
David Majnemerdf8f73f2015-04-09 19:53:25 +000011403 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
11404 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
11405 return;
11406 }
David Majnemer61a5bbf2015-04-07 22:08:51 +000011407 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
11408 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
11409 return;
11410 }
11411
11412 const ArrayType *AT = S.Context.getAsArrayType(PType);
11413 if (!AT)
11414 return;
11415
11416 if (AT->getSizeModifier() != ArrayType::Star) {
11417 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
11418 return;
11419 }
11420
11421 S.Diag(Loc, diag::err_array_star_in_function_definition);
11422}
11423
Mike Stump0c2ec772010-01-21 03:59:47 +000011424/// CheckParmsForFunctionDef - Check that the parameters of the given
11425/// function are appropriate for the definition of a function. This
11426/// takes care of any checks that cannot be performed on the
11427/// declaration itself, e.g., that the types of each of the function
11428/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +000011429bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +000011430 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +000011431 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +000011432 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +000011433 // C99 6.7.5.3p4: the parameters in a parameter type list in a
11434 // function declarator that is part of a function definition of
11435 // that function shall not have incomplete type.
11436 //
11437 // This is also C++ [dcl.fct]p6.
11438 if (!Param->isInvalidDecl() &&
11439 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011440 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +000011441 Param->setInvalidDecl();
11442 HasInvalidParm = true;
11443 }
11444
11445 // C99 6.9.1p5: If the declarator includes a parameter type list, the
11446 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +000011447 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +000011448 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +000011449 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000011450 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +000011451 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +000011452
11453 // C99 6.7.5.3p12:
11454 // If the function declarator is not part of a definition of that
11455 // function, parameters may have incomplete type and may use the [*]
11456 // notation in their sequences of declarator specifiers to specify
11457 // variable length array types.
11458 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +000011459 // FIXME: This diagnostic should point the '[*]' if source-location
11460 // information is added for it.
11461 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000011462
Akira Hatanaka02914dc2018-02-05 20:23:22 +000011463 // If the parameter is a c++ class type and it has to be destructed in the
11464 // callee function, declare the destructor so that it can be called by the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +000011465 // callee function. Do not perform any direct access check on the dtor here.
Akira Hatanaka02914dc2018-02-05 20:23:22 +000011466 if (!Param->isInvalidDecl()) {
11467 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
11468 if (!ClassDecl->isInvalidDecl() &&
11469 !ClassDecl->hasIrrelevantDestructor() &&
11470 !ClassDecl->isDependentContext() &&
Akira Hatanaka85282972018-05-15 21:00:30 +000011471 ClassDecl->isParamDestroyedInCallee()) {
Akira Hatanaka02914dc2018-02-05 20:23:22 +000011472 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
11473 MarkFunctionReferenced(Param->getLocation(), Destructor);
11474 DiagnoseUseOfDecl(Destructor, Param->getLocation());
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000011475 }
11476 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000011477 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011478
11479 // Parameters with the pass_object_size attribute only need to be marked
11480 // constant at function definitions. Because we lack information about
11481 // whether we're on a declaration or definition when we're instantiating the
11482 // attribute, we need to check for constness here.
11483 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
11484 if (!Param->getType().isConstQualified())
11485 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
11486 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +000011487 }
11488
11489 return HasInvalidParm;
11490}
John McCall2b5c1b22010-08-12 21:44:57 +000011491
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000011492/// A helper function to get the alignment of a Decl referred to by DeclRefExpr
11493/// or MemberExpr.
11494static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
11495 ASTContext &Context) {
11496 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
11497 return Context.getDeclAlign(DRE->getDecl());
11498
11499 if (const auto *ME = dyn_cast<MemberExpr>(E))
11500 return Context.getDeclAlign(ME->getMemberDecl());
11501
11502 return TypeAlign;
11503}
11504
John McCall2b5c1b22010-08-12 21:44:57 +000011505/// CheckCastAlign - Implements -Wcast-align, which warns when a
11506/// pointer cast increases the alignment requirements.
11507void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
11508 // This is actually a lot of work to potentially be doing on every
11509 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011510 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +000011511 return;
11512
11513 // Ignore dependent types.
11514 if (T->isDependentType() || Op->getType()->isDependentType())
11515 return;
11516
11517 // Require that the destination be a pointer type.
11518 const PointerType *DestPtr = T->getAs<PointerType>();
11519 if (!DestPtr) return;
11520
11521 // If the destination has alignment 1, we're done.
11522 QualType DestPointee = DestPtr->getPointeeType();
11523 if (DestPointee->isIncompleteType()) return;
11524 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
11525 if (DestAlign.isOne()) return;
11526
11527 // Require that the source be a pointer type.
11528 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
11529 if (!SrcPtr) return;
11530 QualType SrcPointee = SrcPtr->getPointeeType();
11531
11532 // Whitelist casts from cv void*. We already implicitly
11533 // whitelisted casts to cv void*, since they have alignment 1.
11534 // Also whitelist casts involving incomplete types, which implicitly
11535 // includes 'void'.
11536 if (SrcPointee->isIncompleteType()) return;
11537
11538 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000011539
11540 if (auto *CE = dyn_cast<CastExpr>(Op)) {
11541 if (CE->getCastKind() == CK_ArrayToPointerDecay)
11542 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
11543 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
11544 if (UO->getOpcode() == UO_AddrOf)
11545 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
11546 }
11547
John McCall2b5c1b22010-08-12 21:44:57 +000011548 if (SrcAlign >= DestAlign) return;
11549
11550 Diag(TRange.getBegin(), diag::warn_cast_align)
11551 << Op->getType() << T
11552 << static_cast<unsigned>(SrcAlign.getQuantity())
11553 << static_cast<unsigned>(DestAlign.getQuantity())
11554 << TRange << Op->getSourceRange();
11555}
11556
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011557/// Check whether this array fits the idiom of a size-one tail padded
Chandler Carruth28389f02011-08-05 09:10:50 +000011558/// array member of a struct.
11559///
11560/// We avoid emitting out-of-bounds access warnings for such arrays as they are
11561/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +000011562static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +000011563 const NamedDecl *ND) {
11564 if (Size != 1 || !ND) return false;
11565
11566 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
11567 if (!FD) return false;
11568
11569 // Don't consider sizes resulting from macro expansions or template argument
11570 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +000011571
11572 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000011573 while (TInfo) {
11574 TypeLoc TL = TInfo->getTypeLoc();
11575 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +000011576 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
11577 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000011578 TInfo = TDL->getTypeSourceInfo();
11579 continue;
11580 }
David Blaikie6adc78e2013-02-18 22:06:02 +000011581 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
11582 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +000011583 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
11584 return false;
11585 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +000011586 break;
Sean Callanan06a48a62012-05-04 18:22:53 +000011587 }
Chandler Carruth28389f02011-08-05 09:10:50 +000011588
11589 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +000011590 if (!RD) return false;
11591 if (RD->isUnion()) return false;
11592 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
11593 if (!CRD->isStandardLayout()) return false;
11594 }
Chandler Carruth28389f02011-08-05 09:10:50 +000011595
Benjamin Kramer8c543672011-08-06 03:04:42 +000011596 // See if this is the last field decl in the record.
11597 const Decl *D = FD;
11598 while ((D = D->getNextDeclInContext()))
11599 if (isa<FieldDecl>(D))
11600 return false;
11601 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +000011602}
11603
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011604void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011605 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +000011606 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011607 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011608 if (IndexExpr->isValueDependent())
11609 return;
11610
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000011611 const Type *EffectiveType =
11612 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011613 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011614 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011615 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011616 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +000011617 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +000011618
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011619 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +000011620 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +000011621 return;
Richard Smith13f67182011-12-16 19:31:14 +000011622 if (IndexNegated)
11623 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +000011624
Craig Topperc3ec1492014-05-26 06:22:03 +000011625 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +000011626 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011627 ND = DRE->getDecl();
Chandler Carruth28389f02011-08-05 09:10:50 +000011628 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011629 ND = ME->getMemberDecl();
Chandler Carruth126b1552011-08-05 08:07:29 +000011630
Ted Kremeneke4b316c2011-02-23 23:06:04 +000011631 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011632 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +000011633 if (!size.isStrictlyPositive())
11634 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011635
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000011636 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +000011637 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011638 // Make sure we're comparing apples to apples when comparing index to size
11639 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
11640 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +000011641 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +000011642 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011643 if (ptrarith_typesize != array_typesize) {
11644 // There's a cast to a different size type involved
11645 uint64_t ratio = array_typesize / ptrarith_typesize;
11646 // TODO: Be smarter about handling cases where array_typesize is not a
11647 // multiple of ptrarith_typesize
11648 if (ptrarith_typesize * ratio == array_typesize)
11649 size *= llvm::APInt(size.getBitWidth(), ratio);
11650 }
11651 }
11652
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011653 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011654 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011655 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011656 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011657
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011658 // For array subscripting the index must be less than size, but for pointer
11659 // arithmetic also allow the index (offset) to be equal to size since
11660 // computing the next address after the end of the array is legal and
11661 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011662 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +000011663 return;
11664
11665 // Also don't warn for arrays of size 1 which are members of some
11666 // structure. These are often used to approximate flexible arrays in C89
11667 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011668 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +000011669 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011670
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011671 // Suppress the warning if the subscript expression (as identified by the
11672 // ']' location) and the index expression are both from macro expansions
11673 // within a system header.
11674 if (ASE) {
11675 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
11676 ASE->getRBracketLoc());
11677 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
11678 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
11679 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +000011680 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011681 return;
11682 }
11683 }
11684
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011685 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011686 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011687 DiagID = diag::warn_array_index_exceeds_bounds;
11688
11689 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11690 PDiag(DiagID) << index.toString(10, true)
11691 << size.toString(10, true)
11692 << (unsigned)size.getLimitedValue(~0U)
11693 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011694 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011695 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011696 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011697 DiagID = diag::warn_ptr_arith_precedes_bounds;
11698 if (index.isNegative()) index = -index;
11699 }
11700
11701 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11702 PDiag(DiagID) << index.toString(10, true)
11703 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +000011704 }
Chandler Carruth1af88f12011-02-17 21:10:52 +000011705
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000011706 if (!ND) {
11707 // Try harder to find a NamedDecl to point at in the note.
11708 while (const ArraySubscriptExpr *ASE =
11709 dyn_cast<ArraySubscriptExpr>(BaseExpr))
11710 BaseExpr = ASE->getBase()->IgnoreParenCasts();
11711 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011712 ND = DRE->getDecl();
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000011713 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011714 ND = ME->getMemberDecl();
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000011715 }
11716
Chandler Carruth1af88f12011-02-17 21:10:52 +000011717 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011718 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
11719 PDiag(diag::note_array_index_out_of_bounds)
11720 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +000011721}
11722
Ted Kremenekdf26df72011-03-01 18:41:00 +000011723void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011724 int AllowOnePastEnd = 0;
11725 while (expr) {
11726 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +000011727 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011728 case Stmt::ArraySubscriptExprClass: {
11729 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011730 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011731 AllowOnePastEnd > 0);
Aaron Ballman93c6ba12018-04-24 19:21:04 +000011732 expr = ASE->getBase();
11733 break;
11734 }
11735 case Stmt::MemberExprClass: {
11736 expr = cast<MemberExpr>(expr)->getBase();
11737 break;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011738 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +000011739 case Stmt::OMPArraySectionExprClass: {
11740 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
11741 if (ASE->getLowerBound())
11742 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
11743 /*ASE=*/nullptr, AllowOnePastEnd > 0);
11744 return;
11745 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011746 case Stmt::UnaryOperatorClass: {
11747 // Only unwrap the * and & unary operators
11748 const UnaryOperator *UO = cast<UnaryOperator>(expr);
11749 expr = UO->getSubExpr();
11750 switch (UO->getOpcode()) {
11751 case UO_AddrOf:
11752 AllowOnePastEnd++;
11753 break;
11754 case UO_Deref:
11755 AllowOnePastEnd--;
11756 break;
11757 default:
11758 return;
11759 }
11760 break;
11761 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011762 case Stmt::ConditionalOperatorClass: {
11763 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
11764 if (const Expr *lhs = cond->getLHS())
11765 CheckArrayAccess(lhs);
11766 if (const Expr *rhs = cond->getRHS())
11767 CheckArrayAccess(rhs);
11768 return;
11769 }
Daniel Marjamaki20a209e2017-02-28 14:53:50 +000011770 case Stmt::CXXOperatorCallExprClass: {
11771 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
11772 for (const auto *Arg : OCE->arguments())
11773 CheckArrayAccess(Arg);
11774 return;
11775 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011776 default:
11777 return;
11778 }
Peter Collingbourne91147592011-04-15 00:35:48 +000011779 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011780}
John McCall31168b02011-06-15 23:02:42 +000011781
11782//===--- CHECK: Objective-C retain cycles ----------------------------------//
11783
11784namespace {
John McCall31168b02011-06-15 23:02:42 +000011785
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011786struct RetainCycleOwner {
11787 VarDecl *Variable = nullptr;
11788 SourceRange Range;
11789 SourceLocation Loc;
11790 bool Indirect = false;
11791
11792 RetainCycleOwner() = default;
11793
11794 void setLocsFrom(Expr *e) {
11795 Loc = e->getExprLoc();
11796 Range = e->getSourceRange();
11797 }
11798};
11799
11800} // namespace
John McCall31168b02011-06-15 23:02:42 +000011801
11802/// Consider whether capturing the given variable can possibly lead to
11803/// a retain cycle.
11804static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000011805 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +000011806 // lifetime. In MRR, it's captured strongly if the variable is
11807 // __block and has an appropriate type.
11808 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11809 return false;
11810
11811 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011812 if (ref)
11813 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +000011814 return true;
11815}
11816
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011817static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +000011818 while (true) {
11819 e = e->IgnoreParens();
11820 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
11821 switch (cast->getCastKind()) {
11822 case CK_BitCast:
11823 case CK_LValueBitCast:
11824 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +000011825 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +000011826 e = cast->getSubExpr();
11827 continue;
11828
John McCall31168b02011-06-15 23:02:42 +000011829 default:
11830 return false;
11831 }
11832 }
11833
11834 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
11835 ObjCIvarDecl *ivar = ref->getDecl();
11836 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11837 return false;
11838
11839 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011840 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +000011841 return false;
11842
11843 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
11844 owner.Indirect = true;
11845 return true;
11846 }
11847
11848 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
11849 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
11850 if (!var) return false;
11851 return considerVariable(var, ref, owner);
11852 }
11853
John McCall31168b02011-06-15 23:02:42 +000011854 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
11855 if (member->isArrow()) return false;
11856
11857 // Don't count this as an indirect ownership.
11858 e = member->getBase();
11859 continue;
11860 }
11861
John McCallfe96e0b2011-11-06 09:01:30 +000011862 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
11863 // Only pay attention to pseudo-objects on property references.
11864 ObjCPropertyRefExpr *pre
11865 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
11866 ->IgnoreParens());
11867 if (!pre) return false;
11868 if (pre->isImplicitProperty()) return false;
11869 ObjCPropertyDecl *property = pre->getExplicitProperty();
11870 if (!property->isRetaining() &&
11871 !(property->getPropertyIvarDecl() &&
11872 property->getPropertyIvarDecl()->getType()
11873 .getObjCLifetime() == Qualifiers::OCL_Strong))
11874 return false;
11875
11876 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011877 if (pre->isSuperReceiver()) {
11878 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
11879 if (!owner.Variable)
11880 return false;
11881 owner.Loc = pre->getLocation();
11882 owner.Range = pre->getSourceRange();
11883 return true;
11884 }
John McCallfe96e0b2011-11-06 09:01:30 +000011885 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
11886 ->getSourceExpr());
11887 continue;
11888 }
11889
John McCall31168b02011-06-15 23:02:42 +000011890 // Array ivars?
11891
11892 return false;
11893 }
11894}
11895
11896namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011897
John McCall31168b02011-06-15 23:02:42 +000011898 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011899 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +000011900 VarDecl *Variable;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011901 Expr *Capturer = nullptr;
11902 bool VarWillBeReased = false;
11903
11904 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
11905 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
11906 Context(Context), Variable(variable) {}
John McCall31168b02011-06-15 23:02:42 +000011907
11908 void VisitDeclRefExpr(DeclRefExpr *ref) {
11909 if (ref->getDecl() == Variable && !Capturer)
11910 Capturer = ref;
11911 }
11912
John McCall31168b02011-06-15 23:02:42 +000011913 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
11914 if (Capturer) return;
11915 Visit(ref->getBase());
11916 if (Capturer && ref->isFreeIvar())
11917 Capturer = ref;
11918 }
11919
11920 void VisitBlockExpr(BlockExpr *block) {
11921 // Look inside nested blocks
11922 if (block->getBlockDecl()->capturesVariable(Variable))
11923 Visit(block->getBlockDecl()->getBody());
11924 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +000011925
11926 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
11927 if (Capturer) return;
11928 if (OVE->getSourceExpr())
11929 Visit(OVE->getSourceExpr());
11930 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011931
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011932 void VisitBinaryOperator(BinaryOperator *BinOp) {
11933 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
11934 return;
11935 Expr *LHS = BinOp->getLHS();
11936 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
11937 if (DRE->getDecl() != Variable)
11938 return;
11939 if (Expr *RHS = BinOp->getRHS()) {
11940 RHS = RHS->IgnoreParenCasts();
11941 llvm::APSInt Value;
11942 VarWillBeReased =
11943 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
11944 }
11945 }
11946 }
John McCall31168b02011-06-15 23:02:42 +000011947 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011948
11949} // namespace
John McCall31168b02011-06-15 23:02:42 +000011950
11951/// Check whether the given argument is a block which captures a
11952/// variable.
11953static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
11954 assert(owner.Variable && owner.Loc.isValid());
11955
11956 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000011957
11958 // Look through [^{...} copy] and Block_copy(^{...}).
11959 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
11960 Selector Cmd = ME->getSelector();
11961 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
11962 e = ME->getInstanceReceiver();
11963 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000011964 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000011965 e = e->IgnoreParenCasts();
11966 }
11967 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
11968 if (CE->getNumArgs() == 1) {
11969 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000011970 if (Fn) {
11971 const IdentifierInfo *FnI = Fn->getIdentifier();
11972 if (FnI && FnI->isStr("_Block_copy")) {
11973 e = CE->getArg(0)->IgnoreParenCasts();
11974 }
11975 }
Jordan Rose67e887c2012-09-17 17:54:30 +000011976 }
11977 }
11978
John McCall31168b02011-06-15 23:02:42 +000011979 BlockExpr *block = dyn_cast<BlockExpr>(e);
11980 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000011981 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000011982
11983 FindCaptureVisitor visitor(S.Context, owner.Variable);
11984 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011985 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000011986}
11987
11988static void diagnoseRetainCycle(Sema &S, Expr *capturer,
11989 RetainCycleOwner &owner) {
11990 assert(capturer);
11991 assert(owner.Variable && owner.Loc.isValid());
11992
11993 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
11994 << owner.Variable << capturer->getSourceRange();
11995 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
11996 << owner.Indirect << owner.Range;
11997}
11998
11999/// Check for a keyword selector that starts with the word 'add' or
12000/// 'set'.
12001static bool isSetterLikeSelector(Selector sel) {
12002 if (sel.isUnarySelector()) return false;
12003
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012004 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000012005 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000012006 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000012007 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000012008 else if (str.startswith("add")) {
12009 // Specially whitelist 'addOperationWithBlock:'.
12010 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
12011 return false;
12012 str = str.substr(3);
12013 }
John McCall31168b02011-06-15 23:02:42 +000012014 else
12015 return false;
12016
12017 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000012018 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000012019}
12020
Benjamin Kramer3a743452015-03-09 15:03:32 +000012021static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
12022 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000012023 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
12024 Message->getReceiverInterface(),
12025 NSAPI::ClassId_NSMutableArray);
12026 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012027 return None;
12028 }
12029
12030 Selector Sel = Message->getSelector();
12031
12032 Optional<NSAPI::NSArrayMethodKind> MKOpt =
12033 S.NSAPIObj->getNSArrayMethodKind(Sel);
12034 if (!MKOpt) {
12035 return None;
12036 }
12037
12038 NSAPI::NSArrayMethodKind MK = *MKOpt;
12039
12040 switch (MK) {
12041 case NSAPI::NSMutableArr_addObject:
12042 case NSAPI::NSMutableArr_insertObjectAtIndex:
12043 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
12044 return 0;
12045 case NSAPI::NSMutableArr_replaceObjectAtIndex:
12046 return 1;
12047
12048 default:
12049 return None;
12050 }
12051
12052 return None;
12053}
12054
12055static
12056Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
12057 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000012058 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
12059 Message->getReceiverInterface(),
12060 NSAPI::ClassId_NSMutableDictionary);
12061 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012062 return None;
12063 }
12064
12065 Selector Sel = Message->getSelector();
12066
12067 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
12068 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
12069 if (!MKOpt) {
12070 return None;
12071 }
12072
12073 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
12074
12075 switch (MK) {
12076 case NSAPI::NSMutableDict_setObjectForKey:
12077 case NSAPI::NSMutableDict_setValueForKey:
12078 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
12079 return 0;
12080
12081 default:
12082 return None;
12083 }
12084
12085 return None;
12086}
12087
12088static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000012089 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
12090 Message->getReceiverInterface(),
12091 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000012092
Alex Denisov5dfac812015-08-06 04:51:14 +000012093 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
12094 Message->getReceiverInterface(),
12095 NSAPI::ClassId_NSMutableOrderedSet);
12096 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012097 return None;
12098 }
12099
12100 Selector Sel = Message->getSelector();
12101
12102 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
12103 if (!MKOpt) {
12104 return None;
12105 }
12106
12107 NSAPI::NSSetMethodKind MK = *MKOpt;
12108
12109 switch (MK) {
12110 case NSAPI::NSMutableSet_addObject:
12111 case NSAPI::NSOrderedSet_setObjectAtIndex:
12112 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
12113 case NSAPI::NSOrderedSet_insertObjectAtIndex:
12114 return 0;
12115 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
12116 return 1;
12117 }
12118
12119 return None;
12120}
12121
12122void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
12123 if (!Message->isInstanceMessage()) {
12124 return;
12125 }
12126
12127 Optional<int> ArgOpt;
12128
12129 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
12130 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
12131 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
12132 return;
12133 }
12134
12135 int ArgIndex = *ArgOpt;
12136
Alex Denisove1d882c2015-03-04 17:55:52 +000012137 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
12138 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
12139 Arg = OE->getSourceExpr()->IgnoreImpCasts();
12140 }
12141
Alex Denisov5dfac812015-08-06 04:51:14 +000012142 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012143 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000012144 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012145 Diag(Message->getSourceRange().getBegin(),
12146 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000012147 << ArgRE->getDecl() << StringRef("'super'");
Alex Denisove1d882c2015-03-04 17:55:52 +000012148 }
12149 }
Alex Denisov5dfac812015-08-06 04:51:14 +000012150 } else {
12151 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
12152
12153 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
12154 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
12155 }
12156
12157 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
12158 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
12159 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
12160 ValueDecl *Decl = ReceiverRE->getDecl();
12161 Diag(Message->getSourceRange().getBegin(),
12162 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000012163 << Decl << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012164 if (!ArgRE->isObjCSelfExpr()) {
12165 Diag(Decl->getLocation(),
12166 diag::note_objc_circular_container_declared_here)
Richard Trieub4025802018-03-28 04:16:13 +000012167 << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012168 }
12169 }
12170 }
12171 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
12172 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
12173 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
12174 ObjCIvarDecl *Decl = IvarRE->getDecl();
12175 Diag(Message->getSourceRange().getBegin(),
12176 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000012177 << Decl << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012178 Diag(Decl->getLocation(),
12179 diag::note_objc_circular_container_declared_here)
Richard Trieub4025802018-03-28 04:16:13 +000012180 << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012181 }
Alex Denisove1d882c2015-03-04 17:55:52 +000012182 }
12183 }
12184 }
Alex Denisove1d882c2015-03-04 17:55:52 +000012185}
12186
John McCall31168b02011-06-15 23:02:42 +000012187/// Check a message send to see if it's likely to cause a retain cycle.
12188void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
12189 // Only check instance methods whose selector looks like a setter.
12190 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
12191 return;
12192
12193 // Try to find a variable that the receiver is strongly owned by.
12194 RetainCycleOwner owner;
12195 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000012196 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000012197 return;
12198 } else {
12199 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
12200 owner.Variable = getCurMethodDecl()->getSelfDecl();
12201 owner.Loc = msg->getSuperLoc();
12202 owner.Range = msg->getSuperLoc();
12203 }
12204
12205 // Check whether the receiver is captured by any of the arguments.
Alex Lorenz42a97a92017-11-17 20:44:25 +000012206 const ObjCMethodDecl *MD = msg->getMethodDecl();
12207 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
12208 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
12209 // noescape blocks should not be retained by the method.
12210 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
12211 continue;
John McCall31168b02011-06-15 23:02:42 +000012212 return diagnoseRetainCycle(*this, capturer, owner);
Alex Lorenz42a97a92017-11-17 20:44:25 +000012213 }
12214 }
John McCall31168b02011-06-15 23:02:42 +000012215}
12216
12217/// Check a property assign to see if it's likely to cause a retain cycle.
12218void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
12219 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000012220 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000012221 return;
12222
12223 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
12224 diagnoseRetainCycle(*this, capturer, owner);
12225}
12226
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000012227void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
12228 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000012229 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000012230 return;
12231
12232 // Because we don't have an expression for the variable, we have to set the
12233 // location explicitly here.
12234 Owner.Loc = Var->getLocation();
12235 Owner.Range = Var->getSourceRange();
12236
12237 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
12238 diagnoseRetainCycle(*this, Capturer, Owner);
12239}
12240
Ted Kremenek9304da92012-12-21 08:04:28 +000012241static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
12242 Expr *RHS, bool isProperty) {
12243 // Check if RHS is an Objective-C object literal, which also can get
12244 // immediately zapped in a weak reference. Note that we explicitly
12245 // allow ObjCStringLiterals, since those are designed to never really die.
12246 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000012247
Ted Kremenek64873352012-12-21 22:46:35 +000012248 // This enum needs to match with the 'select' in
12249 // warn_objc_arc_literal_assign (off-by-1).
12250 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
12251 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
12252 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000012253
12254 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000012255 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000012256 << (isProperty ? 0 : 1)
12257 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000012258
12259 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000012260}
12261
Ted Kremenekc1f014a2012-12-21 19:45:30 +000012262static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
12263 Qualifiers::ObjCLifetime LT,
12264 Expr *RHS, bool isProperty) {
12265 // Strip off any implicit cast added to get to the one ARC-specific.
12266 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
12267 if (cast->getCastKind() == CK_ARCConsumeObject) {
12268 S.Diag(Loc, diag::warn_arc_retained_assign)
12269 << (LT == Qualifiers::OCL_ExplicitNone)
12270 << (isProperty ? 0 : 1)
12271 << RHS->getSourceRange();
12272 return true;
12273 }
12274 RHS = cast->getSubExpr();
12275 }
12276
12277 if (LT == Qualifiers::OCL_Weak &&
12278 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
12279 return true;
12280
12281 return false;
12282}
12283
Ted Kremenekb36234d2012-12-21 08:04:20 +000012284bool Sema::checkUnsafeAssigns(SourceLocation Loc,
12285 QualType LHS, Expr *RHS) {
12286 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
12287
12288 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
12289 return false;
12290
12291 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
12292 return true;
12293
12294 return false;
12295}
12296
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012297void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
12298 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012299 QualType LHSType;
12300 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000012301 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012302 ObjCPropertyRefExpr *PRE
12303 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
12304 if (PRE && !PRE->isImplicitProperty()) {
12305 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
12306 if (PD)
12307 LHSType = PD->getType();
12308 }
12309
12310 if (LHSType.isNull())
12311 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000012312
12313 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
12314
12315 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000012316 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000012317 getCurFunction()->markSafeWeakUse(LHS);
12318 }
12319
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012320 if (checkUnsafeAssigns(Loc, LHSType, RHS))
12321 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000012322
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012323 // FIXME. Check for other life times.
12324 if (LT != Qualifiers::OCL_None)
12325 return;
12326
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012327 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012328 if (PRE->isImplicitProperty())
12329 return;
12330 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
12331 if (!PD)
12332 return;
12333
Bill Wendling44426052012-12-20 19:22:21 +000012334 unsigned Attributes = PD->getPropertyAttributes();
12335 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012336 // when 'assign' attribute was not explicitly specified
12337 // by user, ignore it and rely on property type itself
12338 // for lifetime info.
12339 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
12340 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
12341 LHSType->isObjCRetainableType())
12342 return;
12343
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012344 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000012345 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012346 Diag(Loc, diag::warn_arc_retained_property_assign)
12347 << RHS->getSourceRange();
12348 return;
12349 }
12350 RHS = cast->getSubExpr();
12351 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012352 }
Bill Wendling44426052012-12-20 19:22:21 +000012353 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000012354 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
12355 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000012356 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012357 }
12358}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012359
12360//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
12361
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012362static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
12363 SourceLocation StmtLoc,
12364 const NullStmt *Body) {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012365 // Do not warn if the body is a macro that expands to nothing, e.g:
12366 //
12367 // #define CALL(x)
12368 // if (condition)
12369 // CALL(0);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012370 if (Body->hasLeadingEmptyMacro())
12371 return false;
12372
12373 // Get line numbers of statement and body.
12374 bool StmtLineInvalid;
Hans Wennborg95419752017-11-20 17:38:16 +000012375 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012376 &StmtLineInvalid);
12377 if (StmtLineInvalid)
12378 return false;
12379
12380 bool BodyLineInvalid;
12381 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
12382 &BodyLineInvalid);
12383 if (BodyLineInvalid)
12384 return false;
12385
12386 // Warn if null statement and body are on the same line.
12387 if (StmtLine != BodyLine)
12388 return false;
12389
12390 return true;
12391}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012392
12393void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
12394 const Stmt *Body,
12395 unsigned DiagID) {
12396 // Since this is a syntactic check, don't emit diagnostic for template
12397 // instantiations, this just adds noise.
12398 if (CurrentInstantiationScope)
12399 return;
12400
12401 // The body should be a null statement.
12402 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
12403 if (!NBody)
12404 return;
12405
12406 // Do the usual checks.
12407 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
12408 return;
12409
12410 Diag(NBody->getSemiLoc(), DiagID);
12411 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
12412}
12413
12414void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
12415 const Stmt *PossibleBody) {
12416 assert(!CurrentInstantiationScope); // Ensured by caller
12417
12418 SourceLocation StmtLoc;
12419 const Stmt *Body;
12420 unsigned DiagID;
12421 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
12422 StmtLoc = FS->getRParenLoc();
12423 Body = FS->getBody();
12424 DiagID = diag::warn_empty_for_body;
12425 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
12426 StmtLoc = WS->getCond()->getSourceRange().getEnd();
12427 Body = WS->getBody();
12428 DiagID = diag::warn_empty_while_body;
12429 } else
12430 return; // Neither `for' nor `while'.
12431
12432 // The body should be a null statement.
12433 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
12434 if (!NBody)
12435 return;
12436
12437 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000012438 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012439 return;
12440
12441 // Do the usual checks.
12442 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
12443 return;
12444
12445 // `for(...);' and `while(...);' are popular idioms, so in order to keep
12446 // noise level low, emit diagnostics only if for/while is followed by a
12447 // CompoundStmt, e.g.:
12448 // for (int i = 0; i < n; i++);
12449 // {
12450 // a(i);
12451 // }
12452 // or if for/while is followed by a statement with more indentation
12453 // than for/while itself:
12454 // for (int i = 0; i < n; i++);
12455 // a(i);
12456 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
12457 if (!ProbableTypo) {
12458 bool BodyColInvalid;
12459 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
12460 PossibleBody->getLocStart(),
12461 &BodyColInvalid);
12462 if (BodyColInvalid)
12463 return;
12464
12465 bool StmtColInvalid;
12466 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
12467 S->getLocStart(),
12468 &StmtColInvalid);
12469 if (StmtColInvalid)
12470 return;
12471
12472 if (BodyCol > StmtCol)
12473 ProbableTypo = true;
12474 }
12475
12476 if (ProbableTypo) {
12477 Diag(NBody->getSemiLoc(), DiagID);
12478 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
12479 }
12480}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012481
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012482//===--- CHECK: Warn on self move with std::move. -------------------------===//
12483
12484/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
12485void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
12486 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012487 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
12488 return;
12489
Richard Smith51ec0cf2017-02-21 01:17:38 +000012490 if (inTemplateInstantiation())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012491 return;
12492
12493 // Strip parens and casts away.
12494 LHSExpr = LHSExpr->IgnoreParenImpCasts();
12495 RHSExpr = RHSExpr->IgnoreParenImpCasts();
12496
12497 // Check for a call expression
12498 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
12499 if (!CE || CE->getNumArgs() != 1)
12500 return;
12501
12502 // Check for a call to std::move
Nico Weberb688d132017-09-28 16:16:39 +000012503 if (!CE->isCallToStdMove())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012504 return;
12505
12506 // Get argument from std::move
12507 RHSExpr = CE->getArg(0);
12508
12509 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
12510 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
12511
12512 // Two DeclRefExpr's, check that the decls are the same.
12513 if (LHSDeclRef && RHSDeclRef) {
12514 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
12515 return;
12516 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
12517 RHSDeclRef->getDecl()->getCanonicalDecl())
12518 return;
12519
12520 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12521 << LHSExpr->getSourceRange()
12522 << RHSExpr->getSourceRange();
12523 return;
12524 }
12525
12526 // Member variables require a different approach to check for self moves.
12527 // MemberExpr's are the same if every nested MemberExpr refers to the same
12528 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
12529 // the base Expr's are CXXThisExpr's.
12530 const Expr *LHSBase = LHSExpr;
12531 const Expr *RHSBase = RHSExpr;
12532 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
12533 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
12534 if (!LHSME || !RHSME)
12535 return;
12536
12537 while (LHSME && RHSME) {
12538 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
12539 RHSME->getMemberDecl()->getCanonicalDecl())
12540 return;
12541
12542 LHSBase = LHSME->getBase();
12543 RHSBase = RHSME->getBase();
12544 LHSME = dyn_cast<MemberExpr>(LHSBase);
12545 RHSME = dyn_cast<MemberExpr>(RHSBase);
12546 }
12547
12548 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
12549 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
12550 if (LHSDeclRef && RHSDeclRef) {
12551 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
12552 return;
12553 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
12554 RHSDeclRef->getDecl()->getCanonicalDecl())
12555 return;
12556
12557 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12558 << LHSExpr->getSourceRange()
12559 << RHSExpr->getSourceRange();
12560 return;
12561 }
12562
12563 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
12564 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12565 << LHSExpr->getSourceRange()
12566 << RHSExpr->getSourceRange();
12567}
12568
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012569//===--- Layout compatibility ----------------------------------------------//
12570
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012571static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012572
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012573/// Check if two enumeration types are layout-compatible.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012574static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012575 // C++11 [dcl.enum] p8:
12576 // Two enumeration types are layout-compatible if they have the same
12577 // underlying type.
12578 return ED1->isComplete() && ED2->isComplete() &&
12579 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
12580}
12581
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012582/// Check if two fields are layout-compatible.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012583static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
12584 FieldDecl *Field2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012585 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
12586 return false;
12587
12588 if (Field1->isBitField() != Field2->isBitField())
12589 return false;
12590
12591 if (Field1->isBitField()) {
12592 // Make sure that the bit-fields are the same length.
12593 unsigned Bits1 = Field1->getBitWidthValue(C);
12594 unsigned Bits2 = Field2->getBitWidthValue(C);
12595
12596 if (Bits1 != Bits2)
12597 return false;
12598 }
12599
12600 return true;
12601}
12602
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012603/// Check if two standard-layout structs are layout-compatible.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012604/// (C++11 [class.mem] p17)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012605static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
12606 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012607 // If both records are C++ classes, check that base classes match.
12608 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
12609 // If one of records is a CXXRecordDecl we are in C++ mode,
12610 // thus the other one is a CXXRecordDecl, too.
12611 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
12612 // Check number of base classes.
12613 if (D1CXX->getNumBases() != D2CXX->getNumBases())
12614 return false;
12615
12616 // Check the base classes.
12617 for (CXXRecordDecl::base_class_const_iterator
12618 Base1 = D1CXX->bases_begin(),
12619 BaseEnd1 = D1CXX->bases_end(),
12620 Base2 = D2CXX->bases_begin();
12621 Base1 != BaseEnd1;
12622 ++Base1, ++Base2) {
12623 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
12624 return false;
12625 }
12626 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
12627 // If only RD2 is a C++ class, it should have zero base classes.
12628 if (D2CXX->getNumBases() > 0)
12629 return false;
12630 }
12631
12632 // Check the fields.
12633 RecordDecl::field_iterator Field2 = RD2->field_begin(),
12634 Field2End = RD2->field_end(),
12635 Field1 = RD1->field_begin(),
12636 Field1End = RD1->field_end();
12637 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
12638 if (!isLayoutCompatible(C, *Field1, *Field2))
12639 return false;
12640 }
12641 if (Field1 != Field1End || Field2 != Field2End)
12642 return false;
12643
12644 return true;
12645}
12646
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012647/// Check if two standard-layout unions are layout-compatible.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012648/// (C++11 [class.mem] p18)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012649static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
12650 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012651 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012652 for (auto *Field2 : RD2->fields())
12653 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012654
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012655 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012656 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
12657 I = UnmatchedFields.begin(),
12658 E = UnmatchedFields.end();
12659
12660 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012661 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012662 bool Result = UnmatchedFields.erase(*I);
12663 (void) Result;
12664 assert(Result);
12665 break;
12666 }
12667 }
12668 if (I == E)
12669 return false;
12670 }
12671
12672 return UnmatchedFields.empty();
12673}
12674
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012675static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
12676 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012677 if (RD1->isUnion() != RD2->isUnion())
12678 return false;
12679
12680 if (RD1->isUnion())
12681 return isLayoutCompatibleUnion(C, RD1, RD2);
12682 else
12683 return isLayoutCompatibleStruct(C, RD1, RD2);
12684}
12685
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012686/// Check if two types are layout-compatible in C++11 sense.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012687static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012688 if (T1.isNull() || T2.isNull())
12689 return false;
12690
12691 // C++11 [basic.types] p11:
12692 // If two types T1 and T2 are the same type, then T1 and T2 are
12693 // layout-compatible types.
12694 if (C.hasSameType(T1, T2))
12695 return true;
12696
12697 T1 = T1.getCanonicalType().getUnqualifiedType();
12698 T2 = T2.getCanonicalType().getUnqualifiedType();
12699
12700 const Type::TypeClass TC1 = T1->getTypeClass();
12701 const Type::TypeClass TC2 = T2->getTypeClass();
12702
12703 if (TC1 != TC2)
12704 return false;
12705
12706 if (TC1 == Type::Enum) {
12707 return isLayoutCompatible(C,
12708 cast<EnumType>(T1)->getDecl(),
12709 cast<EnumType>(T2)->getDecl());
12710 } else if (TC1 == Type::Record) {
12711 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
12712 return false;
12713
12714 return isLayoutCompatible(C,
12715 cast<RecordType>(T1)->getDecl(),
12716 cast<RecordType>(T2)->getDecl());
12717 }
12718
12719 return false;
12720}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012721
12722//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
12723
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012724/// Given a type tag expression find the type tag itself.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012725///
12726/// \param TypeExpr Type tag expression, as it appears in user's code.
12727///
12728/// \param VD Declaration of an identifier that appears in a type tag.
12729///
12730/// \param MagicValue Type tag magic value.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012731static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
12732 const ValueDecl **VD, uint64_t *MagicValue) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012733 while(true) {
12734 if (!TypeExpr)
12735 return false;
12736
12737 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
12738
12739 switch (TypeExpr->getStmtClass()) {
12740 case Stmt::UnaryOperatorClass: {
12741 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
12742 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
12743 TypeExpr = UO->getSubExpr();
12744 continue;
12745 }
12746 return false;
12747 }
12748
12749 case Stmt::DeclRefExprClass: {
12750 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
12751 *VD = DRE->getDecl();
12752 return true;
12753 }
12754
12755 case Stmt::IntegerLiteralClass: {
12756 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
12757 llvm::APInt MagicValueAPInt = IL->getValue();
12758 if (MagicValueAPInt.getActiveBits() <= 64) {
12759 *MagicValue = MagicValueAPInt.getZExtValue();
12760 return true;
12761 } else
12762 return false;
12763 }
12764
12765 case Stmt::BinaryConditionalOperatorClass:
12766 case Stmt::ConditionalOperatorClass: {
12767 const AbstractConditionalOperator *ACO =
12768 cast<AbstractConditionalOperator>(TypeExpr);
12769 bool Result;
12770 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
12771 if (Result)
12772 TypeExpr = ACO->getTrueExpr();
12773 else
12774 TypeExpr = ACO->getFalseExpr();
12775 continue;
12776 }
12777 return false;
12778 }
12779
12780 case Stmt::BinaryOperatorClass: {
12781 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
12782 if (BO->getOpcode() == BO_Comma) {
12783 TypeExpr = BO->getRHS();
12784 continue;
12785 }
12786 return false;
12787 }
12788
12789 default:
12790 return false;
12791 }
12792 }
12793}
12794
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012795/// Retrieve the C type corresponding to type tag TypeExpr.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012796///
12797/// \param TypeExpr Expression that specifies a type tag.
12798///
12799/// \param MagicValues Registered magic values.
12800///
12801/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
12802/// kind.
12803///
12804/// \param TypeInfo Information about the corresponding C type.
12805///
12806/// \returns true if the corresponding C type was found.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012807static bool GetMatchingCType(
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012808 const IdentifierInfo *ArgumentKind,
12809 const Expr *TypeExpr, const ASTContext &Ctx,
12810 const llvm::DenseMap<Sema::TypeTagMagicValue,
12811 Sema::TypeTagData> *MagicValues,
12812 bool &FoundWrongKind,
12813 Sema::TypeTagData &TypeInfo) {
12814 FoundWrongKind = false;
12815
12816 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000012817 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012818
12819 uint64_t MagicValue;
12820
12821 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
12822 return false;
12823
12824 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000012825 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012826 if (I->getArgumentKind() != ArgumentKind) {
12827 FoundWrongKind = true;
12828 return false;
12829 }
12830 TypeInfo.Type = I->getMatchingCType();
12831 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
12832 TypeInfo.MustBeNull = I->getMustBeNull();
12833 return true;
12834 }
12835 return false;
12836 }
12837
12838 if (!MagicValues)
12839 return false;
12840
12841 llvm::DenseMap<Sema::TypeTagMagicValue,
12842 Sema::TypeTagData>::const_iterator I =
12843 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
12844 if (I == MagicValues->end())
12845 return false;
12846
12847 TypeInfo = I->second;
12848 return true;
12849}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012850
12851void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
12852 uint64_t MagicValue, QualType Type,
12853 bool LayoutCompatible,
12854 bool MustBeNull) {
12855 if (!TypeTagForDatatypeMagicValues)
12856 TypeTagForDatatypeMagicValues.reset(
12857 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
12858
12859 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
12860 (*TypeTagForDatatypeMagicValues)[Magic] =
12861 TypeTagData(Type, LayoutCompatible, MustBeNull);
12862}
12863
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012864static bool IsSameCharType(QualType T1, QualType T2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012865 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
12866 if (!BT1)
12867 return false;
12868
12869 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
12870 if (!BT2)
12871 return false;
12872
12873 BuiltinType::Kind T1Kind = BT1->getKind();
12874 BuiltinType::Kind T2Kind = BT2->getKind();
12875
12876 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
12877 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
12878 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
12879 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
12880}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012881
12882void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012883 const ArrayRef<const Expr *> ExprArgs,
12884 SourceLocation CallSiteLoc) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012885 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
12886 bool IsPointerAttr = Attr->getIsPointer();
12887
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012888 // Retrieve the argument representing the 'type_tag'.
Joel E. Denny81508102018-03-13 14:51:22 +000012889 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
12890 if (TypeTagIdxAST >= ExprArgs.size()) {
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012891 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
Joel E. Denny81508102018-03-13 14:51:22 +000012892 << 0 << Attr->getTypeTagIdx().getSourceIndex();
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012893 return;
12894 }
Joel E. Denny81508102018-03-13 14:51:22 +000012895 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012896 bool FoundWrongKind;
12897 TypeTagData TypeInfo;
12898 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
12899 TypeTagForDatatypeMagicValues.get(),
12900 FoundWrongKind, TypeInfo)) {
12901 if (FoundWrongKind)
12902 Diag(TypeTagExpr->getExprLoc(),
12903 diag::warn_type_tag_for_datatype_wrong_kind)
12904 << TypeTagExpr->getSourceRange();
12905 return;
12906 }
12907
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012908 // Retrieve the argument representing the 'arg_idx'.
Joel E. Denny81508102018-03-13 14:51:22 +000012909 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
12910 if (ArgumentIdxAST >= ExprArgs.size()) {
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012911 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
Joel E. Denny81508102018-03-13 14:51:22 +000012912 << 1 << Attr->getArgumentIdx().getSourceIndex();
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012913 return;
12914 }
Joel E. Denny81508102018-03-13 14:51:22 +000012915 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012916 if (IsPointerAttr) {
12917 // Skip implicit cast of pointer to `void *' (as a function argument).
12918 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000012919 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000012920 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012921 ArgumentExpr = ICE->getSubExpr();
12922 }
12923 QualType ArgumentType = ArgumentExpr->getType();
12924
12925 // Passing a `void*' pointer shouldn't trigger a warning.
12926 if (IsPointerAttr && ArgumentType->isVoidPointerType())
12927 return;
12928
12929 if (TypeInfo.MustBeNull) {
12930 // Type tag with matching void type requires a null pointer.
12931 if (!ArgumentExpr->isNullPointerConstant(Context,
12932 Expr::NPC_ValueDependentIsNotNull)) {
12933 Diag(ArgumentExpr->getExprLoc(),
12934 diag::warn_type_safety_null_pointer_required)
12935 << ArgumentKind->getName()
12936 << ArgumentExpr->getSourceRange()
12937 << TypeTagExpr->getSourceRange();
12938 }
12939 return;
12940 }
12941
12942 QualType RequiredType = TypeInfo.Type;
12943 if (IsPointerAttr)
12944 RequiredType = Context.getPointerType(RequiredType);
12945
12946 bool mismatch = false;
12947 if (!TypeInfo.LayoutCompatible) {
12948 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
12949
12950 // C++11 [basic.fundamental] p1:
12951 // Plain char, signed char, and unsigned char are three distinct types.
12952 //
12953 // But we treat plain `char' as equivalent to `signed char' or `unsigned
12954 // char' depending on the current char signedness mode.
12955 if (mismatch)
12956 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
12957 RequiredType->getPointeeType())) ||
12958 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
12959 mismatch = false;
12960 } else
12961 if (IsPointerAttr)
12962 mismatch = !isLayoutCompatible(Context,
12963 ArgumentType->getPointeeType(),
12964 RequiredType->getPointeeType());
12965 else
12966 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
12967
12968 if (mismatch)
12969 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000012970 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012971 << TypeInfo.LayoutCompatible << RequiredType
12972 << ArgumentExpr->getSourceRange()
12973 << TypeTagExpr->getSourceRange();
12974}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012975
12976void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
12977 CharUnits Alignment) {
12978 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
12979}
12980
12981void Sema::DiagnoseMisalignedMembers() {
12982 for (MisalignedMember &m : MisalignedMembers) {
Alex Lorenz014181e2016-10-05 09:27:48 +000012983 const NamedDecl *ND = m.RD;
12984 if (ND->getName().empty()) {
12985 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
12986 ND = TD;
12987 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012988 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
Alex Lorenz014181e2016-10-05 09:27:48 +000012989 << m.MD << ND << m.E->getSourceRange();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012990 }
12991 MisalignedMembers.clear();
12992}
12993
12994void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012995 E = E->IgnoreParens();
12996 if (!T->isPointerType() && !T->isIntegerType())
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012997 return;
12998 if (isa<UnaryOperator>(E) &&
12999 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
13000 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
13001 if (isa<MemberExpr>(Op)) {
13002 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
13003 MisalignedMember(Op));
13004 if (MA != MisalignedMembers.end() &&
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013005 (T->isIntegerType() ||
Roger Ferrer Ibanezd80d6c52017-12-07 09:23:50 +000013006 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
13007 Context.getTypeAlignInChars(
13008 T->getPointeeType()) <= MA->Alignment))))
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013009 MisalignedMembers.erase(MA);
13010 }
13011 }
13012}
13013
13014void Sema::RefersToMemberWithReducedAlignment(
13015 Expr *E,
Benjamin Kramera8c3e672016-12-12 14:41:19 +000013016 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
13017 Action) {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013018 const auto *ME = dyn_cast<MemberExpr>(E);
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013019 if (!ME)
13020 return;
13021
Roger Ferrer Ibanez9f963472017-03-13 13:18:21 +000013022 // No need to check expressions with an __unaligned-qualified type.
13023 if (E->getType().getQualifiers().hasUnaligned())
13024 return;
13025
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013026 // For a chain of MemberExpr like "a.b.c.d" this list
13027 // will keep FieldDecl's like [d, c, b].
13028 SmallVector<FieldDecl *, 4> ReverseMemberChain;
13029 const MemberExpr *TopME = nullptr;
13030 bool AnyIsPacked = false;
13031 do {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013032 QualType BaseType = ME->getBase()->getType();
13033 if (ME->isArrow())
13034 BaseType = BaseType->getPointeeType();
13035 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
Olivier Goffart67049f02017-07-07 09:38:59 +000013036 if (RD->isInvalidDecl())
13037 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013038
13039 ValueDecl *MD = ME->getMemberDecl();
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013040 auto *FD = dyn_cast<FieldDecl>(MD);
13041 // We do not care about non-data members.
13042 if (!FD || FD->isInvalidDecl())
13043 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013044
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013045 AnyIsPacked =
13046 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
13047 ReverseMemberChain.push_back(FD);
13048
13049 TopME = ME;
13050 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
13051 } while (ME);
13052 assert(TopME && "We did not compute a topmost MemberExpr!");
13053
13054 // Not the scope of this diagnostic.
13055 if (!AnyIsPacked)
13056 return;
13057
13058 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
13059 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
13060 // TODO: The innermost base of the member expression may be too complicated.
13061 // For now, just disregard these cases. This is left for future
13062 // improvement.
13063 if (!DRE && !isa<CXXThisExpr>(TopBase))
13064 return;
13065
13066 // Alignment expected by the whole expression.
13067 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
13068
13069 // No need to do anything else with this case.
13070 if (ExpectedAlignment.isOne())
13071 return;
13072
13073 // Synthesize offset of the whole access.
13074 CharUnits Offset;
13075 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
13076 I++) {
13077 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
13078 }
13079
13080 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
13081 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
13082 ReverseMemberChain.back()->getParent()->getTypeForDecl());
13083
13084 // The base expression of the innermost MemberExpr may give
13085 // stronger guarantees than the class containing the member.
13086 if (DRE && !TopME->isArrow()) {
13087 const ValueDecl *VD = DRE->getDecl();
13088 if (!VD->getType()->isReferenceType())
13089 CompleteObjectAlignment =
13090 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
13091 }
13092
13093 // Check if the synthesized offset fulfills the alignment.
13094 if (Offset % ExpectedAlignment != 0 ||
13095 // It may fulfill the offset it but the effective alignment may still be
13096 // lower than the expected expression alignment.
13097 CompleteObjectAlignment < ExpectedAlignment) {
13098 // If this happens, we want to determine a sensible culprit of this.
13099 // Intuitively, watching the chain of member expressions from right to
13100 // left, we start with the required alignment (as required by the field
13101 // type) but some packed attribute in that chain has reduced the alignment.
13102 // It may happen that another packed structure increases it again. But if
13103 // we are here such increase has not been enough. So pointing the first
13104 // FieldDecl that either is packed or else its RecordDecl is,
13105 // seems reasonable.
13106 FieldDecl *FD = nullptr;
13107 CharUnits Alignment;
13108 for (FieldDecl *FDI : ReverseMemberChain) {
13109 if (FDI->hasAttr<PackedAttr>() ||
13110 FDI->getParent()->hasAttr<PackedAttr>()) {
13111 FD = FDI;
13112 Alignment = std::min(
13113 Context.getTypeAlignInChars(FD->getType()),
13114 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
13115 break;
13116 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013117 }
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013118 assert(FD && "We did not find a packed FieldDecl!");
13119 Action(E, FD->getParent(), FD, Alignment);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013120 }
13121}
13122
13123void Sema::CheckAddressOfPackedMember(Expr *rhs) {
13124 using namespace std::placeholders;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013125
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013126 RefersToMemberWithReducedAlignment(
13127 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
13128 _2, _3, _4));
13129}