blob: 70e98e22b39725b12e511d5d9f015226f375bd4c [file] [log] [blame]
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00001//===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerb87b1b32007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump11289f42009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattnerb87b1b32007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000015#include "clang/AST/APValue.h"
Chris Lattnerb87b1b32007-08-10 20:18:51 +000016#include "clang/AST/ASTContext.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000017#include "clang/AST/Attr.h"
18#include "clang/AST/AttrIterator.h"
Ken Dyck40775002010-01-11 17:06:35 +000019#include "clang/AST/CharUnits.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000020#include "clang/AST/Decl.h"
21#include "clang/AST/DeclBase.h"
John McCall28a0cf72010-08-25 07:42:41 +000022#include "clang/AST/DeclCXX.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000023#include "clang/AST/DeclObjC.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000024#include "clang/AST/DeclarationName.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/AST/EvaluatedExprVisitor.h"
David Blaikie7555b6a2012-05-15 16:56:36 +000026#include "clang/AST/Expr.h"
Ted Kremenekc81614d2007-08-20 16:18:38 +000027#include "clang/AST/ExprCXX.h"
Ted Kremenek34f664d2008-06-16 18:00:42 +000028#include "clang/AST/ExprObjC.h"
Alexey Bataev1a3320e2015-08-25 14:24:04 +000029#include "clang/AST/ExprOpenMP.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000030#include "clang/AST/NSAPI.h"
31#include "clang/AST/OperationKinds.h"
32#include "clang/AST/Stmt.h"
33#include "clang/AST/TemplateBase.h"
34#include "clang/AST/Type.h"
35#include "clang/AST/TypeLoc.h"
36#include "clang/AST/UnresolvedSet.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000037#include "clang/Analysis/Analyses/FormatString.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000038#include "clang/Basic/AddressSpaces.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000039#include "clang/Basic/CharInfo.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000040#include "clang/Basic/Diagnostic.h"
41#include "clang/Basic/IdentifierTable.h"
42#include "clang/Basic/LLVM.h"
43#include "clang/Basic/LangOptions.h"
44#include "clang/Basic/OpenCLOptions.h"
45#include "clang/Basic/OperatorKinds.h"
46#include "clang/Basic/PartialDiagnostic.h"
47#include "clang/Basic/SourceLocation.h"
48#include "clang/Basic/SourceManager.h"
49#include "clang/Basic/Specifiers.h"
Yaxun Liu39195062017-08-04 18:16:31 +000050#include "clang/Basic/SyncScope.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000051#include "clang/Basic/TargetBuiltins.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000052#include "clang/Basic/TargetCXXABI.h"
Nate Begeman4904e322010-06-08 02:47:44 +000053#include "clang/Basic/TargetInfo.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000054#include "clang/Basic/TypeTraits.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000055#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
Chandler Carruth3a022472012-12-04 09:13:33 +000056#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000057#include "clang/Sema/Lookup.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000058#include "clang/Sema/Ownership.h"
59#include "clang/Sema/Scope.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000060#include "clang/Sema/ScopeInfo.h"
61#include "clang/Sema/Sema.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000062#include "clang/Sema/SemaInternal.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000063#include "llvm/ADT/APFloat.h"
64#include "llvm/ADT/APInt.h"
65#include "llvm/ADT/APSInt.h"
66#include "llvm/ADT/ArrayRef.h"
67#include "llvm/ADT/DenseMap.h"
68#include "llvm/ADT/FoldingSet.h"
69#include "llvm/ADT/None.h"
70#include "llvm/ADT/Optional.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000071#include "llvm/ADT/STLExtras.h"
Richard Smithd7293d72013-08-05 18:49:43 +000072#include "llvm/ADT/SmallBitVector.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000073#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000074#include "llvm/ADT/SmallString.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000075#include "llvm/ADT/SmallVector.h"
76#include "llvm/ADT/StringRef.h"
77#include "llvm/ADT/StringSwitch.h"
78#include "llvm/ADT/Triple.h"
79#include "llvm/Support/AtomicOrdering.h"
80#include "llvm/Support/Casting.h"
81#include "llvm/Support/Compiler.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000082#include "llvm/Support/ConvertUTF.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000083#include "llvm/Support/ErrorHandling.h"
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +000084#include "llvm/Support/Format.h"
85#include "llvm/Support/Locale.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000086#include "llvm/Support/MathExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000087#include "llvm/Support/raw_ostream.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000088#include <algorithm>
89#include <cassert>
90#include <cstddef>
91#include <cstdint>
92#include <functional>
93#include <limits>
94#include <string>
95#include <tuple>
96#include <utility>
Eugene Zelenko1ced5092016-02-12 22:53:10 +000097
Chris Lattnerb87b1b32007-08-10 20:18:51 +000098using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000099using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +0000100
Chris Lattnera26fb342009-02-18 17:49:48 +0000101SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
102 unsigned ByteNo) const {
Alp Tokerb6cc5922014-05-03 03:45:55 +0000103 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
104 Context.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +0000105}
106
John McCallbebede42011-02-26 05:39:39 +0000107/// Checks that a call expression's argument count is the desired number.
108/// This is useful when doing custom type-checking. Returns true on error.
109static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
110 unsigned argCount = call->getNumArgs();
111 if (argCount == desiredArgCount) return false;
112
113 if (argCount < desiredArgCount)
114 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
115 << 0 /*function call*/ << desiredArgCount << argCount
116 << call->getSourceRange();
117
118 // Highlight all the excess arguments.
119 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
120 call->getArg(argCount - 1)->getLocEnd());
Nico Weberade321e2018-04-10 18:53:28 +0000121
John McCallbebede42011-02-26 05:39:39 +0000122 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
123 << 0 /*function call*/ << desiredArgCount << argCount
124 << call->getArg(1)->getSourceRange();
125}
126
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000127/// Check that the first argument to __builtin_annotation is an integer
128/// and the second argument is a non-wide string literal.
129static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
130 if (checkArgCount(S, TheCall, 2))
131 return true;
132
133 // First argument should be an integer.
134 Expr *ValArg = TheCall->getArg(0);
135 QualType Ty = ValArg->getType();
136 if (!Ty->isIntegerType()) {
137 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
138 << ValArg->getSourceRange();
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000139 return true;
140 }
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000141
142 // Second argument should be a constant string.
143 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
144 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
145 if (!Literal || !Literal->isAscii()) {
146 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
147 << StrArg->getSourceRange();
148 return true;
149 }
150
151 TheCall->setType(Ty);
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000152 return false;
153}
154
Reid Kleckner30701ed2017-09-05 20:27:35 +0000155static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
156 // We need at least one argument.
157 if (TheCall->getNumArgs() < 1) {
158 S.Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
159 << 0 << 1 << TheCall->getNumArgs()
160 << TheCall->getCallee()->getSourceRange();
161 return true;
162 }
163
164 // All arguments should be wide string literals.
165 for (Expr *Arg : TheCall->arguments()) {
166 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
167 if (!Literal || !Literal->isWide()) {
168 S.Diag(Arg->getLocStart(), diag::err_msvc_annotation_wide_str)
169 << Arg->getSourceRange();
170 return true;
171 }
172 }
173
174 return false;
175}
176
Richard Smith6cbd65d2013-07-11 02:27:57 +0000177/// Check that the argument to __builtin_addressof is a glvalue, and set the
178/// result type to the corresponding pointer type.
179static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
180 if (checkArgCount(S, TheCall, 1))
181 return true;
182
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000183 ExprResult Arg(TheCall->getArg(0));
Richard Smith6cbd65d2013-07-11 02:27:57 +0000184 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
185 if (ResultType.isNull())
186 return true;
187
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000188 TheCall->setArg(0, Arg.get());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000189 TheCall->setType(ResultType);
190 return false;
191}
192
John McCall03107a42015-10-29 20:48:01 +0000193static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
194 if (checkArgCount(S, TheCall, 3))
195 return true;
196
197 // First two arguments should be integers.
198 for (unsigned I = 0; I < 2; ++I) {
199 Expr *Arg = TheCall->getArg(I);
200 QualType Ty = Arg->getType();
201 if (!Ty->isIntegerType()) {
202 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
203 << Ty << Arg->getSourceRange();
204 return true;
205 }
206 }
207
208 // Third argument should be a pointer to a non-const integer.
209 // IRGen correctly handles volatile, restrict, and address spaces, and
210 // the other qualifiers aren't possible.
211 {
212 Expr *Arg = TheCall->getArg(2);
213 QualType Ty = Arg->getType();
214 const auto *PtrTy = Ty->getAs<PointerType>();
215 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
216 !PtrTy->getPointeeType().isConstQualified())) {
217 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
218 << Ty << Arg->getSourceRange();
219 return true;
220 }
221 }
222
223 return false;
224}
225
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000226static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
Nico Weberade321e2018-04-10 18:53:28 +0000227 CallExpr *TheCall, unsigned SizeIdx,
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000228 unsigned DstSizeIdx) {
229 if (TheCall->getNumArgs() <= SizeIdx ||
230 TheCall->getNumArgs() <= DstSizeIdx)
231 return;
232
233 const Expr *SizeArg = TheCall->getArg(SizeIdx);
234 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
235
236 llvm::APSInt Size, DstSize;
237
238 // find out if both sizes are known at compile time
239 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
240 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
241 return;
242
243 if (Size.ule(DstSize))
244 return;
245
246 // confirmed overflow so generate the diagnostic.
247 IdentifierInfo *FnName = FDecl->getIdentifier();
248 SourceLocation SL = TheCall->getLocStart();
249 SourceRange SR = TheCall->getSourceRange();
250
251 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
252}
253
Peter Collingbournef7706832014-12-12 23:41:25 +0000254static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
255 if (checkArgCount(S, BuiltinCall, 2))
256 return true;
257
258 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
259 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
260 Expr *Call = BuiltinCall->getArg(0);
261 Expr *Chain = BuiltinCall->getArg(1);
262
263 if (Call->getStmtClass() != Stmt::CallExprClass) {
264 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
265 << Call->getSourceRange();
266 return true;
267 }
268
269 auto CE = cast<CallExpr>(Call);
270 if (CE->getCallee()->getType()->isBlockPointerType()) {
271 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
272 << Call->getSourceRange();
273 return true;
274 }
275
276 const Decl *TargetDecl = CE->getCalleeDecl();
277 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
278 if (FD->getBuiltinID()) {
279 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
280 << Call->getSourceRange();
281 return true;
282 }
283
284 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
285 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
286 << Call->getSourceRange();
287 return true;
288 }
289
290 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
291 if (ChainResult.isInvalid())
292 return true;
293 if (!ChainResult.get()->getType()->isPointerType()) {
294 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
295 << Chain->getSourceRange();
296 return true;
297 }
298
David Majnemerced8bdf2015-02-25 17:36:15 +0000299 QualType ReturnTy = CE->getCallReturnType(S.Context);
Peter Collingbournef7706832014-12-12 23:41:25 +0000300 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
301 QualType BuiltinTy = S.Context.getFunctionType(
302 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
303 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
304
305 Builtin =
306 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
307
308 BuiltinCall->setType(CE->getType());
309 BuiltinCall->setValueKind(CE->getValueKind());
310 BuiltinCall->setObjectKind(CE->getObjectKind());
311 BuiltinCall->setCallee(Builtin);
312 BuiltinCall->setArg(1, ChainResult.get());
313
314 return false;
315}
316
Reid Kleckner1d59f992015-01-22 01:36:17 +0000317static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
318 Scope::ScopeFlags NeededScopeFlags,
319 unsigned DiagID) {
320 // Scopes aren't available during instantiation. Fortunately, builtin
321 // functions cannot be template args so they cannot be formed through template
322 // instantiation. Therefore checking once during the parse is sufficient.
Richard Smith51ec0cf2017-02-21 01:17:38 +0000323 if (SemaRef.inTemplateInstantiation())
Reid Kleckner1d59f992015-01-22 01:36:17 +0000324 return false;
325
326 Scope *S = SemaRef.getCurScope();
327 while (S && !S->isSEHExceptScope())
328 S = S->getParent();
329 if (!S || !(S->getFlags() & NeededScopeFlags)) {
330 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
331 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
332 << DRE->getDecl()->getIdentifier();
333 return true;
334 }
335
336 return false;
337}
338
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000339static inline bool isBlockPointer(Expr *Arg) {
340 return Arg->getType()->isBlockPointerType();
341}
342
343/// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
344/// void*, which is a requirement of device side enqueue.
345static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
346 const BlockPointerType *BPT =
347 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
348 ArrayRef<QualType> Params =
349 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
350 unsigned ArgCounter = 0;
351 bool IllegalParams = false;
352 // Iterate through the block parameters until either one is found that is not
353 // a local void*, or the block is valid.
354 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
355 I != E; ++I, ++ArgCounter) {
356 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
357 (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
358 LangAS::opencl_local) {
359 // Get the location of the error. If a block literal has been passed
360 // (BlockExpr) then we can point straight to the offending argument,
361 // else we just point to the variable reference.
362 SourceLocation ErrorLoc;
363 if (isa<BlockExpr>(BlockArg)) {
364 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
365 ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
366 } else if (isa<DeclRefExpr>(BlockArg)) {
367 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
368 }
369 S.Diag(ErrorLoc,
370 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
371 IllegalParams = true;
372 }
373 }
374
375 return IllegalParams;
376}
377
Joey Gouly84ae3362017-07-31 15:15:59 +0000378static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
379 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
380 S.Diag(Call->getLocStart(), diag::err_opencl_requires_extension)
381 << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
382 return true;
383 }
384 return false;
385}
386
Joey Goulyfa76b492017-08-01 13:27:09 +0000387static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
388 if (checkArgCount(S, TheCall, 2))
389 return true;
390
391 if (checkOpenCLSubgroupExt(S, TheCall))
392 return true;
393
394 // First argument is an ndrange_t type.
395 Expr *NDRangeArg = TheCall->getArg(0);
Yaxun Liub7318e02017-10-13 03:37:48 +0000396 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
Joey Goulyfa76b492017-08-01 13:27:09 +0000397 S.Diag(NDRangeArg->getLocStart(),
398 diag::err_opencl_builtin_expected_type)
399 << TheCall->getDirectCallee() << "'ndrange_t'";
400 return true;
401 }
402
403 Expr *BlockArg = TheCall->getArg(1);
404 if (!isBlockPointer(BlockArg)) {
405 S.Diag(BlockArg->getLocStart(),
406 diag::err_opencl_builtin_expected_type)
407 << TheCall->getDirectCallee() << "block";
408 return true;
409 }
410 return checkOpenCLBlockArgs(S, BlockArg);
411}
412
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000413/// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
414/// get_kernel_work_group_size
415/// and get_kernel_preferred_work_group_size_multiple builtin functions.
416static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
417 if (checkArgCount(S, TheCall, 1))
418 return true;
419
420 Expr *BlockArg = TheCall->getArg(0);
421 if (!isBlockPointer(BlockArg)) {
422 S.Diag(BlockArg->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000423 diag::err_opencl_builtin_expected_type)
424 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000425 return true;
426 }
427 return checkOpenCLBlockArgs(S, BlockArg);
428}
429
Simon Pilgrim2c518802017-03-30 14:13:19 +0000430/// Diagnose integer type and any valid implicit conversion to it.
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000431static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
432 const QualType &IntType);
433
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000434static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000435 unsigned Start, unsigned End) {
436 bool IllegalParams = false;
437 for (unsigned I = Start; I <= End; ++I)
438 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
439 S.Context.getSizeType());
440 return IllegalParams;
441}
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000442
443/// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
444/// 'local void*' parameter of passed block.
445static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
446 Expr *BlockArg,
447 unsigned NumNonVarArgs) {
448 const BlockPointerType *BPT =
449 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
450 unsigned NumBlockParams =
451 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
452 unsigned TotalNumArgs = TheCall->getNumArgs();
453
454 // For each argument passed to the block, a corresponding uint needs to
455 // be passed to describe the size of the local memory.
456 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
457 S.Diag(TheCall->getLocStart(),
458 diag::err_opencl_enqueue_kernel_local_size_args);
459 return true;
460 }
461
462 // Check that the sizes of the local memory are specified by integers.
463 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
464 TotalNumArgs - 1);
465}
466
467/// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
468/// overload formats specified in Table 6.13.17.1.
469/// int enqueue_kernel(queue_t queue,
470/// kernel_enqueue_flags_t flags,
471/// const ndrange_t ndrange,
472/// void (^block)(void))
473/// int enqueue_kernel(queue_t queue,
474/// kernel_enqueue_flags_t flags,
475/// const ndrange_t ndrange,
476/// uint num_events_in_wait_list,
477/// clk_event_t *event_wait_list,
478/// clk_event_t *event_ret,
479/// void (^block)(void))
480/// int enqueue_kernel(queue_t queue,
481/// kernel_enqueue_flags_t flags,
482/// const ndrange_t ndrange,
483/// void (^block)(local void*, ...),
484/// uint size0, ...)
485/// int enqueue_kernel(queue_t queue,
486/// kernel_enqueue_flags_t flags,
487/// const ndrange_t ndrange,
488/// uint num_events_in_wait_list,
489/// clk_event_t *event_wait_list,
490/// clk_event_t *event_ret,
491/// void (^block)(local void*, ...),
492/// uint size0, ...)
493static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
494 unsigned NumArgs = TheCall->getNumArgs();
495
496 if (NumArgs < 4) {
497 S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
498 return true;
499 }
500
501 Expr *Arg0 = TheCall->getArg(0);
502 Expr *Arg1 = TheCall->getArg(1);
503 Expr *Arg2 = TheCall->getArg(2);
504 Expr *Arg3 = TheCall->getArg(3);
505
506 // First argument always needs to be a queue_t type.
507 if (!Arg0->getType()->isQueueT()) {
508 S.Diag(TheCall->getArg(0)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000509 diag::err_opencl_builtin_expected_type)
510 << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000511 return true;
512 }
513
514 // Second argument always needs to be a kernel_enqueue_flags_t enum value.
515 if (!Arg1->getType()->isIntegerType()) {
516 S.Diag(TheCall->getArg(1)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000517 diag::err_opencl_builtin_expected_type)
518 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000519 return true;
520 }
521
522 // Third argument is always an ndrange_t type.
Anastasia Stulovab42f3c02017-04-21 15:13:24 +0000523 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000524 S.Diag(TheCall->getArg(2)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000525 diag::err_opencl_builtin_expected_type)
526 << TheCall->getDirectCallee() << "'ndrange_t'";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000527 return true;
528 }
529
530 // With four arguments, there is only one form that the function could be
531 // called in: no events and no variable arguments.
532 if (NumArgs == 4) {
533 // check that the last argument is the right block type.
534 if (!isBlockPointer(Arg3)) {
Joey Gouly6b03d952017-07-04 11:50:23 +0000535 S.Diag(Arg3->getLocStart(), diag::err_opencl_builtin_expected_type)
536 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000537 return true;
538 }
539 // we have a block type, check the prototype
540 const BlockPointerType *BPT =
541 cast<BlockPointerType>(Arg3->getType().getCanonicalType());
542 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
543 S.Diag(Arg3->getLocStart(),
544 diag::err_opencl_enqueue_kernel_blocks_no_args);
545 return true;
546 }
547 return false;
548 }
549 // we can have block + varargs.
550 if (isBlockPointer(Arg3))
551 return (checkOpenCLBlockArgs(S, Arg3) ||
552 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
553 // last two cases with either exactly 7 args or 7 args and varargs.
554 if (NumArgs >= 7) {
555 // check common block argument.
556 Expr *Arg6 = TheCall->getArg(6);
557 if (!isBlockPointer(Arg6)) {
Joey Gouly6b03d952017-07-04 11:50:23 +0000558 S.Diag(Arg6->getLocStart(), diag::err_opencl_builtin_expected_type)
559 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000560 return true;
561 }
562 if (checkOpenCLBlockArgs(S, Arg6))
563 return true;
564
565 // Forth argument has to be any integer type.
566 if (!Arg3->getType()->isIntegerType()) {
567 S.Diag(TheCall->getArg(3)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000568 diag::err_opencl_builtin_expected_type)
569 << TheCall->getDirectCallee() << "integer";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000570 return true;
571 }
572 // check remaining common arguments.
573 Expr *Arg4 = TheCall->getArg(4);
574 Expr *Arg5 = TheCall->getArg(5);
575
Anastasia Stulova2b461202016-11-14 15:34:01 +0000576 // Fifth argument is always passed as a pointer to clk_event_t.
577 if (!Arg4->isNullPointerConstant(S.Context,
578 Expr::NPC_ValueDependentIsNotNull) &&
579 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000580 S.Diag(TheCall->getArg(4)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000581 diag::err_opencl_builtin_expected_type)
582 << TheCall->getDirectCallee()
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000583 << S.Context.getPointerType(S.Context.OCLClkEventTy);
584 return true;
585 }
586
Anastasia Stulova2b461202016-11-14 15:34:01 +0000587 // Sixth argument is always passed as a pointer to clk_event_t.
588 if (!Arg5->isNullPointerConstant(S.Context,
589 Expr::NPC_ValueDependentIsNotNull) &&
590 !(Arg5->getType()->isPointerType() &&
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000591 Arg5->getType()->getPointeeType()->isClkEventT())) {
592 S.Diag(TheCall->getArg(5)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000593 diag::err_opencl_builtin_expected_type)
594 << TheCall->getDirectCallee()
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000595 << S.Context.getPointerType(S.Context.OCLClkEventTy);
596 return true;
597 }
598
599 if (NumArgs == 7)
600 return false;
601
602 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
603 }
604
605 // None of the specific case has been detected, give generic error
606 S.Diag(TheCall->getLocStart(),
607 diag::err_opencl_enqueue_kernel_incorrect_args);
608 return true;
609}
610
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000611/// Returns OpenCL access qual.
Xiuli Pan11e13f62016-02-26 03:13:03 +0000612static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
Xiuli Pan11e13f62016-02-26 03:13:03 +0000613 return D->getAttr<OpenCLAccessAttr>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000614}
615
616/// Returns true if pipe element type is different from the pointer.
617static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
618 const Expr *Arg0 = Call->getArg(0);
619 // First argument type should always be pipe.
620 if (!Arg0->getType()->isPipeType()) {
621 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000622 << Call->getDirectCallee() << Arg0->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000623 return true;
624 }
Xiuli Pan11e13f62016-02-26 03:13:03 +0000625 OpenCLAccessAttr *AccessQual =
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000626 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
627 // Validates the access qualifier is compatible with the call.
628 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
629 // read_only and write_only, and assumed to be read_only if no qualifier is
630 // specified.
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000631 switch (Call->getDirectCallee()->getBuiltinID()) {
632 case Builtin::BIread_pipe:
633 case Builtin::BIreserve_read_pipe:
634 case Builtin::BIcommit_read_pipe:
635 case Builtin::BIwork_group_reserve_read_pipe:
636 case Builtin::BIsub_group_reserve_read_pipe:
637 case Builtin::BIwork_group_commit_read_pipe:
638 case Builtin::BIsub_group_commit_read_pipe:
639 if (!(!AccessQual || AccessQual->isReadOnly())) {
640 S.Diag(Arg0->getLocStart(),
641 diag::err_opencl_builtin_pipe_invalid_access_modifier)
642 << "read_only" << Arg0->getSourceRange();
643 return true;
644 }
645 break;
646 case Builtin::BIwrite_pipe:
647 case Builtin::BIreserve_write_pipe:
648 case Builtin::BIcommit_write_pipe:
649 case Builtin::BIwork_group_reserve_write_pipe:
650 case Builtin::BIsub_group_reserve_write_pipe:
651 case Builtin::BIwork_group_commit_write_pipe:
652 case Builtin::BIsub_group_commit_write_pipe:
653 if (!(AccessQual && AccessQual->isWriteOnly())) {
654 S.Diag(Arg0->getLocStart(),
655 diag::err_opencl_builtin_pipe_invalid_access_modifier)
656 << "write_only" << Arg0->getSourceRange();
657 return true;
658 }
659 break;
660 default:
661 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000662 }
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000663 return false;
664}
665
666/// Returns true if pipe element type is different from the pointer.
667static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
668 const Expr *Arg0 = Call->getArg(0);
669 const Expr *ArgIdx = Call->getArg(Idx);
670 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000671 const QualType EltTy = PipeTy->getElementType();
672 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000673 // The Idx argument should be a pointer and the type of the pointer and
674 // the type of pipe element should also be the same.
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000675 if (!ArgTy ||
676 !S.Context.hasSameType(
677 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000678 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000679 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000680 << ArgIdx->getType() << ArgIdx->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000681 return true;
682 }
683 return false;
684}
685
686// \brief Performs semantic analysis for the read/write_pipe call.
687// \param S Reference to the semantic analyzer.
688// \param Call A pointer to the builtin call.
689// \return True if a semantic error has been found, false otherwise.
690static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000691 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
692 // functions have two forms.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000693 switch (Call->getNumArgs()) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +0000694 case 2:
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000695 if (checkOpenCLPipeArg(S, Call))
696 return true;
697 // The call with 2 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000698 // read/write_pipe(pipe T, T*).
699 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000700 if (checkOpenCLPipePacketType(S, Call, 1))
701 return true;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +0000702 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000703
704 case 4: {
705 if (checkOpenCLPipeArg(S, Call))
706 return true;
707 // The call with 4 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000708 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
709 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000710 if (!Call->getArg(1)->getType()->isReserveIDT()) {
711 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000712 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000713 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000714 return true;
715 }
716
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000717 // Check the index.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000718 const Expr *Arg2 = Call->getArg(2);
719 if (!Arg2->getType()->isIntegerType() &&
720 !Arg2->getType()->isUnsignedIntegerType()) {
721 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000722 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000723 << Arg2->getType() << Arg2->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000724 return true;
725 }
726
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000727 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000728 if (checkOpenCLPipePacketType(S, Call, 3))
729 return true;
730 } break;
731 default:
732 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000733 << Call->getDirectCallee() << Call->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000734 return true;
735 }
736
737 return false;
738}
739
740// \brief Performs a semantic analysis on the {work_group_/sub_group_
741// /_}reserve_{read/write}_pipe
742// \param S Reference to the semantic analyzer.
743// \param Call The call to the builtin function to be analyzed.
744// \return True if a semantic error was found, false otherwise.
745static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
746 if (checkArgCount(S, Call, 2))
747 return true;
748
749 if (checkOpenCLPipeArg(S, Call))
750 return true;
751
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000752 // Check the reserve size.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000753 if (!Call->getArg(1)->getType()->isIntegerType() &&
754 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
755 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000756 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000757 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000758 return true;
759 }
760
Joey Gouly922ca232017-08-09 14:52:47 +0000761 // Since return type of reserve_read/write_pipe built-in function is
762 // reserve_id_t, which is not defined in the builtin def file , we used int
763 // as return type and need to override the return type of these functions.
764 Call->setType(S.Context.OCLReserveIDTy);
765
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000766 return false;
767}
768
769// \brief Performs a semantic analysis on {work_group_/sub_group_
770// /_}commit_{read/write}_pipe
771// \param S Reference to the semantic analyzer.
772// \param Call The call to the builtin function to be analyzed.
773// \return True if a semantic error was found, false otherwise.
774static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
775 if (checkArgCount(S, Call, 2))
776 return true;
777
778 if (checkOpenCLPipeArg(S, Call))
779 return true;
780
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000781 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000782 if (!Call->getArg(1)->getType()->isReserveIDT()) {
783 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000784 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000785 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000786 return true;
787 }
788
789 return false;
790}
791
792// \brief Performs a semantic analysis on the call to built-in Pipe
793// Query Functions.
794// \param S Reference to the semantic analyzer.
795// \param Call The call to the builtin function to be analyzed.
796// \return True if a semantic error was found, false otherwise.
797static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
798 if (checkArgCount(S, Call, 1))
799 return true;
800
801 if (!Call->getArg(0)->getType()->isPipeType()) {
802 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000803 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000804 return true;
805 }
806
807 return false;
808}
Eugene Zelenko11a7ef82017-11-15 22:00:04 +0000809
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +0000810// \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
Yaxun Liuf7449a12016-05-20 19:54:38 +0000811// \brief Performs semantic analysis for the to_global/local/private call.
812// \param S Reference to the semantic analyzer.
813// \param BuiltinID ID of the builtin function.
814// \param Call A pointer to the builtin call.
815// \return True if a semantic error has been found, false otherwise.
816static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
817 CallExpr *Call) {
Yaxun Liuf7449a12016-05-20 19:54:38 +0000818 if (Call->getNumArgs() != 1) {
819 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
820 << Call->getDirectCallee() << Call->getSourceRange();
821 return true;
822 }
823
824 auto RT = Call->getArg(0)->getType();
825 if (!RT->isPointerType() || RT->getPointeeType()
826 .getAddressSpace() == LangAS::opencl_constant) {
827 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
828 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
829 return true;
830 }
831
832 RT = RT->getPointeeType();
833 auto Qual = RT.getQualifiers();
834 switch (BuiltinID) {
835 case Builtin::BIto_global:
836 Qual.setAddressSpace(LangAS::opencl_global);
837 break;
838 case Builtin::BIto_local:
839 Qual.setAddressSpace(LangAS::opencl_local);
840 break;
Yaxun Liub7318e02017-10-13 03:37:48 +0000841 case Builtin::BIto_private:
842 Qual.setAddressSpace(LangAS::opencl_private);
843 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +0000844 default:
Yaxun Liub7318e02017-10-13 03:37:48 +0000845 llvm_unreachable("Invalid builtin function");
Yaxun Liuf7449a12016-05-20 19:54:38 +0000846 }
847 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
848 RT.getUnqualifiedType(), Qual)));
849
850 return false;
851}
852
John McCalldadc5752010-08-24 06:29:42 +0000853ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000854Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
855 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000856 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000857
Chris Lattner3be167f2010-10-01 23:23:24 +0000858 // Find out if any arguments are required to be integer constant expressions.
859 unsigned ICEArguments = 0;
860 ASTContext::GetBuiltinTypeError Error;
861 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
862 if (Error != ASTContext::GE_None)
863 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
864
865 // If any arguments are required to be ICE's, check and diagnose.
866 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
867 // Skip arguments not required to be ICE's.
868 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
869
870 llvm::APSInt Result;
871 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
872 return true;
873 ICEArguments &= ~(1 << ArgNo);
874 }
875
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000876 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000877 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000878 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000879 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000880 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000881 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000882 break;
Martin Storsjo022e7822017-07-17 20:49:45 +0000883 case Builtin::BI__builtin_ms_va_start:
Ted Kremeneka174c522008-07-09 17:58:53 +0000884 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000885 case Builtin::BI__builtin_va_start:
Reid Kleckner2b0fa122017-05-02 20:10:03 +0000886 if (SemaBuiltinVAStart(BuiltinID, TheCall))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000887 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000888 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000889 case Builtin::BI__va_start: {
890 switch (Context.getTargetInfo().getTriple().getArch()) {
891 case llvm::Triple::arm:
892 case llvm::Triple::thumb:
Saleem Abdulrasool3450aa72017-09-26 20:12:04 +0000893 if (SemaBuiltinVAStartARMMicrosoft(TheCall))
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000894 return ExprError();
895 break;
896 default:
Reid Kleckner2b0fa122017-05-02 20:10:03 +0000897 if (SemaBuiltinVAStart(BuiltinID, TheCall))
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000898 return ExprError();
899 break;
900 }
901 break;
902 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000903 case Builtin::BI__builtin_isgreater:
904 case Builtin::BI__builtin_isgreaterequal:
905 case Builtin::BI__builtin_isless:
906 case Builtin::BI__builtin_islessequal:
907 case Builtin::BI__builtin_islessgreater:
908 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000909 if (SemaBuiltinUnorderedCompare(TheCall))
910 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000911 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000912 case Builtin::BI__builtin_fpclassify:
913 if (SemaBuiltinFPClassification(TheCall, 6))
914 return ExprError();
915 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000916 case Builtin::BI__builtin_isfinite:
917 case Builtin::BI__builtin_isinf:
918 case Builtin::BI__builtin_isinf_sign:
919 case Builtin::BI__builtin_isnan:
920 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000921 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000922 return ExprError();
923 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000924 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000925 return SemaBuiltinShuffleVector(TheCall);
926 // TheCall will be freed by the smart pointer here, but that's fine, since
927 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000928 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000929 if (SemaBuiltinPrefetch(TheCall))
930 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000931 break;
David Majnemer51169932016-10-31 05:37:48 +0000932 case Builtin::BI__builtin_alloca_with_align:
933 if (SemaBuiltinAllocaWithAlign(TheCall))
934 return ExprError();
935 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000936 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000937 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000938 if (SemaBuiltinAssume(TheCall))
939 return ExprError();
940 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000941 case Builtin::BI__builtin_assume_aligned:
942 if (SemaBuiltinAssumeAligned(TheCall))
943 return ExprError();
944 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000945 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000946 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000947 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000948 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000949 case Builtin::BI__builtin_longjmp:
950 if (SemaBuiltinLongjmp(TheCall))
951 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000952 break;
Joerg Sonnenberger27173282015-03-11 23:46:32 +0000953 case Builtin::BI__builtin_setjmp:
954 if (SemaBuiltinSetjmp(TheCall))
955 return ExprError();
956 break;
David Majnemerc403a1c2015-03-20 17:03:35 +0000957 case Builtin::BI_setjmp:
958 case Builtin::BI_setjmpex:
959 if (checkArgCount(*this, TheCall, 1))
960 return true;
961 break;
John McCallbebede42011-02-26 05:39:39 +0000962 case Builtin::BI__builtin_classify_type:
963 if (checkArgCount(*this, TheCall, 1)) return true;
964 TheCall->setType(Context.IntTy);
965 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000966 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000967 if (checkArgCount(*this, TheCall, 1)) return true;
968 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000969 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000970 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000971 case Builtin::BI__sync_fetch_and_add_1:
972 case Builtin::BI__sync_fetch_and_add_2:
973 case Builtin::BI__sync_fetch_and_add_4:
974 case Builtin::BI__sync_fetch_and_add_8:
975 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000976 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000977 case Builtin::BI__sync_fetch_and_sub_1:
978 case Builtin::BI__sync_fetch_and_sub_2:
979 case Builtin::BI__sync_fetch_and_sub_4:
980 case Builtin::BI__sync_fetch_and_sub_8:
981 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000982 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000983 case Builtin::BI__sync_fetch_and_or_1:
984 case Builtin::BI__sync_fetch_and_or_2:
985 case Builtin::BI__sync_fetch_and_or_4:
986 case Builtin::BI__sync_fetch_and_or_8:
987 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000988 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000989 case Builtin::BI__sync_fetch_and_and_1:
990 case Builtin::BI__sync_fetch_and_and_2:
991 case Builtin::BI__sync_fetch_and_and_4:
992 case Builtin::BI__sync_fetch_and_and_8:
993 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000994 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000995 case Builtin::BI__sync_fetch_and_xor_1:
996 case Builtin::BI__sync_fetch_and_xor_2:
997 case Builtin::BI__sync_fetch_and_xor_4:
998 case Builtin::BI__sync_fetch_and_xor_8:
999 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001000 case Builtin::BI__sync_fetch_and_nand:
1001 case Builtin::BI__sync_fetch_and_nand_1:
1002 case Builtin::BI__sync_fetch_and_nand_2:
1003 case Builtin::BI__sync_fetch_and_nand_4:
1004 case Builtin::BI__sync_fetch_and_nand_8:
1005 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001006 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001007 case Builtin::BI__sync_add_and_fetch_1:
1008 case Builtin::BI__sync_add_and_fetch_2:
1009 case Builtin::BI__sync_add_and_fetch_4:
1010 case Builtin::BI__sync_add_and_fetch_8:
1011 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001012 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001013 case Builtin::BI__sync_sub_and_fetch_1:
1014 case Builtin::BI__sync_sub_and_fetch_2:
1015 case Builtin::BI__sync_sub_and_fetch_4:
1016 case Builtin::BI__sync_sub_and_fetch_8:
1017 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001018 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001019 case Builtin::BI__sync_and_and_fetch_1:
1020 case Builtin::BI__sync_and_and_fetch_2:
1021 case Builtin::BI__sync_and_and_fetch_4:
1022 case Builtin::BI__sync_and_and_fetch_8:
1023 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001024 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001025 case Builtin::BI__sync_or_and_fetch_1:
1026 case Builtin::BI__sync_or_and_fetch_2:
1027 case Builtin::BI__sync_or_and_fetch_4:
1028 case Builtin::BI__sync_or_and_fetch_8:
1029 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001030 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001031 case Builtin::BI__sync_xor_and_fetch_1:
1032 case Builtin::BI__sync_xor_and_fetch_2:
1033 case Builtin::BI__sync_xor_and_fetch_4:
1034 case Builtin::BI__sync_xor_and_fetch_8:
1035 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001036 case Builtin::BI__sync_nand_and_fetch:
1037 case Builtin::BI__sync_nand_and_fetch_1:
1038 case Builtin::BI__sync_nand_and_fetch_2:
1039 case Builtin::BI__sync_nand_and_fetch_4:
1040 case Builtin::BI__sync_nand_and_fetch_8:
1041 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001042 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001043 case Builtin::BI__sync_val_compare_and_swap_1:
1044 case Builtin::BI__sync_val_compare_and_swap_2:
1045 case Builtin::BI__sync_val_compare_and_swap_4:
1046 case Builtin::BI__sync_val_compare_and_swap_8:
1047 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001048 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001049 case Builtin::BI__sync_bool_compare_and_swap_1:
1050 case Builtin::BI__sync_bool_compare_and_swap_2:
1051 case Builtin::BI__sync_bool_compare_and_swap_4:
1052 case Builtin::BI__sync_bool_compare_and_swap_8:
1053 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001054 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +00001055 case Builtin::BI__sync_lock_test_and_set_1:
1056 case Builtin::BI__sync_lock_test_and_set_2:
1057 case Builtin::BI__sync_lock_test_and_set_4:
1058 case Builtin::BI__sync_lock_test_and_set_8:
1059 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001060 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001061 case Builtin::BI__sync_lock_release_1:
1062 case Builtin::BI__sync_lock_release_2:
1063 case Builtin::BI__sync_lock_release_4:
1064 case Builtin::BI__sync_lock_release_8:
1065 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001066 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001067 case Builtin::BI__sync_swap_1:
1068 case Builtin::BI__sync_swap_2:
1069 case Builtin::BI__sync_swap_4:
1070 case Builtin::BI__sync_swap_8:
1071 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001072 return SemaBuiltinAtomicOverloaded(TheCallResult);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001073 case Builtin::BI__builtin_nontemporal_load:
1074 case Builtin::BI__builtin_nontemporal_store:
1075 return SemaBuiltinNontemporalOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +00001076#define BUILTIN(ID, TYPE, ATTRS)
1077#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1078 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001079 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +00001080#include "clang/Basic/Builtins.def"
Reid Kleckner30701ed2017-09-05 20:27:35 +00001081 case Builtin::BI__annotation:
1082 if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1083 return ExprError();
1084 break;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001085 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +00001086 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001087 return ExprError();
1088 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +00001089 case Builtin::BI__builtin_addressof:
1090 if (SemaBuiltinAddressof(*this, TheCall))
1091 return ExprError();
1092 break;
John McCall03107a42015-10-29 20:48:01 +00001093 case Builtin::BI__builtin_add_overflow:
1094 case Builtin::BI__builtin_sub_overflow:
1095 case Builtin::BI__builtin_mul_overflow:
Craig Toppera86e70d2015-11-07 06:16:14 +00001096 if (SemaBuiltinOverflow(*this, TheCall))
1097 return ExprError();
1098 break;
Richard Smith760520b2014-06-03 23:27:44 +00001099 case Builtin::BI__builtin_operator_new:
Eric Fiselierfa752f22018-03-21 19:19:48 +00001100 case Builtin::BI__builtin_operator_delete: {
1101 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1102 ExprResult Res =
1103 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1104 if (Res.isInvalid())
1105 CorrectDelayedTyposInExpr(TheCallResult.get());
1106 return Res;
1107 }
Aaron Ballman06525342018-04-10 21:58:13 +00001108 case Builtin::BI__builtin_dump_struct: {
1109 // We first want to ensure we are called with 2 arguments
1110 if (checkArgCount(*this, TheCall, 2))
1111 return ExprError();
1112 // Ensure that the first argument is of type 'struct XX *'
1113 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1114 const QualType PtrArgType = PtrArg->getType();
1115 if (!PtrArgType->isPointerType() ||
1116 !PtrArgType->getPointeeType()->isRecordType()) {
1117 Diag(PtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1118 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1119 << "structure pointer";
1120 return ExprError();
1121 }
1122
1123 // Ensure that the second argument is of type 'FunctionType'
1124 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1125 const QualType FnPtrArgType = FnPtrArg->getType();
1126 if (!FnPtrArgType->isPointerType()) {
1127 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1128 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1129 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1130 return ExprError();
1131 }
1132
1133 const auto *FuncType =
1134 FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1135
1136 if (!FuncType) {
1137 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1138 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1139 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1140 return ExprError();
1141 }
1142
1143 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1144 if (!FT->getNumParams()) {
1145 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1146 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1147 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1148 return ExprError();
1149 }
1150 QualType PT = FT->getParamType(0);
1151 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1152 !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1153 !PT->getPointeeType().isConstQualified()) {
1154 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1155 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1156 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1157 return ExprError();
1158 }
1159 }
1160
1161 TheCall->setType(Context.IntTy);
1162 break;
1163 }
1164
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001165 // check secure string manipulation functions where overflows
1166 // are detectable at compile time
1167 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001168 case Builtin::BI__builtin___memmove_chk:
1169 case Builtin::BI__builtin___memset_chk:
1170 case Builtin::BI__builtin___strlcat_chk:
1171 case Builtin::BI__builtin___strlcpy_chk:
1172 case Builtin::BI__builtin___strncat_chk:
1173 case Builtin::BI__builtin___strncpy_chk:
1174 case Builtin::BI__builtin___stpncpy_chk:
1175 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
1176 break;
Steven Wu566c14e2014-09-24 04:37:33 +00001177 case Builtin::BI__builtin___memccpy_chk:
1178 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
1179 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001180 case Builtin::BI__builtin___snprintf_chk:
1181 case Builtin::BI__builtin___vsnprintf_chk:
1182 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
1183 break;
Peter Collingbournef7706832014-12-12 23:41:25 +00001184 case Builtin::BI__builtin_call_with_static_chain:
1185 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1186 return ExprError();
1187 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001188 case Builtin::BI__exception_code:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001189 case Builtin::BI_exception_code:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001190 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1191 diag::err_seh___except_block))
1192 return ExprError();
1193 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001194 case Builtin::BI__exception_info:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001195 case Builtin::BI_exception_info:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001196 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1197 diag::err_seh___except_filter))
1198 return ExprError();
1199 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +00001200 case Builtin::BI__GetExceptionInfo:
1201 if (checkArgCount(*this, TheCall, 1))
1202 return ExprError();
1203
1204 if (CheckCXXThrowOperand(
1205 TheCall->getLocStart(),
1206 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1207 TheCall))
1208 return ExprError();
1209
1210 TheCall->setType(Context.VoidPtrTy);
1211 break;
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +00001212 // OpenCL v2.0, s6.13.16 - Pipe functions
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001213 case Builtin::BIread_pipe:
1214 case Builtin::BIwrite_pipe:
1215 // Since those two functions are declared with var args, we need a semantic
1216 // check for the argument.
1217 if (SemaBuiltinRWPipe(*this, TheCall))
1218 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001219 TheCall->setType(Context.IntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001220 break;
1221 case Builtin::BIreserve_read_pipe:
1222 case Builtin::BIreserve_write_pipe:
1223 case Builtin::BIwork_group_reserve_read_pipe:
1224 case Builtin::BIwork_group_reserve_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001225 if (SemaBuiltinReserveRWPipe(*this, TheCall))
1226 return ExprError();
Joey Gouly84ae3362017-07-31 15:15:59 +00001227 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001228 case Builtin::BIsub_group_reserve_read_pipe:
1229 case Builtin::BIsub_group_reserve_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001230 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1231 SemaBuiltinReserveRWPipe(*this, TheCall))
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001232 return ExprError();
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001233 break;
1234 case Builtin::BIcommit_read_pipe:
1235 case Builtin::BIcommit_write_pipe:
1236 case Builtin::BIwork_group_commit_read_pipe:
1237 case Builtin::BIwork_group_commit_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001238 if (SemaBuiltinCommitRWPipe(*this, TheCall))
1239 return ExprError();
1240 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001241 case Builtin::BIsub_group_commit_read_pipe:
1242 case Builtin::BIsub_group_commit_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001243 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1244 SemaBuiltinCommitRWPipe(*this, TheCall))
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001245 return ExprError();
1246 break;
1247 case Builtin::BIget_pipe_num_packets:
1248 case Builtin::BIget_pipe_max_packets:
1249 if (SemaBuiltinPipePackets(*this, TheCall))
1250 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001251 TheCall->setType(Context.UnsignedIntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001252 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +00001253 case Builtin::BIto_global:
1254 case Builtin::BIto_local:
1255 case Builtin::BIto_private:
1256 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1257 return ExprError();
1258 break;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001259 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1260 case Builtin::BIenqueue_kernel:
1261 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1262 return ExprError();
1263 break;
1264 case Builtin::BIget_kernel_work_group_size:
1265 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1266 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1267 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001268 break;
Joey Goulyfa76b492017-08-01 13:27:09 +00001269 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1270 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1271 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1272 return ExprError();
1273 break;
Mehdi Amini06d367c2016-10-24 20:39:34 +00001274 case Builtin::BI__builtin_os_log_format:
1275 case Builtin::BI__builtin_os_log_format_buffer_size:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00001276 if (SemaBuiltinOSLogFormat(TheCall))
Mehdi Amini06d367c2016-10-24 20:39:34 +00001277 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001278 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001279 }
Richard Smith760520b2014-06-03 23:27:44 +00001280
Nate Begeman4904e322010-06-08 02:47:44 +00001281 // Since the target specific builtins for each arch overlap, only check those
1282 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +00001283 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001284 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +00001285 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001286 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001287 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001288 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001289 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1290 return ExprError();
1291 break;
Tim Northover25e8a672014-05-24 12:51:25 +00001292 case llvm::Triple::aarch64:
1293 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +00001294 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +00001295 return ExprError();
1296 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001297 case llvm::Triple::mips:
1298 case llvm::Triple::mipsel:
1299 case llvm::Triple::mips64:
1300 case llvm::Triple::mips64el:
1301 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1302 return ExprError();
1303 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001304 case llvm::Triple::systemz:
1305 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1306 return ExprError();
1307 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001308 case llvm::Triple::x86:
1309 case llvm::Triple::x86_64:
1310 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1311 return ExprError();
1312 break;
Kit Bartone50adcb2015-03-30 19:40:59 +00001313 case llvm::Triple::ppc:
1314 case llvm::Triple::ppc64:
1315 case llvm::Triple::ppc64le:
1316 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1317 return ExprError();
1318 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001319 default:
1320 break;
1321 }
1322 }
1323
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001324 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +00001325}
1326
Nate Begeman91e1fea2010-06-14 05:21:25 +00001327// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +00001328static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +00001329 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +00001330 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +00001331 switch (Type.getEltType()) {
1332 case NeonTypeFlags::Int8:
1333 case NeonTypeFlags::Poly8:
1334 return shift ? 7 : (8 << IsQuad) - 1;
1335 case NeonTypeFlags::Int16:
1336 case NeonTypeFlags::Poly16:
1337 return shift ? 15 : (4 << IsQuad) - 1;
1338 case NeonTypeFlags::Int32:
1339 return shift ? 31 : (2 << IsQuad) - 1;
1340 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +00001341 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +00001342 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001343 case NeonTypeFlags::Poly128:
1344 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +00001345 case NeonTypeFlags::Float16:
1346 assert(!shift && "cannot shift float types!");
1347 return (4 << IsQuad) - 1;
1348 case NeonTypeFlags::Float32:
1349 assert(!shift && "cannot shift float types!");
1350 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001351 case NeonTypeFlags::Float64:
1352 assert(!shift && "cannot shift float types!");
1353 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +00001354 }
David Blaikie8a40f702012-01-17 06:56:22 +00001355 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +00001356}
1357
Bob Wilsone4d77232011-11-08 05:04:11 +00001358/// getNeonEltType - Return the QualType corresponding to the elements of
1359/// the vector type specified by the NeonTypeFlags. This is used to check
1360/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +00001361static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +00001362 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +00001363 switch (Flags.getEltType()) {
1364 case NeonTypeFlags::Int8:
1365 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1366 case NeonTypeFlags::Int16:
1367 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1368 case NeonTypeFlags::Int32:
1369 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1370 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +00001371 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +00001372 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1373 else
1374 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1375 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001376 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +00001377 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001378 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +00001379 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +00001380 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +00001381 if (IsInt64Long)
1382 return Context.UnsignedLongTy;
1383 else
1384 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001385 case NeonTypeFlags::Poly128:
1386 break;
Bob Wilsone4d77232011-11-08 05:04:11 +00001387 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +00001388 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001389 case NeonTypeFlags::Float32:
1390 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +00001391 case NeonTypeFlags::Float64:
1392 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001393 }
David Blaikie8a40f702012-01-17 06:56:22 +00001394 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +00001395}
1396
Tim Northover12670412014-02-19 10:37:05 +00001397bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +00001398 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +00001399 uint64_t mask = 0;
1400 unsigned TV = 0;
1401 int PtrArgNum = -1;
1402 bool HasConstPtr = false;
1403 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +00001404#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001405#include "clang/Basic/arm_neon.inc"
Abderrazek Zaafranice8746d2018-01-19 23:11:18 +00001406#include "clang/Basic/arm_fp16.inc"
Tim Northover12670412014-02-19 10:37:05 +00001407#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001408 }
1409
1410 // For NEON intrinsics which are overloaded on vector element type, validate
1411 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +00001412 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001413 if (mask) {
1414 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1415 return true;
1416
1417 TV = Result.getLimitedValue(64);
1418 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1419 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +00001420 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +00001421 }
1422
1423 if (PtrArgNum >= 0) {
1424 // Check that pointer arguments have the specified type.
1425 Expr *Arg = TheCall->getArg(PtrArgNum);
1426 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1427 Arg = ICE->getSubExpr();
1428 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1429 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +00001430
Tim Northovera2ee4332014-03-29 15:09:45 +00001431 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Joerg Sonnenberger47006c52017-01-09 11:40:41 +00001432 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1433 Arch == llvm::Triple::aarch64_be;
Tim Northovera2ee4332014-03-29 15:09:45 +00001434 bool IsInt64Long =
1435 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1436 QualType EltTy =
1437 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +00001438 if (HasConstPtr)
1439 EltTy = EltTy.withConst();
1440 QualType LHSTy = Context.getPointerType(EltTy);
1441 AssignConvertType ConvTy;
1442 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1443 if (RHS.isInvalid())
1444 return true;
1445 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1446 RHS.get(), AA_Assigning))
1447 return true;
1448 }
1449
1450 // For NEON intrinsics which take an immediate value as part of the
1451 // instruction, range check them here.
1452 unsigned i = 0, l = 0, u = 0;
1453 switch (BuiltinID) {
1454 default:
1455 return false;
Tim Northover12670412014-02-19 10:37:05 +00001456#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001457#include "clang/Basic/arm_neon.inc"
Abderrazek Zaafranice8746d2018-01-19 23:11:18 +00001458#include "clang/Basic/arm_fp16.inc"
Tim Northover12670412014-02-19 10:37:05 +00001459#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001460 }
Tim Northover2fe823a2013-08-01 09:23:19 +00001461
Richard Sandiford28940af2014-04-16 08:47:51 +00001462 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +00001463}
1464
Tim Northovera2ee4332014-03-29 15:09:45 +00001465bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1466 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +00001467 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001468 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +00001469 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001470 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +00001471 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001472 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1473 BuiltinID == AArch64::BI__builtin_arm_strex ||
1474 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +00001475 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +00001476 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001477 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1478 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1479 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +00001480
1481 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1482
1483 // Ensure that we have the proper number of arguments.
1484 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1485 return true;
1486
1487 // Inspect the pointer argument of the atomic builtin. This should always be
1488 // a pointer type, whose element is an integral scalar or pointer type.
1489 // Because it is a pointer type, we don't have to worry about any implicit
1490 // casts here.
1491 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1492 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1493 if (PointerArgRes.isInvalid())
1494 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001495 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001496
1497 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1498 if (!pointerType) {
1499 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1500 << PointerArg->getType() << PointerArg->getSourceRange();
1501 return true;
1502 }
1503
1504 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1505 // task is to insert the appropriate casts into the AST. First work out just
1506 // what the appropriate type is.
1507 QualType ValType = pointerType->getPointeeType();
1508 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1509 if (IsLdrex)
1510 AddrType.addConst();
1511
1512 // Issue a warning if the cast is dodgy.
1513 CastKind CastNeeded = CK_NoOp;
1514 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1515 CastNeeded = CK_BitCast;
1516 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1517 << PointerArg->getType()
1518 << Context.getPointerType(AddrType)
1519 << AA_Passing << PointerArg->getSourceRange();
1520 }
1521
1522 // Finally, do the cast and replace the argument with the corrected version.
1523 AddrType = Context.getPointerType(AddrType);
1524 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1525 if (PointerArgRes.isInvalid())
1526 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001527 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001528
1529 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1530
1531 // In general, we allow ints, floats and pointers to be loaded and stored.
1532 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1533 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1534 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1535 << PointerArg->getType() << PointerArg->getSourceRange();
1536 return true;
1537 }
1538
1539 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001540 if (Context.getTypeSize(ValType) > MaxWidth) {
1541 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +00001542 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1543 << PointerArg->getType() << PointerArg->getSourceRange();
1544 return true;
1545 }
1546
1547 switch (ValType.getObjCLifetime()) {
1548 case Qualifiers::OCL_None:
1549 case Qualifiers::OCL_ExplicitNone:
1550 // okay
1551 break;
1552
1553 case Qualifiers::OCL_Weak:
1554 case Qualifiers::OCL_Strong:
1555 case Qualifiers::OCL_Autoreleasing:
1556 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1557 << ValType << PointerArg->getSourceRange();
1558 return true;
1559 }
1560
Tim Northover6aacd492013-07-16 09:47:53 +00001561 if (IsLdrex) {
1562 TheCall->setType(ValType);
1563 return false;
1564 }
1565
1566 // Initialize the argument to be stored.
1567 ExprResult ValArg = TheCall->getArg(0);
1568 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1569 Context, ValType, /*consume*/ false);
1570 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1571 if (ValArg.isInvalid())
1572 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001573 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001574
1575 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1576 // but the custom checker bypasses all default analysis.
1577 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001578 return false;
1579}
1580
Nate Begeman4904e322010-06-08 02:47:44 +00001581bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover6aacd492013-07-16 09:47:53 +00001582 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001583 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1584 BuiltinID == ARM::BI__builtin_arm_strex ||
1585 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001586 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001587 }
1588
Yi Kong26d104a2014-08-13 19:18:14 +00001589 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1590 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1591 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1592 }
1593
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001594 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1595 BuiltinID == ARM::BI__builtin_arm_wsr64)
1596 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1597
1598 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1599 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1600 BuiltinID == ARM::BI__builtin_arm_wsr ||
1601 BuiltinID == ARM::BI__builtin_arm_wsrp)
1602 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1603
Tim Northover12670412014-02-19 10:37:05 +00001604 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1605 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001606
Yi Kong4efadfb2014-07-03 16:01:25 +00001607 // For intrinsics which take an immediate value as part of the instruction,
1608 // range check them here.
Sjoerd Meijer293da702017-12-07 09:54:39 +00001609 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begemand773fe62010-06-13 04:47:52 +00001610 switch (BuiltinID) {
1611 default: return false;
Sjoerd Meijer293da702017-12-07 09:54:39 +00001612 case ARM::BI__builtin_arm_ssat:
1613 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
1614 case ARM::BI__builtin_arm_usat:
1615 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
1616 case ARM::BI__builtin_arm_ssat16:
1617 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
1618 case ARM::BI__builtin_arm_usat16:
1619 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
Nate Begemanf568b072010-08-03 21:32:34 +00001620 case ARM::BI__builtin_arm_vcvtr_f:
Sjoerd Meijer293da702017-12-07 09:54:39 +00001621 case ARM::BI__builtin_arm_vcvtr_d:
1622 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
Weiming Zhao87bb4922013-11-12 21:42:50 +00001623 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001624 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001625 case ARM::BI__builtin_arm_isb:
Sjoerd Meijer293da702017-12-07 09:54:39 +00001626 case ARM::BI__builtin_arm_dbg:
1627 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
Richard Sandiford28940af2014-04-16 08:47:51 +00001628 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001629}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001630
Tim Northover573cbee2014-05-24 12:52:07 +00001631bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001632 CallExpr *TheCall) {
Tim Northover573cbee2014-05-24 12:52:07 +00001633 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001634 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1635 BuiltinID == AArch64::BI__builtin_arm_strex ||
1636 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001637 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1638 }
1639
Yi Konga5548432014-08-13 19:18:20 +00001640 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1641 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1642 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1643 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1644 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1645 }
1646
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001647 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1648 BuiltinID == AArch64::BI__builtin_arm_wsr64)
Tim Northover54e50002016-04-13 17:08:55 +00001649 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001650
1651 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1652 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1653 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1654 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1655 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1656
Tim Northovera2ee4332014-03-29 15:09:45 +00001657 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1658 return true;
1659
Yi Kong19a29ac2014-07-17 10:52:06 +00001660 // For intrinsics which take an immediate value as part of the instruction,
1661 // range check them here.
1662 unsigned i = 0, l = 0, u = 0;
1663 switch (BuiltinID) {
1664 default: return false;
1665 case AArch64::BI__builtin_arm_dmb:
1666 case AArch64::BI__builtin_arm_dsb:
1667 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1668 }
1669
Yi Kong19a29ac2014-07-17 10:52:06 +00001670 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001671}
1672
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001673// CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1674// intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1675// ordering for DSP is unspecified. MSA is ordered by the data format used
1676// by the underlying instruction i.e., df/m, df/n and then by size.
1677//
1678// FIXME: The size tests here should instead be tablegen'd along with the
1679// definitions from include/clang/Basic/BuiltinsMips.def.
1680// FIXME: GCC is strict on signedness for some of these intrinsics, we should
1681// be too.
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001682bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001683 unsigned i = 0, l = 0, u = 0, m = 0;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001684 switch (BuiltinID) {
1685 default: return false;
1686 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1687 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00001688 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1689 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1690 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1691 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1692 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001693 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1694 // df/m field.
1695 // These intrinsics take an unsigned 3 bit immediate.
1696 case Mips::BI__builtin_msa_bclri_b:
1697 case Mips::BI__builtin_msa_bnegi_b:
1698 case Mips::BI__builtin_msa_bseti_b:
1699 case Mips::BI__builtin_msa_sat_s_b:
1700 case Mips::BI__builtin_msa_sat_u_b:
1701 case Mips::BI__builtin_msa_slli_b:
1702 case Mips::BI__builtin_msa_srai_b:
1703 case Mips::BI__builtin_msa_srari_b:
1704 case Mips::BI__builtin_msa_srli_b:
1705 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1706 case Mips::BI__builtin_msa_binsli_b:
1707 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1708 // These intrinsics take an unsigned 4 bit immediate.
1709 case Mips::BI__builtin_msa_bclri_h:
1710 case Mips::BI__builtin_msa_bnegi_h:
1711 case Mips::BI__builtin_msa_bseti_h:
1712 case Mips::BI__builtin_msa_sat_s_h:
1713 case Mips::BI__builtin_msa_sat_u_h:
1714 case Mips::BI__builtin_msa_slli_h:
1715 case Mips::BI__builtin_msa_srai_h:
1716 case Mips::BI__builtin_msa_srari_h:
1717 case Mips::BI__builtin_msa_srli_h:
1718 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1719 case Mips::BI__builtin_msa_binsli_h:
1720 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00001721 // These intrinsics take an unsigned 5 bit immediate.
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001722 // The first block of intrinsics actually have an unsigned 5 bit field,
1723 // not a df/n field.
1724 case Mips::BI__builtin_msa_clei_u_b:
1725 case Mips::BI__builtin_msa_clei_u_h:
1726 case Mips::BI__builtin_msa_clei_u_w:
1727 case Mips::BI__builtin_msa_clei_u_d:
1728 case Mips::BI__builtin_msa_clti_u_b:
1729 case Mips::BI__builtin_msa_clti_u_h:
1730 case Mips::BI__builtin_msa_clti_u_w:
1731 case Mips::BI__builtin_msa_clti_u_d:
1732 case Mips::BI__builtin_msa_maxi_u_b:
1733 case Mips::BI__builtin_msa_maxi_u_h:
1734 case Mips::BI__builtin_msa_maxi_u_w:
1735 case Mips::BI__builtin_msa_maxi_u_d:
1736 case Mips::BI__builtin_msa_mini_u_b:
1737 case Mips::BI__builtin_msa_mini_u_h:
1738 case Mips::BI__builtin_msa_mini_u_w:
1739 case Mips::BI__builtin_msa_mini_u_d:
1740 case Mips::BI__builtin_msa_addvi_b:
1741 case Mips::BI__builtin_msa_addvi_h:
1742 case Mips::BI__builtin_msa_addvi_w:
1743 case Mips::BI__builtin_msa_addvi_d:
1744 case Mips::BI__builtin_msa_bclri_w:
1745 case Mips::BI__builtin_msa_bnegi_w:
1746 case Mips::BI__builtin_msa_bseti_w:
1747 case Mips::BI__builtin_msa_sat_s_w:
1748 case Mips::BI__builtin_msa_sat_u_w:
1749 case Mips::BI__builtin_msa_slli_w:
1750 case Mips::BI__builtin_msa_srai_w:
1751 case Mips::BI__builtin_msa_srari_w:
1752 case Mips::BI__builtin_msa_srli_w:
1753 case Mips::BI__builtin_msa_srlri_w:
1754 case Mips::BI__builtin_msa_subvi_b:
1755 case Mips::BI__builtin_msa_subvi_h:
1756 case Mips::BI__builtin_msa_subvi_w:
1757 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1758 case Mips::BI__builtin_msa_binsli_w:
1759 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1760 // These intrinsics take an unsigned 6 bit immediate.
1761 case Mips::BI__builtin_msa_bclri_d:
1762 case Mips::BI__builtin_msa_bnegi_d:
1763 case Mips::BI__builtin_msa_bseti_d:
1764 case Mips::BI__builtin_msa_sat_s_d:
1765 case Mips::BI__builtin_msa_sat_u_d:
1766 case Mips::BI__builtin_msa_slli_d:
1767 case Mips::BI__builtin_msa_srai_d:
1768 case Mips::BI__builtin_msa_srari_d:
1769 case Mips::BI__builtin_msa_srli_d:
1770 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1771 case Mips::BI__builtin_msa_binsli_d:
1772 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1773 // These intrinsics take a signed 5 bit immediate.
1774 case Mips::BI__builtin_msa_ceqi_b:
1775 case Mips::BI__builtin_msa_ceqi_h:
1776 case Mips::BI__builtin_msa_ceqi_w:
1777 case Mips::BI__builtin_msa_ceqi_d:
1778 case Mips::BI__builtin_msa_clti_s_b:
1779 case Mips::BI__builtin_msa_clti_s_h:
1780 case Mips::BI__builtin_msa_clti_s_w:
1781 case Mips::BI__builtin_msa_clti_s_d:
1782 case Mips::BI__builtin_msa_clei_s_b:
1783 case Mips::BI__builtin_msa_clei_s_h:
1784 case Mips::BI__builtin_msa_clei_s_w:
1785 case Mips::BI__builtin_msa_clei_s_d:
1786 case Mips::BI__builtin_msa_maxi_s_b:
1787 case Mips::BI__builtin_msa_maxi_s_h:
1788 case Mips::BI__builtin_msa_maxi_s_w:
1789 case Mips::BI__builtin_msa_maxi_s_d:
1790 case Mips::BI__builtin_msa_mini_s_b:
1791 case Mips::BI__builtin_msa_mini_s_h:
1792 case Mips::BI__builtin_msa_mini_s_w:
1793 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
1794 // These intrinsics take an unsigned 8 bit immediate.
1795 case Mips::BI__builtin_msa_andi_b:
1796 case Mips::BI__builtin_msa_nori_b:
1797 case Mips::BI__builtin_msa_ori_b:
1798 case Mips::BI__builtin_msa_shf_b:
1799 case Mips::BI__builtin_msa_shf_h:
1800 case Mips::BI__builtin_msa_shf_w:
1801 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
1802 case Mips::BI__builtin_msa_bseli_b:
1803 case Mips::BI__builtin_msa_bmnzi_b:
1804 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
1805 // df/n format
1806 // These intrinsics take an unsigned 4 bit immediate.
1807 case Mips::BI__builtin_msa_copy_s_b:
1808 case Mips::BI__builtin_msa_copy_u_b:
1809 case Mips::BI__builtin_msa_insve_b:
1810 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001811 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
1812 // These intrinsics take an unsigned 3 bit immediate.
1813 case Mips::BI__builtin_msa_copy_s_h:
1814 case Mips::BI__builtin_msa_copy_u_h:
1815 case Mips::BI__builtin_msa_insve_h:
1816 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001817 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1818 // These intrinsics take an unsigned 2 bit immediate.
1819 case Mips::BI__builtin_msa_copy_s_w:
1820 case Mips::BI__builtin_msa_copy_u_w:
1821 case Mips::BI__builtin_msa_insve_w:
1822 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001823 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1824 // These intrinsics take an unsigned 1 bit immediate.
1825 case Mips::BI__builtin_msa_copy_s_d:
1826 case Mips::BI__builtin_msa_copy_u_d:
1827 case Mips::BI__builtin_msa_insve_d:
1828 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001829 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1830 // Memory offsets and immediate loads.
1831 // These intrinsics take a signed 10 bit immediate.
Petar Jovanovic9b8b9e82017-03-31 16:16:43 +00001832 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001833 case Mips::BI__builtin_msa_ldi_h:
1834 case Mips::BI__builtin_msa_ldi_w:
1835 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1836 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1837 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1838 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1839 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1840 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1841 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1842 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1843 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001844 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001845
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001846 if (!m)
1847 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1848
1849 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1850 SemaBuiltinConstantArgMultiple(TheCall, i, m);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001851}
1852
Kit Bartone50adcb2015-03-30 19:40:59 +00001853bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1854 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00001855 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1856 BuiltinID == PPC::BI__builtin_divdeu ||
1857 BuiltinID == PPC::BI__builtin_bpermd;
1858 bool IsTarget64Bit = Context.getTargetInfo()
1859 .getTypeWidth(Context
1860 .getTargetInfo()
1861 .getIntPtrType()) == 64;
1862 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1863 BuiltinID == PPC::BI__builtin_divweu ||
1864 BuiltinID == PPC::BI__builtin_divde ||
1865 BuiltinID == PPC::BI__builtin_divdeu;
1866
1867 if (Is64BitBltin && !IsTarget64Bit)
1868 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1869 << TheCall->getSourceRange();
1870
1871 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1872 (BuiltinID == PPC::BI__builtin_bpermd &&
1873 !Context.getTargetInfo().hasFeature("bpermd")))
1874 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1875 << TheCall->getSourceRange();
1876
Kit Bartone50adcb2015-03-30 19:40:59 +00001877 switch (BuiltinID) {
1878 default: return false;
1879 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1880 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1881 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1882 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1883 case PPC::BI__builtin_tbegin:
1884 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1885 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1886 case PPC::BI__builtin_tabortwc:
1887 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1888 case PPC::BI__builtin_tabortwci:
1889 case PPC::BI__builtin_tabortdci:
1890 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1891 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
Tony Jiangbbc48e92017-05-24 15:13:32 +00001892 case PPC::BI__builtin_vsx_xxpermdi:
Tony Jiang9aa2c032017-05-24 15:54:13 +00001893 case PPC::BI__builtin_vsx_xxsldwi:
Tony Jiangbbc48e92017-05-24 15:13:32 +00001894 return SemaBuiltinVSX(TheCall);
Kit Bartone50adcb2015-03-30 19:40:59 +00001895 }
1896 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1897}
1898
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001899bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1900 CallExpr *TheCall) {
1901 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1902 Expr *Arg = TheCall->getArg(0);
1903 llvm::APSInt AbortCode(32);
1904 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1905 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1906 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1907 << Arg->getSourceRange();
1908 }
1909
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001910 // For intrinsics which take an immediate value as part of the instruction,
1911 // range check them here.
1912 unsigned i = 0, l = 0, u = 0;
1913 switch (BuiltinID) {
1914 default: return false;
1915 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1916 case SystemZ::BI__builtin_s390_verimb:
1917 case SystemZ::BI__builtin_s390_verimh:
1918 case SystemZ::BI__builtin_s390_verimf:
1919 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1920 case SystemZ::BI__builtin_s390_vfaeb:
1921 case SystemZ::BI__builtin_s390_vfaeh:
1922 case SystemZ::BI__builtin_s390_vfaef:
1923 case SystemZ::BI__builtin_s390_vfaebs:
1924 case SystemZ::BI__builtin_s390_vfaehs:
1925 case SystemZ::BI__builtin_s390_vfaefs:
1926 case SystemZ::BI__builtin_s390_vfaezb:
1927 case SystemZ::BI__builtin_s390_vfaezh:
1928 case SystemZ::BI__builtin_s390_vfaezf:
1929 case SystemZ::BI__builtin_s390_vfaezbs:
1930 case SystemZ::BI__builtin_s390_vfaezhs:
1931 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00001932 case SystemZ::BI__builtin_s390_vfisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001933 case SystemZ::BI__builtin_s390_vfidb:
1934 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1935 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00001936 case SystemZ::BI__builtin_s390_vftcisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001937 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1938 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1939 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1940 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1941 case SystemZ::BI__builtin_s390_vstrcb:
1942 case SystemZ::BI__builtin_s390_vstrch:
1943 case SystemZ::BI__builtin_s390_vstrcf:
1944 case SystemZ::BI__builtin_s390_vstrczb:
1945 case SystemZ::BI__builtin_s390_vstrczh:
1946 case SystemZ::BI__builtin_s390_vstrczf:
1947 case SystemZ::BI__builtin_s390_vstrcbs:
1948 case SystemZ::BI__builtin_s390_vstrchs:
1949 case SystemZ::BI__builtin_s390_vstrcfs:
1950 case SystemZ::BI__builtin_s390_vstrczbs:
1951 case SystemZ::BI__builtin_s390_vstrczhs:
1952 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00001953 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
1954 case SystemZ::BI__builtin_s390_vfminsb:
1955 case SystemZ::BI__builtin_s390_vfmaxsb:
1956 case SystemZ::BI__builtin_s390_vfmindb:
1957 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001958 }
1959 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001960}
1961
Craig Topper5ba2c502015-11-07 08:08:31 +00001962/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1963/// This checks that the target supports __builtin_cpu_supports and
1964/// that the string argument is constant and valid.
1965static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1966 Expr *Arg = TheCall->getArg(0);
1967
1968 // Check if the argument is a string literal.
1969 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1970 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1971 << Arg->getSourceRange();
1972
1973 // Check the contents of the string.
1974 StringRef Feature =
1975 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1976 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1977 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1978 << Arg->getSourceRange();
1979 return false;
1980}
1981
Craig Topper699ae0c2017-08-10 20:28:30 +00001982/// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
1983/// This checks that the target supports __builtin_cpu_is and
1984/// that the string argument is constant and valid.
1985static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
1986 Expr *Arg = TheCall->getArg(0);
1987
1988 // Check if the argument is a string literal.
1989 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1990 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1991 << Arg->getSourceRange();
1992
1993 // Check the contents of the string.
1994 StringRef Feature =
1995 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1996 if (!S.Context.getTargetInfo().validateCpuIs(Feature))
1997 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is)
1998 << Arg->getSourceRange();
1999 return false;
2000}
2001
Craig Toppera7e253e2016-09-23 04:48:31 +00002002// Check if the rounding mode is legal.
2003bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
2004 // Indicates if this instruction has rounding control or just SAE.
2005 bool HasRC = false;
2006
2007 unsigned ArgNum = 0;
2008 switch (BuiltinID) {
2009 default:
2010 return false;
2011 case X86::BI__builtin_ia32_vcvttsd2si32:
2012 case X86::BI__builtin_ia32_vcvttsd2si64:
2013 case X86::BI__builtin_ia32_vcvttsd2usi32:
2014 case X86::BI__builtin_ia32_vcvttsd2usi64:
2015 case X86::BI__builtin_ia32_vcvttss2si32:
2016 case X86::BI__builtin_ia32_vcvttss2si64:
2017 case X86::BI__builtin_ia32_vcvttss2usi32:
2018 case X86::BI__builtin_ia32_vcvttss2usi64:
2019 ArgNum = 1;
2020 break;
2021 case X86::BI__builtin_ia32_cvtps2pd512_mask:
2022 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
2023 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
2024 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
2025 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
2026 case X86::BI__builtin_ia32_cvttps2dq512_mask:
2027 case X86::BI__builtin_ia32_cvttps2qq512_mask:
2028 case X86::BI__builtin_ia32_cvttps2udq512_mask:
2029 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
2030 case X86::BI__builtin_ia32_exp2pd_mask:
2031 case X86::BI__builtin_ia32_exp2ps_mask:
2032 case X86::BI__builtin_ia32_getexppd512_mask:
2033 case X86::BI__builtin_ia32_getexpps512_mask:
2034 case X86::BI__builtin_ia32_rcp28pd_mask:
2035 case X86::BI__builtin_ia32_rcp28ps_mask:
2036 case X86::BI__builtin_ia32_rsqrt28pd_mask:
2037 case X86::BI__builtin_ia32_rsqrt28ps_mask:
2038 case X86::BI__builtin_ia32_vcomisd:
2039 case X86::BI__builtin_ia32_vcomiss:
2040 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
2041 ArgNum = 3;
2042 break;
2043 case X86::BI__builtin_ia32_cmppd512_mask:
2044 case X86::BI__builtin_ia32_cmpps512_mask:
2045 case X86::BI__builtin_ia32_cmpsd_mask:
2046 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002047 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00002048 case X86::BI__builtin_ia32_getexpsd128_round_mask:
2049 case X86::BI__builtin_ia32_getexpss128_round_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002050 case X86::BI__builtin_ia32_maxpd512_mask:
2051 case X86::BI__builtin_ia32_maxps512_mask:
2052 case X86::BI__builtin_ia32_maxsd_round_mask:
2053 case X86::BI__builtin_ia32_maxss_round_mask:
2054 case X86::BI__builtin_ia32_minpd512_mask:
2055 case X86::BI__builtin_ia32_minps512_mask:
2056 case X86::BI__builtin_ia32_minsd_round_mask:
2057 case X86::BI__builtin_ia32_minss_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00002058 case X86::BI__builtin_ia32_rcp28sd_round_mask:
2059 case X86::BI__builtin_ia32_rcp28ss_round_mask:
2060 case X86::BI__builtin_ia32_reducepd512_mask:
2061 case X86::BI__builtin_ia32_reduceps512_mask:
2062 case X86::BI__builtin_ia32_rndscalepd_mask:
2063 case X86::BI__builtin_ia32_rndscaleps_mask:
2064 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
2065 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
2066 ArgNum = 4;
2067 break;
2068 case X86::BI__builtin_ia32_fixupimmpd512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002069 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002070 case X86::BI__builtin_ia32_fixupimmps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002071 case X86::BI__builtin_ia32_fixupimmps512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002072 case X86::BI__builtin_ia32_fixupimmsd_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002073 case X86::BI__builtin_ia32_fixupimmsd_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002074 case X86::BI__builtin_ia32_fixupimmss_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002075 case X86::BI__builtin_ia32_fixupimmss_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002076 case X86::BI__builtin_ia32_rangepd512_mask:
2077 case X86::BI__builtin_ia32_rangeps512_mask:
2078 case X86::BI__builtin_ia32_rangesd128_round_mask:
2079 case X86::BI__builtin_ia32_rangess128_round_mask:
2080 case X86::BI__builtin_ia32_reducesd_mask:
2081 case X86::BI__builtin_ia32_reducess_mask:
2082 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2083 case X86::BI__builtin_ia32_rndscaless_round_mask:
2084 ArgNum = 5;
2085 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00002086 case X86::BI__builtin_ia32_vcvtsd2si64:
2087 case X86::BI__builtin_ia32_vcvtsd2si32:
2088 case X86::BI__builtin_ia32_vcvtsd2usi32:
2089 case X86::BI__builtin_ia32_vcvtsd2usi64:
2090 case X86::BI__builtin_ia32_vcvtss2si32:
2091 case X86::BI__builtin_ia32_vcvtss2si64:
2092 case X86::BI__builtin_ia32_vcvtss2usi32:
2093 case X86::BI__builtin_ia32_vcvtss2usi64:
2094 ArgNum = 1;
2095 HasRC = true;
2096 break;
Craig Topper8e066312016-11-07 07:01:09 +00002097 case X86::BI__builtin_ia32_cvtsi2sd64:
2098 case X86::BI__builtin_ia32_cvtsi2ss32:
2099 case X86::BI__builtin_ia32_cvtsi2ss64:
Craig Topper7609f1c2016-10-01 21:03:50 +00002100 case X86::BI__builtin_ia32_cvtusi2sd64:
2101 case X86::BI__builtin_ia32_cvtusi2ss32:
2102 case X86::BI__builtin_ia32_cvtusi2ss64:
2103 ArgNum = 2;
2104 HasRC = true;
2105 break;
2106 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
2107 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
2108 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
2109 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
2110 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
2111 case X86::BI__builtin_ia32_cvtps2qq512_mask:
2112 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
2113 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
2114 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
2115 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
2116 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002117 case X86::BI__builtin_ia32_sqrtpd512_mask:
2118 case X86::BI__builtin_ia32_sqrtps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002119 ArgNum = 3;
2120 HasRC = true;
2121 break;
2122 case X86::BI__builtin_ia32_addpd512_mask:
2123 case X86::BI__builtin_ia32_addps512_mask:
2124 case X86::BI__builtin_ia32_divpd512_mask:
2125 case X86::BI__builtin_ia32_divps512_mask:
2126 case X86::BI__builtin_ia32_mulpd512_mask:
2127 case X86::BI__builtin_ia32_mulps512_mask:
2128 case X86::BI__builtin_ia32_subpd512_mask:
2129 case X86::BI__builtin_ia32_subps512_mask:
2130 case X86::BI__builtin_ia32_addss_round_mask:
2131 case X86::BI__builtin_ia32_addsd_round_mask:
2132 case X86::BI__builtin_ia32_divss_round_mask:
2133 case X86::BI__builtin_ia32_divsd_round_mask:
2134 case X86::BI__builtin_ia32_mulss_round_mask:
2135 case X86::BI__builtin_ia32_mulsd_round_mask:
2136 case X86::BI__builtin_ia32_subss_round_mask:
2137 case X86::BI__builtin_ia32_subsd_round_mask:
2138 case X86::BI__builtin_ia32_scalefpd512_mask:
2139 case X86::BI__builtin_ia32_scalefps512_mask:
2140 case X86::BI__builtin_ia32_scalefsd_round_mask:
2141 case X86::BI__builtin_ia32_scalefss_round_mask:
2142 case X86::BI__builtin_ia32_getmantpd512_mask:
2143 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002144 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
2145 case X86::BI__builtin_ia32_sqrtsd_round_mask:
2146 case X86::BI__builtin_ia32_sqrtss_round_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002147 case X86::BI__builtin_ia32_vfmaddpd512_mask:
2148 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
2149 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
2150 case X86::BI__builtin_ia32_vfmaddps512_mask:
2151 case X86::BI__builtin_ia32_vfmaddps512_mask3:
2152 case X86::BI__builtin_ia32_vfmaddps512_maskz:
2153 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
2154 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
2155 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
2156 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
2157 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
2158 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
2159 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
2160 case X86::BI__builtin_ia32_vfmsubps512_mask3:
2161 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
2162 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
2163 case X86::BI__builtin_ia32_vfnmaddpd512_mask:
2164 case X86::BI__builtin_ia32_vfnmaddps512_mask:
2165 case X86::BI__builtin_ia32_vfnmsubpd512_mask:
2166 case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
2167 case X86::BI__builtin_ia32_vfnmsubps512_mask:
2168 case X86::BI__builtin_ia32_vfnmsubps512_mask3:
2169 case X86::BI__builtin_ia32_vfmaddsd3_mask:
2170 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
2171 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
2172 case X86::BI__builtin_ia32_vfmaddss3_mask:
2173 case X86::BI__builtin_ia32_vfmaddss3_maskz:
2174 case X86::BI__builtin_ia32_vfmaddss3_mask3:
2175 ArgNum = 4;
2176 HasRC = true;
2177 break;
2178 case X86::BI__builtin_ia32_getmantsd_round_mask:
2179 case X86::BI__builtin_ia32_getmantss_round_mask:
2180 ArgNum = 5;
2181 HasRC = true;
2182 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00002183 }
2184
2185 llvm::APSInt Result;
2186
2187 // We can't check the value of a dependent argument.
2188 Expr *Arg = TheCall->getArg(ArgNum);
2189 if (Arg->isTypeDependent() || Arg->isValueDependent())
2190 return false;
2191
2192 // Check constant-ness first.
2193 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2194 return true;
2195
2196 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
2197 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
2198 // combined with ROUND_NO_EXC.
2199 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
2200 Result == 8/*ROUND_NO_EXC*/ ||
2201 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
2202 return false;
2203
2204 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
2205 << Arg->getSourceRange();
2206}
2207
Craig Topperdf5beb22017-03-13 17:16:50 +00002208// Check if the gather/scatter scale is legal.
2209bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
2210 CallExpr *TheCall) {
2211 unsigned ArgNum = 0;
2212 switch (BuiltinID) {
2213 default:
2214 return false;
2215 case X86::BI__builtin_ia32_gatherpfdpd:
2216 case X86::BI__builtin_ia32_gatherpfdps:
2217 case X86::BI__builtin_ia32_gatherpfqpd:
2218 case X86::BI__builtin_ia32_gatherpfqps:
2219 case X86::BI__builtin_ia32_scatterpfdpd:
2220 case X86::BI__builtin_ia32_scatterpfdps:
2221 case X86::BI__builtin_ia32_scatterpfqpd:
2222 case X86::BI__builtin_ia32_scatterpfqps:
2223 ArgNum = 3;
2224 break;
2225 case X86::BI__builtin_ia32_gatherd_pd:
2226 case X86::BI__builtin_ia32_gatherd_pd256:
2227 case X86::BI__builtin_ia32_gatherq_pd:
2228 case X86::BI__builtin_ia32_gatherq_pd256:
2229 case X86::BI__builtin_ia32_gatherd_ps:
2230 case X86::BI__builtin_ia32_gatherd_ps256:
2231 case X86::BI__builtin_ia32_gatherq_ps:
2232 case X86::BI__builtin_ia32_gatherq_ps256:
2233 case X86::BI__builtin_ia32_gatherd_q:
2234 case X86::BI__builtin_ia32_gatherd_q256:
2235 case X86::BI__builtin_ia32_gatherq_q:
2236 case X86::BI__builtin_ia32_gatherq_q256:
2237 case X86::BI__builtin_ia32_gatherd_d:
2238 case X86::BI__builtin_ia32_gatherd_d256:
2239 case X86::BI__builtin_ia32_gatherq_d:
2240 case X86::BI__builtin_ia32_gatherq_d256:
2241 case X86::BI__builtin_ia32_gather3div2df:
2242 case X86::BI__builtin_ia32_gather3div2di:
2243 case X86::BI__builtin_ia32_gather3div4df:
2244 case X86::BI__builtin_ia32_gather3div4di:
2245 case X86::BI__builtin_ia32_gather3div4sf:
2246 case X86::BI__builtin_ia32_gather3div4si:
2247 case X86::BI__builtin_ia32_gather3div8sf:
2248 case X86::BI__builtin_ia32_gather3div8si:
2249 case X86::BI__builtin_ia32_gather3siv2df:
2250 case X86::BI__builtin_ia32_gather3siv2di:
2251 case X86::BI__builtin_ia32_gather3siv4df:
2252 case X86::BI__builtin_ia32_gather3siv4di:
2253 case X86::BI__builtin_ia32_gather3siv4sf:
2254 case X86::BI__builtin_ia32_gather3siv4si:
2255 case X86::BI__builtin_ia32_gather3siv8sf:
2256 case X86::BI__builtin_ia32_gather3siv8si:
2257 case X86::BI__builtin_ia32_gathersiv8df:
2258 case X86::BI__builtin_ia32_gathersiv16sf:
2259 case X86::BI__builtin_ia32_gatherdiv8df:
2260 case X86::BI__builtin_ia32_gatherdiv16sf:
2261 case X86::BI__builtin_ia32_gathersiv8di:
2262 case X86::BI__builtin_ia32_gathersiv16si:
2263 case X86::BI__builtin_ia32_gatherdiv8di:
2264 case X86::BI__builtin_ia32_gatherdiv16si:
2265 case X86::BI__builtin_ia32_scatterdiv2df:
2266 case X86::BI__builtin_ia32_scatterdiv2di:
2267 case X86::BI__builtin_ia32_scatterdiv4df:
2268 case X86::BI__builtin_ia32_scatterdiv4di:
2269 case X86::BI__builtin_ia32_scatterdiv4sf:
2270 case X86::BI__builtin_ia32_scatterdiv4si:
2271 case X86::BI__builtin_ia32_scatterdiv8sf:
2272 case X86::BI__builtin_ia32_scatterdiv8si:
2273 case X86::BI__builtin_ia32_scattersiv2df:
2274 case X86::BI__builtin_ia32_scattersiv2di:
2275 case X86::BI__builtin_ia32_scattersiv4df:
2276 case X86::BI__builtin_ia32_scattersiv4di:
2277 case X86::BI__builtin_ia32_scattersiv4sf:
2278 case X86::BI__builtin_ia32_scattersiv4si:
2279 case X86::BI__builtin_ia32_scattersiv8sf:
2280 case X86::BI__builtin_ia32_scattersiv8si:
2281 case X86::BI__builtin_ia32_scattersiv8df:
2282 case X86::BI__builtin_ia32_scattersiv16sf:
2283 case X86::BI__builtin_ia32_scatterdiv8df:
2284 case X86::BI__builtin_ia32_scatterdiv16sf:
2285 case X86::BI__builtin_ia32_scattersiv8di:
2286 case X86::BI__builtin_ia32_scattersiv16si:
2287 case X86::BI__builtin_ia32_scatterdiv8di:
2288 case X86::BI__builtin_ia32_scatterdiv16si:
2289 ArgNum = 4;
2290 break;
2291 }
2292
2293 llvm::APSInt Result;
2294
2295 // We can't check the value of a dependent argument.
2296 Expr *Arg = TheCall->getArg(ArgNum);
2297 if (Arg->isTypeDependent() || Arg->isValueDependent())
2298 return false;
2299
2300 // Check constant-ness first.
2301 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2302 return true;
2303
2304 if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
2305 return false;
2306
2307 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
2308 << Arg->getSourceRange();
2309}
2310
Craig Topperf0ddc892016-09-23 04:48:27 +00002311bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2312 if (BuiltinID == X86::BI__builtin_cpu_supports)
2313 return SemaBuiltinCpuSupports(*this, TheCall);
2314
Craig Topper699ae0c2017-08-10 20:28:30 +00002315 if (BuiltinID == X86::BI__builtin_cpu_is)
2316 return SemaBuiltinCpuIs(*this, TheCall);
2317
Craig Toppera7e253e2016-09-23 04:48:31 +00002318 // If the intrinsic has rounding or SAE make sure its valid.
2319 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2320 return true;
2321
Craig Topperdf5beb22017-03-13 17:16:50 +00002322 // If the intrinsic has a gather/scatter scale immediate make sure its valid.
2323 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
2324 return true;
2325
Craig Topperf0ddc892016-09-23 04:48:27 +00002326 // For intrinsics which take an immediate value as part of the instruction,
2327 // range check them here.
2328 int i = 0, l = 0, u = 0;
2329 switch (BuiltinID) {
2330 default:
2331 return false;
Richard Trieucc3949d2016-02-18 22:34:54 +00002332 case X86::BI_mm_prefetch:
Craig Topper170de4b2017-12-21 23:50:22 +00002333 i = 1; l = 0; u = 7;
Craig Topper39c87102016-05-18 03:18:12 +00002334 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00002335 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper39c87102016-05-18 03:18:12 +00002336 case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2337 case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2338 case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2339 case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002340 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002341 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00002342 case X86::BI__builtin_ia32_vpermil2pd:
2343 case X86::BI__builtin_ia32_vpermil2pd256:
2344 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00002345 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00002346 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002347 break;
Craig Topper95b0d732015-01-25 23:30:05 +00002348 case X86::BI__builtin_ia32_cmpb128_mask:
2349 case X86::BI__builtin_ia32_cmpw128_mask:
2350 case X86::BI__builtin_ia32_cmpd128_mask:
2351 case X86::BI__builtin_ia32_cmpq128_mask:
2352 case X86::BI__builtin_ia32_cmpb256_mask:
2353 case X86::BI__builtin_ia32_cmpw256_mask:
2354 case X86::BI__builtin_ia32_cmpd256_mask:
2355 case X86::BI__builtin_ia32_cmpq256_mask:
2356 case X86::BI__builtin_ia32_cmpb512_mask:
2357 case X86::BI__builtin_ia32_cmpw512_mask:
2358 case X86::BI__builtin_ia32_cmpd512_mask:
2359 case X86::BI__builtin_ia32_cmpq512_mask:
2360 case X86::BI__builtin_ia32_ucmpb128_mask:
2361 case X86::BI__builtin_ia32_ucmpw128_mask:
2362 case X86::BI__builtin_ia32_ucmpd128_mask:
2363 case X86::BI__builtin_ia32_ucmpq128_mask:
2364 case X86::BI__builtin_ia32_ucmpb256_mask:
2365 case X86::BI__builtin_ia32_ucmpw256_mask:
2366 case X86::BI__builtin_ia32_ucmpd256_mask:
2367 case X86::BI__builtin_ia32_ucmpq256_mask:
2368 case X86::BI__builtin_ia32_ucmpb512_mask:
2369 case X86::BI__builtin_ia32_ucmpw512_mask:
2370 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00002371 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00002372 case X86::BI__builtin_ia32_vpcomub:
2373 case X86::BI__builtin_ia32_vpcomuw:
2374 case X86::BI__builtin_ia32_vpcomud:
2375 case X86::BI__builtin_ia32_vpcomuq:
2376 case X86::BI__builtin_ia32_vpcomb:
2377 case X86::BI__builtin_ia32_vpcomw:
2378 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00002379 case X86::BI__builtin_ia32_vpcomq:
Craig Topper39c87102016-05-18 03:18:12 +00002380 i = 2; l = 0; u = 7;
2381 break;
2382 case X86::BI__builtin_ia32_roundps:
2383 case X86::BI__builtin_ia32_roundpd:
2384 case X86::BI__builtin_ia32_roundps256:
2385 case X86::BI__builtin_ia32_roundpd256:
Craig Topper39c87102016-05-18 03:18:12 +00002386 i = 1; l = 0; u = 15;
2387 break;
2388 case X86::BI__builtin_ia32_roundss:
2389 case X86::BI__builtin_ia32_roundsd:
2390 case X86::BI__builtin_ia32_rangepd128_mask:
2391 case X86::BI__builtin_ia32_rangepd256_mask:
2392 case X86::BI__builtin_ia32_rangepd512_mask:
2393 case X86::BI__builtin_ia32_rangeps128_mask:
2394 case X86::BI__builtin_ia32_rangeps256_mask:
2395 case X86::BI__builtin_ia32_rangeps512_mask:
2396 case X86::BI__builtin_ia32_getmantsd_round_mask:
2397 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002398 i = 2; l = 0; u = 15;
2399 break;
2400 case X86::BI__builtin_ia32_cmpps:
2401 case X86::BI__builtin_ia32_cmpss:
2402 case X86::BI__builtin_ia32_cmppd:
2403 case X86::BI__builtin_ia32_cmpsd:
2404 case X86::BI__builtin_ia32_cmpps256:
2405 case X86::BI__builtin_ia32_cmppd256:
2406 case X86::BI__builtin_ia32_cmpps128_mask:
2407 case X86::BI__builtin_ia32_cmppd128_mask:
2408 case X86::BI__builtin_ia32_cmpps256_mask:
2409 case X86::BI__builtin_ia32_cmppd256_mask:
2410 case X86::BI__builtin_ia32_cmpps512_mask:
2411 case X86::BI__builtin_ia32_cmppd512_mask:
2412 case X86::BI__builtin_ia32_cmpsd_mask:
2413 case X86::BI__builtin_ia32_cmpss_mask:
2414 i = 2; l = 0; u = 31;
2415 break;
Craig Topper39c87102016-05-18 03:18:12 +00002416 case X86::BI__builtin_ia32_vcvtps2ph:
Craig Topper23a30222017-11-08 04:54:26 +00002417 case X86::BI__builtin_ia32_vcvtps2ph_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002418 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper23a30222017-11-08 04:54:26 +00002419 case X86::BI__builtin_ia32_vcvtps2ph256_mask:
2420 case X86::BI__builtin_ia32_vcvtps2ph512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002421 case X86::BI__builtin_ia32_rndscaleps_128_mask:
2422 case X86::BI__builtin_ia32_rndscalepd_128_mask:
2423 case X86::BI__builtin_ia32_rndscaleps_256_mask:
2424 case X86::BI__builtin_ia32_rndscalepd_256_mask:
2425 case X86::BI__builtin_ia32_rndscaleps_mask:
2426 case X86::BI__builtin_ia32_rndscalepd_mask:
2427 case X86::BI__builtin_ia32_reducepd128_mask:
2428 case X86::BI__builtin_ia32_reducepd256_mask:
2429 case X86::BI__builtin_ia32_reducepd512_mask:
2430 case X86::BI__builtin_ia32_reduceps128_mask:
2431 case X86::BI__builtin_ia32_reduceps256_mask:
2432 case X86::BI__builtin_ia32_reduceps512_mask:
2433 case X86::BI__builtin_ia32_prold512_mask:
2434 case X86::BI__builtin_ia32_prolq512_mask:
2435 case X86::BI__builtin_ia32_prold128_mask:
2436 case X86::BI__builtin_ia32_prold256_mask:
2437 case X86::BI__builtin_ia32_prolq128_mask:
2438 case X86::BI__builtin_ia32_prolq256_mask:
2439 case X86::BI__builtin_ia32_prord128_mask:
2440 case X86::BI__builtin_ia32_prord256_mask:
2441 case X86::BI__builtin_ia32_prorq128_mask:
2442 case X86::BI__builtin_ia32_prorq256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002443 case X86::BI__builtin_ia32_fpclasspd128_mask:
2444 case X86::BI__builtin_ia32_fpclasspd256_mask:
2445 case X86::BI__builtin_ia32_fpclassps128_mask:
2446 case X86::BI__builtin_ia32_fpclassps256_mask:
2447 case X86::BI__builtin_ia32_fpclassps512_mask:
2448 case X86::BI__builtin_ia32_fpclasspd512_mask:
2449 case X86::BI__builtin_ia32_fpclasssd_mask:
2450 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002451 i = 1; l = 0; u = 255;
2452 break;
Craig Topper39c87102016-05-18 03:18:12 +00002453 case X86::BI__builtin_ia32_palignr128:
2454 case X86::BI__builtin_ia32_palignr256:
Craig Topper39c87102016-05-18 03:18:12 +00002455 case X86::BI__builtin_ia32_palignr512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002456 case X86::BI__builtin_ia32_vcomisd:
2457 case X86::BI__builtin_ia32_vcomiss:
2458 case X86::BI__builtin_ia32_shuf_f32x4_mask:
2459 case X86::BI__builtin_ia32_shuf_f64x2_mask:
2460 case X86::BI__builtin_ia32_shuf_i32x4_mask:
2461 case X86::BI__builtin_ia32_shuf_i64x2_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002462 case X86::BI__builtin_ia32_dbpsadbw128_mask:
2463 case X86::BI__builtin_ia32_dbpsadbw256_mask:
2464 case X86::BI__builtin_ia32_dbpsadbw512_mask:
Craig Topper91926432018-01-11 01:38:02 +00002465 case X86::BI__builtin_ia32_vpshldd128_mask:
2466 case X86::BI__builtin_ia32_vpshldd256_mask:
2467 case X86::BI__builtin_ia32_vpshldd512_mask:
2468 case X86::BI__builtin_ia32_vpshldq128_mask:
2469 case X86::BI__builtin_ia32_vpshldq256_mask:
2470 case X86::BI__builtin_ia32_vpshldq512_mask:
2471 case X86::BI__builtin_ia32_vpshldw128_mask:
2472 case X86::BI__builtin_ia32_vpshldw256_mask:
2473 case X86::BI__builtin_ia32_vpshldw512_mask:
2474 case X86::BI__builtin_ia32_vpshrdd128_mask:
2475 case X86::BI__builtin_ia32_vpshrdd256_mask:
2476 case X86::BI__builtin_ia32_vpshrdd512_mask:
2477 case X86::BI__builtin_ia32_vpshrdq128_mask:
2478 case X86::BI__builtin_ia32_vpshrdq256_mask:
2479 case X86::BI__builtin_ia32_vpshrdq512_mask:
2480 case X86::BI__builtin_ia32_vpshrdw128_mask:
2481 case X86::BI__builtin_ia32_vpshrdw256_mask:
2482 case X86::BI__builtin_ia32_vpshrdw512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002483 i = 2; l = 0; u = 255;
2484 break;
2485 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2486 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2487 case X86::BI__builtin_ia32_fixupimmps512_mask:
2488 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2489 case X86::BI__builtin_ia32_fixupimmsd_mask:
2490 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2491 case X86::BI__builtin_ia32_fixupimmss_mask:
2492 case X86::BI__builtin_ia32_fixupimmss_maskz:
2493 case X86::BI__builtin_ia32_fixupimmpd128_mask:
2494 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2495 case X86::BI__builtin_ia32_fixupimmpd256_mask:
2496 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2497 case X86::BI__builtin_ia32_fixupimmps128_mask:
2498 case X86::BI__builtin_ia32_fixupimmps128_maskz:
2499 case X86::BI__builtin_ia32_fixupimmps256_mask:
2500 case X86::BI__builtin_ia32_fixupimmps256_maskz:
2501 case X86::BI__builtin_ia32_pternlogd512_mask:
2502 case X86::BI__builtin_ia32_pternlogd512_maskz:
2503 case X86::BI__builtin_ia32_pternlogq512_mask:
2504 case X86::BI__builtin_ia32_pternlogq512_maskz:
2505 case X86::BI__builtin_ia32_pternlogd128_mask:
2506 case X86::BI__builtin_ia32_pternlogd128_maskz:
2507 case X86::BI__builtin_ia32_pternlogd256_mask:
2508 case X86::BI__builtin_ia32_pternlogd256_maskz:
2509 case X86::BI__builtin_ia32_pternlogq128_mask:
2510 case X86::BI__builtin_ia32_pternlogq128_maskz:
2511 case X86::BI__builtin_ia32_pternlogq256_mask:
2512 case X86::BI__builtin_ia32_pternlogq256_maskz:
2513 i = 3; l = 0; u = 255;
2514 break;
Craig Topper9625db02017-03-12 22:19:10 +00002515 case X86::BI__builtin_ia32_gatherpfdpd:
2516 case X86::BI__builtin_ia32_gatherpfdps:
2517 case X86::BI__builtin_ia32_gatherpfqpd:
2518 case X86::BI__builtin_ia32_gatherpfqps:
2519 case X86::BI__builtin_ia32_scatterpfdpd:
2520 case X86::BI__builtin_ia32_scatterpfdps:
2521 case X86::BI__builtin_ia32_scatterpfqpd:
2522 case X86::BI__builtin_ia32_scatterpfqps:
Craig Topperf771f79b2017-03-31 17:22:30 +00002523 i = 4; l = 2; u = 3;
Craig Topper9625db02017-03-12 22:19:10 +00002524 break;
Craig Topper39c87102016-05-18 03:18:12 +00002525 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2526 case X86::BI__builtin_ia32_rndscaless_round_mask:
2527 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00002528 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002529 }
Craig Topperdd84ec52014-12-27 07:00:08 +00002530 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002531}
2532
Richard Smith55ce3522012-06-25 20:30:08 +00002533/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2534/// parameter with the FormatAttr's correct format_idx and firstDataArg.
2535/// Returns true when the format fits the function and the FormatStringInfo has
2536/// been populated.
2537bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2538 FormatStringInfo *FSI) {
2539 FSI->HasVAListArg = Format->getFirstArg() == 0;
2540 FSI->FormatIdx = Format->getFormatIdx() - 1;
2541 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002542
Richard Smith55ce3522012-06-25 20:30:08 +00002543 // The way the format attribute works in GCC, the implicit this argument
2544 // of member functions is counted. However, it doesn't appear in our own
2545 // lists, so decrement format_idx in that case.
2546 if (IsCXXMember) {
2547 if(FSI->FormatIdx == 0)
2548 return false;
2549 --FSI->FormatIdx;
2550 if (FSI->FirstDataArg != 0)
2551 --FSI->FirstDataArg;
2552 }
2553 return true;
2554}
Mike Stump11289f42009-09-09 15:08:12 +00002555
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002556/// Checks if a the given expression evaluates to null.
2557///
2558/// \brief Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00002559static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002560 // If the expression has non-null type, it doesn't evaluate to null.
2561 if (auto nullability
2562 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2563 if (*nullability == NullabilityKind::NonNull)
2564 return false;
2565 }
2566
Ted Kremeneka146db32014-01-17 06:24:47 +00002567 // As a special case, transparent unions initialized with zero are
2568 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002569 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00002570 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2571 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002572 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00002573 if (const InitListExpr *ILE =
2574 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002575 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00002576 }
2577
2578 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00002579 return (!Expr->isValueDependent() &&
2580 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2581 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002582}
2583
2584static void CheckNonNullArgument(Sema &S,
2585 const Expr *ArgExpr,
2586 SourceLocation CallSiteLoc) {
2587 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00002588 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2589 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00002590}
2591
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002592bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2593 FormatStringInfo FSI;
2594 if ((GetFormatStringType(Format) == FST_NSString) &&
2595 getFormatStringInfo(Format, false, &FSI)) {
2596 Idx = FSI.FormatIdx;
2597 return true;
2598 }
2599 return false;
2600}
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002601
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002602/// \brief Diagnose use of %s directive in an NSString which is being passed
2603/// as formatting string to formatting method.
2604static void
2605DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2606 const NamedDecl *FDecl,
2607 Expr **Args,
2608 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002609 unsigned Idx = 0;
2610 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002611 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2612 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002613 Idx = 2;
2614 Format = true;
2615 }
2616 else
2617 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2618 if (S.GetFormatNSStringIdx(I, Idx)) {
2619 Format = true;
2620 break;
2621 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002622 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002623 if (!Format || NumArgs <= Idx)
2624 return;
2625 const Expr *FormatExpr = Args[Idx];
2626 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2627 FormatExpr = CSCE->getSubExpr();
2628 const StringLiteral *FormatString;
2629 if (const ObjCStringLiteral *OSL =
2630 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2631 FormatString = OSL->getString();
2632 else
2633 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2634 if (!FormatString)
2635 return;
2636 if (S.FormatStringHasSArg(FormatString)) {
2637 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2638 << "%s" << 1 << 1;
2639 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2640 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002641 }
2642}
2643
Douglas Gregorb4866e82015-06-19 18:13:19 +00002644/// Determine whether the given type has a non-null nullability annotation.
2645static bool isNonNullType(ASTContext &ctx, QualType type) {
2646 if (auto nullability = type->getNullability(ctx))
2647 return *nullability == NullabilityKind::NonNull;
2648
2649 return false;
2650}
2651
Ted Kremenek2bc73332014-01-17 06:24:43 +00002652static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00002653 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002654 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00002655 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00002656 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002657 assert((FDecl || Proto) && "Need a function declaration or prototype");
2658
Ted Kremenek9aedc152014-01-17 06:24:56 +00002659 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00002660 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00002661 if (FDecl) {
2662 // Handle the nonnull attribute on the function/method declaration itself.
2663 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2664 if (!NonNull->args_size()) {
2665 // Easy case: all pointer arguments are nonnull.
2666 for (const auto *Arg : Args)
2667 if (S.isValidPointerAttrType(Arg->getType()))
2668 CheckNonNullArgument(S, Arg, CallSiteLoc);
2669 return;
2670 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002671
Joel E. Denny81508102018-03-13 14:51:22 +00002672 for (const ParamIdx &Idx : NonNull->args()) {
2673 unsigned IdxAST = Idx.getASTIndex();
2674 if (IdxAST >= Args.size())
Douglas Gregorb4866e82015-06-19 18:13:19 +00002675 continue;
2676 if (NonNullArgs.empty())
2677 NonNullArgs.resize(Args.size());
Joel E. Denny81508102018-03-13 14:51:22 +00002678 NonNullArgs.set(IdxAST);
Douglas Gregorb4866e82015-06-19 18:13:19 +00002679 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002680 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002681 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002682
Douglas Gregorb4866e82015-06-19 18:13:19 +00002683 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2684 // Handle the nonnull attribute on the parameters of the
2685 // function/method.
2686 ArrayRef<ParmVarDecl*> parms;
2687 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2688 parms = FD->parameters();
2689 else
2690 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2691
2692 unsigned ParamIndex = 0;
2693 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2694 I != E; ++I, ++ParamIndex) {
2695 const ParmVarDecl *PVD = *I;
2696 if (PVD->hasAttr<NonNullAttr>() ||
2697 isNonNullType(S.Context, PVD->getType())) {
2698 if (NonNullArgs.empty())
2699 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00002700
Douglas Gregorb4866e82015-06-19 18:13:19 +00002701 NonNullArgs.set(ParamIndex);
2702 }
2703 }
2704 } else {
2705 // If we have a non-function, non-method declaration but no
2706 // function prototype, try to dig out the function prototype.
2707 if (!Proto) {
2708 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2709 QualType type = VD->getType().getNonReferenceType();
2710 if (auto pointerType = type->getAs<PointerType>())
2711 type = pointerType->getPointeeType();
2712 else if (auto blockType = type->getAs<BlockPointerType>())
2713 type = blockType->getPointeeType();
2714 // FIXME: data member pointers?
2715
2716 // Dig out the function prototype, if there is one.
2717 Proto = type->getAs<FunctionProtoType>();
2718 }
2719 }
2720
2721 // Fill in non-null argument information from the nullability
2722 // information on the parameter types (if we have them).
2723 if (Proto) {
2724 unsigned Index = 0;
2725 for (auto paramType : Proto->getParamTypes()) {
2726 if (isNonNullType(S.Context, paramType)) {
2727 if (NonNullArgs.empty())
2728 NonNullArgs.resize(Args.size());
2729
2730 NonNullArgs.set(Index);
2731 }
2732
2733 ++Index;
2734 }
2735 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002736 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002737
Douglas Gregorb4866e82015-06-19 18:13:19 +00002738 // Check for non-null arguments.
2739 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2740 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00002741 if (NonNullArgs[ArgIndex])
2742 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00002743 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002744}
2745
Richard Smith55ce3522012-06-25 20:30:08 +00002746/// Handles the checks for format strings, non-POD arguments to vararg
George Burgess IVce6284b2017-01-28 02:19:40 +00002747/// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
2748/// attributes.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002749void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
George Burgess IVce6284b2017-01-28 02:19:40 +00002750 const Expr *ThisArg, ArrayRef<const Expr *> Args,
2751 bool IsMemberFunction, SourceLocation Loc,
2752 SourceRange Range, VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00002753 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00002754 if (CurContext->isDependentContext())
2755 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00002756
Ted Kremenekb8176da2010-09-09 04:33:05 +00002757 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00002758 llvm::SmallBitVector CheckedVarArgs;
2759 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002760 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002761 // Only create vector if there are format attributes.
2762 CheckedVarArgs.resize(Args.size());
2763
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002764 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00002765 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002766 }
Richard Smithd7293d72013-08-05 18:49:43 +00002767 }
Richard Smith55ce3522012-06-25 20:30:08 +00002768
2769 // Refuse POD arguments that weren't caught by the format string
2770 // checks above.
Richard Smith836de6b2016-12-19 23:59:34 +00002771 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
2772 if (CallType != VariadicDoesNotApply &&
2773 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002774 unsigned NumParams = Proto ? Proto->getNumParams()
2775 : FDecl && isa<FunctionDecl>(FDecl)
2776 ? cast<FunctionDecl>(FDecl)->getNumParams()
2777 : FDecl && isa<ObjCMethodDecl>(FDecl)
2778 ? cast<ObjCMethodDecl>(FDecl)->param_size()
2779 : 0;
2780
Alp Toker9cacbab2014-01-20 20:26:09 +00002781 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002782 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00002783 if (const Expr *Arg = Args[ArgIdx]) {
2784 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2785 checkVariadicArgument(Arg, CallType);
2786 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002787 }
Richard Smithd7293d72013-08-05 18:49:43 +00002788 }
Mike Stump11289f42009-09-09 15:08:12 +00002789
Douglas Gregorb4866e82015-06-19 18:13:19 +00002790 if (FDecl || Proto) {
2791 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002792
Richard Trieu41bc0992013-06-22 00:20:41 +00002793 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002794 if (FDecl) {
2795 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +00002796 CheckArgumentWithTypeTag(I, Args, Loc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00002797 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002798 }
George Burgess IVce6284b2017-01-28 02:19:40 +00002799
2800 if (FD)
2801 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
Richard Smith55ce3522012-06-25 20:30:08 +00002802}
2803
2804/// CheckConstructorCall - Check a constructor call for correctness and safety
2805/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002806void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2807 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002808 const FunctionProtoType *Proto,
2809 SourceLocation Loc) {
2810 VariadicCallType CallType =
2811 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
George Burgess IVce6284b2017-01-28 02:19:40 +00002812 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
2813 Loc, SourceRange(), CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00002814}
2815
2816/// CheckFunctionCall - Check a direct function call for various correctness
2817/// and safety properties not strictly enforced by the C type system.
2818bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2819 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002820 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2821 isa<CXXMethodDecl>(FDecl);
2822 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2823 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00002824 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2825 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00002826 Expr** Args = TheCall->getArgs();
2827 unsigned NumArgs = TheCall->getNumArgs();
George Burgess IVce6284b2017-01-28 02:19:40 +00002828
2829 Expr *ImplicitThis = nullptr;
Eli Friedmanadf42182012-10-11 00:34:15 +00002830 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002831 // If this is a call to a member operator, hide the first argument
2832 // from checkCall.
2833 // FIXME: Our choice of AST representation here is less than ideal.
George Burgess IVce6284b2017-01-28 02:19:40 +00002834 ImplicitThis = Args[0];
Eli Friedman726d11c2012-10-11 00:30:58 +00002835 ++Args;
2836 --NumArgs;
George Burgess IVce6284b2017-01-28 02:19:40 +00002837 } else if (IsMemberFunction)
2838 ImplicitThis =
2839 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
2840
2841 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00002842 IsMemberFunction, TheCall->getRParenLoc(),
2843 TheCall->getCallee()->getSourceRange(), CallType);
2844
2845 IdentifierInfo *FnInfo = FDecl->getIdentifier();
2846 // None of the checks below are needed for functions that don't have
2847 // simple names (e.g., C++ conversion functions).
2848 if (!FnInfo)
2849 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002850
Richard Trieua7f30b12016-12-06 01:42:28 +00002851 CheckAbsoluteValueFunction(TheCall, FDecl);
2852 CheckMaxUnsignedZero(TheCall, FDecl);
Richard Trieu67c00712016-12-05 23:41:46 +00002853
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002854 if (getLangOpts().ObjC1)
2855 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00002856
Anna Zaks22122702012-01-17 00:37:07 +00002857 unsigned CMId = FDecl->getMemoryFunctionKind();
2858 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00002859 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00002860
Anna Zaks201d4892012-01-13 21:52:01 +00002861 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00002862 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00002863 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00002864 else if (CMId == Builtin::BIstrncat)
2865 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00002866 else
Anna Zaks22122702012-01-17 00:37:07 +00002867 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002868
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002869 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00002870}
2871
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002872bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00002873 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00002874 VariadicCallType CallType =
2875 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002876
George Burgess IVce6284b2017-01-28 02:19:40 +00002877 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
2878 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002879 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002880
2881 return false;
2882}
2883
Richard Trieu664c4c62013-06-20 21:03:13 +00002884bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2885 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00002886 QualType Ty;
2887 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002888 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002889 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002890 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002891 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002892 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002893
Douglas Gregorb4866e82015-06-19 18:13:19 +00002894 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2895 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002896 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002897
Richard Trieu664c4c62013-06-20 21:03:13 +00002898 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00002899 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00002900 CallType = VariadicDoesNotApply;
2901 } else if (Ty->isBlockPointerType()) {
2902 CallType = VariadicBlock;
2903 } else { // Ty->isFunctionPointerType()
2904 CallType = VariadicFunction;
2905 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002906
George Burgess IVce6284b2017-01-28 02:19:40 +00002907 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002908 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2909 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00002910 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00002911
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002912 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00002913}
2914
Richard Trieu41bc0992013-06-22 00:20:41 +00002915/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2916/// such as function pointers returned from functions.
2917bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002918 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00002919 TheCall->getCallee());
George Burgess IVce6284b2017-01-28 02:19:40 +00002920 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00002921 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002922 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00002923 TheCall->getCallee()->getSourceRange(), CallType);
2924
2925 return false;
2926}
2927
Tim Northovere94a34c2014-03-11 10:49:14 +00002928static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00002929 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00002930 return false;
2931
JF Bastiendda2cb12016-04-18 18:01:49 +00002932 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00002933 switch (Op) {
2934 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00002935 case AtomicExpr::AO__opencl_atomic_init:
Tim Northovere94a34c2014-03-11 10:49:14 +00002936 llvm_unreachable("There is no ordering argument for an init");
2937
2938 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00002939 case AtomicExpr::AO__opencl_atomic_load:
Tim Northovere94a34c2014-03-11 10:49:14 +00002940 case AtomicExpr::AO__atomic_load_n:
2941 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00002942 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2943 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002944
2945 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00002946 case AtomicExpr::AO__opencl_atomic_store:
Tim Northovere94a34c2014-03-11 10:49:14 +00002947 case AtomicExpr::AO__atomic_store:
2948 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00002949 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2950 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2951 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002952
2953 default:
2954 return true;
2955 }
2956}
2957
Richard Smithfeea8832012-04-12 05:08:17 +00002958ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2959 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002960 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2961 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002962
Yaxun Liu39195062017-08-04 18:16:31 +00002963 // All the non-OpenCL operations take one of the following forms.
2964 // The OpenCL operations take the __c11 forms with one extra argument for
2965 // synchronization scope.
Richard Smithfeea8832012-04-12 05:08:17 +00002966 enum {
2967 // C __c11_atomic_init(A *, C)
2968 Init,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002969
Richard Smithfeea8832012-04-12 05:08:17 +00002970 // C __c11_atomic_load(A *, int)
2971 Load,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002972
Richard Smithfeea8832012-04-12 05:08:17 +00002973 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00002974 LoadCopy,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002975
Eric Fiselier8d662442016-03-30 23:39:56 +00002976 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00002977 Copy,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002978
Richard Smithfeea8832012-04-12 05:08:17 +00002979 // C __c11_atomic_add(A *, M, int)
2980 Arithmetic,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002981
Richard Smithfeea8832012-04-12 05:08:17 +00002982 // C __atomic_exchange_n(A *, CP, int)
2983 Xchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002984
Richard Smithfeea8832012-04-12 05:08:17 +00002985 // void __atomic_exchange(A *, C *, CP, int)
2986 GNUXchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002987
Richard Smithfeea8832012-04-12 05:08:17 +00002988 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2989 C11CmpXchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002990
Richard Smithfeea8832012-04-12 05:08:17 +00002991 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2992 GNUCmpXchg
2993 } Form = Init;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002994
Yaxun Liu39195062017-08-04 18:16:31 +00002995 const unsigned NumForm = GNUCmpXchg + 1;
Eric Fiselier8d662442016-03-30 23:39:56 +00002996 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2997 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00002998 // where:
2999 // C is an appropriate type,
3000 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
3001 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
3002 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
3003 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003004
Yaxun Liu39195062017-08-04 18:16:31 +00003005 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
3006 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
3007 "need to update code for modified forms");
Gabor Horvath98bd0982015-03-16 09:59:54 +00003008 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
3009 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
3010 AtomicExpr::AO__atomic_load,
3011 "need to update code for modified C11 atomics");
Yaxun Liu39195062017-08-04 18:16:31 +00003012 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
3013 Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
3014 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
3015 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
3016 IsOpenCL;
Richard Smithfeea8832012-04-12 05:08:17 +00003017 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
3018 Op == AtomicExpr::AO__atomic_store_n ||
3019 Op == AtomicExpr::AO__atomic_exchange_n ||
3020 Op == AtomicExpr::AO__atomic_compare_exchange_n;
3021 bool IsAddSub = false;
3022
3023 switch (Op) {
3024 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00003025 case AtomicExpr::AO__opencl_atomic_init:
Richard Smithfeea8832012-04-12 05:08:17 +00003026 Form = Init;
3027 break;
3028
3029 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00003030 case AtomicExpr::AO__opencl_atomic_load:
Richard Smithfeea8832012-04-12 05:08:17 +00003031 case AtomicExpr::AO__atomic_load_n:
3032 Form = Load;
3033 break;
3034
Richard Smithfeea8832012-04-12 05:08:17 +00003035 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00003036 Form = LoadCopy;
3037 break;
3038
3039 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00003040 case AtomicExpr::AO__opencl_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00003041 case AtomicExpr::AO__atomic_store:
3042 case AtomicExpr::AO__atomic_store_n:
3043 Form = Copy;
3044 break;
3045
3046 case AtomicExpr::AO__c11_atomic_fetch_add:
3047 case AtomicExpr::AO__c11_atomic_fetch_sub:
Yaxun Liu39195062017-08-04 18:16:31 +00003048 case AtomicExpr::AO__opencl_atomic_fetch_add:
3049 case AtomicExpr::AO__opencl_atomic_fetch_sub:
3050 case AtomicExpr::AO__opencl_atomic_fetch_min:
3051 case AtomicExpr::AO__opencl_atomic_fetch_max:
Richard Smithfeea8832012-04-12 05:08:17 +00003052 case AtomicExpr::AO__atomic_fetch_add:
3053 case AtomicExpr::AO__atomic_fetch_sub:
3054 case AtomicExpr::AO__atomic_add_fetch:
3055 case AtomicExpr::AO__atomic_sub_fetch:
3056 IsAddSub = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00003057 LLVM_FALLTHROUGH;
Richard Smithfeea8832012-04-12 05:08:17 +00003058 case AtomicExpr::AO__c11_atomic_fetch_and:
3059 case AtomicExpr::AO__c11_atomic_fetch_or:
3060 case AtomicExpr::AO__c11_atomic_fetch_xor:
Yaxun Liu39195062017-08-04 18:16:31 +00003061 case AtomicExpr::AO__opencl_atomic_fetch_and:
3062 case AtomicExpr::AO__opencl_atomic_fetch_or:
3063 case AtomicExpr::AO__opencl_atomic_fetch_xor:
Richard Smithfeea8832012-04-12 05:08:17 +00003064 case AtomicExpr::AO__atomic_fetch_and:
3065 case AtomicExpr::AO__atomic_fetch_or:
3066 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00003067 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00003068 case AtomicExpr::AO__atomic_and_fetch:
3069 case AtomicExpr::AO__atomic_or_fetch:
3070 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00003071 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00003072 Form = Arithmetic;
3073 break;
3074
3075 case AtomicExpr::AO__c11_atomic_exchange:
Yaxun Liu39195062017-08-04 18:16:31 +00003076 case AtomicExpr::AO__opencl_atomic_exchange:
Richard Smithfeea8832012-04-12 05:08:17 +00003077 case AtomicExpr::AO__atomic_exchange_n:
3078 Form = Xchg;
3079 break;
3080
3081 case AtomicExpr::AO__atomic_exchange:
3082 Form = GNUXchg;
3083 break;
3084
3085 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3086 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
Yaxun Liu39195062017-08-04 18:16:31 +00003087 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
3088 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
Richard Smithfeea8832012-04-12 05:08:17 +00003089 Form = C11CmpXchg;
3090 break;
3091
3092 case AtomicExpr::AO__atomic_compare_exchange:
3093 case AtomicExpr::AO__atomic_compare_exchange_n:
3094 Form = GNUCmpXchg;
3095 break;
3096 }
3097
Yaxun Liu39195062017-08-04 18:16:31 +00003098 unsigned AdjustedNumArgs = NumArgs[Form];
3099 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
3100 ++AdjustedNumArgs;
Richard Smithfeea8832012-04-12 05:08:17 +00003101 // Check we have the right number of arguments.
Yaxun Liu39195062017-08-04 18:16:31 +00003102 if (TheCall->getNumArgs() < AdjustedNumArgs) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003103 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Yaxun Liu39195062017-08-04 18:16:31 +00003104 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003105 << TheCall->getCallee()->getSourceRange();
3106 return ExprError();
Yaxun Liu39195062017-08-04 18:16:31 +00003107 } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
3108 Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003109 diag::err_typecheck_call_too_many_args)
Yaxun Liu39195062017-08-04 18:16:31 +00003110 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003111 << TheCall->getCallee()->getSourceRange();
3112 return ExprError();
3113 }
3114
Richard Smithfeea8832012-04-12 05:08:17 +00003115 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003116 Expr *Ptr = TheCall->getArg(0);
George Burgess IV92b43a42016-07-21 03:28:13 +00003117 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
3118 if (ConvertedPtr.isInvalid())
3119 return ExprError();
3120
3121 Ptr = ConvertedPtr.get();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003122 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
3123 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00003124 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003125 << Ptr->getType() << Ptr->getSourceRange();
3126 return ExprError();
3127 }
3128
Richard Smithfeea8832012-04-12 05:08:17 +00003129 // For a __c11 builtin, this should be a pointer to an _Atomic type.
3130 QualType AtomTy = pointerType->getPointeeType(); // 'A'
3131 QualType ValType = AtomTy; // 'C'
3132 if (IsC11) {
3133 if (!AtomTy->isAtomicType()) {
3134 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
3135 << Ptr->getType() << Ptr->getSourceRange();
3136 return ExprError();
3137 }
Yaxun Liu39195062017-08-04 18:16:31 +00003138 if (AtomTy.isConstQualified() ||
3139 AtomTy.getAddressSpace() == LangAS::opencl_constant) {
Richard Smithe00921a2012-09-15 06:09:58 +00003140 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
Yaxun Liu39195062017-08-04 18:16:31 +00003141 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
3142 << Ptr->getSourceRange();
Richard Smithe00921a2012-09-15 06:09:58 +00003143 return ExprError();
3144 }
Richard Smithfeea8832012-04-12 05:08:17 +00003145 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00003146 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00003147 if (ValType.isConstQualified()) {
3148 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
3149 << Ptr->getType() << Ptr->getSourceRange();
3150 return ExprError();
3151 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003152 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003153
Richard Smithfeea8832012-04-12 05:08:17 +00003154 // For an arithmetic operation, the implied arithmetic must be well-formed.
3155 if (Form == Arithmetic) {
3156 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
3157 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
3158 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3159 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3160 return ExprError();
3161 }
3162 if (!IsAddSub && !ValType->isIntegerType()) {
3163 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
3164 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3165 return ExprError();
3166 }
David Majnemere85cff82015-01-28 05:48:06 +00003167 if (IsC11 && ValType->isPointerType() &&
3168 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
3169 diag::err_incomplete_type)) {
3170 return ExprError();
3171 }
Richard Smithfeea8832012-04-12 05:08:17 +00003172 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
3173 // For __atomic_*_n operations, the value type must be a scalar integral or
3174 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003175 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00003176 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3177 return ExprError();
3178 }
3179
Eli Friedmanaa769812013-09-11 03:49:34 +00003180 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
3181 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00003182 // For GNU atomics, require a trivially-copyable type. This is not part of
3183 // the GNU atomics specification, but we enforce it for sanity.
3184 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003185 << Ptr->getType() << Ptr->getSourceRange();
3186 return ExprError();
3187 }
3188
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003189 switch (ValType.getObjCLifetime()) {
3190 case Qualifiers::OCL_None:
3191 case Qualifiers::OCL_ExplicitNone:
3192 // okay
3193 break;
3194
3195 case Qualifiers::OCL_Weak:
3196 case Qualifiers::OCL_Strong:
3197 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00003198 // FIXME: Can this happen? By this point, ValType should be known
3199 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003200 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3201 << ValType << Ptr->getSourceRange();
3202 return ExprError();
3203 }
3204
David Majnemerc6eb6502015-06-03 00:26:35 +00003205 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
3206 // volatile-ness of the pointee-type inject itself into the result or the
Eric Fiselier8d662442016-03-30 23:39:56 +00003207 // other operands. Similarly atomic_load can take a pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00003208 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00003209 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003210 QualType ResultType = ValType;
Yaxun Liu39195062017-08-04 18:16:31 +00003211 if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
3212 Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003213 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00003214 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003215 ResultType = Context.BoolTy;
3216
Richard Smithfeea8832012-04-12 05:08:17 +00003217 // The type of a parameter passed 'by value'. In the GNU atomics, such
3218 // arguments are actually passed as pointers.
3219 QualType ByValType = ValType; // 'CP'
3220 if (!IsC11 && !IsN)
3221 ByValType = Ptr->getType();
3222
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003223 // The first argument --- the pointer --- has a fixed type; we
3224 // deduce the types of the rest of the arguments accordingly. Walk
3225 // the remaining arguments, converting them to the deduced value type.
Yaxun Liu39195062017-08-04 18:16:31 +00003226 for (unsigned i = 1; i != TheCall->getNumArgs(); ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003227 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00003228 if (i < NumVals[Form] + 1) {
3229 switch (i) {
3230 case 1:
3231 // The second argument is the non-atomic operand. For arithmetic, this
3232 // is always passed by value, and for a compare_exchange it is always
3233 // passed by address. For the rest, GNU uses by-address and C11 uses
3234 // by-value.
3235 assert(Form != Load);
3236 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
3237 Ty = ValType;
3238 else if (Form == Copy || Form == Xchg)
3239 Ty = ByValType;
3240 else if (Form == Arithmetic)
3241 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003242 else {
3243 Expr *ValArg = TheCall->getArg(i);
Alex Lorenz67522152016-11-23 16:57:03 +00003244 // Treat this argument as _Nonnull as we want to show a warning if
3245 // NULL is passed into it.
3246 CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
Alexander Richardson6d989432017-10-15 18:48:14 +00003247 LangAS AS = LangAS::Default;
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003248 // Keep address space of non-atomic pointer type.
3249 if (const PointerType *PtrTy =
3250 ValArg->getType()->getAs<PointerType>()) {
3251 AS = PtrTy->getPointeeType().getAddressSpace();
3252 }
3253 Ty = Context.getPointerType(
3254 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
3255 }
Richard Smithfeea8832012-04-12 05:08:17 +00003256 break;
3257 case 2:
3258 // The third argument to compare_exchange / GNU exchange is a
3259 // (pointer to a) desired value.
3260 Ty = ByValType;
3261 break;
3262 case 3:
3263 // The fourth argument to GNU compare_exchange is a 'weak' flag.
3264 Ty = Context.BoolTy;
3265 break;
3266 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003267 } else {
Yaxun Liu39195062017-08-04 18:16:31 +00003268 // The order(s) and scope are always converted to int.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003269 Ty = Context.IntTy;
3270 }
Richard Smithfeea8832012-04-12 05:08:17 +00003271
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003272 InitializedEntity Entity =
3273 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00003274 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003275 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3276 if (Arg.isInvalid())
3277 return true;
3278 TheCall->setArg(i, Arg.get());
3279 }
3280
Richard Smithfeea8832012-04-12 05:08:17 +00003281 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003282 SmallVector<Expr*, 5> SubExprs;
3283 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00003284 switch (Form) {
3285 case Init:
3286 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00003287 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003288 break;
3289 case Load:
3290 SubExprs.push_back(TheCall->getArg(1)); // Order
3291 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00003292 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00003293 case Copy:
3294 case Arithmetic:
3295 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003296 SubExprs.push_back(TheCall->getArg(2)); // Order
3297 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003298 break;
3299 case GNUXchg:
3300 // Note, AtomicExpr::getVal2() has a special case for this atomic.
3301 SubExprs.push_back(TheCall->getArg(3)); // Order
3302 SubExprs.push_back(TheCall->getArg(1)); // Val1
3303 SubExprs.push_back(TheCall->getArg(2)); // Val2
3304 break;
3305 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003306 SubExprs.push_back(TheCall->getArg(3)); // Order
3307 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003308 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00003309 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00003310 break;
3311 case GNUCmpXchg:
3312 SubExprs.push_back(TheCall->getArg(4)); // Order
3313 SubExprs.push_back(TheCall->getArg(1)); // Val1
3314 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
3315 SubExprs.push_back(TheCall->getArg(2)); // Val2
3316 SubExprs.push_back(TheCall->getArg(3)); // Weak
3317 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003318 }
Tim Northovere94a34c2014-03-11 10:49:14 +00003319
3320 if (SubExprs.size() >= 2 && Form != Init) {
3321 llvm::APSInt Result(32);
3322 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
3323 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00003324 Diag(SubExprs[1]->getLocStart(),
3325 diag::warn_atomic_op_has_invalid_memory_order)
3326 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00003327 }
3328
Yaxun Liu30d652a2017-08-15 16:02:49 +00003329 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
3330 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
3331 llvm::APSInt Result(32);
3332 if (Scope->isIntegerConstantExpr(Result, Context) &&
3333 !ScopeModel->isValid(Result.getZExtValue())) {
3334 Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope)
3335 << Scope->getSourceRange();
3336 }
3337 SubExprs.push_back(Scope);
3338 }
3339
Fariborz Jahanian615de762013-05-28 17:37:39 +00003340 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
3341 SubExprs, ResultType, Op,
3342 TheCall->getRParenLoc());
3343
3344 if ((Op == AtomicExpr::AO__c11_atomic_load ||
Yaxun Liu39195062017-08-04 18:16:31 +00003345 Op == AtomicExpr::AO__c11_atomic_store ||
3346 Op == AtomicExpr::AO__opencl_atomic_load ||
3347 Op == AtomicExpr::AO__opencl_atomic_store ) &&
Fariborz Jahanian615de762013-05-28 17:37:39 +00003348 Context.AtomicUsesUnsupportedLibcall(AE))
Yaxun Liu39195062017-08-04 18:16:31 +00003349 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib)
3350 << ((Op == AtomicExpr::AO__c11_atomic_load ||
3351 Op == AtomicExpr::AO__opencl_atomic_load)
3352 ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003353
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003354 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003355}
3356
John McCall29ad95b2011-08-27 01:09:30 +00003357/// checkBuiltinArgument - Given a call to a builtin function, perform
3358/// normal type-checking on the given argument, updating the call in
3359/// place. This is useful when a builtin function requires custom
3360/// type-checking for some of its arguments but not necessarily all of
3361/// them.
3362///
3363/// Returns true on error.
3364static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
3365 FunctionDecl *Fn = E->getDirectCallee();
3366 assert(Fn && "builtin call without direct callee!");
3367
3368 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
3369 InitializedEntity Entity =
3370 InitializedEntity::InitializeParameter(S.Context, Param);
3371
3372 ExprResult Arg = E->getArg(0);
3373 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3374 if (Arg.isInvalid())
3375 return true;
3376
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003377 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00003378 return false;
3379}
3380
Chris Lattnerdc046542009-05-08 06:58:22 +00003381/// SemaBuiltinAtomicOverloaded - We have a call to a function like
3382/// __sync_fetch_and_add, which is an overloaded function based on the pointer
3383/// type of its first argument. The main ActOnCallExpr routines have already
3384/// promoted the types of arguments because all of these calls are prototyped as
3385/// void(...).
3386///
3387/// This function goes through and does final semantic checking for these
3388/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00003389ExprResult
3390Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003391 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00003392 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3393 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3394
3395 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003396 if (TheCall->getNumArgs() < 1) {
3397 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3398 << 0 << 1 << TheCall->getNumArgs()
3399 << TheCall->getCallee()->getSourceRange();
3400 return ExprError();
3401 }
Mike Stump11289f42009-09-09 15:08:12 +00003402
Chris Lattnerdc046542009-05-08 06:58:22 +00003403 // Inspect the first argument of the atomic builtin. This should always be
3404 // a pointer type, whose element is an integral scalar or pointer type.
3405 // Because it is a pointer type, we don't have to worry about any implicit
3406 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003407 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00003408 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00003409 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3410 if (FirstArgResult.isInvalid())
3411 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003412 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00003413 TheCall->setArg(0, FirstArg);
3414
John McCall31168b02011-06-15 23:02:42 +00003415 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3416 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003417 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3418 << FirstArg->getType() << FirstArg->getSourceRange();
3419 return ExprError();
3420 }
Mike Stump11289f42009-09-09 15:08:12 +00003421
John McCall31168b02011-06-15 23:02:42 +00003422 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00003423 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003424 !ValType->isBlockPointerType()) {
3425 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3426 << FirstArg->getType() << FirstArg->getSourceRange();
3427 return ExprError();
3428 }
Chris Lattnerdc046542009-05-08 06:58:22 +00003429
John McCall31168b02011-06-15 23:02:42 +00003430 switch (ValType.getObjCLifetime()) {
3431 case Qualifiers::OCL_None:
3432 case Qualifiers::OCL_ExplicitNone:
3433 // okay
3434 break;
3435
3436 case Qualifiers::OCL_Weak:
3437 case Qualifiers::OCL_Strong:
3438 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00003439 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00003440 << ValType << FirstArg->getSourceRange();
3441 return ExprError();
3442 }
3443
John McCallb50451a2011-10-05 07:41:44 +00003444 // Strip any qualifiers off ValType.
3445 ValType = ValType.getUnqualifiedType();
3446
Chandler Carruth3973af72010-07-18 20:54:12 +00003447 // The majority of builtins return a value, but a few have special return
3448 // types, so allow them to override appropriately below.
3449 QualType ResultType = ValType;
3450
Chris Lattnerdc046542009-05-08 06:58:22 +00003451 // We need to figure out which concrete builtin this maps onto. For example,
3452 // __sync_fetch_and_add with a 2 byte object turns into
3453 // __sync_fetch_and_add_2.
3454#define BUILTIN_ROW(x) \
3455 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3456 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00003457
Chris Lattnerdc046542009-05-08 06:58:22 +00003458 static const unsigned BuiltinIndices[][5] = {
3459 BUILTIN_ROW(__sync_fetch_and_add),
3460 BUILTIN_ROW(__sync_fetch_and_sub),
3461 BUILTIN_ROW(__sync_fetch_and_or),
3462 BUILTIN_ROW(__sync_fetch_and_and),
3463 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00003464 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00003465
Chris Lattnerdc046542009-05-08 06:58:22 +00003466 BUILTIN_ROW(__sync_add_and_fetch),
3467 BUILTIN_ROW(__sync_sub_and_fetch),
3468 BUILTIN_ROW(__sync_and_and_fetch),
3469 BUILTIN_ROW(__sync_or_and_fetch),
3470 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00003471 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00003472
Chris Lattnerdc046542009-05-08 06:58:22 +00003473 BUILTIN_ROW(__sync_val_compare_and_swap),
3474 BUILTIN_ROW(__sync_bool_compare_and_swap),
3475 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00003476 BUILTIN_ROW(__sync_lock_release),
3477 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00003478 };
Mike Stump11289f42009-09-09 15:08:12 +00003479#undef BUILTIN_ROW
3480
Chris Lattnerdc046542009-05-08 06:58:22 +00003481 // Determine the index of the size.
3482 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00003483 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00003484 case 1: SizeIndex = 0; break;
3485 case 2: SizeIndex = 1; break;
3486 case 4: SizeIndex = 2; break;
3487 case 8: SizeIndex = 3; break;
3488 case 16: SizeIndex = 4; break;
3489 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003490 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3491 << FirstArg->getType() << FirstArg->getSourceRange();
3492 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00003493 }
Mike Stump11289f42009-09-09 15:08:12 +00003494
Chris Lattnerdc046542009-05-08 06:58:22 +00003495 // Each of these builtins has one pointer argument, followed by some number of
3496 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3497 // that we ignore. Find out which row of BuiltinIndices to read from as well
3498 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00003499 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00003500 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00003501 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00003502 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00003503 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00003504 case Builtin::BI__sync_fetch_and_add:
3505 case Builtin::BI__sync_fetch_and_add_1:
3506 case Builtin::BI__sync_fetch_and_add_2:
3507 case Builtin::BI__sync_fetch_and_add_4:
3508 case Builtin::BI__sync_fetch_and_add_8:
3509 case Builtin::BI__sync_fetch_and_add_16:
3510 BuiltinIndex = 0;
3511 break;
3512
3513 case Builtin::BI__sync_fetch_and_sub:
3514 case Builtin::BI__sync_fetch_and_sub_1:
3515 case Builtin::BI__sync_fetch_and_sub_2:
3516 case Builtin::BI__sync_fetch_and_sub_4:
3517 case Builtin::BI__sync_fetch_and_sub_8:
3518 case Builtin::BI__sync_fetch_and_sub_16:
3519 BuiltinIndex = 1;
3520 break;
3521
3522 case Builtin::BI__sync_fetch_and_or:
3523 case Builtin::BI__sync_fetch_and_or_1:
3524 case Builtin::BI__sync_fetch_and_or_2:
3525 case Builtin::BI__sync_fetch_and_or_4:
3526 case Builtin::BI__sync_fetch_and_or_8:
3527 case Builtin::BI__sync_fetch_and_or_16:
3528 BuiltinIndex = 2;
3529 break;
3530
3531 case Builtin::BI__sync_fetch_and_and:
3532 case Builtin::BI__sync_fetch_and_and_1:
3533 case Builtin::BI__sync_fetch_and_and_2:
3534 case Builtin::BI__sync_fetch_and_and_4:
3535 case Builtin::BI__sync_fetch_and_and_8:
3536 case Builtin::BI__sync_fetch_and_and_16:
3537 BuiltinIndex = 3;
3538 break;
Mike Stump11289f42009-09-09 15:08:12 +00003539
Douglas Gregor73722482011-11-28 16:30:08 +00003540 case Builtin::BI__sync_fetch_and_xor:
3541 case Builtin::BI__sync_fetch_and_xor_1:
3542 case Builtin::BI__sync_fetch_and_xor_2:
3543 case Builtin::BI__sync_fetch_and_xor_4:
3544 case Builtin::BI__sync_fetch_and_xor_8:
3545 case Builtin::BI__sync_fetch_and_xor_16:
3546 BuiltinIndex = 4;
3547 break;
3548
Hal Finkeld2208b52014-10-02 20:53:50 +00003549 case Builtin::BI__sync_fetch_and_nand:
3550 case Builtin::BI__sync_fetch_and_nand_1:
3551 case Builtin::BI__sync_fetch_and_nand_2:
3552 case Builtin::BI__sync_fetch_and_nand_4:
3553 case Builtin::BI__sync_fetch_and_nand_8:
3554 case Builtin::BI__sync_fetch_and_nand_16:
3555 BuiltinIndex = 5;
3556 WarnAboutSemanticsChange = true;
3557 break;
3558
Douglas Gregor73722482011-11-28 16:30:08 +00003559 case Builtin::BI__sync_add_and_fetch:
3560 case Builtin::BI__sync_add_and_fetch_1:
3561 case Builtin::BI__sync_add_and_fetch_2:
3562 case Builtin::BI__sync_add_and_fetch_4:
3563 case Builtin::BI__sync_add_and_fetch_8:
3564 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003565 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00003566 break;
3567
3568 case Builtin::BI__sync_sub_and_fetch:
3569 case Builtin::BI__sync_sub_and_fetch_1:
3570 case Builtin::BI__sync_sub_and_fetch_2:
3571 case Builtin::BI__sync_sub_and_fetch_4:
3572 case Builtin::BI__sync_sub_and_fetch_8:
3573 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003574 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00003575 break;
3576
3577 case Builtin::BI__sync_and_and_fetch:
3578 case Builtin::BI__sync_and_and_fetch_1:
3579 case Builtin::BI__sync_and_and_fetch_2:
3580 case Builtin::BI__sync_and_and_fetch_4:
3581 case Builtin::BI__sync_and_and_fetch_8:
3582 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003583 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00003584 break;
3585
3586 case Builtin::BI__sync_or_and_fetch:
3587 case Builtin::BI__sync_or_and_fetch_1:
3588 case Builtin::BI__sync_or_and_fetch_2:
3589 case Builtin::BI__sync_or_and_fetch_4:
3590 case Builtin::BI__sync_or_and_fetch_8:
3591 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003592 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00003593 break;
3594
3595 case Builtin::BI__sync_xor_and_fetch:
3596 case Builtin::BI__sync_xor_and_fetch_1:
3597 case Builtin::BI__sync_xor_and_fetch_2:
3598 case Builtin::BI__sync_xor_and_fetch_4:
3599 case Builtin::BI__sync_xor_and_fetch_8:
3600 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003601 BuiltinIndex = 10;
3602 break;
3603
3604 case Builtin::BI__sync_nand_and_fetch:
3605 case Builtin::BI__sync_nand_and_fetch_1:
3606 case Builtin::BI__sync_nand_and_fetch_2:
3607 case Builtin::BI__sync_nand_and_fetch_4:
3608 case Builtin::BI__sync_nand_and_fetch_8:
3609 case Builtin::BI__sync_nand_and_fetch_16:
3610 BuiltinIndex = 11;
3611 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00003612 break;
Mike Stump11289f42009-09-09 15:08:12 +00003613
Chris Lattnerdc046542009-05-08 06:58:22 +00003614 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003615 case Builtin::BI__sync_val_compare_and_swap_1:
3616 case Builtin::BI__sync_val_compare_and_swap_2:
3617 case Builtin::BI__sync_val_compare_and_swap_4:
3618 case Builtin::BI__sync_val_compare_and_swap_8:
3619 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003620 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00003621 NumFixed = 2;
3622 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003623
Chris Lattnerdc046542009-05-08 06:58:22 +00003624 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003625 case Builtin::BI__sync_bool_compare_and_swap_1:
3626 case Builtin::BI__sync_bool_compare_and_swap_2:
3627 case Builtin::BI__sync_bool_compare_and_swap_4:
3628 case Builtin::BI__sync_bool_compare_and_swap_8:
3629 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003630 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00003631 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00003632 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003633 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003634
3635 case Builtin::BI__sync_lock_test_and_set:
3636 case Builtin::BI__sync_lock_test_and_set_1:
3637 case Builtin::BI__sync_lock_test_and_set_2:
3638 case Builtin::BI__sync_lock_test_and_set_4:
3639 case Builtin::BI__sync_lock_test_and_set_8:
3640 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003641 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00003642 break;
3643
Chris Lattnerdc046542009-05-08 06:58:22 +00003644 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00003645 case Builtin::BI__sync_lock_release_1:
3646 case Builtin::BI__sync_lock_release_2:
3647 case Builtin::BI__sync_lock_release_4:
3648 case Builtin::BI__sync_lock_release_8:
3649 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003650 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00003651 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00003652 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003653 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003654
3655 case Builtin::BI__sync_swap:
3656 case Builtin::BI__sync_swap_1:
3657 case Builtin::BI__sync_swap_2:
3658 case Builtin::BI__sync_swap_4:
3659 case Builtin::BI__sync_swap_8:
3660 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003661 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00003662 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00003663 }
Mike Stump11289f42009-09-09 15:08:12 +00003664
Chris Lattnerdc046542009-05-08 06:58:22 +00003665 // Now that we know how many fixed arguments we expect, first check that we
3666 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003667 if (TheCall->getNumArgs() < 1+NumFixed) {
3668 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3669 << 0 << 1+NumFixed << TheCall->getNumArgs()
3670 << TheCall->getCallee()->getSourceRange();
3671 return ExprError();
3672 }
Mike Stump11289f42009-09-09 15:08:12 +00003673
Hal Finkeld2208b52014-10-02 20:53:50 +00003674 if (WarnAboutSemanticsChange) {
3675 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3676 << TheCall->getCallee()->getSourceRange();
3677 }
3678
Chris Lattner5b9241b2009-05-08 15:36:58 +00003679 // Get the decl for the concrete builtin from this, we can tell what the
3680 // concrete integer type we should convert to is.
3681 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Mehdi Amini7186a432016-10-11 19:04:24 +00003682 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003683 FunctionDecl *NewBuiltinDecl;
3684 if (NewBuiltinID == BuiltinID)
3685 NewBuiltinDecl = FDecl;
3686 else {
3687 // Perform builtin lookup to avoid redeclaring it.
3688 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3689 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3690 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3691 assert(Res.getFoundDecl());
3692 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00003693 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003694 return ExprError();
3695 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003696
John McCallcf142162010-08-07 06:22:56 +00003697 // The first argument --- the pointer --- has a fixed type; we
3698 // deduce the types of the rest of the arguments accordingly. Walk
3699 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00003700 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00003701 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00003702
Chris Lattnerdc046542009-05-08 06:58:22 +00003703 // GCC does an implicit conversion to the pointer or integer ValType. This
3704 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00003705 // Initialize the argument.
3706 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3707 ValType, /*consume*/ false);
3708 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00003709 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003710 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003711
Chris Lattnerdc046542009-05-08 06:58:22 +00003712 // Okay, we have something that *can* be converted to the right type. Check
3713 // to see if there is a potentially weird extension going on here. This can
3714 // happen when you do an atomic operation on something like an char* and
3715 // pass in 42. The 42 gets converted to char. This is even more strange
3716 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00003717 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003718 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00003719 }
Mike Stump11289f42009-09-09 15:08:12 +00003720
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003721 ASTContext& Context = this->getASTContext();
3722
3723 // Create a new DeclRefExpr to refer to the new decl.
3724 DeclRefExpr* NewDRE = DeclRefExpr::Create(
3725 Context,
3726 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00003727 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003728 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00003729 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003730 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00003731 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003732 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00003733
Chris Lattnerdc046542009-05-08 06:58:22 +00003734 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00003735 // FIXME: This loses syntactic information.
3736 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3737 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3738 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003739 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00003740
Chandler Carruthbc8cab12010-07-18 07:23:17 +00003741 // Change the result type of the call to match the original value type. This
3742 // is arbitrary, but the codegen for these builtins ins design to handle it
3743 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00003744 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003745
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003746 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00003747}
3748
Michael Zolotukhin84df1232015-09-08 23:52:33 +00003749/// SemaBuiltinNontemporalOverloaded - We have a call to
3750/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3751/// overloaded function based on the pointer type of its last argument.
3752///
3753/// This function goes through and does final semantic checking for these
3754/// builtins.
3755ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3756 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3757 DeclRefExpr *DRE =
3758 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3759 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3760 unsigned BuiltinID = FDecl->getBuiltinID();
3761 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3762 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3763 "Unexpected nontemporal load/store builtin!");
3764 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3765 unsigned numArgs = isStore ? 2 : 1;
3766
3767 // Ensure that we have the proper number of arguments.
3768 if (checkArgCount(*this, TheCall, numArgs))
3769 return ExprError();
3770
3771 // Inspect the last argument of the nontemporal builtin. This should always
3772 // be a pointer type, from which we imply the type of the memory access.
3773 // Because it is a pointer type, we don't have to worry about any implicit
3774 // casts here.
3775 Expr *PointerArg = TheCall->getArg(numArgs - 1);
3776 ExprResult PointerArgResult =
3777 DefaultFunctionArrayLvalueConversion(PointerArg);
3778
3779 if (PointerArgResult.isInvalid())
3780 return ExprError();
3781 PointerArg = PointerArgResult.get();
3782 TheCall->setArg(numArgs - 1, PointerArg);
3783
3784 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3785 if (!pointerType) {
3786 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3787 << PointerArg->getType() << PointerArg->getSourceRange();
3788 return ExprError();
3789 }
3790
3791 QualType ValType = pointerType->getPointeeType();
3792
3793 // Strip any qualifiers off ValType.
3794 ValType = ValType.getUnqualifiedType();
3795 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3796 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3797 !ValType->isVectorType()) {
3798 Diag(DRE->getLocStart(),
3799 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3800 << PointerArg->getType() << PointerArg->getSourceRange();
3801 return ExprError();
3802 }
3803
3804 if (!isStore) {
3805 TheCall->setType(ValType);
3806 return TheCallResult;
3807 }
3808
3809 ExprResult ValArg = TheCall->getArg(0);
3810 InitializedEntity Entity = InitializedEntity::InitializeParameter(
3811 Context, ValType, /*consume*/ false);
3812 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3813 if (ValArg.isInvalid())
3814 return ExprError();
3815
3816 TheCall->setArg(0, ValArg.get());
3817 TheCall->setType(Context.VoidTy);
3818 return TheCallResult;
3819}
3820
Chris Lattner6436fb62009-02-18 06:01:06 +00003821/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00003822/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00003823/// Note: It might also make sense to do the UTF-16 conversion here (would
3824/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00003825bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00003826 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00003827 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3828
Douglas Gregorfb65e592011-07-27 05:40:30 +00003829 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003830 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3831 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00003832 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00003833 }
Mike Stump11289f42009-09-09 15:08:12 +00003834
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003835 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003836 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003837 unsigned NumBytes = String.size();
Justin Lebar90910552016-09-30 00:38:45 +00003838 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3839 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3840 llvm::UTF16 *ToPtr = &ToBuf[0];
3841
3842 llvm::ConversionResult Result =
3843 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3844 ToPtr + NumBytes, llvm::strictConversion);
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003845 // Check for conversion failure.
Justin Lebar90910552016-09-30 00:38:45 +00003846 if (Result != llvm::conversionOK)
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003847 Diag(Arg->getLocStart(),
3848 diag::warn_cfstring_truncated) << Arg->getSourceRange();
3849 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00003850 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003851}
3852
Mehdi Amini06d367c2016-10-24 20:39:34 +00003853/// CheckObjCString - Checks that the format string argument to the os_log()
3854/// and os_trace() functions is correct, and converts it to const char *.
3855ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3856 Arg = Arg->IgnoreParenCasts();
3857 auto *Literal = dyn_cast<StringLiteral>(Arg);
3858 if (!Literal) {
3859 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3860 Literal = ObjcLiteral->getString();
3861 }
3862 }
3863
3864 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3865 return ExprError(
3866 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3867 << Arg->getSourceRange());
3868 }
3869
3870 ExprResult Result(Literal);
3871 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3872 InitializedEntity Entity =
3873 InitializedEntity::InitializeParameter(Context, ResultTy, false);
3874 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3875 return Result;
3876}
3877
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003878/// Check that the user is calling the appropriate va_start builtin for the
3879/// target and calling convention.
3880static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
3881 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
3882 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
Martin Storsjo022e7822017-07-17 20:49:45 +00003883 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003884 bool IsWindows = TT.isOSWindows();
Martin Storsjo022e7822017-07-17 20:49:45 +00003885 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
3886 if (IsX64 || IsAArch64) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003887 CallingConv CC = CC_C;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003888 if (const FunctionDecl *FD = S.getCurFunctionDecl())
3889 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3890 if (IsMSVAStart) {
3891 // Don't allow this in System V ABI functions.
Martin Storsjo022e7822017-07-17 20:49:45 +00003892 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003893 return S.Diag(Fn->getLocStart(),
3894 diag::err_ms_va_start_used_in_sysv_function);
3895 } else {
Martin Storsjo022e7822017-07-17 20:49:45 +00003896 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003897 // On x64 Windows, don't allow this in System V ABI functions.
3898 // (Yes, that means there's no corresponding way to support variadic
3899 // System V ABI functions on Windows.)
3900 if ((IsWindows && CC == CC_X86_64SysV) ||
Martin Storsjo022e7822017-07-17 20:49:45 +00003901 (!IsWindows && CC == CC_Win64))
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003902 return S.Diag(Fn->getLocStart(),
3903 diag::err_va_start_used_in_wrong_abi_function)
3904 << !IsWindows;
3905 }
3906 return false;
3907 }
3908
3909 if (IsMSVAStart)
Martin Storsjo022e7822017-07-17 20:49:45 +00003910 return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003911 return false;
3912}
3913
3914static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
3915 ParmVarDecl **LastParam = nullptr) {
3916 // Determine whether the current function, block, or obj-c method is variadic
3917 // and get its parameter list.
3918 bool IsVariadic = false;
3919 ArrayRef<ParmVarDecl *> Params;
Reid Klecknerf1deb832017-05-04 19:51:05 +00003920 DeclContext *Caller = S.CurContext;
3921 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
3922 IsVariadic = Block->isVariadic();
3923 Params = Block->parameters();
3924 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003925 IsVariadic = FD->isVariadic();
3926 Params = FD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00003927 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003928 IsVariadic = MD->isVariadic();
3929 // FIXME: This isn't correct for methods (results in bogus warning).
3930 Params = MD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00003931 } else if (isa<CapturedDecl>(Caller)) {
3932 // We don't support va_start in a CapturedDecl.
3933 S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
3934 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003935 } else {
Reid Klecknerf1deb832017-05-04 19:51:05 +00003936 // This must be some other declcontext that parses exprs.
3937 S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
3938 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003939 }
3940
3941 if (!IsVariadic) {
Reid Klecknerf1deb832017-05-04 19:51:05 +00003942 S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003943 return true;
3944 }
3945
3946 if (LastParam)
3947 *LastParam = Params.empty() ? nullptr : Params.back();
3948
3949 return false;
3950}
3951
Charles Davisc7d5c942015-09-17 20:55:33 +00003952/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3953/// for validity. Emit an error and return true on failure; return false
3954/// on success.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003955bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00003956 Expr *Fn = TheCall->getCallee();
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003957
3958 if (checkVAStartABI(*this, BuiltinID, Fn))
3959 return true;
3960
Chris Lattner08464942007-12-28 05:29:59 +00003961 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00003962 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003963 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003964 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3965 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00003966 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003967 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00003968 return true;
3969 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003970
3971 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00003972 return Diag(TheCall->getLocEnd(),
3973 diag::err_typecheck_call_too_few_args_at_least)
3974 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003975 }
3976
John McCall29ad95b2011-08-27 01:09:30 +00003977 // Type-check the first argument normally.
3978 if (checkBuiltinArgument(*this, TheCall, 0))
3979 return true;
3980
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003981 // Check that the current function is variadic, and get its last parameter.
3982 ParmVarDecl *LastParam;
3983 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
Chris Lattner43be2e62007-12-19 23:59:04 +00003984 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003985
Chris Lattner43be2e62007-12-19 23:59:04 +00003986 // Verify that the second argument to the builtin is the last argument of the
3987 // current function or method.
3988 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00003989 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003990
Nico Weber9eea7642013-05-24 23:31:57 +00003991 // These are valid if SecondArgIsLastNamedArgument is false after the next
3992 // block.
3993 QualType Type;
3994 SourceLocation ParamLoc;
Aaron Ballman1de59c52016-04-24 13:30:21 +00003995 bool IsCRegister = false;
Nico Weber9eea7642013-05-24 23:31:57 +00003996
Anders Carlsson6a8350b2008-02-11 04:20:54 +00003997 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3998 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003999 SecondArgIsLastNamedArgument = PV == LastParam;
Nico Weber9eea7642013-05-24 23:31:57 +00004000
4001 Type = PV->getType();
4002 ParamLoc = PV->getLocation();
Aaron Ballman1de59c52016-04-24 13:30:21 +00004003 IsCRegister =
4004 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
Chris Lattner43be2e62007-12-19 23:59:04 +00004005 }
4006 }
Mike Stump11289f42009-09-09 15:08:12 +00004007
Chris Lattner43be2e62007-12-19 23:59:04 +00004008 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00004009 Diag(TheCall->getArg(1)->getLocStart(),
Aaron Ballman05164812016-04-18 18:10:53 +00004010 diag::warn_second_arg_of_va_start_not_last_named_param);
Aaron Ballman1de59c52016-04-24 13:30:21 +00004011 else if (IsCRegister || Type->isReferenceType() ||
Aaron Ballmana4f597f2016-09-15 18:07:51 +00004012 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
4013 // Promotable integers are UB, but enumerations need a bit of
4014 // extra checking to see what their promotable type actually is.
4015 if (!Type->isPromotableIntegerType())
4016 return false;
4017 if (!Type->isEnumeralType())
4018 return true;
4019 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
4020 return !(ED &&
4021 Context.typesAreCompatible(ED->getPromotionType(), Type));
4022 }()) {
Aaron Ballman1de59c52016-04-24 13:30:21 +00004023 unsigned Reason = 0;
4024 if (Type->isReferenceType()) Reason = 1;
4025 else if (IsCRegister) Reason = 2;
4026 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
Nico Weber9eea7642013-05-24 23:31:57 +00004027 Diag(ParamLoc, diag::note_parameter_type) << Type;
4028 }
4029
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00004030 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00004031 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00004032}
Chris Lattner43be2e62007-12-19 23:59:04 +00004033
Saleem Abdulrasool3450aa72017-09-26 20:12:04 +00004034bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004035 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
4036 // const char *named_addr);
4037
4038 Expr *Func = Call->getCallee();
4039
4040 if (Call->getNumArgs() < 3)
4041 return Diag(Call->getLocEnd(),
4042 diag::err_typecheck_call_too_few_args_at_least)
4043 << 0 /*function call*/ << 3 << Call->getNumArgs();
4044
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004045 // Type-check the first argument normally.
4046 if (checkBuiltinArgument(*this, Call, 0))
4047 return true;
4048
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004049 // Check that the current function is variadic.
4050 if (checkVAStartIsInVariadicFunction(*this, Func))
4051 return true;
4052
Saleem Abdulrasool448e8ad2017-09-26 17:44:10 +00004053 // __va_start on Windows does not validate the parameter qualifiers
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004054
Saleem Abdulrasool448e8ad2017-09-26 17:44:10 +00004055 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
4056 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
4057
4058 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
4059 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
4060
4061 const QualType &ConstCharPtrTy =
4062 Context.getPointerType(Context.CharTy.withConst());
4063 if (!Arg1Ty->isPointerType() ||
4064 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
4065 Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible)
4066 << Arg1->getType() << ConstCharPtrTy
4067 << 1 /* different class */
4068 << 0 /* qualifier difference */
4069 << 3 /* parameter mismatch */
4070 << 2 << Arg1->getType() << ConstCharPtrTy;
4071
4072 const QualType SizeTy = Context.getSizeType();
4073 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
4074 Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible)
4075 << Arg2->getType() << SizeTy
4076 << 1 /* different class */
4077 << 0 /* qualifier difference */
4078 << 3 /* parameter mismatch */
4079 << 3 << Arg2->getType() << SizeTy;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004080
4081 return false;
4082}
4083
Chris Lattner2da14fb2007-12-20 00:26:33 +00004084/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
4085/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00004086bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
4087 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00004088 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00004089 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00004090 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00004091 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004092 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004093 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00004094 << SourceRange(TheCall->getArg(2)->getLocStart(),
4095 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00004096
John Wiegley01296292011-04-08 18:41:53 +00004097 ExprResult OrigArg0 = TheCall->getArg(0);
4098 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00004099
Chris Lattner2da14fb2007-12-20 00:26:33 +00004100 // Do standard promotions between the two arguments, returning their common
4101 // type.
Chris Lattner08464942007-12-28 05:29:59 +00004102 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00004103 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
4104 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00004105
4106 // Make sure any conversions are pushed back into the call; this is
4107 // type safe since unordered compare builtins are declared as "_Bool
4108 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00004109 TheCall->setArg(0, OrigArg0.get());
4110 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00004111
John Wiegley01296292011-04-08 18:41:53 +00004112 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00004113 return false;
4114
Chris Lattner2da14fb2007-12-20 00:26:33 +00004115 // If the common type isn't a real floating type, then the arguments were
4116 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00004117 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00004118 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004119 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00004120 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
4121 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00004122
Chris Lattner2da14fb2007-12-20 00:26:33 +00004123 return false;
4124}
4125
Benjamin Kramer634fc102010-02-15 22:42:31 +00004126/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
4127/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00004128/// to check everything. We expect the last argument to be a floating point
4129/// value.
4130bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
4131 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00004132 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00004133 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00004134 if (TheCall->getNumArgs() > NumArgs)
4135 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004136 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004137 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00004138 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004139 (*(TheCall->arg_end()-1))->getLocEnd());
4140
Benjamin Kramer64aae502010-02-16 10:07:31 +00004141 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00004142
Eli Friedman7e4faac2009-08-31 20:06:00 +00004143 if (OrigArg->isTypeDependent())
4144 return false;
4145
Chris Lattner68784ef2010-05-06 05:50:07 +00004146 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00004147 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00004148 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004149 diag::err_typecheck_call_invalid_unary_fp)
4150 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004151
Neil Hickey88c0fac2016-12-13 16:22:50 +00004152 // If this is an implicit conversion from float -> float or double, remove it.
Chris Lattner68784ef2010-05-06 05:50:07 +00004153 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
Neil Hickey7b5ddab2016-12-14 13:18:48 +00004154 // Only remove standard FloatCasts, leaving other casts inplace
4155 if (Cast->getCastKind() == CK_FloatingCast) {
4156 Expr *CastArg = Cast->getSubExpr();
4157 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
4158 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
4159 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
4160 "promotion from float to either float or double is the only expected cast here");
4161 Cast->setSubExpr(nullptr);
4162 TheCall->setArg(NumArgs-1, CastArg);
4163 }
Chris Lattner68784ef2010-05-06 05:50:07 +00004164 }
4165 }
4166
Eli Friedman7e4faac2009-08-31 20:06:00 +00004167 return false;
4168}
4169
Tony Jiangbbc48e92017-05-24 15:13:32 +00004170// Customized Sema Checking for VSX builtins that have the following signature:
4171// vector [...] builtinName(vector [...], vector [...], const int);
4172// Which takes the same type of vectors (any legal vector type) for the first
4173// two arguments and takes compile time constant for the third argument.
4174// Example builtins are :
4175// vector double vec_xxpermdi(vector double, vector double, int);
4176// vector short vec_xxsldwi(vector short, vector short, int);
4177bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
4178 unsigned ExpectedNumArgs = 3;
4179 if (TheCall->getNumArgs() < ExpectedNumArgs)
4180 return Diag(TheCall->getLocEnd(),
4181 diag::err_typecheck_call_too_few_args_at_least)
4182 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4183 << TheCall->getSourceRange();
4184
4185 if (TheCall->getNumArgs() > ExpectedNumArgs)
4186 return Diag(TheCall->getLocEnd(),
4187 diag::err_typecheck_call_too_many_args_at_most)
4188 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4189 << TheCall->getSourceRange();
4190
4191 // Check the third argument is a compile time constant
4192 llvm::APSInt Value;
4193 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
4194 return Diag(TheCall->getLocStart(),
4195 diag::err_vsx_builtin_nonconstant_argument)
4196 << 3 /* argument index */ << TheCall->getDirectCallee()
4197 << SourceRange(TheCall->getArg(2)->getLocStart(),
4198 TheCall->getArg(2)->getLocEnd());
4199
4200 QualType Arg1Ty = TheCall->getArg(0)->getType();
4201 QualType Arg2Ty = TheCall->getArg(1)->getType();
4202
4203 // Check the type of argument 1 and argument 2 are vectors.
4204 SourceLocation BuiltinLoc = TheCall->getLocStart();
4205 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
4206 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
4207 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
4208 << TheCall->getDirectCallee()
4209 << SourceRange(TheCall->getArg(0)->getLocStart(),
4210 TheCall->getArg(1)->getLocEnd());
4211 }
4212
4213 // Check the first two arguments are the same type.
4214 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
4215 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
4216 << TheCall->getDirectCallee()
4217 << SourceRange(TheCall->getArg(0)->getLocStart(),
4218 TheCall->getArg(1)->getLocEnd());
4219 }
4220
4221 // When default clang type checking is turned off and the customized type
4222 // checking is used, the returning type of the function must be explicitly
4223 // set. Otherwise it is _Bool by default.
4224 TheCall->setType(Arg1Ty);
4225
4226 return false;
4227}
4228
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004229/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
4230// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00004231ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00004232 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004233 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00004234 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00004235 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4236 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004237
Nate Begemana0110022010-06-08 00:16:34 +00004238 // Determine which of the following types of shufflevector we're checking:
4239 // 1) unary, vector mask: (lhs, mask)
Craig Topperb3174a82016-05-18 04:11:25 +00004240 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
Nate Begemana0110022010-06-08 00:16:34 +00004241 QualType resType = TheCall->getArg(0)->getType();
4242 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00004243
Douglas Gregorc25f7662009-05-19 22:10:17 +00004244 if (!TheCall->getArg(0)->isTypeDependent() &&
4245 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00004246 QualType LHSType = TheCall->getArg(0)->getType();
4247 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00004248
Craig Topperbaca3892013-07-29 06:47:04 +00004249 if (!LHSType->isVectorType() || !RHSType->isVectorType())
4250 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004251 diag::err_vec_builtin_non_vector)
4252 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004253 << SourceRange(TheCall->getArg(0)->getLocStart(),
4254 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00004255
Nate Begemana0110022010-06-08 00:16:34 +00004256 numElements = LHSType->getAs<VectorType>()->getNumElements();
4257 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00004258
Nate Begemana0110022010-06-08 00:16:34 +00004259 // Check to see if we have a call with 2 vector arguments, the unary shuffle
4260 // with mask. If so, verify that RHS is an integer vector type with the
4261 // same number of elts as lhs.
4262 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00004263 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00004264 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00004265 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004266 diag::err_vec_builtin_incompatible_vector)
4267 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004268 << SourceRange(TheCall->getArg(1)->getLocStart(),
4269 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00004270 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00004271 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004272 diag::err_vec_builtin_incompatible_vector)
4273 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004274 << SourceRange(TheCall->getArg(0)->getLocStart(),
4275 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00004276 } else if (numElements != numResElements) {
4277 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00004278 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00004279 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00004280 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004281 }
4282
4283 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00004284 if (TheCall->getArg(i)->isTypeDependent() ||
4285 TheCall->getArg(i)->isValueDependent())
4286 continue;
4287
Nate Begemana0110022010-06-08 00:16:34 +00004288 llvm::APSInt Result(32);
4289 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
4290 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004291 diag::err_shufflevector_nonconstant_argument)
4292 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004293
Craig Topper50ad5b72013-08-03 17:40:38 +00004294 // Allow -1 which will be translated to undef in the IR.
4295 if (Result.isSigned() && Result.isAllOnesValue())
4296 continue;
4297
Chris Lattner7ab824e2008-08-10 02:05:13 +00004298 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004299 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004300 diag::err_shufflevector_argument_too_large)
4301 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004302 }
4303
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004304 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004305
Chris Lattner7ab824e2008-08-10 02:05:13 +00004306 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004307 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00004308 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004309 }
4310
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004311 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
4312 TheCall->getCallee()->getLocStart(),
4313 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004314}
Chris Lattner43be2e62007-12-19 23:59:04 +00004315
Hal Finkelc4d7c822013-09-18 03:29:45 +00004316/// SemaConvertVectorExpr - Handle __builtin_convertvector
4317ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
4318 SourceLocation BuiltinLoc,
4319 SourceLocation RParenLoc) {
4320 ExprValueKind VK = VK_RValue;
4321 ExprObjectKind OK = OK_Ordinary;
4322 QualType DstTy = TInfo->getType();
4323 QualType SrcTy = E->getType();
4324
4325 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
4326 return ExprError(Diag(BuiltinLoc,
4327 diag::err_convertvector_non_vector)
4328 << E->getSourceRange());
4329 if (!DstTy->isVectorType() && !DstTy->isDependentType())
4330 return ExprError(Diag(BuiltinLoc,
4331 diag::err_convertvector_non_vector_type));
4332
4333 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
4334 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
4335 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
4336 if (SrcElts != DstElts)
4337 return ExprError(Diag(BuiltinLoc,
4338 diag::err_convertvector_incompatible_vector)
4339 << E->getSourceRange());
4340 }
4341
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004342 return new (Context)
4343 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00004344}
4345
Daniel Dunbarb7257262008-07-21 22:59:13 +00004346/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
4347// This is declared to take (const void*, ...) and can take two
4348// optional constant int args.
4349bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00004350 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004351
Chris Lattner3b054132008-11-19 05:08:23 +00004352 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004353 return Diag(TheCall->getLocEnd(),
4354 diag::err_typecheck_call_too_many_args_at_most)
4355 << 0 /*function call*/ << 3 << NumArgs
4356 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004357
4358 // Argument 0 is checked for us and the remaining arguments must be
4359 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00004360 for (unsigned i = 1; i != NumArgs; ++i)
4361 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004362 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004363
Warren Hunt20e4a5d2014-02-21 23:08:53 +00004364 return false;
4365}
4366
Hal Finkelf0417332014-07-17 14:25:55 +00004367/// SemaBuiltinAssume - Handle __assume (MS Extension).
4368// __assume does not evaluate its arguments, and should warn if its argument
4369// has side effects.
4370bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
4371 Expr *Arg = TheCall->getArg(0);
4372 if (Arg->isInstantiationDependent()) return false;
4373
4374 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00004375 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00004376 << Arg->getSourceRange()
4377 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
4378
4379 return false;
4380}
4381
David Majnemer86b1bfa2016-10-31 18:07:57 +00004382/// Handle __builtin_alloca_with_align. This is declared
David Majnemer51169932016-10-31 05:37:48 +00004383/// as (size_t, size_t) where the second size_t must be a power of 2 greater
4384/// than 8.
4385bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
4386 // The alignment must be a constant integer.
4387 Expr *Arg = TheCall->getArg(1);
4388
4389 // We can't check the value of a dependent argument.
4390 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
David Majnemer86b1bfa2016-10-31 18:07:57 +00004391 if (const auto *UE =
4392 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
4393 if (UE->getKind() == UETT_AlignOf)
4394 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
4395 << Arg->getSourceRange();
4396
David Majnemer51169932016-10-31 05:37:48 +00004397 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
4398
4399 if (!Result.isPowerOf2())
4400 return Diag(TheCall->getLocStart(),
4401 diag::err_alignment_not_power_of_two)
4402 << Arg->getSourceRange();
4403
4404 if (Result < Context.getCharWidth())
4405 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
4406 << (unsigned)Context.getCharWidth()
4407 << Arg->getSourceRange();
4408
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004409 if (Result > std::numeric_limits<int32_t>::max())
David Majnemer51169932016-10-31 05:37:48 +00004410 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004411 << std::numeric_limits<int32_t>::max()
David Majnemer51169932016-10-31 05:37:48 +00004412 << Arg->getSourceRange();
4413 }
4414
4415 return false;
4416}
4417
4418/// Handle __builtin_assume_aligned. This is declared
Hal Finkelbcc06082014-09-07 22:58:14 +00004419/// as (const void*, size_t, ...) and can take one optional constant int arg.
4420bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
4421 unsigned NumArgs = TheCall->getNumArgs();
4422
4423 if (NumArgs > 3)
4424 return Diag(TheCall->getLocEnd(),
4425 diag::err_typecheck_call_too_many_args_at_most)
4426 << 0 /*function call*/ << 3 << NumArgs
4427 << TheCall->getSourceRange();
4428
4429 // The alignment must be a constant integer.
4430 Expr *Arg = TheCall->getArg(1);
4431
4432 // We can't check the value of a dependent argument.
4433 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4434 llvm::APSInt Result;
4435 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4436 return true;
4437
4438 if (!Result.isPowerOf2())
4439 return Diag(TheCall->getLocStart(),
4440 diag::err_alignment_not_power_of_two)
4441 << Arg->getSourceRange();
4442 }
4443
4444 if (NumArgs > 2) {
4445 ExprResult Arg(TheCall->getArg(2));
4446 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4447 Context.getSizeType(), false);
4448 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4449 if (Arg.isInvalid()) return true;
4450 TheCall->setArg(2, Arg.get());
4451 }
Hal Finkelf0417332014-07-17 14:25:55 +00004452
4453 return false;
4454}
4455
Mehdi Amini06d367c2016-10-24 20:39:34 +00004456bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4457 unsigned BuiltinID =
4458 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4459 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4460
4461 unsigned NumArgs = TheCall->getNumArgs();
4462 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4463 if (NumArgs < NumRequiredArgs) {
4464 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4465 << 0 /* function call */ << NumRequiredArgs << NumArgs
4466 << TheCall->getSourceRange();
4467 }
4468 if (NumArgs >= NumRequiredArgs + 0x100) {
4469 return Diag(TheCall->getLocEnd(),
4470 diag::err_typecheck_call_too_many_args_at_most)
4471 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4472 << TheCall->getSourceRange();
4473 }
4474 unsigned i = 0;
4475
4476 // For formatting call, check buffer arg.
4477 if (!IsSizeCall) {
4478 ExprResult Arg(TheCall->getArg(i));
4479 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4480 Context, Context.VoidPtrTy, false);
4481 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4482 if (Arg.isInvalid())
4483 return true;
4484 TheCall->setArg(i, Arg.get());
4485 i++;
4486 }
4487
4488 // Check string literal arg.
4489 unsigned FormatIdx = i;
4490 {
4491 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4492 if (Arg.isInvalid())
4493 return true;
4494 TheCall->setArg(i, Arg.get());
4495 i++;
4496 }
4497
4498 // Make sure variadic args are scalar.
4499 unsigned FirstDataArg = i;
4500 while (i < NumArgs) {
4501 ExprResult Arg = DefaultVariadicArgumentPromotion(
4502 TheCall->getArg(i), VariadicFunction, nullptr);
4503 if (Arg.isInvalid())
4504 return true;
4505 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4506 if (ArgSize.getQuantity() >= 0x100) {
4507 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4508 << i << (int)ArgSize.getQuantity() << 0xff
4509 << TheCall->getSourceRange();
4510 }
4511 TheCall->setArg(i, Arg.get());
4512 i++;
4513 }
4514
4515 // Check formatting specifiers. NOTE: We're only doing this for the non-size
4516 // call to avoid duplicate diagnostics.
4517 if (!IsSizeCall) {
4518 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4519 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4520 bool Success = CheckFormatArguments(
4521 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4522 VariadicFunction, TheCall->getLocStart(), SourceRange(),
4523 CheckedVarArgs);
4524 if (!Success)
4525 return true;
4526 }
4527
4528 if (IsSizeCall) {
4529 TheCall->setType(Context.getSizeType());
4530 } else {
4531 TheCall->setType(Context.VoidPtrTy);
4532 }
4533 return false;
4534}
4535
Eric Christopher8d0c6212010-04-17 02:26:23 +00004536/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4537/// TheCall is a constant expression.
4538bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4539 llvm::APSInt &Result) {
4540 Expr *Arg = TheCall->getArg(ArgNum);
4541 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4542 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4543
4544 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4545
4546 if (!Arg->isIntegerConstantExpr(Result, Context))
4547 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00004548 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00004549
Chris Lattnerd545ad12009-09-23 06:06:36 +00004550 return false;
4551}
4552
Richard Sandiford28940af2014-04-16 08:47:51 +00004553/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4554/// TheCall is a constant expression in the range [Low, High].
4555bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4556 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00004557 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004558
4559 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00004560 Expr *Arg = TheCall->getArg(ArgNum);
4561 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004562 return false;
4563
Eric Christopher8d0c6212010-04-17 02:26:23 +00004564 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00004565 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004566 return true;
4567
Richard Sandiford28940af2014-04-16 08:47:51 +00004568 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00004569 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00004570 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00004571
4572 return false;
4573}
4574
Simon Dardis1f90f2d2016-10-19 17:50:52 +00004575/// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4576/// TheCall is a constant expression is a multiple of Num..
4577bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4578 unsigned Num) {
4579 llvm::APSInt Result;
4580
4581 // We can't check the value of a dependent argument.
4582 Expr *Arg = TheCall->getArg(ArgNum);
4583 if (Arg->isTypeDependent() || Arg->isValueDependent())
4584 return false;
4585
4586 // Check constant-ness first.
4587 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4588 return true;
4589
4590 if (Result.getSExtValue() % Num != 0)
4591 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4592 << Num << Arg->getSourceRange();
4593
4594 return false;
4595}
4596
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004597/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4598/// TheCall is an ARM/AArch64 special register string literal.
4599bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4600 int ArgNum, unsigned ExpectedFieldNum,
4601 bool AllowName) {
4602 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4603 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4604 BuiltinID == ARM::BI__builtin_arm_rsr ||
4605 BuiltinID == ARM::BI__builtin_arm_rsrp ||
4606 BuiltinID == ARM::BI__builtin_arm_wsr ||
4607 BuiltinID == ARM::BI__builtin_arm_wsrp;
4608 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4609 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4610 BuiltinID == AArch64::BI__builtin_arm_rsr ||
4611 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4612 BuiltinID == AArch64::BI__builtin_arm_wsr ||
4613 BuiltinID == AArch64::BI__builtin_arm_wsrp;
4614 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4615
4616 // We can't check the value of a dependent argument.
4617 Expr *Arg = TheCall->getArg(ArgNum);
4618 if (Arg->isTypeDependent() || Arg->isValueDependent())
4619 return false;
4620
4621 // Check if the argument is a string literal.
4622 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4623 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4624 << Arg->getSourceRange();
4625
4626 // Check the type of special register given.
4627 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4628 SmallVector<StringRef, 6> Fields;
4629 Reg.split(Fields, ":");
4630
4631 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4632 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4633 << Arg->getSourceRange();
4634
4635 // If the string is the name of a register then we cannot check that it is
4636 // valid here but if the string is of one the forms described in ACLE then we
4637 // can check that the supplied fields are integers and within the valid
4638 // ranges.
4639 if (Fields.size() > 1) {
4640 bool FiveFields = Fields.size() == 5;
4641
4642 bool ValidString = true;
4643 if (IsARMBuiltin) {
4644 ValidString &= Fields[0].startswith_lower("cp") ||
4645 Fields[0].startswith_lower("p");
4646 if (ValidString)
4647 Fields[0] =
4648 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4649
4650 ValidString &= Fields[2].startswith_lower("c");
4651 if (ValidString)
4652 Fields[2] = Fields[2].drop_front(1);
4653
4654 if (FiveFields) {
4655 ValidString &= Fields[3].startswith_lower("c");
4656 if (ValidString)
4657 Fields[3] = Fields[3].drop_front(1);
4658 }
4659 }
4660
4661 SmallVector<int, 5> Ranges;
4662 if (FiveFields)
Oleg Ranevskyy85d93a82016-11-18 21:00:08 +00004663 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004664 else
4665 Ranges.append({15, 7, 15});
4666
4667 for (unsigned i=0; i<Fields.size(); ++i) {
4668 int IntField;
4669 ValidString &= !Fields[i].getAsInteger(10, IntField);
4670 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4671 }
4672
4673 if (!ValidString)
4674 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4675 << Arg->getSourceRange();
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004676 } else if (IsAArch64Builtin && Fields.size() == 1) {
4677 // If the register name is one of those that appear in the condition below
4678 // and the special register builtin being used is one of the write builtins,
4679 // then we require that the argument provided for writing to the register
4680 // is an integer constant expression. This is because it will be lowered to
4681 // an MSR (immediate) instruction, so we need to know the immediate at
4682 // compile time.
4683 if (TheCall->getNumArgs() != 2)
4684 return false;
4685
4686 std::string RegLower = Reg.lower();
4687 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4688 RegLower != "pan" && RegLower != "uao")
4689 return false;
4690
4691 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4692 }
4693
4694 return false;
4695}
4696
Eli Friedmanc97d0142009-05-03 06:04:26 +00004697/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004698/// This checks that the target supports __builtin_longjmp and
4699/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004700bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004701 if (!Context.getTargetInfo().hasSjLjLowering())
4702 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4703 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4704
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004705 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00004706 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00004707
Eric Christopher8d0c6212010-04-17 02:26:23 +00004708 // TODO: This is less than ideal. Overload this to take a value.
4709 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4710 return true;
4711
4712 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004713 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4714 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4715
4716 return false;
4717}
4718
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004719/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4720/// This checks that the target supports __builtin_setjmp.
4721bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4722 if (!Context.getTargetInfo().hasSjLjLowering())
4723 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4724 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4725 return false;
4726}
4727
Richard Smithd7293d72013-08-05 18:49:43 +00004728namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004729
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004730class UncoveredArgHandler {
4731 enum { Unknown = -1, AllCovered = -2 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004732
4733 signed FirstUncoveredArg = Unknown;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004734 SmallVector<const Expr *, 4> DiagnosticExprs;
4735
4736public:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004737 UncoveredArgHandler() = default;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004738
4739 bool hasUncoveredArg() const {
4740 return (FirstUncoveredArg >= 0);
4741 }
4742
4743 unsigned getUncoveredArg() const {
4744 assert(hasUncoveredArg() && "no uncovered argument");
4745 return FirstUncoveredArg;
4746 }
4747
4748 void setAllCovered() {
4749 // A string has been found with all arguments covered, so clear out
4750 // the diagnostics.
4751 DiagnosticExprs.clear();
4752 FirstUncoveredArg = AllCovered;
4753 }
4754
4755 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4756 assert(NewFirstUncoveredArg >= 0 && "Outside range");
4757
4758 // Don't update if a previous string covers all arguments.
4759 if (FirstUncoveredArg == AllCovered)
4760 return;
4761
4762 // UncoveredArgHandler tracks the highest uncovered argument index
4763 // and with it all the strings that match this index.
4764 if (NewFirstUncoveredArg == FirstUncoveredArg)
4765 DiagnosticExprs.push_back(StrExpr);
4766 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4767 DiagnosticExprs.clear();
4768 DiagnosticExprs.push_back(StrExpr);
4769 FirstUncoveredArg = NewFirstUncoveredArg;
4770 }
4771 }
4772
4773 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4774};
4775
Richard Smithd7293d72013-08-05 18:49:43 +00004776enum StringLiteralCheckType {
4777 SLCT_NotALiteral,
4778 SLCT_UncheckedLiteral,
4779 SLCT_CheckedLiteral
4780};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004781
4782} // namespace
Richard Smithd7293d72013-08-05 18:49:43 +00004783
Stephen Hines648c3692016-09-16 01:07:04 +00004784static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4785 BinaryOperatorKind BinOpKind,
4786 bool AddendIsRight) {
4787 unsigned BitWidth = Offset.getBitWidth();
4788 unsigned AddendBitWidth = Addend.getBitWidth();
4789 // There might be negative interim results.
4790 if (Addend.isUnsigned()) {
4791 Addend = Addend.zext(++AddendBitWidth);
4792 Addend.setIsSigned(true);
4793 }
4794 // Adjust the bit width of the APSInts.
4795 if (AddendBitWidth > BitWidth) {
4796 Offset = Offset.sext(AddendBitWidth);
4797 BitWidth = AddendBitWidth;
4798 } else if (BitWidth > AddendBitWidth) {
4799 Addend = Addend.sext(BitWidth);
4800 }
4801
4802 bool Ov = false;
4803 llvm::APSInt ResOffset = Offset;
4804 if (BinOpKind == BO_Add)
4805 ResOffset = Offset.sadd_ov(Addend, Ov);
4806 else {
4807 assert(AddendIsRight && BinOpKind == BO_Sub &&
4808 "operator must be add or sub with addend on the right");
4809 ResOffset = Offset.ssub_ov(Addend, Ov);
4810 }
4811
4812 // We add an offset to a pointer here so we should support an offset as big as
4813 // possible.
4814 if (Ov) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004815 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
4816 "index (intermediate) result too big");
Stephen Hinesfec73ad2016-09-16 07:21:24 +00004817 Offset = Offset.sext(2 * BitWidth);
Stephen Hines648c3692016-09-16 01:07:04 +00004818 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4819 return;
4820 }
4821
4822 Offset = ResOffset;
4823}
4824
4825namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004826
Stephen Hines648c3692016-09-16 01:07:04 +00004827// This is a wrapper class around StringLiteral to support offsetted string
4828// literals as format strings. It takes the offset into account when returning
4829// the string and its length or the source locations to display notes correctly.
4830class FormatStringLiteral {
4831 const StringLiteral *FExpr;
4832 int64_t Offset;
4833
4834 public:
4835 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4836 : FExpr(fexpr), Offset(Offset) {}
4837
4838 StringRef getString() const {
4839 return FExpr->getString().drop_front(Offset);
4840 }
4841
4842 unsigned getByteLength() const {
4843 return FExpr->getByteLength() - getCharByteWidth() * Offset;
4844 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004845
Stephen Hines648c3692016-09-16 01:07:04 +00004846 unsigned getLength() const { return FExpr->getLength() - Offset; }
4847 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4848
4849 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4850
4851 QualType getType() const { return FExpr->getType(); }
4852
4853 bool isAscii() const { return FExpr->isAscii(); }
4854 bool isWide() const { return FExpr->isWide(); }
4855 bool isUTF8() const { return FExpr->isUTF8(); }
4856 bool isUTF16() const { return FExpr->isUTF16(); }
4857 bool isUTF32() const { return FExpr->isUTF32(); }
4858 bool isPascal() const { return FExpr->isPascal(); }
4859
4860 SourceLocation getLocationOfByte(
4861 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4862 const TargetInfo &Target, unsigned *StartToken = nullptr,
4863 unsigned *StartTokenByteOffset = nullptr) const {
4864 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4865 StartToken, StartTokenByteOffset);
4866 }
4867
4868 SourceLocation getLocStart() const LLVM_READONLY {
4869 return FExpr->getLocStart().getLocWithOffset(Offset);
4870 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004871
Stephen Hines648c3692016-09-16 01:07:04 +00004872 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4873};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004874
4875} // namespace
Stephen Hines648c3692016-09-16 01:07:04 +00004876
4877static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004878 const Expr *OrigFormatExpr,
4879 ArrayRef<const Expr *> Args,
4880 bool HasVAListArg, unsigned format_idx,
4881 unsigned firstDataArg,
4882 Sema::FormatStringType Type,
4883 bool inFunctionCall,
4884 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004885 llvm::SmallBitVector &CheckedVarArgs,
4886 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004887
Richard Smith55ce3522012-06-25 20:30:08 +00004888// Determine if an expression is a string literal or constant string.
4889// If this function returns false on the arguments to a function expecting a
4890// format string, we will usually need to emit a warning.
4891// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00004892static StringLiteralCheckType
4893checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4894 bool HasVAListArg, unsigned format_idx,
4895 unsigned firstDataArg, Sema::FormatStringType Type,
4896 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004897 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004898 UncoveredArgHandler &UncoveredArg,
4899 llvm::APSInt Offset) {
Ted Kremenek808829352010-09-09 03:51:39 +00004900 tryAgain:
Stephen Hines648c3692016-09-16 01:07:04 +00004901 assert(Offset.isSigned() && "invalid offset");
4902
Douglas Gregorc25f7662009-05-19 22:10:17 +00004903 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00004904 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004905
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004906 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00004907
Richard Smithd7293d72013-08-05 18:49:43 +00004908 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00004909 // Technically -Wformat-nonliteral does not warn about this case.
4910 // The behavior of printf and friends in this case is implementation
4911 // dependent. Ideally if the format string cannot be null then
4912 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00004913 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00004914
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004915 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00004916 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004917 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00004918 // The expression is a literal if both sub-expressions were, and it was
4919 // completely checked only if both sub-expressions were checked.
4920 const AbstractConditionalOperator *C =
4921 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004922
4923 // Determine whether it is necessary to check both sub-expressions, for
4924 // example, because the condition expression is a constant that can be
4925 // evaluated at compile time.
4926 bool CheckLeft = true, CheckRight = true;
4927
4928 bool Cond;
4929 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4930 if (Cond)
4931 CheckRight = false;
4932 else
4933 CheckLeft = false;
4934 }
4935
Stephen Hines648c3692016-09-16 01:07:04 +00004936 // We need to maintain the offsets for the right and the left hand side
4937 // separately to check if every possible indexed expression is a valid
4938 // string literal. They might have different offsets for different string
4939 // literals in the end.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004940 StringLiteralCheckType Left;
4941 if (!CheckLeft)
4942 Left = SLCT_UncheckedLiteral;
4943 else {
4944 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4945 HasVAListArg, format_idx, firstDataArg,
4946 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004947 CheckedVarArgs, UncoveredArg, Offset);
4948 if (Left == SLCT_NotALiteral || !CheckRight) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004949 return Left;
Stephen Hines648c3692016-09-16 01:07:04 +00004950 }
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004951 }
4952
Richard Smith55ce3522012-06-25 20:30:08 +00004953 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00004954 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004955 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004956 Type, CallType, InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004957 UncoveredArg, Offset);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004958
4959 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004960 }
4961
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004962 case Stmt::ImplicitCastExprClass:
Ted Kremenek808829352010-09-09 03:51:39 +00004963 E = cast<ImplicitCastExpr>(E)->getSubExpr();
4964 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004965
John McCallc07a0c72011-02-17 10:25:35 +00004966 case Stmt::OpaqueValueExprClass:
4967 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4968 E = src;
4969 goto tryAgain;
4970 }
Richard Smith55ce3522012-06-25 20:30:08 +00004971 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00004972
Ted Kremeneka8890832011-02-24 23:03:04 +00004973 case Stmt::PredefinedExprClass:
4974 // While __func__, etc., are technically not string literals, they
4975 // cannot contain format specifiers and thus are not a security
4976 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00004977 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00004978
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004979 case Stmt::DeclRefExprClass: {
4980 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004981
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004982 // As an exception, do not flag errors for variables binding to
4983 // const string literals.
4984 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4985 bool isConstant = false;
4986 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004987
Richard Smithd7293d72013-08-05 18:49:43 +00004988 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4989 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00004990 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00004991 isConstant = T.isConstant(S.Context) &&
4992 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00004993 } else if (T->isObjCObjectPointerType()) {
4994 // In ObjC, there is usually no "const ObjectPointer" type,
4995 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00004996 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004997 }
Mike Stump11289f42009-09-09 15:08:12 +00004998
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004999 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00005000 if (const Expr *Init = VD->getAnyInitializer()) {
5001 // Look through initializers like const char c[] = { "foo" }
5002 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
5003 if (InitList->isStringLiteralInit())
5004 Init = InitList->getInit(0)->IgnoreParenImpCasts();
5005 }
Richard Smithd7293d72013-08-05 18:49:43 +00005006 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005007 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005008 firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00005009 /*InFunctionCall*/ false, CheckedVarArgs,
5010 UncoveredArg, Offset);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00005011 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005012 }
Mike Stump11289f42009-09-09 15:08:12 +00005013
Anders Carlssonb012ca92009-06-28 19:55:58 +00005014 // For vprintf* functions (i.e., HasVAListArg==true), we add a
5015 // special check to see if the format string is a function parameter
5016 // of the function calling the printf function. If the function
5017 // has an attribute indicating it is a printf-like function, then we
5018 // should suppress warnings concerning non-literals being used in a call
5019 // to a vprintf function. For example:
5020 //
5021 // void
5022 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
5023 // va_list ap;
5024 // va_start(ap, fmt);
5025 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
5026 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00005027 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00005028 if (HasVAListArg) {
5029 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
5030 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
5031 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00005032 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00005033 // adjust for implicit parameter
5034 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5035 if (MD->isInstance())
5036 ++PVIndex;
5037 // We also check if the formats are compatible.
5038 // We can't pass a 'scanf' string to a 'printf' function.
5039 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00005040 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00005041 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00005042 }
5043 }
5044 }
5045 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005046 }
Mike Stump11289f42009-09-09 15:08:12 +00005047
Richard Smith55ce3522012-06-25 20:30:08 +00005048 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005049 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005050
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00005051 case Stmt::CallExprClass:
5052 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005053 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00005054 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
5055 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
Joel E. Denny81508102018-03-13 14:51:22 +00005056 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
Richard Smithd7293d72013-08-05 18:49:43 +00005057 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005058 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00005059 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00005060 CheckedVarArgs, UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005061 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5062 unsigned BuiltinID = FD->getBuiltinID();
5063 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
5064 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
5065 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00005066 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005067 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005068 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005069 InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00005070 UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005071 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005072 }
5073 }
Mike Stump11289f42009-09-09 15:08:12 +00005074
Richard Smith55ce3522012-06-25 20:30:08 +00005075 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005076 }
Alex Lorenzd9007142016-10-24 09:42:34 +00005077 case Stmt::ObjCMessageExprClass: {
5078 const auto *ME = cast<ObjCMessageExpr>(E);
5079 if (const auto *ND = ME->getMethodDecl()) {
5080 if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
Joel E. Denny81508102018-03-13 14:51:22 +00005081 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
Alex Lorenzd9007142016-10-24 09:42:34 +00005082 return checkFormatStringExpr(
5083 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
5084 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
5085 }
5086 }
5087
5088 return SLCT_NotALiteral;
5089 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005090 case Stmt::ObjCStringLiteralClass:
5091 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00005092 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005093
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005094 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005095 StrE = ObjCFExpr->getString();
5096 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005097 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005098
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005099 if (StrE) {
Stephen Hines648c3692016-09-16 01:07:04 +00005100 if (Offset.isNegative() || Offset > StrE->getLength()) {
5101 // TODO: It would be better to have an explicit warning for out of
5102 // bounds literals.
5103 return SLCT_NotALiteral;
5104 }
5105 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
5106 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005107 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005108 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00005109 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005110 }
Mike Stump11289f42009-09-09 15:08:12 +00005111
Richard Smith55ce3522012-06-25 20:30:08 +00005112 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005113 }
Stephen Hines648c3692016-09-16 01:07:04 +00005114 case Stmt::BinaryOperatorClass: {
5115 llvm::APSInt LResult;
5116 llvm::APSInt RResult;
5117
5118 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
5119
5120 // A string literal + an int offset is still a string literal.
5121 if (BinOp->isAdditiveOp()) {
5122 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
5123 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
5124
5125 if (LIsInt != RIsInt) {
5126 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
5127
5128 if (LIsInt) {
5129 if (BinOpKind == BO_Add) {
5130 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
5131 E = BinOp->getRHS();
5132 goto tryAgain;
5133 }
5134 } else {
5135 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
5136 E = BinOp->getLHS();
5137 goto tryAgain;
5138 }
5139 }
Stephen Hines648c3692016-09-16 01:07:04 +00005140 }
George Burgess IVd273aab2016-09-22 00:00:26 +00005141
5142 return SLCT_NotALiteral;
Stephen Hines648c3692016-09-16 01:07:04 +00005143 }
5144 case Stmt::UnaryOperatorClass: {
5145 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
5146 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005147 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
Stephen Hines648c3692016-09-16 01:07:04 +00005148 llvm::APSInt IndexResult;
5149 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
5150 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
5151 E = ASE->getBase();
5152 goto tryAgain;
5153 }
5154 }
5155
5156 return SLCT_NotALiteral;
5157 }
Mike Stump11289f42009-09-09 15:08:12 +00005158
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005159 default:
Richard Smith55ce3522012-06-25 20:30:08 +00005160 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005161 }
5162}
5163
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005164Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00005165 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Mehdi Amini06d367c2016-10-24 20:39:34 +00005166 .Case("scanf", FST_Scanf)
5167 .Cases("printf", "printf0", FST_Printf)
5168 .Cases("NSString", "CFString", FST_NSString)
5169 .Case("strftime", FST_Strftime)
5170 .Case("strfmon", FST_Strfmon)
5171 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
5172 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
5173 .Case("os_trace", FST_OSLog)
5174 .Case("os_log", FST_OSLog)
5175 .Default(FST_Unknown);
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005176}
5177
Jordan Rose3e0ec582012-07-19 18:10:23 +00005178/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00005179/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00005180/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005181bool Sema::CheckFormatArguments(const FormatAttr *Format,
5182 ArrayRef<const Expr *> Args,
5183 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005184 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00005185 SourceLocation Loc, SourceRange Range,
5186 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00005187 FormatStringInfo FSI;
5188 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005189 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00005190 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00005191 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00005192 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005193}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00005194
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005195bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005196 bool HasVAListArg, unsigned format_idx,
5197 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005198 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00005199 SourceLocation Loc, SourceRange Range,
5200 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00005201 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005202 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005203 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00005204 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005205 }
Mike Stump11289f42009-09-09 15:08:12 +00005206
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005207 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00005208
Chris Lattnerb87b1b32007-08-10 20:18:51 +00005209 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00005210 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005211 // Dynamically generated format strings are difficult to
5212 // automatically vet at compile time. Requiring that format strings
5213 // are string literals: (1) permits the checking of format strings by
5214 // the compiler and thereby (2) can practically remove the source of
5215 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00005216
Mike Stump11289f42009-09-09 15:08:12 +00005217 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00005218 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00005219 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00005220 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005221 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00005222 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00005223 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
5224 format_idx, firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00005225 /*IsFunctionCall*/ true, CheckedVarArgs,
5226 UncoveredArg,
5227 /*no string offset*/ llvm::APSInt(64, false) = 0);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005228
5229 // Generate a diagnostic where an uncovered argument is detected.
5230 if (UncoveredArg.hasUncoveredArg()) {
5231 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
5232 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
5233 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
5234 }
5235
Richard Smith55ce3522012-06-25 20:30:08 +00005236 if (CT != SLCT_NotALiteral)
5237 // Literal format string found, check done!
5238 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00005239
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00005240 // Strftime is particular as it always uses a single 'time' argument,
5241 // so it is safe to pass a non-literal string.
5242 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00005243 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00005244
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00005245 // Do not emit diag when the string param is a macro expansion and the
5246 // format is either NSString or CFString. This is a hack to prevent
5247 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
5248 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005249 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
5250 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00005251 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00005252
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005253 // If there are no arguments specified, warn with -Wformat-security, otherwise
5254 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005255 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00005256 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
5257 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005258 switch (Type) {
5259 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005260 break;
5261 case FST_Kprintf:
5262 case FST_FreeBSDKPrintf:
5263 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00005264 Diag(FormatLoc, diag::note_format_security_fixit)
5265 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005266 break;
5267 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00005268 Diag(FormatLoc, diag::note_format_security_fixit)
5269 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005270 break;
5271 }
5272 } else {
5273 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005274 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005275 }
Richard Smith55ce3522012-06-25 20:30:08 +00005276 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005277}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005278
Ted Kremenekab278de2010-01-28 23:39:18 +00005279namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005280
Ted Kremenek02087932010-07-16 02:11:22 +00005281class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
5282protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00005283 Sema &S;
Stephen Hines648c3692016-09-16 01:07:04 +00005284 const FormatStringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00005285 const Expr *OrigFormatExpr;
Mehdi Amini06d367c2016-10-24 20:39:34 +00005286 const Sema::FormatStringType FSType;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00005287 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00005288 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00005289 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00005290 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005291 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00005292 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00005293 llvm::SmallBitVector CoveredArgs;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005294 bool usesPositionalArgs = false;
5295 bool atFirstArg = true;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005296 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00005297 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00005298 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005299 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005300
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005301public:
Stephen Hines648c3692016-09-16 01:07:04 +00005302 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005303 const Expr *origFormatExpr,
5304 const Sema::FormatStringType type, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005305 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005306 ArrayRef<const Expr *> Args, unsigned formatIdx,
5307 bool inFunctionCall, Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005308 llvm::SmallBitVector &CheckedVarArgs,
5309 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005310 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
5311 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
5312 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
Mehdi Amini06d367c2016-10-24 20:39:34 +00005313 inFunctionCall(inFunctionCall), CallType(callType),
5314 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00005315 CoveredArgs.resize(numDataArgs);
5316 CoveredArgs.reset();
5317 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005318
Ted Kremenek019d2242010-01-29 01:50:07 +00005319 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005320
Ted Kremenek02087932010-07-16 02:11:22 +00005321 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005322 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005323
Jordan Rose92303592012-09-08 04:00:03 +00005324 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005325 const analyze_format_string::FormatSpecifier &FS,
5326 const analyze_format_string::ConversionSpecifier &CS,
5327 const char *startSpecifier, unsigned specifierLen,
5328 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00005329
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005330 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005331 const analyze_format_string::FormatSpecifier &FS,
5332 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005333
5334 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005335 const analyze_format_string::ConversionSpecifier &CS,
5336 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005337
Craig Toppere14c0f82014-03-12 04:55:44 +00005338 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005339
Craig Toppere14c0f82014-03-12 04:55:44 +00005340 void HandleInvalidPosition(const char *startSpecifier,
5341 unsigned specifierLen,
5342 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005343
Craig Toppere14c0f82014-03-12 04:55:44 +00005344 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005345
Craig Toppere14c0f82014-03-12 04:55:44 +00005346 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005347
Richard Trieu03cf7b72011-10-28 00:41:25 +00005348 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00005349 static void
5350 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
5351 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
5352 bool IsStringLocation, Range StringRange,
5353 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005354
Ted Kremenek02087932010-07-16 02:11:22 +00005355protected:
Ted Kremenekce815422010-07-19 21:25:57 +00005356 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
5357 const char *startSpec,
5358 unsigned specifierLen,
5359 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005360
5361 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
5362 const char *startSpec,
5363 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00005364
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005365 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00005366 CharSourceRange getSpecifierRange(const char *startSpecifier,
5367 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00005368 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005369
Ted Kremenek5739de72010-01-29 01:06:55 +00005370 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005371
5372 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
5373 const analyze_format_string::ConversionSpecifier &CS,
5374 const char *startSpecifier, unsigned specifierLen,
5375 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005376
5377 template <typename Range>
5378 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5379 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00005380 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00005381};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005382
5383} // namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00005384
Ted Kremenek02087932010-07-16 02:11:22 +00005385SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00005386 return OrigFormatExpr->getSourceRange();
5387}
5388
Ted Kremenek02087932010-07-16 02:11:22 +00005389CharSourceRange CheckFormatHandler::
5390getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00005391 SourceLocation Start = getLocationOfByte(startSpecifier);
5392 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
5393
5394 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00005395 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00005396
5397 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005398}
5399
Ted Kremenek02087932010-07-16 02:11:22 +00005400SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines648c3692016-09-16 01:07:04 +00005401 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
5402 S.getLangOpts(), S.Context.getTargetInfo());
Ted Kremenekab278de2010-01-28 23:39:18 +00005403}
5404
Ted Kremenek02087932010-07-16 02:11:22 +00005405void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
5406 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00005407 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
5408 getLocationOfByte(startSpecifier),
5409 /*IsStringLocation*/true,
5410 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00005411}
5412
Jordan Rose92303592012-09-08 04:00:03 +00005413void CheckFormatHandler::HandleInvalidLengthModifier(
5414 const analyze_format_string::FormatSpecifier &FS,
5415 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00005416 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00005417 using namespace analyze_format_string;
5418
5419 const LengthModifier &LM = FS.getLengthModifier();
5420 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5421
5422 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005423 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00005424 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005425 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005426 getLocationOfByte(LM.getStart()),
5427 /*IsStringLocation*/true,
5428 getSpecifierRange(startSpecifier, specifierLen));
5429
5430 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5431 << FixedLM->toString()
5432 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5433
5434 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005435 FixItHint Hint;
5436 if (DiagID == diag::warn_format_nonsensical_length)
5437 Hint = FixItHint::CreateRemoval(LMRange);
5438
5439 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005440 getLocationOfByte(LM.getStart()),
5441 /*IsStringLocation*/true,
5442 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00005443 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00005444 }
5445}
5446
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005447void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00005448 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005449 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005450 using namespace analyze_format_string;
5451
5452 const LengthModifier &LM = FS.getLengthModifier();
5453 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5454
5455 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005456 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00005457 if (FixedLM) {
5458 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5459 << LM.toString() << 0,
5460 getLocationOfByte(LM.getStart()),
5461 /*IsStringLocation*/true,
5462 getSpecifierRange(startSpecifier, specifierLen));
5463
5464 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5465 << FixedLM->toString()
5466 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5467
5468 } else {
5469 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5470 << LM.toString() << 0,
5471 getLocationOfByte(LM.getStart()),
5472 /*IsStringLocation*/true,
5473 getSpecifierRange(startSpecifier, specifierLen));
5474 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005475}
5476
5477void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5478 const analyze_format_string::ConversionSpecifier &CS,
5479 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00005480 using namespace analyze_format_string;
5481
5482 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00005483 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00005484 if (FixedCS) {
5485 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5486 << CS.toString() << /*conversion specifier*/1,
5487 getLocationOfByte(CS.getStart()),
5488 /*IsStringLocation*/true,
5489 getSpecifierRange(startSpecifier, specifierLen));
5490
5491 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5492 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5493 << FixedCS->toString()
5494 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5495 } else {
5496 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5497 << CS.toString() << /*conversion specifier*/1,
5498 getLocationOfByte(CS.getStart()),
5499 /*IsStringLocation*/true,
5500 getSpecifierRange(startSpecifier, specifierLen));
5501 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005502}
5503
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005504void CheckFormatHandler::HandlePosition(const char *startPos,
5505 unsigned posLen) {
5506 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5507 getLocationOfByte(startPos),
5508 /*IsStringLocation*/true,
5509 getSpecifierRange(startPos, posLen));
5510}
5511
Ted Kremenekd1668192010-02-27 01:41:03 +00005512void
Ted Kremenek02087932010-07-16 02:11:22 +00005513CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5514 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005515 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5516 << (unsigned) p,
5517 getLocationOfByte(startPos), /*IsStringLocation*/true,
5518 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005519}
5520
Ted Kremenek02087932010-07-16 02:11:22 +00005521void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00005522 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005523 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5524 getLocationOfByte(startPos),
5525 /*IsStringLocation*/true,
5526 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005527}
5528
Ted Kremenek02087932010-07-16 02:11:22 +00005529void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005530 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005531 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005532 EmitFormatDiagnostic(
5533 S.PDiag(diag::warn_printf_format_string_contains_null_char),
5534 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5535 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005536 }
Ted Kremenek02087932010-07-16 02:11:22 +00005537}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005538
Jordan Rose58bbe422012-07-19 18:10:08 +00005539// Note that this may return NULL if there was an error parsing or building
5540// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00005541const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005542 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00005543}
5544
5545void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005546 // Does the number of data arguments exceed the number of
5547 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00005548 if (!HasVAListArg) {
5549 // Find any arguments that weren't covered.
5550 CoveredArgs.flip();
5551 signed notCoveredArg = CoveredArgs.find_first();
5552 if (notCoveredArg >= 0) {
5553 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005554 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5555 } else {
5556 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00005557 }
5558 }
5559}
5560
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005561void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5562 const Expr *ArgExpr) {
5563 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5564 "Invalid state");
5565
5566 if (!ArgExpr)
5567 return;
5568
5569 SourceLocation Loc = ArgExpr->getLocStart();
5570
5571 if (S.getSourceManager().isInSystemMacro(Loc))
5572 return;
5573
5574 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5575 for (auto E : DiagnosticExprs)
5576 PDiag << E->getSourceRange();
5577
5578 CheckFormatHandler::EmitFormatDiagnostic(
5579 S, IsFunctionCall, DiagnosticExprs[0],
5580 PDiag, Loc, /*IsStringLocation*/false,
5581 DiagnosticExprs[0]->getSourceRange());
5582}
5583
Ted Kremenekce815422010-07-19 21:25:57 +00005584bool
5585CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5586 SourceLocation Loc,
5587 const char *startSpec,
5588 unsigned specifierLen,
5589 const char *csStart,
5590 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00005591 bool keepGoing = true;
5592 if (argIndex < NumDataArgs) {
5593 // Consider the argument coverered, even though the specifier doesn't
5594 // make sense.
5595 CoveredArgs.set(argIndex);
5596 }
5597 else {
5598 // If argIndex exceeds the number of data arguments we
5599 // don't issue a warning because that is just a cascade of warnings (and
5600 // they may have intended '%%' anyway). We don't want to continue processing
5601 // the format string after this point, however, as we will like just get
5602 // gibberish when trying to match arguments.
5603 keepGoing = false;
5604 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005605
5606 StringRef Specifier(csStart, csLen);
5607
5608 // If the specifier in non-printable, it could be the first byte of a UTF-8
5609 // sequence. In that case, print the UTF-8 code point. If not, print the byte
5610 // hex value.
5611 std::string CodePointStr;
5612 if (!llvm::sys::locale::isPrint(*csStart)) {
Justin Lebar90910552016-09-30 00:38:45 +00005613 llvm::UTF32 CodePoint;
5614 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5615 const llvm::UTF8 *E =
5616 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5617 llvm::ConversionResult Result =
5618 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005619
Justin Lebar90910552016-09-30 00:38:45 +00005620 if (Result != llvm::conversionOK) {
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005621 unsigned char FirstChar = *csStart;
Justin Lebar90910552016-09-30 00:38:45 +00005622 CodePoint = (llvm::UTF32)FirstChar;
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005623 }
5624
5625 llvm::raw_string_ostream OS(CodePointStr);
5626 if (CodePoint < 256)
5627 OS << "\\x" << llvm::format("%02x", CodePoint);
5628 else if (CodePoint <= 0xFFFF)
5629 OS << "\\u" << llvm::format("%04x", CodePoint);
5630 else
5631 OS << "\\U" << llvm::format("%08x", CodePoint);
5632 OS.flush();
5633 Specifier = CodePointStr;
5634 }
5635
5636 EmitFormatDiagnostic(
5637 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5638 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5639
Ted Kremenekce815422010-07-19 21:25:57 +00005640 return keepGoing;
5641}
5642
Richard Trieu03cf7b72011-10-28 00:41:25 +00005643void
5644CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5645 const char *startSpec,
5646 unsigned specifierLen) {
5647 EmitFormatDiagnostic(
5648 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5649 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5650}
5651
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005652bool
5653CheckFormatHandler::CheckNumArgs(
5654 const analyze_format_string::FormatSpecifier &FS,
5655 const analyze_format_string::ConversionSpecifier &CS,
5656 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5657
5658 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005659 PartialDiagnostic PDiag = FS.usesPositionalArg()
5660 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5661 << (argIndex+1) << NumDataArgs)
5662 : S.PDiag(diag::warn_printf_insufficient_data_args);
5663 EmitFormatDiagnostic(
5664 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5665 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005666
5667 // Since more arguments than conversion tokens are given, by extension
5668 // all arguments are covered, so mark this as so.
5669 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005670 return false;
5671 }
5672 return true;
5673}
5674
Richard Trieu03cf7b72011-10-28 00:41:25 +00005675template<typename Range>
5676void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5677 SourceLocation Loc,
5678 bool IsStringLocation,
5679 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00005680 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005681 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00005682 Loc, IsStringLocation, StringRange, FixIt);
5683}
5684
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005685/// \brief If the format string is not within the function call, emit a note
Richard Trieu03cf7b72011-10-28 00:41:25 +00005686/// so that the function call and string are in diagnostic messages.
5687///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005688/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00005689/// call and only one diagnostic message will be produced. Otherwise, an
5690/// extra note will be emitted pointing to location of the format string.
5691///
5692/// \param ArgumentExpr the expression that is passed as the format string
5693/// argument in the function call. Used for getting locations when two
5694/// diagnostics are emitted.
5695///
5696/// \param PDiag the callee should already have provided any strings for the
5697/// diagnostic message. This function only adds locations and fixits
5698/// to diagnostics.
5699///
5700/// \param Loc primary location for diagnostic. If two diagnostics are
5701/// required, one will be at Loc and a new SourceLocation will be created for
5702/// the other one.
5703///
5704/// \param IsStringLocation if true, Loc points to the format string should be
5705/// used for the note. Otherwise, Loc points to the argument list and will
5706/// be used with PDiag.
5707///
5708/// \param StringRange some or all of the string to highlight. This is
5709/// templated so it can accept either a CharSourceRange or a SourceRange.
5710///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005711/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00005712template <typename Range>
5713void CheckFormatHandler::EmitFormatDiagnostic(
5714 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5715 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5716 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00005717 if (InFunctionCall) {
5718 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5719 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005720 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00005721 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005722 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5723 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00005724
5725 const Sema::SemaDiagnosticBuilder &Note =
5726 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5727 diag::note_format_string_defined);
5728
5729 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005730 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005731 }
5732}
5733
Ted Kremenek02087932010-07-16 02:11:22 +00005734//===--- CHECK: Printf format string checking ------------------------------===//
5735
5736namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005737
Ted Kremenek02087932010-07-16 02:11:22 +00005738class CheckPrintfHandler : public CheckFormatHandler {
5739public:
Stephen Hines648c3692016-09-16 01:07:04 +00005740 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005741 const Expr *origFormatExpr,
5742 const Sema::FormatStringType type, unsigned firstDataArg,
5743 unsigned numDataArgs, bool isObjC, const char *beg,
5744 bool hasVAListArg, ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005745 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00005746 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005747 llvm::SmallBitVector &CheckedVarArgs,
5748 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005749 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5750 numDataArgs, beg, hasVAListArg, Args, formatIdx,
5751 inFunctionCall, CallType, CheckedVarArgs,
5752 UncoveredArg) {}
5753
5754 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5755
5756 /// Returns true if '%@' specifiers are allowed in the format string.
5757 bool allowsObjCArg() const {
5758 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5759 FSType == Sema::FST_OSTrace;
5760 }
Jordan Rose3e0ec582012-07-19 18:10:23 +00005761
Ted Kremenek02087932010-07-16 02:11:22 +00005762 bool HandleInvalidPrintfConversionSpecifier(
5763 const analyze_printf::PrintfSpecifier &FS,
5764 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005765 unsigned specifierLen) override;
5766
Ted Kremenek02087932010-07-16 02:11:22 +00005767 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5768 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005769 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005770 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5771 const char *StartSpecifier,
5772 unsigned SpecifierLen,
5773 const Expr *E);
5774
Ted Kremenek02087932010-07-16 02:11:22 +00005775 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5776 const char *startSpecifier, unsigned specifierLen);
5777 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5778 const analyze_printf::OptionalAmount &Amt,
5779 unsigned type,
5780 const char *startSpecifier, unsigned specifierLen);
5781 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5782 const analyze_printf::OptionalFlag &flag,
5783 const char *startSpecifier, unsigned specifierLen);
5784 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5785 const analyze_printf::OptionalFlag &ignoredFlag,
5786 const analyze_printf::OptionalFlag &flag,
5787 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005788 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00005789 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00005790
5791 void HandleEmptyObjCModifierFlag(const char *startFlag,
5792 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005793
Ted Kremenek2b417712015-07-02 05:39:16 +00005794 void HandleInvalidObjCModifierFlag(const char *startFlag,
5795 unsigned flagLen) override;
5796
5797 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5798 const char *flagsEnd,
5799 const char *conversionPosition)
5800 override;
5801};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005802
5803} // namespace
Ted Kremenek02087932010-07-16 02:11:22 +00005804
5805bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5806 const analyze_printf::PrintfSpecifier &FS,
5807 const char *startSpecifier,
5808 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005809 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00005810 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00005811
Ted Kremenekce815422010-07-19 21:25:57 +00005812 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5813 getLocationOfByte(CS.getStart()),
5814 startSpecifier, specifierLen,
5815 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00005816}
5817
Ted Kremenek02087932010-07-16 02:11:22 +00005818bool CheckPrintfHandler::HandleAmount(
5819 const analyze_format_string::OptionalAmount &Amt,
5820 unsigned k, const char *startSpecifier,
5821 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005822 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005823 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00005824 unsigned argIndex = Amt.getArgIndex();
5825 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005826 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5827 << k,
5828 getLocationOfByte(Amt.getStart()),
5829 /*IsStringLocation*/true,
5830 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005831 // Don't do any more checking. We will just emit
5832 // spurious errors.
5833 return false;
5834 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005835
Ted Kremenek5739de72010-01-29 01:06:55 +00005836 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00005837 // Although not in conformance with C99, we also allow the argument to be
5838 // an 'unsigned int' as that is a reasonably safe case. GCC also
5839 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00005840 CoveredArgs.set(argIndex);
5841 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00005842 if (!Arg)
5843 return false;
5844
Ted Kremenek5739de72010-01-29 01:06:55 +00005845 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005846
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005847 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5848 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005849
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005850 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005851 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005852 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00005853 << T << Arg->getSourceRange(),
5854 getLocationOfByte(Amt.getStart()),
5855 /*IsStringLocation*/true,
5856 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005857 // Don't do any more checking. We will just emit
5858 // spurious errors.
5859 return false;
5860 }
5861 }
5862 }
5863 return true;
5864}
Ted Kremenek5739de72010-01-29 01:06:55 +00005865
Tom Careb49ec692010-06-17 19:00:27 +00005866void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00005867 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005868 const analyze_printf::OptionalAmount &Amt,
5869 unsigned type,
5870 const char *startSpecifier,
5871 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005872 const analyze_printf::PrintfConversionSpecifier &CS =
5873 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00005874
Richard Trieu03cf7b72011-10-28 00:41:25 +00005875 FixItHint fixit =
5876 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5877 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5878 Amt.getConstantLength()))
5879 : FixItHint();
5880
5881 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5882 << type << CS.toString(),
5883 getLocationOfByte(Amt.getStart()),
5884 /*IsStringLocation*/true,
5885 getSpecifierRange(startSpecifier, specifierLen),
5886 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00005887}
5888
Ted Kremenek02087932010-07-16 02:11:22 +00005889void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005890 const analyze_printf::OptionalFlag &flag,
5891 const char *startSpecifier,
5892 unsigned specifierLen) {
5893 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005894 const analyze_printf::PrintfConversionSpecifier &CS =
5895 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00005896 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5897 << flag.toString() << CS.toString(),
5898 getLocationOfByte(flag.getPosition()),
5899 /*IsStringLocation*/true,
5900 getSpecifierRange(startSpecifier, specifierLen),
5901 FixItHint::CreateRemoval(
5902 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005903}
5904
5905void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00005906 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005907 const analyze_printf::OptionalFlag &ignoredFlag,
5908 const analyze_printf::OptionalFlag &flag,
5909 const char *startSpecifier,
5910 unsigned specifierLen) {
5911 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005912 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5913 << ignoredFlag.toString() << flag.toString(),
5914 getLocationOfByte(ignoredFlag.getPosition()),
5915 /*IsStringLocation*/true,
5916 getSpecifierRange(startSpecifier, specifierLen),
5917 FixItHint::CreateRemoval(
5918 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005919}
5920
Ted Kremenek2b417712015-07-02 05:39:16 +00005921void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5922 unsigned flagLen) {
5923 // Warn about an empty flag.
5924 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5925 getLocationOfByte(startFlag),
5926 /*IsStringLocation*/true,
5927 getSpecifierRange(startFlag, flagLen));
5928}
5929
5930void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5931 unsigned flagLen) {
5932 // Warn about an invalid flag.
5933 auto Range = getSpecifierRange(startFlag, flagLen);
5934 StringRef flag(startFlag, flagLen);
5935 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5936 getLocationOfByte(startFlag),
5937 /*IsStringLocation*/true,
5938 Range, FixItHint::CreateRemoval(Range));
5939}
5940
5941void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5942 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5943 // Warn about using '[...]' without a '@' conversion.
5944 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5945 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5946 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5947 getLocationOfByte(conversionPosition),
5948 /*IsStringLocation*/true,
5949 Range, FixItHint::CreateRemoval(Range));
5950}
5951
Richard Smith55ce3522012-06-25 20:30:08 +00005952// Determines if the specified is a C++ class or struct containing
5953// a member with the specified name and kind (e.g. a CXXMethodDecl named
5954// "c_str()").
5955template<typename MemberKind>
5956static llvm::SmallPtrSet<MemberKind*, 1>
5957CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5958 const RecordType *RT = Ty->getAs<RecordType>();
5959 llvm::SmallPtrSet<MemberKind*, 1> Results;
5960
5961 if (!RT)
5962 return Results;
5963 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00005964 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00005965 return Results;
5966
Alp Tokerb6cc5922014-05-03 03:45:55 +00005967 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00005968 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00005969 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00005970
5971 // We just need to include all members of the right kind turned up by the
5972 // filter, at this point.
5973 if (S.LookupQualifiedName(R, RT->getDecl()))
5974 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5975 NamedDecl *decl = (*I)->getUnderlyingDecl();
5976 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5977 Results.insert(FK);
5978 }
5979 return Results;
5980}
5981
Richard Smith2868a732014-02-28 01:36:39 +00005982/// Check if we could call '.c_str()' on an object.
5983///
5984/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5985/// allow the call, or if it would be ambiguous).
5986bool Sema::hasCStrMethod(const Expr *E) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005987 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
5988
Richard Smith2868a732014-02-28 01:36:39 +00005989 MethodSet Results =
5990 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5991 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5992 MI != ME; ++MI)
5993 if ((*MI)->getMinRequiredArguments() == 0)
5994 return true;
5995 return false;
5996}
5997
Richard Smith55ce3522012-06-25 20:30:08 +00005998// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005999// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00006000// Returns true when a c_str() conversion method is found.
6001bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00006002 const analyze_printf::ArgType &AT, const Expr *E) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006003 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
Richard Smith55ce3522012-06-25 20:30:08 +00006004
6005 MethodSet Results =
6006 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
6007
6008 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
6009 MI != ME; ++MI) {
6010 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00006011 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00006012 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00006013 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00006014 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00006015 S.Diag(E->getLocStart(), diag::note_printf_c_str)
6016 << "c_str()"
6017 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
6018 return true;
6019 }
6020 }
6021
6022 return false;
6023}
6024
Ted Kremenekab278de2010-01-28 23:39:18 +00006025bool
Ted Kremenek02087932010-07-16 02:11:22 +00006026CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00006027 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00006028 const char *startSpecifier,
6029 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006030 using namespace analyze_format_string;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006031 using namespace analyze_printf;
6032
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006033 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00006034
Ted Kremenek6cd69422010-07-19 22:01:06 +00006035 if (FS.consumesDataArgument()) {
6036 if (atFirstArg) {
6037 atFirstArg = false;
6038 usesPositionalArgs = FS.usesPositionalArg();
6039 }
6040 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006041 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6042 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00006043 return false;
6044 }
Ted Kremenek5739de72010-01-29 01:06:55 +00006045 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006046
Ted Kremenekd1668192010-02-27 01:41:03 +00006047 // First check if the field width, precision, and conversion specifier
6048 // have matching data arguments.
6049 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
6050 startSpecifier, specifierLen)) {
6051 return false;
6052 }
6053
6054 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
6055 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00006056 return false;
6057 }
6058
Ted Kremenek8d9842d2010-01-29 20:55:36 +00006059 if (!CS.consumesDataArgument()) {
6060 // FIXME: Technically specifying a precision or field width here
6061 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00006062 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00006063 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006064
Ted Kremenek4a49d982010-02-26 19:18:41 +00006065 // Consume the argument.
6066 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00006067 if (argIndex < NumDataArgs) {
6068 // The check to see if the argIndex is valid will come later.
6069 // We set the bit here because we may exit early from this
6070 // function if we encounter some other error.
6071 CoveredArgs.set(argIndex);
6072 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00006073
Dimitry Andric6b5ed342015-02-19 22:32:33 +00006074 // FreeBSD kernel extensions.
6075 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
6076 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
6077 // We need at least two arguments.
6078 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
6079 return false;
6080
6081 // Claim the second argument.
6082 CoveredArgs.set(argIndex + 1);
6083
6084 // Type check the first argument (int for %b, pointer for %D)
6085 const Expr *Ex = getDataArg(argIndex);
6086 const analyze_printf::ArgType &AT =
6087 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
6088 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
6089 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
6090 EmitFormatDiagnostic(
6091 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6092 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
6093 << false << Ex->getSourceRange(),
6094 Ex->getLocStart(), /*IsStringLocation*/false,
6095 getSpecifierRange(startSpecifier, specifierLen));
6096
6097 // Type check the second argument (char * for both %b and %D)
6098 Ex = getDataArg(argIndex + 1);
6099 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
6100 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
6101 EmitFormatDiagnostic(
6102 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6103 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
6104 << false << Ex->getSourceRange(),
6105 Ex->getLocStart(), /*IsStringLocation*/false,
6106 getSpecifierRange(startSpecifier, specifierLen));
6107
6108 return true;
6109 }
6110
Ted Kremenek4a49d982010-02-26 19:18:41 +00006111 // Check for using an Objective-C specific conversion specifier
6112 // in a non-ObjC literal.
Mehdi Amini06d367c2016-10-24 20:39:34 +00006113 if (!allowsObjCArg() && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00006114 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6115 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00006116 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006117
Mehdi Amini06d367c2016-10-24 20:39:34 +00006118 // %P can only be used with os_log.
6119 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
6120 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6121 specifierLen);
6122 }
6123
6124 // %n is not allowed with os_log.
6125 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
6126 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
6127 getLocationOfByte(CS.getStart()),
6128 /*IsStringLocation*/ false,
6129 getSpecifierRange(startSpecifier, specifierLen));
6130
6131 return true;
6132 }
6133
6134 // Only scalars are allowed for os_trace.
6135 if (FSType == Sema::FST_OSTrace &&
6136 (CS.getKind() == ConversionSpecifier::PArg ||
6137 CS.getKind() == ConversionSpecifier::sArg ||
6138 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
6139 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6140 specifierLen);
6141 }
6142
6143 // Check for use of public/private annotation outside of os_log().
6144 if (FSType != Sema::FST_OSLog) {
6145 if (FS.isPublic().isSet()) {
6146 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6147 << "public",
6148 getLocationOfByte(FS.isPublic().getPosition()),
6149 /*IsStringLocation*/ false,
6150 getSpecifierRange(startSpecifier, specifierLen));
6151 }
6152 if (FS.isPrivate().isSet()) {
6153 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6154 << "private",
6155 getLocationOfByte(FS.isPrivate().getPosition()),
6156 /*IsStringLocation*/ false,
6157 getSpecifierRange(startSpecifier, specifierLen));
6158 }
6159 }
6160
Tom Careb49ec692010-06-17 19:00:27 +00006161 // Check for invalid use of field width
6162 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00006163 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00006164 startSpecifier, specifierLen);
6165 }
6166
6167 // Check for invalid use of precision
6168 if (!FS.hasValidPrecision()) {
6169 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
6170 startSpecifier, specifierLen);
6171 }
6172
Mehdi Amini06d367c2016-10-24 20:39:34 +00006173 // Precision is mandatory for %P specifier.
6174 if (CS.getKind() == ConversionSpecifier::PArg &&
6175 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
6176 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
6177 getLocationOfByte(startSpecifier),
6178 /*IsStringLocation*/ false,
6179 getSpecifierRange(startSpecifier, specifierLen));
6180 }
6181
Tom Careb49ec692010-06-17 19:00:27 +00006182 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00006183 if (!FS.hasValidThousandsGroupingPrefix())
6184 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006185 if (!FS.hasValidLeadingZeros())
6186 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
6187 if (!FS.hasValidPlusPrefix())
6188 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00006189 if (!FS.hasValidSpacePrefix())
6190 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006191 if (!FS.hasValidAlternativeForm())
6192 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
6193 if (!FS.hasValidLeftJustified())
6194 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
6195
6196 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00006197 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
6198 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
6199 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006200 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
6201 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
6202 startSpecifier, specifierLen);
6203
6204 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006205 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006206 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6207 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006208 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006209 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006210 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006211 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6212 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00006213
Jordan Rose92303592012-09-08 04:00:03 +00006214 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6215 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6216
Ted Kremenek9fcd8302010-01-29 01:43:31 +00006217 // The remaining checks depend on the data arguments.
6218 if (HasVAListArg)
6219 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006220
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006221 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00006222 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006223
Jordan Rose58bbe422012-07-19 18:10:08 +00006224 const Expr *Arg = getDataArg(argIndex);
6225 if (!Arg)
6226 return true;
6227
6228 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00006229}
6230
Jordan Roseaee34382012-09-05 22:56:26 +00006231static bool requiresParensToAddCast(const Expr *E) {
6232 // FIXME: We should have a general way to reason about operator
6233 // precedence and whether parens are actually needed here.
6234 // Take care of a few common cases where they aren't.
6235 const Expr *Inside = E->IgnoreImpCasts();
6236 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
6237 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
6238
6239 switch (Inside->getStmtClass()) {
6240 case Stmt::ArraySubscriptExprClass:
6241 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006242 case Stmt::CharacterLiteralClass:
6243 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006244 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006245 case Stmt::FloatingLiteralClass:
6246 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006247 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006248 case Stmt::ObjCArrayLiteralClass:
6249 case Stmt::ObjCBoolLiteralExprClass:
6250 case Stmt::ObjCBoxedExprClass:
6251 case Stmt::ObjCDictionaryLiteralClass:
6252 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006253 case Stmt::ObjCIvarRefExprClass:
6254 case Stmt::ObjCMessageExprClass:
6255 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006256 case Stmt::ObjCStringLiteralClass:
6257 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006258 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006259 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006260 case Stmt::UnaryOperatorClass:
6261 return false;
6262 default:
6263 return true;
6264 }
6265}
6266
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006267static std::pair<QualType, StringRef>
6268shouldNotPrintDirectly(const ASTContext &Context,
6269 QualType IntendedTy,
6270 const Expr *E) {
6271 // Use a 'while' to peel off layers of typedefs.
6272 QualType TyTy = IntendedTy;
6273 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
6274 StringRef Name = UserTy->getDecl()->getName();
6275 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Saleem Abdulrasoola01ed932017-10-17 17:39:32 +00006276 .Case("CFIndex", Context.getNSIntegerType())
6277 .Case("NSInteger", Context.getNSIntegerType())
6278 .Case("NSUInteger", Context.getNSUIntegerType())
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006279 .Case("SInt32", Context.IntTy)
6280 .Case("UInt32", Context.UnsignedIntTy)
6281 .Default(QualType());
6282
6283 if (!CastTy.isNull())
6284 return std::make_pair(CastTy, Name);
6285
6286 TyTy = UserTy->desugar();
6287 }
6288
6289 // Strip parens if necessary.
6290 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
6291 return shouldNotPrintDirectly(Context,
6292 PE->getSubExpr()->getType(),
6293 PE->getSubExpr());
6294
6295 // If this is a conditional expression, then its result type is constructed
6296 // via usual arithmetic conversions and thus there might be no necessary
6297 // typedef sugar there. Recurse to operands to check for NSInteger &
6298 // Co. usage condition.
6299 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6300 QualType TrueTy, FalseTy;
6301 StringRef TrueName, FalseName;
6302
6303 std::tie(TrueTy, TrueName) =
6304 shouldNotPrintDirectly(Context,
6305 CO->getTrueExpr()->getType(),
6306 CO->getTrueExpr());
6307 std::tie(FalseTy, FalseName) =
6308 shouldNotPrintDirectly(Context,
6309 CO->getFalseExpr()->getType(),
6310 CO->getFalseExpr());
6311
6312 if (TrueTy == FalseTy)
6313 return std::make_pair(TrueTy, TrueName);
6314 else if (TrueTy.isNull())
6315 return std::make_pair(FalseTy, FalseName);
6316 else if (FalseTy.isNull())
6317 return std::make_pair(TrueTy, TrueName);
6318 }
6319
6320 return std::make_pair(QualType(), StringRef());
6321}
6322
Richard Smith55ce3522012-06-25 20:30:08 +00006323bool
6324CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6325 const char *StartSpecifier,
6326 unsigned SpecifierLen,
6327 const Expr *E) {
6328 using namespace analyze_format_string;
6329 using namespace analyze_printf;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006330
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006331 // Now type check the data expression that matches the
6332 // format specifier.
Mehdi Amini06d367c2016-10-24 20:39:34 +00006333 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
Jordan Rose22b74712012-09-05 22:56:19 +00006334 if (!AT.isValid())
6335 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00006336
Jordan Rose598ec092012-12-05 18:44:40 +00006337 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00006338 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
6339 ExprTy = TET->getUnderlyingExpr()->getType();
6340 }
6341
Seth Cantrellb4802962015-03-04 03:12:10 +00006342 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
6343
6344 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00006345 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006346 }
Jordan Rose98709982012-06-04 22:48:57 +00006347
Jordan Rose22b74712012-09-05 22:56:19 +00006348 // Look through argument promotions for our error message's reported type.
6349 // This includes the integral and floating promotions, but excludes array
6350 // and function pointer decay; seeing that an argument intended to be a
6351 // string has type 'char [6]' is probably more confusing than 'char *'.
6352 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6353 if (ICE->getCastKind() == CK_IntegralCast ||
6354 ICE->getCastKind() == CK_FloatingCast) {
6355 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00006356 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00006357
6358 // Check if we didn't match because of an implicit cast from a 'char'
6359 // or 'short' to an 'int'. This is done because printf is a varargs
6360 // function.
6361 if (ICE->getType() == S.Context.IntTy ||
6362 ICE->getType() == S.Context.UnsignedIntTy) {
6363 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00006364 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00006365 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00006366 }
Jordan Rose98709982012-06-04 22:48:57 +00006367 }
Jordan Rose598ec092012-12-05 18:44:40 +00006368 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
6369 // Special case for 'a', which has type 'int' in C.
6370 // Note, however, that we do /not/ want to treat multibyte constants like
6371 // 'MooV' as characters! This form is deprecated but still exists.
6372 if (ExprTy == S.Context.IntTy)
6373 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6374 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00006375 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006376
Jordan Rosebc53ed12014-05-31 04:12:14 +00006377 // Look through enums to their underlying type.
6378 bool IsEnum = false;
6379 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
6380 ExprTy = EnumTy->getDecl()->getIntegerType();
6381 IsEnum = true;
6382 }
6383
Jordan Rose0e5badd2012-12-05 18:44:49 +00006384 // %C in an Objective-C context prints a unichar, not a wchar_t.
6385 // If the argument is an integer of some kind, believe the %C and suggest
6386 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00006387 QualType IntendedTy = ExprTy;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006388 if (isObjCContext() &&
Jordan Rose0e5badd2012-12-05 18:44:49 +00006389 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
6390 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6391 !ExprTy->isCharType()) {
6392 // 'unichar' is defined as a typedef of unsigned short, but we should
6393 // prefer using the typedef if it is visible.
6394 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00006395
6396 // While we are here, check if the value is an IntegerLiteral that happens
6397 // to be within the valid range.
6398 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
6399 const llvm::APInt &V = IL->getValue();
6400 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6401 return true;
6402 }
6403
Jordan Rose0e5badd2012-12-05 18:44:49 +00006404 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
6405 Sema::LookupOrdinaryName);
6406 if (S.LookupName(Result, S.getCurScope())) {
6407 NamedDecl *ND = Result.getFoundDecl();
6408 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
6409 if (TD->getUnderlyingType() == IntendedTy)
6410 IntendedTy = S.Context.getTypedefType(TD);
6411 }
6412 }
6413 }
6414
6415 // Special-case some of Darwin's platform-independence types by suggesting
6416 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006417 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00006418 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006419 QualType CastTy;
6420 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
6421 if (!CastTy.isNull()) {
6422 IntendedTy = CastTy;
6423 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00006424 }
6425 }
6426
Jordan Rose22b74712012-09-05 22:56:19 +00006427 // We may be able to offer a FixItHint if it is a supported type.
6428 PrintfSpecifier fixedFS = FS;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006429 bool success =
6430 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006431
Jordan Rose22b74712012-09-05 22:56:19 +00006432 if (success) {
6433 // Get the fix string from the fixed format specifier
6434 SmallString<16> buf;
6435 llvm::raw_svector_ostream os(buf);
6436 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006437
Jordan Roseaee34382012-09-05 22:56:26 +00006438 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6439
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006440 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00006441 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6442 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6443 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6444 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00006445 // In this case, the specifier is wrong and should be changed to match
6446 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00006447 EmitFormatDiagnostic(S.PDiag(diag)
6448 << AT.getRepresentativeTypeName(S.Context)
6449 << IntendedTy << IsEnum << E->getSourceRange(),
6450 E->getLocStart(),
6451 /*IsStringLocation*/ false, SpecRange,
6452 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00006453 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00006454 // The canonical type for formatting this value is different from the
6455 // actual type of the expression. (This occurs, for example, with Darwin's
6456 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6457 // should be printed as 'long' for 64-bit compatibility.)
6458 // Rather than emitting a normal format/argument mismatch, we want to
6459 // add a cast to the recommended type (and correct the format string
6460 // if necessary).
6461 SmallString<16> CastBuf;
6462 llvm::raw_svector_ostream CastFix(CastBuf);
6463 CastFix << "(";
6464 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6465 CastFix << ")";
6466
6467 SmallVector<FixItHint,4> Hints;
Alexander Shaposhnikov1788a9b2017-09-22 18:36:06 +00006468 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
Jordan Roseaee34382012-09-05 22:56:26 +00006469 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6470
6471 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6472 // If there's already a cast present, just replace it.
6473 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6474 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6475
6476 } else if (!requiresParensToAddCast(E)) {
6477 // If the expression has high enough precedence,
6478 // just write the C-style cast.
6479 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6480 CastFix.str()));
6481 } else {
6482 // Otherwise, add parens around the expression as well as the cast.
6483 CastFix << "(";
6484 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6485 CastFix.str()));
6486
Alp Tokerb6cc5922014-05-03 03:45:55 +00006487 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00006488 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6489 }
6490
Jordan Rose0e5badd2012-12-05 18:44:49 +00006491 if (ShouldNotPrintDirectly) {
6492 // The expression has a type that should not be printed directly.
6493 // We extract the name from the typedef because we don't want to show
6494 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006495 StringRef Name;
6496 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6497 Name = TypedefTy->getDecl()->getName();
6498 else
6499 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00006500 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00006501 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006502 << E->getSourceRange(),
6503 E->getLocStart(), /*IsStringLocation=*/false,
6504 SpecRange, Hints);
6505 } else {
6506 // In this case, the expression could be printed using a different
6507 // specifier, but we've decided that the specifier is probably correct
6508 // and we should cast instead. Just use the normal warning message.
6509 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00006510 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6511 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006512 << E->getSourceRange(),
6513 E->getLocStart(), /*IsStringLocation*/false,
6514 SpecRange, Hints);
6515 }
Jordan Roseaee34382012-09-05 22:56:26 +00006516 }
Jordan Rose22b74712012-09-05 22:56:19 +00006517 } else {
6518 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6519 SpecifierLen);
6520 // Since the warning for passing non-POD types to variadic functions
6521 // was deferred until now, we emit a warning for non-POD
6522 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00006523 switch (S.isValidVarArgType(ExprTy)) {
6524 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00006525 case Sema::VAK_ValidInCXX11: {
6526 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6527 if (match == analyze_printf::ArgType::NoMatchPedantic) {
6528 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6529 }
Richard Smithd7293d72013-08-05 18:49:43 +00006530
Seth Cantrellb4802962015-03-04 03:12:10 +00006531 EmitFormatDiagnostic(
6532 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6533 << IsEnum << CSR << E->getSourceRange(),
6534 E->getLocStart(), /*IsStringLocation*/ false, CSR);
6535 break;
6536 }
Richard Smithd7293d72013-08-05 18:49:43 +00006537 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00006538 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00006539 EmitFormatDiagnostic(
6540 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006541 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00006542 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00006543 << CallType
6544 << AT.getRepresentativeTypeName(S.Context)
6545 << CSR
6546 << E->getSourceRange(),
6547 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00006548 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00006549 break;
6550
6551 case Sema::VAK_Invalid:
6552 if (ExprTy->isObjCObjectType())
6553 EmitFormatDiagnostic(
6554 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6555 << S.getLangOpts().CPlusPlus11
6556 << ExprTy
6557 << CallType
6558 << AT.getRepresentativeTypeName(S.Context)
6559 << CSR
6560 << E->getSourceRange(),
6561 E->getLocStart(), /*IsStringLocation*/false, CSR);
6562 else
6563 // FIXME: If this is an initializer list, suggest removing the braces
6564 // or inserting a cast to the target type.
6565 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6566 << isa<InitListExpr>(E) << ExprTy << CallType
6567 << AT.getRepresentativeTypeName(S.Context)
6568 << E->getSourceRange();
6569 break;
6570 }
6571
6572 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6573 "format string specifier index out of range");
6574 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006575 }
6576
Ted Kremenekab278de2010-01-28 23:39:18 +00006577 return true;
6578}
6579
Ted Kremenek02087932010-07-16 02:11:22 +00006580//===--- CHECK: Scanf format string checking ------------------------------===//
6581
6582namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006583
Ted Kremenek02087932010-07-16 02:11:22 +00006584class CheckScanfHandler : public CheckFormatHandler {
6585public:
Stephen Hines648c3692016-09-16 01:07:04 +00006586 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006587 const Expr *origFormatExpr, Sema::FormatStringType type,
6588 unsigned firstDataArg, unsigned numDataArgs,
6589 const char *beg, bool hasVAListArg,
6590 ArrayRef<const Expr *> Args, unsigned formatIdx,
6591 bool inFunctionCall, Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006592 llvm::SmallBitVector &CheckedVarArgs,
6593 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006594 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6595 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6596 inFunctionCall, CallType, CheckedVarArgs,
6597 UncoveredArg) {}
6598
Ted Kremenek02087932010-07-16 02:11:22 +00006599 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6600 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006601 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00006602
6603 bool HandleInvalidScanfConversionSpecifier(
6604 const analyze_scanf::ScanfSpecifier &FS,
6605 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006606 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006607
Craig Toppere14c0f82014-03-12 04:55:44 +00006608 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00006609};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006610
6611} // namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00006612
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006613void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6614 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006615 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6616 getLocationOfByte(end), /*IsStringLocation*/true,
6617 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006618}
6619
Ted Kremenekce815422010-07-19 21:25:57 +00006620bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6621 const analyze_scanf::ScanfSpecifier &FS,
6622 const char *startSpecifier,
6623 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006624 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00006625 FS.getConversionSpecifier();
6626
6627 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6628 getLocationOfByte(CS.getStart()),
6629 startSpecifier, specifierLen,
6630 CS.getStart(), CS.getLength());
6631}
6632
Ted Kremenek02087932010-07-16 02:11:22 +00006633bool CheckScanfHandler::HandleScanfSpecifier(
6634 const analyze_scanf::ScanfSpecifier &FS,
6635 const char *startSpecifier,
6636 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00006637 using namespace analyze_scanf;
6638 using namespace analyze_format_string;
6639
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006640 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00006641
Ted Kremenek6cd69422010-07-19 22:01:06 +00006642 // Handle case where '%' and '*' don't consume an argument. These shouldn't
6643 // be used to decide if we are using positional arguments consistently.
6644 if (FS.consumesDataArgument()) {
6645 if (atFirstArg) {
6646 atFirstArg = false;
6647 usesPositionalArgs = FS.usesPositionalArg();
6648 }
6649 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006650 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6651 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00006652 return false;
6653 }
Ted Kremenek02087932010-07-16 02:11:22 +00006654 }
6655
6656 // Check if the field with is non-zero.
6657 const OptionalAmount &Amt = FS.getFieldWidth();
6658 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6659 if (Amt.getConstantAmount() == 0) {
6660 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6661 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00006662 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6663 getLocationOfByte(Amt.getStart()),
6664 /*IsStringLocation*/true, R,
6665 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00006666 }
6667 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006668
Ted Kremenek02087932010-07-16 02:11:22 +00006669 if (!FS.consumesDataArgument()) {
6670 // FIXME: Technically specifying a precision or field width here
6671 // makes no sense. Worth issuing a warning at some point.
6672 return true;
6673 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006674
Ted Kremenek02087932010-07-16 02:11:22 +00006675 // Consume the argument.
6676 unsigned argIndex = FS.getArgIndex();
6677 if (argIndex < NumDataArgs) {
6678 // The check to see if the argIndex is valid will come later.
6679 // We set the bit here because we may exit early from this
6680 // function if we encounter some other error.
6681 CoveredArgs.set(argIndex);
6682 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006683
Ted Kremenek4407ea42010-07-20 20:04:47 +00006684 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006685 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006686 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6687 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006688 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006689 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006690 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006691 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6692 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006693
Jordan Rose92303592012-09-08 04:00:03 +00006694 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6695 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6696
Ted Kremenek02087932010-07-16 02:11:22 +00006697 // The remaining checks depend on the data arguments.
6698 if (HasVAListArg)
6699 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006700
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006701 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00006702 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00006703
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006704 // Check that the argument type matches the format specifier.
6705 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00006706 if (!Ex)
6707 return true;
6708
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00006709 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00006710
6711 if (!AT.isValid()) {
6712 return true;
6713 }
6714
Seth Cantrellb4802962015-03-04 03:12:10 +00006715 analyze_format_string::ArgType::MatchKind match =
6716 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00006717 if (match == analyze_format_string::ArgType::Match) {
6718 return true;
6719 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006720
Seth Cantrell79340072015-03-04 05:58:08 +00006721 ScanfSpecifier fixedFS = FS;
6722 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6723 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006724
Seth Cantrell79340072015-03-04 05:58:08 +00006725 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6726 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6727 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6728 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006729
Seth Cantrell79340072015-03-04 05:58:08 +00006730 if (success) {
6731 // Get the fix string from the fixed format specifier.
6732 SmallString<128> buf;
6733 llvm::raw_svector_ostream os(buf);
6734 fixedFS.toString(os);
6735
6736 EmitFormatDiagnostic(
6737 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6738 << Ex->getType() << false << Ex->getSourceRange(),
6739 Ex->getLocStart(),
6740 /*IsStringLocation*/ false,
6741 getSpecifierRange(startSpecifier, specifierLen),
6742 FixItHint::CreateReplacement(
6743 getSpecifierRange(startSpecifier, specifierLen), os.str()));
6744 } else {
6745 EmitFormatDiagnostic(S.PDiag(diag)
6746 << AT.getRepresentativeTypeName(S.Context)
6747 << Ex->getType() << false << Ex->getSourceRange(),
6748 Ex->getLocStart(),
6749 /*IsStringLocation*/ false,
6750 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006751 }
6752
Ted Kremenek02087932010-07-16 02:11:22 +00006753 return true;
6754}
6755
Stephen Hines648c3692016-09-16 01:07:04 +00006756static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006757 const Expr *OrigFormatExpr,
6758 ArrayRef<const Expr *> Args,
6759 bool HasVAListArg, unsigned format_idx,
6760 unsigned firstDataArg,
6761 Sema::FormatStringType Type,
6762 bool inFunctionCall,
6763 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006764 llvm::SmallBitVector &CheckedVarArgs,
6765 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00006766 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00006767 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006768 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006769 S, inFunctionCall, Args[format_idx],
6770 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006771 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006772 return;
6773 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006774
Ted Kremenekab278de2010-01-28 23:39:18 +00006775 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006776 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00006777 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006778 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006779 const ConstantArrayType *T =
6780 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006781 assert(T && "String literal not of constant array type!");
6782 size_t TypeSize = T->getSize().getZExtValue();
6783 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006784 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006785
6786 // Emit a warning if the string literal is truncated and does not contain an
6787 // embedded null character.
6788 if (TypeSize <= StrRef.size() &&
6789 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6790 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006791 S, inFunctionCall, Args[format_idx],
6792 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006793 FExpr->getLocStart(),
6794 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6795 return;
6796 }
6797
Ted Kremenekab278de2010-01-28 23:39:18 +00006798 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00006799 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006800 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006801 S, inFunctionCall, Args[format_idx],
6802 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006803 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006804 return;
6805 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006806
6807 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
Mehdi Amini06d367c2016-10-24 20:39:34 +00006808 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6809 Type == Sema::FST_OSTrace) {
6810 CheckPrintfHandler H(
6811 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6812 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6813 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6814 CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006815
Hans Wennborg23926bd2011-12-15 10:25:47 +00006816 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006817 S.getLangOpts(),
6818 S.Context.getTargetInfo(),
6819 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00006820 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006821 } else if (Type == Sema::FST_Scanf) {
Mehdi Amini06d367c2016-10-24 20:39:34 +00006822 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6823 numDataArgs, Str, HasVAListArg, Args, format_idx,
6824 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006825
Hans Wennborg23926bd2011-12-15 10:25:47 +00006826 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006827 S.getLangOpts(),
6828 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00006829 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006830 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00006831}
6832
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00006833bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6834 // Str - The format string. NOTE: this is NOT null-terminated!
6835 StringRef StrRef = FExpr->getString();
6836 const char *Str = StrRef.data();
6837 // Account for cases where the string literal is truncated in a declaration.
6838 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6839 assert(T && "String literal not of constant array type!");
6840 size_t TypeSize = T->getSize().getZExtValue();
6841 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6842 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6843 getLangOpts(),
6844 Context.getTargetInfo());
6845}
6846
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006847//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6848
6849// Returns the related absolute value function that is larger, of 0 if one
6850// does not exist.
6851static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6852 switch (AbsFunction) {
6853 default:
6854 return 0;
6855
6856 case Builtin::BI__builtin_abs:
6857 return Builtin::BI__builtin_labs;
6858 case Builtin::BI__builtin_labs:
6859 return Builtin::BI__builtin_llabs;
6860 case Builtin::BI__builtin_llabs:
6861 return 0;
6862
6863 case Builtin::BI__builtin_fabsf:
6864 return Builtin::BI__builtin_fabs;
6865 case Builtin::BI__builtin_fabs:
6866 return Builtin::BI__builtin_fabsl;
6867 case Builtin::BI__builtin_fabsl:
6868 return 0;
6869
6870 case Builtin::BI__builtin_cabsf:
6871 return Builtin::BI__builtin_cabs;
6872 case Builtin::BI__builtin_cabs:
6873 return Builtin::BI__builtin_cabsl;
6874 case Builtin::BI__builtin_cabsl:
6875 return 0;
6876
6877 case Builtin::BIabs:
6878 return Builtin::BIlabs;
6879 case Builtin::BIlabs:
6880 return Builtin::BIllabs;
6881 case Builtin::BIllabs:
6882 return 0;
6883
6884 case Builtin::BIfabsf:
6885 return Builtin::BIfabs;
6886 case Builtin::BIfabs:
6887 return Builtin::BIfabsl;
6888 case Builtin::BIfabsl:
6889 return 0;
6890
6891 case Builtin::BIcabsf:
6892 return Builtin::BIcabs;
6893 case Builtin::BIcabs:
6894 return Builtin::BIcabsl;
6895 case Builtin::BIcabsl:
6896 return 0;
6897 }
6898}
6899
6900// Returns the argument type of the absolute value function.
6901static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6902 unsigned AbsType) {
6903 if (AbsType == 0)
6904 return QualType();
6905
6906 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6907 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6908 if (Error != ASTContext::GE_None)
6909 return QualType();
6910
6911 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6912 if (!FT)
6913 return QualType();
6914
6915 if (FT->getNumParams() != 1)
6916 return QualType();
6917
6918 return FT->getParamType(0);
6919}
6920
6921// Returns the best absolute value function, or zero, based on type and
6922// current absolute value function.
6923static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6924 unsigned AbsFunctionKind) {
6925 unsigned BestKind = 0;
6926 uint64_t ArgSize = Context.getTypeSize(ArgType);
6927 for (unsigned Kind = AbsFunctionKind; Kind != 0;
6928 Kind = getLargerAbsoluteValueFunction(Kind)) {
6929 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6930 if (Context.getTypeSize(ParamType) >= ArgSize) {
6931 if (BestKind == 0)
6932 BestKind = Kind;
6933 else if (Context.hasSameType(ParamType, ArgType)) {
6934 BestKind = Kind;
6935 break;
6936 }
6937 }
6938 }
6939 return BestKind;
6940}
6941
6942enum AbsoluteValueKind {
6943 AVK_Integer,
6944 AVK_Floating,
6945 AVK_Complex
6946};
6947
6948static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6949 if (T->isIntegralOrEnumerationType())
6950 return AVK_Integer;
6951 if (T->isRealFloatingType())
6952 return AVK_Floating;
6953 if (T->isAnyComplexType())
6954 return AVK_Complex;
6955
6956 llvm_unreachable("Type not integer, floating, or complex");
6957}
6958
6959// Changes the absolute value function to a different type. Preserves whether
6960// the function is a builtin.
6961static unsigned changeAbsFunction(unsigned AbsKind,
6962 AbsoluteValueKind ValueKind) {
6963 switch (ValueKind) {
6964 case AVK_Integer:
6965 switch (AbsKind) {
6966 default:
6967 return 0;
6968 case Builtin::BI__builtin_fabsf:
6969 case Builtin::BI__builtin_fabs:
6970 case Builtin::BI__builtin_fabsl:
6971 case Builtin::BI__builtin_cabsf:
6972 case Builtin::BI__builtin_cabs:
6973 case Builtin::BI__builtin_cabsl:
6974 return Builtin::BI__builtin_abs;
6975 case Builtin::BIfabsf:
6976 case Builtin::BIfabs:
6977 case Builtin::BIfabsl:
6978 case Builtin::BIcabsf:
6979 case Builtin::BIcabs:
6980 case Builtin::BIcabsl:
6981 return Builtin::BIabs;
6982 }
6983 case AVK_Floating:
6984 switch (AbsKind) {
6985 default:
6986 return 0;
6987 case Builtin::BI__builtin_abs:
6988 case Builtin::BI__builtin_labs:
6989 case Builtin::BI__builtin_llabs:
6990 case Builtin::BI__builtin_cabsf:
6991 case Builtin::BI__builtin_cabs:
6992 case Builtin::BI__builtin_cabsl:
6993 return Builtin::BI__builtin_fabsf;
6994 case Builtin::BIabs:
6995 case Builtin::BIlabs:
6996 case Builtin::BIllabs:
6997 case Builtin::BIcabsf:
6998 case Builtin::BIcabs:
6999 case Builtin::BIcabsl:
7000 return Builtin::BIfabsf;
7001 }
7002 case AVK_Complex:
7003 switch (AbsKind) {
7004 default:
7005 return 0;
7006 case Builtin::BI__builtin_abs:
7007 case Builtin::BI__builtin_labs:
7008 case Builtin::BI__builtin_llabs:
7009 case Builtin::BI__builtin_fabsf:
7010 case Builtin::BI__builtin_fabs:
7011 case Builtin::BI__builtin_fabsl:
7012 return Builtin::BI__builtin_cabsf;
7013 case Builtin::BIabs:
7014 case Builtin::BIlabs:
7015 case Builtin::BIllabs:
7016 case Builtin::BIfabsf:
7017 case Builtin::BIfabs:
7018 case Builtin::BIfabsl:
7019 return Builtin::BIcabsf;
7020 }
7021 }
7022 llvm_unreachable("Unable to convert function");
7023}
7024
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00007025static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007026 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
7027 if (!FnInfo)
7028 return 0;
7029
7030 switch (FDecl->getBuiltinID()) {
7031 default:
7032 return 0;
7033 case Builtin::BI__builtin_abs:
7034 case Builtin::BI__builtin_fabs:
7035 case Builtin::BI__builtin_fabsf:
7036 case Builtin::BI__builtin_fabsl:
7037 case Builtin::BI__builtin_labs:
7038 case Builtin::BI__builtin_llabs:
7039 case Builtin::BI__builtin_cabs:
7040 case Builtin::BI__builtin_cabsf:
7041 case Builtin::BI__builtin_cabsl:
7042 case Builtin::BIabs:
7043 case Builtin::BIlabs:
7044 case Builtin::BIllabs:
7045 case Builtin::BIfabs:
7046 case Builtin::BIfabsf:
7047 case Builtin::BIfabsl:
7048 case Builtin::BIcabs:
7049 case Builtin::BIcabsf:
7050 case Builtin::BIcabsl:
7051 return FDecl->getBuiltinID();
7052 }
7053 llvm_unreachable("Unknown Builtin type");
7054}
7055
7056// If the replacement is valid, emit a note with replacement function.
7057// Additionally, suggest including the proper header if not already included.
7058static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00007059 unsigned AbsKind, QualType ArgType) {
7060 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00007061 const char *HeaderName = nullptr;
Mehdi Amini7186a432016-10-11 19:04:24 +00007062 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00007063 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
7064 FunctionName = "std::abs";
7065 if (ArgType->isIntegralOrEnumerationType()) {
7066 HeaderName = "cstdlib";
7067 } else if (ArgType->isRealFloatingType()) {
7068 HeaderName = "cmath";
7069 } else {
7070 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007071 }
Richard Trieubeffb832014-04-15 23:47:53 +00007072
7073 // Lookup all std::abs
7074 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00007075 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00007076 R.suppressDiagnostics();
7077 S.LookupQualifiedName(R, Std);
7078
7079 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007080 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00007081 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
7082 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
7083 } else {
7084 FDecl = dyn_cast<FunctionDecl>(I);
7085 }
7086 if (!FDecl)
7087 continue;
7088
7089 // Found std::abs(), check that they are the right ones.
7090 if (FDecl->getNumParams() != 1)
7091 continue;
7092
7093 // Check that the parameter type can handle the argument.
7094 QualType ParamType = FDecl->getParamDecl(0)->getType();
7095 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
7096 S.Context.getTypeSize(ArgType) <=
7097 S.Context.getTypeSize(ParamType)) {
7098 // Found a function, don't need the header hint.
7099 EmitHeaderHint = false;
7100 break;
7101 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007102 }
Richard Trieubeffb832014-04-15 23:47:53 +00007103 }
7104 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00007105 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00007106 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
7107
7108 if (HeaderName) {
7109 DeclarationName DN(&S.Context.Idents.get(FunctionName));
7110 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
7111 R.suppressDiagnostics();
7112 S.LookupName(R, S.getCurScope());
7113
7114 if (R.isSingleResult()) {
7115 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
7116 if (FD && FD->getBuiltinID() == AbsKind) {
7117 EmitHeaderHint = false;
7118 } else {
7119 return;
7120 }
7121 } else if (!R.empty()) {
7122 return;
7123 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007124 }
7125 }
7126
7127 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00007128 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007129
Richard Trieubeffb832014-04-15 23:47:53 +00007130 if (!HeaderName)
7131 return;
7132
7133 if (!EmitHeaderHint)
7134 return;
7135
Alp Toker5d96e0a2014-07-11 20:53:51 +00007136 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
7137 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00007138}
7139
Richard Trieua7f30b12016-12-06 01:42:28 +00007140template <std::size_t StrLen>
7141static bool IsStdFunction(const FunctionDecl *FDecl,
7142 const char (&Str)[StrLen]) {
Richard Trieubeffb832014-04-15 23:47:53 +00007143 if (!FDecl)
7144 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00007145 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
Richard Trieubeffb832014-04-15 23:47:53 +00007146 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00007147 if (!FDecl->isInStdNamespace())
Richard Trieubeffb832014-04-15 23:47:53 +00007148 return false;
7149
7150 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007151}
7152
7153// Warn when using the wrong abs() function.
7154void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
Richard Trieua7f30b12016-12-06 01:42:28 +00007155 const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007156 if (Call->getNumArgs() != 1)
7157 return;
7158
7159 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieua7f30b12016-12-06 01:42:28 +00007160 bool IsStdAbs = IsStdFunction(FDecl, "abs");
Richard Trieubeffb832014-04-15 23:47:53 +00007161 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007162 return;
7163
7164 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7165 QualType ParamType = Call->getArg(0)->getType();
7166
Alp Toker5d96e0a2014-07-11 20:53:51 +00007167 // Unsigned types cannot be negative. Suggest removing the absolute value
7168 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007169 if (ArgType->isUnsignedIntegerType()) {
Mehdi Amini7186a432016-10-11 19:04:24 +00007170 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00007171 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007172 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
7173 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00007174 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007175 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
7176 return;
7177 }
7178
David Majnemer7f77eb92015-11-15 03:04:34 +00007179 // Taking the absolute value of a pointer is very suspicious, they probably
7180 // wanted to index into an array, dereference a pointer, call a function, etc.
7181 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
7182 unsigned DiagType = 0;
7183 if (ArgType->isFunctionType())
7184 DiagType = 1;
7185 else if (ArgType->isArrayType())
7186 DiagType = 2;
7187
7188 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
7189 return;
7190 }
7191
Richard Trieubeffb832014-04-15 23:47:53 +00007192 // std::abs has overloads which prevent most of the absolute value problems
7193 // from occurring.
7194 if (IsStdAbs)
7195 return;
7196
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007197 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
7198 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
7199
7200 // The argument and parameter are the same kind. Check if they are the right
7201 // size.
7202 if (ArgValueKind == ParamValueKind) {
7203 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
7204 return;
7205
7206 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
7207 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
7208 << FDecl << ArgType << ParamType;
7209
7210 if (NewAbsKind == 0)
7211 return;
7212
7213 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00007214 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007215 return;
7216 }
7217
7218 // ArgValueKind != ParamValueKind
7219 // The wrong type of absolute value function was used. Attempt to find the
7220 // proper one.
7221 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
7222 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
7223 if (NewAbsKind == 0)
7224 return;
7225
7226 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
7227 << FDecl << ParamValueKind << ArgValueKind;
7228
7229 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00007230 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007231}
7232
Richard Trieu67c00712016-12-05 23:41:46 +00007233//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
Richard Trieua7f30b12016-12-06 01:42:28 +00007234void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
7235 const FunctionDecl *FDecl) {
Richard Trieu67c00712016-12-05 23:41:46 +00007236 if (!Call || !FDecl) return;
7237
7238 // Ignore template specializations and macros.
Richard Smith51ec0cf2017-02-21 01:17:38 +00007239 if (inTemplateInstantiation()) return;
Richard Trieu67c00712016-12-05 23:41:46 +00007240 if (Call->getExprLoc().isMacroID()) return;
7241
7242 // Only care about the one template argument, two function parameter std::max
7243 if (Call->getNumArgs() != 2) return;
Richard Trieua7f30b12016-12-06 01:42:28 +00007244 if (!IsStdFunction(FDecl, "max")) return;
Richard Trieu67c00712016-12-05 23:41:46 +00007245 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
7246 if (!ArgList) return;
7247 if (ArgList->size() != 1) return;
7248
7249 // Check that template type argument is unsigned integer.
7250 const auto& TA = ArgList->get(0);
7251 if (TA.getKind() != TemplateArgument::Type) return;
7252 QualType ArgType = TA.getAsType();
7253 if (!ArgType->isUnsignedIntegerType()) return;
7254
7255 // See if either argument is a literal zero.
7256 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
7257 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
7258 if (!MTE) return false;
7259 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
7260 if (!Num) return false;
7261 if (Num->getValue() != 0) return false;
7262 return true;
7263 };
7264
7265 const Expr *FirstArg = Call->getArg(0);
7266 const Expr *SecondArg = Call->getArg(1);
7267 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
7268 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
7269
7270 // Only warn when exactly one argument is zero.
7271 if (IsFirstArgZero == IsSecondArgZero) return;
7272
7273 SourceRange FirstRange = FirstArg->getSourceRange();
7274 SourceRange SecondRange = SecondArg->getSourceRange();
7275
7276 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
7277
7278 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
7279 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
7280
7281 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
7282 SourceRange RemovalRange;
7283 if (IsFirstArgZero) {
7284 RemovalRange = SourceRange(FirstRange.getBegin(),
7285 SecondRange.getBegin().getLocWithOffset(-1));
7286 } else {
7287 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
7288 SecondRange.getEnd());
7289 }
7290
7291 Diag(Call->getExprLoc(), diag::note_remove_max_call)
7292 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
7293 << FixItHint::CreateRemoval(RemovalRange);
7294}
7295
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007296//===--- CHECK: Standard memory functions ---------------------------------===//
7297
Nico Weber0e6daef2013-12-26 23:38:39 +00007298/// \brief Takes the expression passed to the size_t parameter of functions
7299/// such as memcmp, strncat, etc and warns if it's a comparison.
7300///
7301/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
7302static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
7303 IdentifierInfo *FnName,
7304 SourceLocation FnLoc,
7305 SourceLocation RParenLoc) {
7306 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
7307 if (!Size)
7308 return false;
7309
Richard Smithc70f1d62017-12-14 15:16:18 +00007310 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
7311 if (!Size->isComparisonOp() && !Size->isLogicalOp())
Nico Weber0e6daef2013-12-26 23:38:39 +00007312 return false;
7313
Nico Weber0e6daef2013-12-26 23:38:39 +00007314 SourceRange SizeRange = Size->getSourceRange();
7315 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
7316 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00007317 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007318 << FnName << FixItHint::CreateInsertion(
7319 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00007320 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00007321 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00007322 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00007323 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
7324 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00007325
7326 return true;
7327}
7328
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007329/// \brief Determine whether the given type is or contains a dynamic class type
7330/// (e.g., whether it has a vtable).
7331static const CXXRecordDecl *getContainedDynamicClass(QualType T,
7332 bool &IsContained) {
7333 // Look through array types while ignoring qualifiers.
7334 const Type *Ty = T->getBaseElementTypeUnsafe();
7335 IsContained = false;
7336
7337 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
7338 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00007339 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007340 return nullptr;
7341
7342 if (RD->isDynamicClass())
7343 return RD;
7344
7345 // Check all the fields. If any bases were dynamic, the class is dynamic.
7346 // It's impossible for a class to transitively contain itself by value, so
7347 // infinite recursion is impossible.
7348 for (auto *FD : RD->fields()) {
7349 bool SubContained;
7350 if (const CXXRecordDecl *ContainedRD =
7351 getContainedDynamicClass(FD->getType(), SubContained)) {
7352 IsContained = true;
7353 return ContainedRD;
7354 }
7355 }
7356
7357 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00007358}
7359
Chandler Carruth889ed862011-06-21 23:04:20 +00007360/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007361/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00007362static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00007363 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007364 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007365 if (SizeOf->getKind() == UETT_SizeOf && !SizeOf->isArgumentType())
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007366 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007367
Craig Topperc3ec1492014-05-26 06:22:03 +00007368 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007369}
7370
Chandler Carruth889ed862011-06-21 23:04:20 +00007371/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00007372static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007373 if (const UnaryExprOrTypeTraitExpr *SizeOf =
7374 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007375 if (SizeOf->getKind() == UETT_SizeOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007376 return SizeOf->getTypeOfArgument();
7377
7378 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00007379}
7380
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007381/// \brief Check for dangerous or invalid arguments to memset().
7382///
Chandler Carruthac687262011-06-03 06:23:57 +00007383/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007384/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
7385/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007386///
7387/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007388void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00007389 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007390 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00007391 assert(BId != 0);
7392
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007393 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00007394 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007395 unsigned ExpectedNumArgs =
7396 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00007397 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007398 return;
7399
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007400 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00007401 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007402 unsigned LenArg =
7403 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00007404 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007405
Nico Weber0e6daef2013-12-26 23:38:39 +00007406 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
7407 Call->getLocStart(), Call->getRParenLoc()))
7408 return;
7409
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007410 // We have special checking when the length is a sizeof expression.
7411 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
7412 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
7413 llvm::FoldingSetNodeID SizeOfArgID;
7414
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00007415 // Although widely used, 'bzero' is not a standard function. Be more strict
7416 // with the argument types before allowing diagnostics and only allow the
7417 // form bzero(ptr, sizeof(...)).
7418 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7419 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
7420 return;
7421
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007422 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7423 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007424 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007425
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007426 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00007427 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007428 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00007429 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00007430
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007431 // Never warn about void type pointers. This can be used to suppress
7432 // false positives.
7433 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007434 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007435
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007436 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
7437 // actually comparing the expressions for equality. Because computing the
7438 // expression IDs can be expensive, we only do this if the diagnostic is
7439 // enabled.
7440 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007441 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
7442 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007443 // We only compute IDs for expressions if the warning is enabled, and
7444 // cache the sizeof arg's ID.
7445 if (SizeOfArgID == llvm::FoldingSetNodeID())
7446 SizeOfArg->Profile(SizeOfArgID, Context, true);
7447 llvm::FoldingSetNodeID DestID;
7448 Dest->Profile(DestID, Context, true);
7449 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00007450 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
7451 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007452 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00007453 StringRef ReadableName = FnName->getName();
7454
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007455 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00007456 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007457 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00007458 if (!PointeeTy->isIncompleteType() &&
7459 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007460 ActionIdx = 2; // If the pointee's size is sizeof(char),
7461 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00007462
7463 // If the function is defined as a builtin macro, do not show macro
7464 // expansion.
7465 SourceLocation SL = SizeOfArg->getExprLoc();
7466 SourceRange DSR = Dest->getSourceRange();
7467 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007468 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00007469
7470 if (SM.isMacroArgExpansion(SL)) {
7471 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7472 SL = SM.getSpellingLoc(SL);
7473 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7474 SM.getSpellingLoc(DSR.getEnd()));
7475 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7476 SM.getSpellingLoc(SSR.getEnd()));
7477 }
7478
Anna Zaksd08d9152012-05-30 23:14:52 +00007479 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007480 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00007481 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00007482 << PointeeTy
7483 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00007484 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00007485 << SSR);
7486 DiagRuntimeBehavior(SL, SizeOfArg,
7487 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7488 << ActionIdx
7489 << SSR);
7490
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007491 break;
7492 }
7493 }
7494
7495 // Also check for cases where the sizeof argument is the exact same
7496 // type as the memory argument, and where it points to a user-defined
7497 // record type.
7498 if (SizeOfArgTy != QualType()) {
7499 if (PointeeTy->isRecordType() &&
7500 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7501 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7502 PDiag(diag::warn_sizeof_pointer_type_memaccess)
7503 << FnName << SizeOfArgTy << ArgIdx
7504 << PointeeTy << Dest->getSourceRange()
7505 << LenExpr->getSourceRange());
7506 break;
7507 }
Nico Weberc5e73862011-06-14 16:14:58 +00007508 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00007509 } else if (DestTy->isArrayType()) {
7510 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00007511 }
Nico Weberc5e73862011-06-14 16:14:58 +00007512
Nico Weberc44b35e2015-03-21 17:37:46 +00007513 if (PointeeTy == QualType())
7514 continue;
Anna Zaks22122702012-01-17 00:37:07 +00007515
Nico Weberc44b35e2015-03-21 17:37:46 +00007516 // Always complain about dynamic classes.
7517 bool IsContained;
7518 if (const CXXRecordDecl *ContainedRD =
7519 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00007520
Nico Weberc44b35e2015-03-21 17:37:46 +00007521 unsigned OperationType = 0;
7522 // "overwritten" if we're warning about the destination for any call
7523 // but memcmp; otherwise a verb appropriate to the call.
7524 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7525 if (BId == Builtin::BImemcpy)
7526 OperationType = 1;
7527 else if(BId == Builtin::BImemmove)
7528 OperationType = 2;
7529 else if (BId == Builtin::BImemcmp)
7530 OperationType = 3;
7531 }
7532
John McCall31168b02011-06-15 23:02:42 +00007533 DiagRuntimeBehavior(
7534 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00007535 PDiag(diag::warn_dyn_class_memaccess)
7536 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7537 << FnName << IsContained << ContainedRD << OperationType
7538 << Call->getCallee()->getSourceRange());
7539 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7540 BId != Builtin::BImemset)
7541 DiagRuntimeBehavior(
7542 Dest->getExprLoc(), Dest,
7543 PDiag(diag::warn_arc_object_memaccess)
7544 << ArgIdx << FnName << PointeeTy
7545 << Call->getCallee()->getSourceRange());
7546 else
7547 continue;
7548
7549 DiagRuntimeBehavior(
7550 Dest->getExprLoc(), Dest,
7551 PDiag(diag::note_bad_memaccess_silence)
7552 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7553 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007554 }
7555}
7556
Ted Kremenek6865f772011-08-18 20:55:45 +00007557// A little helper routine: ignore addition and subtraction of integer literals.
7558// This intentionally does not ignore all integer constant expressions because
7559// we don't want to remove sizeof().
7560static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7561 Ex = Ex->IgnoreParenCasts();
7562
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007563 while (true) {
Ted Kremenek6865f772011-08-18 20:55:45 +00007564 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7565 if (!BO || !BO->isAdditiveOp())
7566 break;
7567
7568 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7569 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7570
7571 if (isa<IntegerLiteral>(RHS))
7572 Ex = LHS;
7573 else if (isa<IntegerLiteral>(LHS))
7574 Ex = RHS;
7575 else
7576 break;
7577 }
7578
7579 return Ex;
7580}
7581
Anna Zaks13b08572012-08-08 21:42:23 +00007582static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7583 ASTContext &Context) {
7584 // Only handle constant-sized or VLAs, but not flexible members.
7585 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7586 // Only issue the FIXIT for arrays of size > 1.
7587 if (CAT->getSize().getSExtValue() <= 1)
7588 return false;
7589 } else if (!Ty->isVariableArrayType()) {
7590 return false;
7591 }
7592 return true;
7593}
7594
Ted Kremenek6865f772011-08-18 20:55:45 +00007595// Warn if the user has made the 'size' argument to strlcpy or strlcat
7596// be the size of the source, instead of the destination.
7597void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7598 IdentifierInfo *FnName) {
7599
7600 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00007601 unsigned NumArgs = Call->getNumArgs();
7602 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00007603 return;
7604
7605 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7606 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00007607 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00007608
7609 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7610 Call->getLocStart(), Call->getRParenLoc()))
7611 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00007612
7613 // Look for 'strlcpy(dst, x, sizeof(x))'
7614 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7615 CompareWithSrc = Ex;
7616 else {
7617 // Look for 'strlcpy(dst, x, strlen(x))'
7618 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00007619 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7620 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00007621 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7622 }
7623 }
7624
7625 if (!CompareWithSrc)
7626 return;
7627
7628 // Determine if the argument to sizeof/strlen is equal to the source
7629 // argument. In principle there's all kinds of things you could do
7630 // here, for instance creating an == expression and evaluating it with
7631 // EvaluateAsBooleanCondition, but this uses a more direct technique:
7632 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7633 if (!SrcArgDRE)
7634 return;
7635
7636 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7637 if (!CompareWithSrcDRE ||
7638 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7639 return;
7640
7641 const Expr *OriginalSizeArg = Call->getArg(2);
7642 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7643 << OriginalSizeArg->getSourceRange() << FnName;
7644
7645 // Output a FIXIT hint if the destination is an array (rather than a
7646 // pointer to an array). This could be enhanced to handle some
7647 // pointers if we know the actual size, like if DstArg is 'array+2'
7648 // we could say 'sizeof(array)-2'.
7649 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00007650 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00007651 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007652
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007653 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007654 llvm::raw_svector_ostream OS(sizeString);
7655 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007656 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00007657 OS << ")";
7658
7659 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7660 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7661 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00007662}
7663
Anna Zaks314cd092012-02-01 19:08:57 +00007664/// Check if two expressions refer to the same declaration.
7665static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7666 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7667 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7668 return D1->getDecl() == D2->getDecl();
7669 return false;
7670}
7671
7672static const Expr *getStrlenExprArg(const Expr *E) {
7673 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7674 const FunctionDecl *FD = CE->getDirectCallee();
7675 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00007676 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007677 return CE->getArg(0)->IgnoreParenCasts();
7678 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007679 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007680}
7681
7682// Warn on anti-patterns as the 'size' argument to strncat.
7683// The correct size argument should look like following:
7684// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7685void Sema::CheckStrncatArguments(const CallExpr *CE,
7686 IdentifierInfo *FnName) {
7687 // Don't crash if the user has the wrong number of arguments.
7688 if (CE->getNumArgs() < 3)
7689 return;
7690 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7691 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7692 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7693
Nico Weber0e6daef2013-12-26 23:38:39 +00007694 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7695 CE->getRParenLoc()))
7696 return;
7697
Anna Zaks314cd092012-02-01 19:08:57 +00007698 // Identify common expressions, which are wrongly used as the size argument
7699 // to strncat and may lead to buffer overflows.
7700 unsigned PatternType = 0;
7701 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7702 // - sizeof(dst)
7703 if (referToTheSameDecl(SizeOfArg, DstArg))
7704 PatternType = 1;
7705 // - sizeof(src)
7706 else if (referToTheSameDecl(SizeOfArg, SrcArg))
7707 PatternType = 2;
7708 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7709 if (BE->getOpcode() == BO_Sub) {
7710 const Expr *L = BE->getLHS()->IgnoreParenCasts();
7711 const Expr *R = BE->getRHS()->IgnoreParenCasts();
7712 // - sizeof(dst) - strlen(dst)
7713 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7714 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7715 PatternType = 1;
7716 // - sizeof(src) - (anything)
7717 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7718 PatternType = 2;
7719 }
7720 }
7721
7722 if (PatternType == 0)
7723 return;
7724
Anna Zaks5069aa32012-02-03 01:27:37 +00007725 // Generate the diagnostic.
7726 SourceLocation SL = LenArg->getLocStart();
7727 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007728 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00007729
7730 // If the function is defined as a builtin macro, do not show macro expansion.
7731 if (SM.isMacroArgExpansion(SL)) {
7732 SL = SM.getSpellingLoc(SL);
7733 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7734 SM.getSpellingLoc(SR.getEnd()));
7735 }
7736
Anna Zaks13b08572012-08-08 21:42:23 +00007737 // Check if the destination is an array (rather than a pointer to an array).
7738 QualType DstTy = DstArg->getType();
7739 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7740 Context);
7741 if (!isKnownSizeArray) {
7742 if (PatternType == 1)
7743 Diag(SL, diag::warn_strncat_wrong_size) << SR;
7744 else
7745 Diag(SL, diag::warn_strncat_src_size) << SR;
7746 return;
7747 }
7748
Anna Zaks314cd092012-02-01 19:08:57 +00007749 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00007750 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007751 else
Anna Zaks5069aa32012-02-03 01:27:37 +00007752 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007753
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007754 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00007755 llvm::raw_svector_ostream OS(sizeString);
7756 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007757 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007758 OS << ") - ";
7759 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007760 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007761 OS << ") - 1";
7762
Anna Zaks5069aa32012-02-03 01:27:37 +00007763 Diag(SL, diag::note_strncat_wrong_size)
7764 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00007765}
7766
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007767//===--- CHECK: Return Address of Stack Variable --------------------------===//
7768
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007769static const Expr *EvalVal(const Expr *E,
7770 SmallVectorImpl<const DeclRefExpr *> &refVars,
7771 const Decl *ParentDecl);
7772static const Expr *EvalAddr(const Expr *E,
7773 SmallVectorImpl<const DeclRefExpr *> &refVars,
7774 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007775
7776/// CheckReturnStackAddr - Check if a return statement returns the address
7777/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007778static void
7779CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7780 SourceLocation ReturnLoc) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007781 const Expr *stackE = nullptr;
7782 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007783
7784 // Perform checking for returned stack addresses, local blocks,
7785 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00007786 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007787 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007788 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00007789 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007790 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007791 }
7792
Craig Topperc3ec1492014-05-26 06:22:03 +00007793 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007794 return; // Nothing suspicious was found.
7795
Simon Pilgrim750bde62017-03-31 11:00:53 +00007796 // Parameters are initialized in the calling scope, so taking the address
Richard Trieu81b6c562016-08-05 23:24:47 +00007797 // of a parameter reference doesn't need a warning.
7798 for (auto *DRE : refVars)
7799 if (isa<ParmVarDecl>(DRE->getDecl()))
7800 return;
7801
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007802 SourceLocation diagLoc;
7803 SourceRange diagRange;
7804 if (refVars.empty()) {
7805 diagLoc = stackE->getLocStart();
7806 diagRange = stackE->getSourceRange();
7807 } else {
7808 // We followed through a reference variable. 'stackE' contains the
7809 // problematic expression but we will warn at the return statement pointing
7810 // at the reference variable. We will later display the "trail" of
7811 // reference variables using notes.
7812 diagLoc = refVars[0]->getLocStart();
7813 diagRange = refVars[0]->getSourceRange();
7814 }
7815
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007816 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7817 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00007818 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007819 << DR->getDecl()->getDeclName() << diagRange;
7820 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007821 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007822 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007823 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007824 } else { // local temporary.
Richard Trieu81b6c562016-08-05 23:24:47 +00007825 // If there is an LValue->RValue conversion, then the value of the
7826 // reference type is used, not the reference.
7827 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7828 if (ICE->getCastKind() == CK_LValueToRValue) {
7829 return;
7830 }
7831 }
Craig Topperda7b27f2015-11-17 05:40:09 +00007832 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7833 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007834 }
7835
7836 // Display the "trail" of reference variables that we followed until we
7837 // found the problematic expression using notes.
7838 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007839 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007840 // If this var binds to another reference var, show the range of the next
7841 // var, otherwise the var binds to the problematic expression, in which case
7842 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007843 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7844 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007845 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7846 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007847 }
7848}
7849
7850/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7851/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007852/// to a location on the stack, a local block, an address of a label, or a
7853/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007854/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007855/// encounter a subexpression that (1) clearly does not lead to one of the
7856/// above problematic expressions (2) is something we cannot determine leads to
7857/// a problematic expression based on such local checking.
7858///
7859/// Both EvalAddr and EvalVal follow through reference variables to evaluate
7860/// the expression that they point to. Such variables are added to the
7861/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007862///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00007863/// EvalAddr processes expressions that are pointers that are used as
7864/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007865/// At the base case of the recursion is a check for the above problematic
7866/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007867///
7868/// This implementation handles:
7869///
7870/// * pointer-to-pointer casts
7871/// * implicit conversions from array references to pointers
7872/// * taking the address of fields
7873/// * arbitrary interplay between "&" and "*" operators
7874/// * pointer arithmetic from an address of a stack variable
7875/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007876static const Expr *EvalAddr(const Expr *E,
7877 SmallVectorImpl<const DeclRefExpr *> &refVars,
7878 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007879 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00007880 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007881
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007882 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00007883 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00007884 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007885 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00007886 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00007887
Peter Collingbourne91147592011-04-15 00:35:48 +00007888 E = E->IgnoreParens();
7889
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007890 // Our "symbolic interpreter" is just a dispatch off the currently
7891 // viewed AST node. We then recursively traverse the AST by calling
7892 // EvalAddr and EvalVal appropriately.
7893 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007894 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007895 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007896
Richard Smith40f08eb2014-01-30 22:05:38 +00007897 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00007898 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00007899 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00007900
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007901 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007902 // If this is a reference variable, follow through to the expression that
7903 // it points to.
7904 if (V->hasLocalStorage() &&
7905 V->getType()->isReferenceType() && V->hasInit()) {
7906 // Add the reference variable to the "trail".
7907 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007908 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007909 }
7910
Craig Topperc3ec1492014-05-26 06:22:03 +00007911 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007912 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007913
Chris Lattner934edb22007-12-28 05:31:15 +00007914 case Stmt::UnaryOperatorClass: {
7915 // The only unary operator that make sense to handle here
7916 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007917 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007918
John McCalle3027922010-08-25 11:45:40 +00007919 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007920 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007921 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007922 }
Mike Stump11289f42009-09-09 15:08:12 +00007923
Chris Lattner934edb22007-12-28 05:31:15 +00007924 case Stmt::BinaryOperatorClass: {
7925 // Handle pointer arithmetic. All other binary operators are not valid
7926 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007927 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00007928 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00007929
John McCalle3027922010-08-25 11:45:40 +00007930 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00007931 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007932
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007933 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00007934
7935 // Determine which argument is the real pointer base. It could be
7936 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007937 if (!Base->getType()->isPointerType())
7938 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00007939
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007940 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007941 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007942 }
Steve Naroff2752a172008-09-10 19:17:48 +00007943
Chris Lattner934edb22007-12-28 05:31:15 +00007944 // For conditional operators we need to see if either the LHS or RHS are
7945 // valid DeclRefExpr*s. If one of them is valid, we return it.
7946 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007947 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007948
Chris Lattner934edb22007-12-28 05:31:15 +00007949 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007950 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007951 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007952 // In C++, we can have a throw-expression, which has 'void' type.
7953 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007954 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007955 return LHS;
7956 }
Chris Lattner934edb22007-12-28 05:31:15 +00007957
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007958 // In C++, we can have a throw-expression, which has 'void' type.
7959 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00007960 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007961
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007962 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007963 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007964
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007965 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00007966 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007967 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00007968 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007969
7970 case Stmt::AddrLabelExprClass:
7971 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00007972
John McCall28fc7092011-11-10 05:35:25 +00007973 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007974 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7975 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00007976
Ted Kremenekc3b4c522008-08-07 00:49:01 +00007977 // For casts, we need to handle conversions from arrays to
7978 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00007979 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00007980 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00007981 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00007982 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00007983 case Stmt::CXXStaticCastExprClass:
7984 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00007985 case Stmt::CXXConstCastExprClass:
7986 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007987 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00007988 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00007989 case CK_LValueToRValue:
7990 case CK_NoOp:
7991 case CK_BaseToDerived:
7992 case CK_DerivedToBase:
7993 case CK_UncheckedDerivedToBase:
7994 case CK_Dynamic:
7995 case CK_CPointerToObjCPointerCast:
7996 case CK_BlockPointerToObjCPointerCast:
7997 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007998 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007999
8000 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008001 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00008002
Richard Trieudadefde2014-07-02 04:39:38 +00008003 case CK_BitCast:
8004 if (SubExpr->getType()->isAnyPointerType() ||
8005 SubExpr->getType()->isBlockPointerType() ||
8006 SubExpr->getType()->isObjCQualifiedIdType())
8007 return EvalAddr(SubExpr, refVars, ParentDecl);
8008 else
8009 return nullptr;
8010
Eli Friedman8195ad72012-02-23 23:04:32 +00008011 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00008012 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00008013 }
Chris Lattner934edb22007-12-28 05:31:15 +00008014 }
Mike Stump11289f42009-09-09 15:08:12 +00008015
Douglas Gregorfe314812011-06-21 17:03:29 +00008016 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008017 if (const Expr *Result =
8018 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8019 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00008020 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00008021 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008022
Chris Lattner934edb22007-12-28 05:31:15 +00008023 // Everything else: we simply don't reason about them.
8024 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00008025 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00008026 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008027}
Mike Stump11289f42009-09-09 15:08:12 +00008028
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008029/// EvalVal - This function is complements EvalAddr in the mutual recursion.
8030/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008031static const Expr *EvalVal(const Expr *E,
8032 SmallVectorImpl<const DeclRefExpr *> &refVars,
8033 const Decl *ParentDecl) {
8034 do {
8035 // We should only be called for evaluating non-pointer expressions, or
8036 // expressions with a pointer type that are not used as references but
8037 // instead
8038 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00008039
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008040 // Our "symbolic interpreter" is just a dispatch off the currently
8041 // viewed AST node. We then recursively traverse the AST by calling
8042 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00008043
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008044 E = E->IgnoreParens();
8045 switch (E->getStmtClass()) {
8046 case Stmt::ImplicitCastExprClass: {
8047 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
8048 if (IE->getValueKind() == VK_LValue) {
8049 E = IE->getSubExpr();
8050 continue;
8051 }
Craig Topperc3ec1492014-05-26 06:22:03 +00008052 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008053 }
Richard Smith40f08eb2014-01-30 22:05:38 +00008054
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008055 case Stmt::ExprWithCleanupsClass:
8056 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
8057 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008058
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008059 case Stmt::DeclRefExprClass: {
8060 // When we hit a DeclRefExpr we are looking at code that refers to a
8061 // variable's name. If it's not a reference variable we check if it has
8062 // local storage within the function, and if so, return the expression.
8063 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
8064
8065 // If we leave the immediate function, the lifetime isn't about to end.
8066 if (DR->refersToEnclosingVariableOrCapture())
8067 return nullptr;
8068
8069 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
8070 // Check if it refers to itself, e.g. "int& i = i;".
8071 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008072 return DR;
8073
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008074 if (V->hasLocalStorage()) {
8075 if (!V->getType()->isReferenceType())
8076 return DR;
8077
8078 // Reference variable, follow through to the expression that
8079 // it points to.
8080 if (V->hasInit()) {
8081 // Add the reference variable to the "trail".
8082 refVars.push_back(DR);
8083 return EvalVal(V->getInit(), refVars, V);
8084 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008085 }
8086 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008087
8088 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008089 }
Mike Stump11289f42009-09-09 15:08:12 +00008090
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008091 case Stmt::UnaryOperatorClass: {
8092 // The only unary operator that make sense to handle here
8093 // is Deref. All others don't resolve to a "name." This includes
8094 // handling all sorts of rvalues passed to a unary operator.
8095 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00008096
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008097 if (U->getOpcode() == UO_Deref)
8098 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00008099
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008100 return nullptr;
8101 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008102
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008103 case Stmt::ArraySubscriptExprClass: {
8104 // Array subscripts are potential references to data on the stack. We
8105 // retrieve the DeclRefExpr* for the array variable if it indeed
8106 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00008107 const auto *ASE = cast<ArraySubscriptExpr>(E);
8108 if (ASE->isTypeDependent())
8109 return nullptr;
8110 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008111 }
Mike Stump11289f42009-09-09 15:08:12 +00008112
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008113 case Stmt::OMPArraySectionExprClass: {
8114 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
8115 ParentDecl);
8116 }
Mike Stump11289f42009-09-09 15:08:12 +00008117
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008118 case Stmt::ConditionalOperatorClass: {
8119 // For conditional operators we need to see if either the LHS or RHS are
8120 // non-NULL Expr's. If one is non-NULL, we return it.
8121 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00008122
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008123 // Handle the GNU extension for missing LHS.
8124 if (const Expr *LHSExpr = C->getLHS()) {
8125 // In C++, we can have a throw-expression, which has 'void' type.
8126 if (!LHSExpr->getType()->isVoidType())
8127 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
8128 return LHS;
8129 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008130
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008131 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008132 if (C->getRHS()->getType()->isVoidType())
8133 return nullptr;
8134
8135 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008136 }
8137
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008138 // Accesses to members are potential references to data on the stack.
8139 case Stmt::MemberExprClass: {
8140 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00008141
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008142 // Check for indirect access. We only want direct field accesses.
8143 if (M->isArrow())
8144 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008145
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008146 // Check whether the member type is itself a reference, in which case
8147 // we're not going to refer to the member, but to what the member refers
8148 // to.
8149 if (M->getMemberDecl()->getType()->isReferenceType())
8150 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008151
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008152 return EvalVal(M->getBase(), refVars, ParentDecl);
8153 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00008154
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008155 case Stmt::MaterializeTemporaryExprClass:
8156 if (const Expr *Result =
8157 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8158 refVars, ParentDecl))
8159 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008160 return E;
8161
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008162 default:
8163 // Check that we don't return or take the address of a reference to a
8164 // temporary. This is only useful in C++.
8165 if (!E->isTypeDependent() && E->isRValue())
8166 return E;
8167
8168 // Everything else: we simply don't reason about them.
8169 return nullptr;
8170 }
8171 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008172}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008173
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008174void
8175Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
8176 SourceLocation ReturnLoc,
8177 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00008178 const AttrVec *Attrs,
8179 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008180 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
8181
8182 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00008183 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
8184 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00008185 CheckNonNullExpr(*this, RetValExp))
8186 Diag(ReturnLoc, diag::warn_null_ret)
8187 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00008188
8189 // C++11 [basic.stc.dynamic.allocation]p4:
8190 // If an allocation function declared with a non-throwing
8191 // exception-specification fails to allocate storage, it shall return
8192 // a null pointer. Any other allocation function that fails to allocate
8193 // storage shall indicate failure only by throwing an exception [...]
8194 if (FD) {
8195 OverloadedOperatorKind Op = FD->getOverloadedOperator();
8196 if (Op == OO_New || Op == OO_Array_New) {
8197 const FunctionProtoType *Proto
8198 = FD->getType()->castAs<FunctionProtoType>();
8199 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
8200 CheckNonNullExpr(*this, RetValExp))
8201 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
8202 << FD << getLangOpts().CPlusPlus11;
8203 }
8204 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008205}
8206
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008207//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
8208
8209/// Check for comparisons of floating point operands using != and ==.
8210/// Issue a warning if these are no self-comparisons, as they are not likely
8211/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00008212void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00008213 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
8214 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008215
8216 // Special case: check for x == x (which is OK).
8217 // Do not emit warnings for such cases.
8218 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
8219 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
8220 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00008221 return;
Mike Stump11289f42009-09-09 15:08:12 +00008222
Ted Kremenekeda40e22007-11-29 00:59:04 +00008223 // Special case: check for comparisons against literals that can be exactly
8224 // represented by APFloat. In such cases, do not emit a warning. This
8225 // is a heuristic: often comparison against such literals are used to
8226 // detect if a value in a variable has not changed. This clearly can
8227 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00008228 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
8229 if (FLL->isExact())
8230 return;
8231 } else
8232 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
8233 if (FLR->isExact())
8234 return;
Mike Stump11289f42009-09-09 15:08:12 +00008235
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008236 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00008237 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00008238 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00008239 return;
Mike Stump11289f42009-09-09 15:08:12 +00008240
David Blaikie1f4ff152012-07-16 20:47:22 +00008241 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00008242 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00008243 return;
Mike Stump11289f42009-09-09 15:08:12 +00008244
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008245 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00008246 Diag(Loc, diag::warn_floatingpoint_eq)
8247 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008248}
John McCallca01b222010-01-04 23:21:16 +00008249
John McCall70aa5392010-01-06 05:24:50 +00008250//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
8251//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00008252
John McCall70aa5392010-01-06 05:24:50 +00008253namespace {
John McCallca01b222010-01-04 23:21:16 +00008254
John McCall70aa5392010-01-06 05:24:50 +00008255/// Structure recording the 'active' range of an integer-valued
8256/// expression.
8257struct IntRange {
8258 /// The number of bits active in the int.
8259 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00008260
John McCall70aa5392010-01-06 05:24:50 +00008261 /// True if the int is known not to have negative values.
8262 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00008263
John McCall70aa5392010-01-06 05:24:50 +00008264 IntRange(unsigned Width, bool NonNegative)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008265 : Width(Width), NonNegative(NonNegative) {}
John McCallca01b222010-01-04 23:21:16 +00008266
John McCall817d4af2010-11-10 23:38:19 +00008267 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00008268 static IntRange forBoolType() {
8269 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00008270 }
8271
John McCall817d4af2010-11-10 23:38:19 +00008272 /// Returns the range of an opaque value of the given integral type.
8273 static IntRange forValueOfType(ASTContext &C, QualType T) {
8274 return forValueOfCanonicalType(C,
8275 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00008276 }
8277
John McCall817d4af2010-11-10 23:38:19 +00008278 /// Returns the range of an opaque value of a canonical integral type.
8279 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00008280 assert(T->isCanonicalUnqualified());
8281
8282 if (const VectorType *VT = dyn_cast<VectorType>(T))
8283 T = VT->getElementType().getTypePtr();
8284 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8285 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008286 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8287 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00008288
Roman Lebedevca1aaac2017-10-21 16:44:03 +00008289 if (!C.getLangOpts().CPlusPlus) {
8290 // For enum types in C code, use the underlying datatype.
8291 if (const EnumType *ET = dyn_cast<EnumType>(T))
8292 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
8293 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
8294 // For enum types in C++, use the known bit width of the enumerators.
David Majnemer6a426652013-06-07 22:07:20 +00008295 EnumDecl *Enum = ET->getDecl();
Richard Smith371e9e8a2017-12-06 03:00:51 +00008296 // In C++11, enums can have a fixed underlying type. Use this type to
8297 // compute the range.
8298 if (Enum->isFixed()) {
Erich Keane69dbbb02017-09-21 19:58:55 +00008299 return IntRange(C.getIntWidth(QualType(T, 0)),
8300 !ET->isSignedIntegerOrEnumerationType());
Richard Smith371e9e8a2017-12-06 03:00:51 +00008301 }
John McCall18a2c2c2010-11-09 22:22:12 +00008302
David Majnemer6a426652013-06-07 22:07:20 +00008303 unsigned NumPositive = Enum->getNumPositiveBits();
8304 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00008305
David Majnemer6a426652013-06-07 22:07:20 +00008306 if (NumNegative == 0)
8307 return IntRange(NumPositive, true/*NonNegative*/);
8308 else
8309 return IntRange(std::max(NumPositive + 1, NumNegative),
8310 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00008311 }
John McCall70aa5392010-01-06 05:24:50 +00008312
8313 const BuiltinType *BT = cast<BuiltinType>(T);
8314 assert(BT->isInteger());
8315
8316 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8317 }
8318
John McCall817d4af2010-11-10 23:38:19 +00008319 /// Returns the "target" range of a canonical integral type, i.e.
8320 /// the range of values expressible in the type.
8321 ///
8322 /// This matches forValueOfCanonicalType except that enums have the
8323 /// full range of their type, not the range of their enumerators.
8324 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
8325 assert(T->isCanonicalUnqualified());
8326
8327 if (const VectorType *VT = dyn_cast<VectorType>(T))
8328 T = VT->getElementType().getTypePtr();
8329 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8330 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008331 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8332 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008333 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00008334 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008335
8336 const BuiltinType *BT = cast<BuiltinType>(T);
8337 assert(BT->isInteger());
8338
8339 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8340 }
8341
8342 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00008343 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00008344 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00008345 L.NonNegative && R.NonNegative);
8346 }
8347
John McCall817d4af2010-11-10 23:38:19 +00008348 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00008349 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00008350 return IntRange(std::min(L.Width, R.Width),
8351 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00008352 }
8353};
8354
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008355} // namespace
8356
8357static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
8358 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008359 if (value.isSigned() && value.isNegative())
8360 return IntRange(value.getMinSignedBits(), false);
8361
8362 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00008363 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008364
8365 // isNonNegative() just checks the sign bit without considering
8366 // signedness.
8367 return IntRange(value.getActiveBits(), true);
8368}
8369
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008370static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
8371 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008372 if (result.isInt())
8373 return GetValueRange(C, result.getInt(), MaxWidth);
8374
8375 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00008376 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
8377 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
8378 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
8379 R = IntRange::join(R, El);
8380 }
John McCall70aa5392010-01-06 05:24:50 +00008381 return R;
8382 }
8383
8384 if (result.isComplexInt()) {
8385 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
8386 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
8387 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00008388 }
8389
8390 // This can happen with lossless casts to intptr_t of "based" lvalues.
8391 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00008392 // FIXME: The only reason we need to pass the type in here is to get
8393 // the sign right on this one case. It would be nice if APValue
8394 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008395 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00008396 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00008397}
John McCall70aa5392010-01-06 05:24:50 +00008398
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008399static QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008400 QualType Ty = E->getType();
8401 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
8402 Ty = AtomicRHS->getValueType();
8403 return Ty;
8404}
8405
John McCall70aa5392010-01-06 05:24:50 +00008406/// Pseudo-evaluate the given integer expression, estimating the
8407/// range of values it might take.
8408///
8409/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008410static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008411 E = E->IgnoreParens();
8412
8413 // Try a full evaluation first.
8414 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00008415 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00008416 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008417
8418 // I think we only want to look through implicit casts here; if the
8419 // user has an explicit widening cast, we should treat the value as
8420 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008421 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00008422 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00008423 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
8424
Eli Friedmane6d33952013-07-08 20:20:06 +00008425 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00008426
George Burgess IVdf1ed002016-01-13 01:52:39 +00008427 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
8428 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00008429
John McCall70aa5392010-01-06 05:24:50 +00008430 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00008431 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00008432 return OutputTypeRange;
8433
8434 IntRange SubRange
8435 = GetExprRange(C, CE->getSubExpr(),
8436 std::min(MaxWidth, OutputTypeRange.Width));
8437
8438 // Bail out if the subexpr's range is as wide as the cast type.
8439 if (SubRange.Width >= OutputTypeRange.Width)
8440 return OutputTypeRange;
8441
8442 // Otherwise, we take the smaller width, and we're non-negative if
8443 // either the output type or the subexpr is.
8444 return IntRange(SubRange.Width,
8445 SubRange.NonNegative || OutputTypeRange.NonNegative);
8446 }
8447
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008448 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008449 // If we can fold the condition, just take that operand.
8450 bool CondResult;
8451 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
8452 return GetExprRange(C, CondResult ? CO->getTrueExpr()
8453 : CO->getFalseExpr(),
8454 MaxWidth);
8455
8456 // Otherwise, conservatively merge.
8457 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
8458 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
8459 return IntRange::join(L, R);
8460 }
8461
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008462 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008463 switch (BO->getOpcode()) {
Richard Smithc70f1d62017-12-14 15:16:18 +00008464 case BO_Cmp:
8465 llvm_unreachable("builtin <=> should have class type");
John McCall70aa5392010-01-06 05:24:50 +00008466
8467 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00008468 case BO_LAnd:
8469 case BO_LOr:
8470 case BO_LT:
8471 case BO_GT:
8472 case BO_LE:
8473 case BO_GE:
8474 case BO_EQ:
8475 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00008476 return IntRange::forBoolType();
8477
John McCallc3688382011-07-13 06:35:24 +00008478 // The type of the assignments is the type of the LHS, so the RHS
8479 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00008480 case BO_MulAssign:
8481 case BO_DivAssign:
8482 case BO_RemAssign:
8483 case BO_AddAssign:
8484 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00008485 case BO_XorAssign:
8486 case BO_OrAssign:
8487 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00008488 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00008489
John McCallc3688382011-07-13 06:35:24 +00008490 // Simple assignments just pass through the RHS, which will have
8491 // been coerced to the LHS type.
8492 case BO_Assign:
8493 // TODO: bitfields?
8494 return GetExprRange(C, BO->getRHS(), MaxWidth);
8495
John McCall70aa5392010-01-06 05:24:50 +00008496 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008497 case BO_PtrMemD:
8498 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00008499 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008500
John McCall2ce81ad2010-01-06 22:07:33 +00008501 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00008502 case BO_And:
8503 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00008504 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8505 GetExprRange(C, BO->getRHS(), MaxWidth));
8506
John McCall70aa5392010-01-06 05:24:50 +00008507 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00008508 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00008509 // ...except that we want to treat '1 << (blah)' as logically
8510 // positive. It's an important idiom.
8511 if (IntegerLiteral *I
8512 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8513 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008514 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00008515 return IntRange(R.Width, /*NonNegative*/ true);
8516 }
8517 }
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008518 LLVM_FALLTHROUGH;
John McCall1bff9932010-04-07 01:14:35 +00008519
John McCalle3027922010-08-25 11:45:40 +00008520 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00008521 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008522
John McCall2ce81ad2010-01-06 22:07:33 +00008523 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00008524 case BO_Shr:
8525 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00008526 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8527
8528 // If the shift amount is a positive constant, drop the width by
8529 // that much.
8530 llvm::APSInt shift;
8531 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8532 shift.isNonNegative()) {
8533 unsigned zext = shift.getZExtValue();
8534 if (zext >= L.Width)
8535 L.Width = (L.NonNegative ? 0 : 1);
8536 else
8537 L.Width -= zext;
8538 }
8539
8540 return L;
8541 }
8542
8543 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00008544 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00008545 return GetExprRange(C, BO->getRHS(), MaxWidth);
8546
John McCall2ce81ad2010-01-06 22:07:33 +00008547 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00008548 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00008549 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00008550 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008551 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00008552
John McCall51431812011-07-14 22:39:48 +00008553 // The width of a division result is mostly determined by the size
8554 // of the LHS.
8555 case BO_Div: {
8556 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008557 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008558 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8559
8560 // If the divisor is constant, use that.
8561 llvm::APSInt divisor;
8562 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8563 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8564 if (log2 >= L.Width)
8565 L.Width = (L.NonNegative ? 0 : 1);
8566 else
8567 L.Width = std::min(L.Width - log2, MaxWidth);
8568 return L;
8569 }
8570
8571 // Otherwise, just use the LHS's width.
8572 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8573 return IntRange(L.Width, L.NonNegative && R.NonNegative);
8574 }
8575
8576 // The result of a remainder can't be larger than the result of
8577 // either side.
8578 case BO_Rem: {
8579 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008580 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008581 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8582 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8583
8584 IntRange meet = IntRange::meet(L, R);
8585 meet.Width = std::min(meet.Width, MaxWidth);
8586 return meet;
8587 }
8588
8589 // The default behavior is okay for these.
8590 case BO_Mul:
8591 case BO_Add:
8592 case BO_Xor:
8593 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00008594 break;
8595 }
8596
John McCall51431812011-07-14 22:39:48 +00008597 // The default case is to treat the operation as if it were closed
8598 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00008599 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8600 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8601 return IntRange::join(L, R);
8602 }
8603
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008604 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008605 switch (UO->getOpcode()) {
8606 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00008607 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00008608 return IntRange::forBoolType();
8609
8610 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008611 case UO_Deref:
8612 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00008613 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008614
8615 default:
8616 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8617 }
8618 }
8619
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008620 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00008621 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8622
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008623 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00008624 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00008625 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00008626
Eli Friedmane6d33952013-07-08 20:20:06 +00008627 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008628}
John McCall263a48b2010-01-04 23:31:57 +00008629
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008630static IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008631 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00008632}
8633
John McCall263a48b2010-01-04 23:31:57 +00008634/// Checks whether the given value, which currently has the given
8635/// source semantics, has the same value when coerced through the
8636/// target semantics.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008637static bool IsSameFloatAfterCast(const llvm::APFloat &value,
8638 const llvm::fltSemantics &Src,
8639 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008640 llvm::APFloat truncated = value;
8641
8642 bool ignored;
8643 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8644 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8645
8646 return truncated.bitwiseIsEqual(value);
8647}
8648
8649/// Checks whether the given value, which currently has the given
8650/// source semantics, has the same value when coerced through the
8651/// target semantics.
8652///
8653/// The value might be a vector of floats (or a complex number).
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008654static bool IsSameFloatAfterCast(const APValue &value,
8655 const llvm::fltSemantics &Src,
8656 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008657 if (value.isFloat())
8658 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8659
8660 if (value.isVector()) {
8661 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8662 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8663 return false;
8664 return true;
8665 }
8666
8667 assert(value.isComplexFloat());
8668 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8669 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8670}
8671
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008672static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008673
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008674static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00008675 // Suppress cases where we are comparing against an enum constant.
8676 if (const DeclRefExpr *DR =
8677 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8678 if (isa<EnumConstantDecl>(DR->getDecl()))
Roman Lebedev6de129e2017-10-15 20:13:17 +00008679 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +00008680
8681 // Suppress cases where the '0' value is expanded from a macro.
8682 if (E->getLocStart().isMacroID())
Roman Lebedev6de129e2017-10-15 20:13:17 +00008683 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +00008684
Roman Lebedev6de129e2017-10-15 20:13:17 +00008685 return false;
8686}
8687
Richard Smith692f66ab2017-12-06 19:23:19 +00008688static bool isKnownToHaveUnsignedValue(Expr *E) {
8689 return E->getType()->isIntegerType() &&
Roman Lebedev6de129e2017-10-15 20:13:17 +00008690 (!E->getType()->isSignedIntegerType() ||
8691 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
8692}
8693
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008694namespace {
Richard Smitha5370fb2017-12-08 22:57:11 +00008695/// The promoted range of values of a type. In general this has the
8696/// following structure:
8697///
8698/// |-----------| . . . |-----------|
8699/// ^ ^ ^ ^
8700/// Min HoleMin HoleMax Max
8701///
8702/// ... where there is only a hole if a signed type is promoted to unsigned
8703/// (in which case Min and Max are the smallest and largest representable
8704/// values).
8705struct PromotedRange {
8706 // Min, or HoleMax if there is a hole.
8707 llvm::APSInt PromotedMin;
8708 // Max, or HoleMin if there is a hole.
8709 llvm::APSInt PromotedMax;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008710
Richard Smitha5370fb2017-12-08 22:57:11 +00008711 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
8712 if (R.Width == 0)
8713 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
8714 else if (R.Width >= BitWidth && !Unsigned) {
8715 // Promotion made the type *narrower*. This happens when promoting
8716 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
8717 // Treat all values of 'signed int' as being in range for now.
8718 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
8719 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
8720 } else {
8721 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
8722 .extOrTrunc(BitWidth);
8723 PromotedMin.setIsUnsigned(Unsigned);
8724
8725 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
8726 .extOrTrunc(BitWidth);
8727 PromotedMax.setIsUnsigned(Unsigned);
8728 }
8729 }
8730
8731 // Determine whether this range is contiguous (has no hole).
8732 bool isContiguous() const { return PromotedMin <= PromotedMax; }
8733
8734 // Where a constant value is within the range.
8735 enum ComparisonResult {
8736 LT = 0x1,
8737 LE = 0x2,
8738 GT = 0x4,
8739 GE = 0x8,
8740 EQ = 0x10,
8741 NE = 0x20,
8742 InRangeFlag = 0x40,
8743
8744 Less = LE | LT | NE,
8745 Min = LE | InRangeFlag,
8746 InRange = InRangeFlag,
8747 Max = GE | InRangeFlag,
8748 Greater = GE | GT | NE,
8749
8750 OnlyValue = LE | GE | EQ | InRangeFlag,
8751 InHole = NE
8752 };
8753
8754 ComparisonResult compare(const llvm::APSInt &Value) const {
8755 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
8756 Value.isUnsigned() == PromotedMin.isUnsigned());
8757 if (!isContiguous()) {
8758 assert(Value.isUnsigned() && "discontiguous range for signed compare");
8759 if (Value.isMinValue()) return Min;
8760 if (Value.isMaxValue()) return Max;
8761 if (Value >= PromotedMin) return InRange;
8762 if (Value <= PromotedMax) return InRange;
8763 return InHole;
8764 }
8765
8766 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
8767 case -1: return Less;
8768 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
8769 case 1:
8770 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
8771 case -1: return InRange;
8772 case 0: return Max;
8773 case 1: return Greater;
8774 }
8775 }
8776
8777 llvm_unreachable("impossible compare result");
8778 }
8779
Richard Smithc70f1d62017-12-14 15:16:18 +00008780 static llvm::Optional<StringRef>
8781 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
8782 if (Op == BO_Cmp) {
8783 ComparisonResult LTFlag = LT, GTFlag = GT;
8784 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
8785
8786 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
8787 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
8788 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
8789 return llvm::None;
8790 }
8791
Richard Smitha5370fb2017-12-08 22:57:11 +00008792 ComparisonResult TrueFlag, FalseFlag;
8793 if (Op == BO_EQ) {
8794 TrueFlag = EQ;
8795 FalseFlag = NE;
8796 } else if (Op == BO_NE) {
8797 TrueFlag = NE;
8798 FalseFlag = EQ;
8799 } else {
8800 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
8801 TrueFlag = LT;
8802 FalseFlag = GE;
8803 } else {
8804 TrueFlag = GT;
8805 FalseFlag = LE;
8806 }
8807 if (Op == BO_GE || Op == BO_LE)
8808 std::swap(TrueFlag, FalseFlag);
8809 }
8810 if (R & TrueFlag)
Richard Smithc70f1d62017-12-14 15:16:18 +00008811 return StringRef("true");
Richard Smitha5370fb2017-12-08 22:57:11 +00008812 if (R & FalseFlag)
Richard Smithc70f1d62017-12-14 15:16:18 +00008813 return StringRef("false");
Richard Smitha5370fb2017-12-08 22:57:11 +00008814 return llvm::None;
8815 }
Roman Lebedev6de129e2017-10-15 20:13:17 +00008816};
John McCallcc7e5bf2010-05-06 08:58:33 +00008817}
8818
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008819static bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00008820 // Strip off implicit integral promotions.
8821 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008822 if (ICE->getCastKind() != CK_IntegralCast &&
8823 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00008824 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008825 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00008826 }
8827
8828 return E->getType()->isEnumeralType();
8829}
8830
Richard Smith692f66ab2017-12-06 19:23:19 +00008831static int classifyConstantValue(Expr *Constant) {
8832 // The values of this enumeration are used in the diagnostics
8833 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
8834 enum ConstantValueKind {
8835 Miscellaneous = 0,
8836 LiteralTrue,
8837 LiteralFalse
8838 };
8839 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
8840 return BL->getValue() ? ConstantValueKind::LiteralTrue
8841 : ConstantValueKind::LiteralFalse;
8842 return ConstantValueKind::Miscellaneous;
8843}
8844
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008845static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
8846 Expr *Constant, Expr *Other,
8847 const llvm::APSInt &Value,
8848 bool RhsConstant) {
Hans Wennborg5bb88e02017-12-08 05:19:12 +00008849 if (S.inTemplateInstantiation())
8850 return false;
8851
Richard Smitha5370fb2017-12-08 22:57:11 +00008852 Expr *OriginalOther = Other;
8853
Hans Wennborg5bb88e02017-12-08 05:19:12 +00008854 Constant = Constant->IgnoreParenImpCasts();
8855 Other = Other->IgnoreParenImpCasts();
8856
Richard Smitha5370fb2017-12-08 22:57:11 +00008857 // Suppress warnings on tautological comparisons between values of the same
8858 // enumeration type. There are only two ways we could warn on this:
8859 // - If the constant is outside the range of representable values of
8860 // the enumeration. In such a case, we should warn about the cast
8861 // to enumeration type, not about the comparison.
8862 // - If the constant is the maximum / minimum in-range value. For an
8863 // enumeratin type, such comparisons can be meaningful and useful.
8864 if (Constant->getType()->isEnumeralType() &&
8865 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
8866 return false;
8867
Hans Wennborg5bb88e02017-12-08 05:19:12 +00008868 // TODO: Investigate using GetExprRange() to get tighter bounds
8869 // on the bit ranges.
8870 QualType OtherT = Other->getType();
8871 if (const auto *AT = OtherT->getAs<AtomicType>())
8872 OtherT = AT->getValueType();
8873 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8874
8875 // Whether we're treating Other as being a bool because of the form of
8876 // expression despite it having another type (typically 'int' in C).
8877 bool OtherIsBooleanDespiteType =
8878 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
8879 if (OtherIsBooleanDespiteType)
8880 OtherRange = IntRange::forBoolType();
8881
Richard Smitha5370fb2017-12-08 22:57:11 +00008882 // Determine the promoted range of the other type and see if a comparison of
8883 // the constant against that range is tautological.
8884 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
8885 Value.isUnsigned());
8886 auto Cmp = OtherPromotedRange.compare(Value);
8887 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
8888 if (!Result)
8889 return false;
Hans Wennborg5791ce72017-12-08 16:54:08 +00008890
Richard Smitha5370fb2017-12-08 22:57:11 +00008891 // Suppress the diagnostic for an in-range comparison if the constant comes
8892 // from a macro or enumerator. We don't want to diagnose
8893 //
8894 // some_long_value <= INT_MAX
8895 //
8896 // when sizeof(int) == sizeof(long).
8897 bool InRange = Cmp & PromotedRange::InRangeFlag;
8898 if (InRange && IsEnumConstOrFromMacro(S, Constant))
8899 return false;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008900
8901 // If this is a comparison to an enum constant, include that
8902 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00008903 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008904 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8905 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8906
Richard Smitha5370fb2017-12-08 22:57:11 +00008907 // Should be enough for uint128 (39 decimal digits)
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008908 SmallString<64> PrettySourceValue;
8909 llvm::raw_svector_ostream OS(PrettySourceValue);
8910 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00008911 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008912 else
8913 OS << Value;
8914
Richard Smitha5370fb2017-12-08 22:57:11 +00008915 // FIXME: We use a somewhat different formatting for the in-range cases and
8916 // cases involving boolean values for historical reasons. We should pick a
8917 // consistent way of presenting these diagnostics.
8918 if (!InRange || Other->isKnownToHaveBooleanValue()) {
8919 S.DiagRuntimeBehavior(
8920 E->getOperatorLoc(), E,
8921 S.PDiag(!InRange ? diag::warn_out_of_range_compare
8922 : diag::warn_tautological_bool_compare)
8923 << OS.str() << classifyConstantValue(Constant)
8924 << OtherT << OtherIsBooleanDespiteType << *Result
8925 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
8926 } else {
8927 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
8928 ? (HasEnumType(OriginalOther)
8929 ? diag::warn_unsigned_enum_always_true_comparison
8930 : diag::warn_unsigned_always_true_comparison)
8931 : diag::warn_tautological_constant_compare;
Roman Lebedev6de129e2017-10-15 20:13:17 +00008932
Richard Smitha5370fb2017-12-08 22:57:11 +00008933 S.Diag(E->getOperatorLoc(), Diag)
8934 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
8935 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8936 }
8937
8938 return true;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008939}
8940
John McCallcc7e5bf2010-05-06 08:58:33 +00008941/// Analyze the operands of the given comparison. Implements the
8942/// fallback case from AnalyzeComparison.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008943static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00008944 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8945 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00008946}
John McCall263a48b2010-01-04 23:31:57 +00008947
John McCallca01b222010-01-04 23:21:16 +00008948/// \brief Implements -Wsign-compare.
8949///
Richard Trieu82402a02011-09-15 21:56:47 +00008950/// \param E the binary operator to check for warnings
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008951static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008952 // The type the comparison is being performed in.
8953 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00008954
8955 // Only analyze comparison operators where both sides have been converted to
8956 // the same type.
8957 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8958 return AnalyzeImpConvsInComparison(S, E);
8959
8960 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00008961 if (E->isValueDependent())
8962 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008963
Roman Lebedev6de129e2017-10-15 20:13:17 +00008964 Expr *LHS = E->getLHS();
8965 Expr *RHS = E->getRHS();
8966
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008967 if (T->isIntegralType(S.Context)) {
8968 llvm::APSInt RHSValue;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008969 llvm::APSInt LHSValue;
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008970
Roman Lebedev6de129e2017-10-15 20:13:17 +00008971 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
8972 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
Roman Lebedevbd1fc222017-10-12 20:16:51 +00008973
Roman Lebedev6de129e2017-10-15 20:13:17 +00008974 // We don't care about expressions whose result is a constant.
8975 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8976 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6f405db2017-10-12 22:03:20 +00008977
Roman Lebedev6de129e2017-10-15 20:13:17 +00008978 // We only care about expressions where just one side is literal
8979 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
8980 // Is the constant on the RHS or LHS?
8981 const bool RhsConstant = IsRHSIntegralLiteral;
8982 Expr *Const = RhsConstant ? RHS : LHS;
8983 Expr *Other = RhsConstant ? LHS : RHS;
8984 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
8985
8986 // Check whether an integer constant comparison results in a value
8987 // of 'true' or 'false'.
Roman Lebedev6de129e2017-10-15 20:13:17 +00008988 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
8989 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6de129e2017-10-15 20:13:17 +00008990 }
8991 }
8992
8993 if (!T->hasUnsignedIntegerRepresentation()) {
8994 // We don't do anything special if this isn't an unsigned integral
8995 // comparison: we're only interested in integral comparisons, and
8996 // signed comparisons only happen in cases we don't care to warn about.
Roman Lebedev6f405db2017-10-12 22:03:20 +00008997 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6de129e2017-10-15 20:13:17 +00008998 }
8999
9000 LHS = LHS->IgnoreParenImpCasts();
9001 RHS = RHS->IgnoreParenImpCasts();
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009002
Alex Lorenzb57409f2018-02-07 20:45:39 +00009003 if (!S.getLangOpts().CPlusPlus) {
9004 // Avoid warning about comparison of integers with different signs when
9005 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
9006 // the type of `E`.
9007 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
9008 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
9009 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
9010 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
9011 }
9012
John McCallcc7e5bf2010-05-06 08:58:33 +00009013 // Check to see if one of the (unmodified) operands is of different
9014 // signedness.
9015 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00009016 if (LHS->getType()->hasSignedIntegerRepresentation()) {
9017 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00009018 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00009019 signedOperand = LHS;
9020 unsignedOperand = RHS;
9021 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
9022 signedOperand = RHS;
9023 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00009024 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00009025 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00009026 }
9027
John McCallcc7e5bf2010-05-06 08:58:33 +00009028 // Otherwise, calculate the effective range of the signed operand.
9029 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00009030
John McCallcc7e5bf2010-05-06 08:58:33 +00009031 // Go ahead and analyze implicit conversions in the operands. Note
9032 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00009033 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
9034 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00009035
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009036 // If the signed range is non-negative, -Wsign-compare won't fire.
John McCallcc7e5bf2010-05-06 08:58:33 +00009037 if (signedRange.NonNegative)
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009038 return;
John McCallca01b222010-01-04 23:21:16 +00009039
9040 // For (in)equality comparisons, if the unsigned operand is a
9041 // constant which cannot collide with a overflowed signed operand,
9042 // then reinterpreting the signed operand as unsigned will not
9043 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00009044 if (E->isEqualityOp()) {
9045 unsigned comparisonWidth = S.Context.getIntWidth(T);
9046 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00009047
John McCallcc7e5bf2010-05-06 08:58:33 +00009048 // We should never be unable to prove that the unsigned operand is
9049 // non-negative.
9050 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
9051
9052 if (unsignedRange.Width < comparisonWidth)
9053 return;
9054 }
9055
Douglas Gregorbfb4a212012-05-01 01:53:49 +00009056 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
9057 S.PDiag(diag::warn_mixed_sign_comparison)
9058 << LHS->getType() << RHS->getType()
9059 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00009060}
9061
John McCall1f425642010-11-11 03:21:53 +00009062/// Analyzes an attempt to assign the given value to a bitfield.
9063///
9064/// Returns true if there was something fishy about the attempt.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009065static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
9066 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00009067 assert(Bitfield->isBitField());
9068 if (Bitfield->isInvalidDecl())
9069 return false;
9070
John McCalldeebbcf2010-11-11 05:33:51 +00009071 // White-list bool bitfields.
Reid Klecknerad425622016-11-16 23:40:00 +00009072 QualType BitfieldType = Bitfield->getType();
9073 if (BitfieldType->isBooleanType())
9074 return false;
9075
9076 if (BitfieldType->isEnumeralType()) {
9077 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
9078 // If the underlying enum type was not explicitly specified as an unsigned
9079 // type and the enum contain only positive values, MSVC++ will cause an
9080 // inconsistency by storing this as a signed type.
9081 if (S.getLangOpts().CPlusPlus11 &&
9082 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
9083 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
9084 BitfieldEnumDecl->getNumNegativeBits() == 0) {
9085 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
9086 << BitfieldEnumDecl->getNameAsString();
9087 }
9088 }
9089
John McCalldeebbcf2010-11-11 05:33:51 +00009090 if (Bitfield->getType()->isBooleanType())
9091 return false;
9092
Douglas Gregor789adec2011-02-04 13:09:01 +00009093 // Ignore value- or type-dependent expressions.
9094 if (Bitfield->getBitWidth()->isValueDependent() ||
9095 Bitfield->getBitWidth()->isTypeDependent() ||
9096 Init->isValueDependent() ||
9097 Init->isTypeDependent())
9098 return false;
9099
John McCall1f425642010-11-11 03:21:53 +00009100 Expr *OriginalInit = Init->IgnoreParenImpCasts();
Reid Kleckner329f24d2017-03-14 18:01:02 +00009101 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00009102
Richard Smith5fab0c92011-12-28 19:48:30 +00009103 llvm::APSInt Value;
Reid Kleckner329f24d2017-03-14 18:01:02 +00009104 if (!OriginalInit->EvaluateAsInt(Value, S.Context,
9105 Expr::SE_AllowSideEffects)) {
9106 // The RHS is not constant. If the RHS has an enum type, make sure the
9107 // bitfield is wide enough to hold all the values of the enum without
9108 // truncation.
9109 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
9110 EnumDecl *ED = EnumTy->getDecl();
9111 bool SignedBitfield = BitfieldType->isSignedIntegerType();
9112
9113 // Enum types are implicitly signed on Windows, so check if there are any
9114 // negative enumerators to see if the enum was intended to be signed or
9115 // not.
9116 bool SignedEnum = ED->getNumNegativeBits() > 0;
9117
9118 // Check for surprising sign changes when assigning enum values to a
9119 // bitfield of different signedness. If the bitfield is signed and we
9120 // have exactly the right number of bits to store this unsigned enum,
9121 // suggest changing the enum to an unsigned type. This typically happens
9122 // on Windows where unfixed enums always use an underlying type of 'int'.
9123 unsigned DiagID = 0;
9124 if (SignedEnum && !SignedBitfield) {
9125 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
9126 } else if (SignedBitfield && !SignedEnum &&
9127 ED->getNumPositiveBits() == FieldWidth) {
9128 DiagID = diag::warn_signed_bitfield_enum_conversion;
9129 }
9130
9131 if (DiagID) {
9132 S.Diag(InitLoc, DiagID) << Bitfield << ED;
9133 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
9134 SourceRange TypeRange =
9135 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
9136 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
9137 << SignedEnum << TypeRange;
9138 }
9139
9140 // Compute the required bitwidth. If the enum has negative values, we need
9141 // one more bit than the normal number of positive bits to represent the
9142 // sign bit.
9143 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
9144 ED->getNumNegativeBits())
9145 : ED->getNumPositiveBits();
9146
9147 // Check the bitwidth.
9148 if (BitsNeeded > FieldWidth) {
9149 Expr *WidthExpr = Bitfield->getBitWidth();
9150 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
9151 << Bitfield << ED;
9152 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
9153 << BitsNeeded << ED << WidthExpr->getSourceRange();
9154 }
9155 }
9156
John McCall1f425642010-11-11 03:21:53 +00009157 return false;
Reid Kleckner329f24d2017-03-14 18:01:02 +00009158 }
John McCall1f425642010-11-11 03:21:53 +00009159
John McCall1f425642010-11-11 03:21:53 +00009160 unsigned OriginalWidth = Value.getBitWidth();
John McCall1f425642010-11-11 03:21:53 +00009161
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00009162 if (!Value.isSigned() || Value.isNegative())
Richard Trieu7561ed02016-08-05 02:39:30 +00009163 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00009164 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
9165 OriginalWidth = Value.getMinSignedBits();
Richard Trieu7561ed02016-08-05 02:39:30 +00009166
John McCall1f425642010-11-11 03:21:53 +00009167 if (OriginalWidth <= FieldWidth)
9168 return false;
9169
Eli Friedmanc267a322012-01-26 23:11:39 +00009170 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00009171 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Reid Klecknerad425622016-11-16 23:40:00 +00009172 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00009173
Eli Friedmanc267a322012-01-26 23:11:39 +00009174 // Check whether the stored value is equal to the original value.
9175 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00009176 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00009177 return false;
9178
Eli Friedmanc267a322012-01-26 23:11:39 +00009179 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00009180 // therefore don't strictly fit into a signed bitfield of width 1.
9181 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00009182 return false;
9183
John McCall1f425642010-11-11 03:21:53 +00009184 std::string PrettyValue = Value.toString(10);
9185 std::string PrettyTrunc = TruncatedValue.toString(10);
9186
9187 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
9188 << PrettyValue << PrettyTrunc << OriginalInit->getType()
9189 << Init->getSourceRange();
9190
9191 return true;
9192}
9193
John McCalld2a53122010-11-09 23:24:47 +00009194/// Analyze the given simple or compound assignment for warning-worthy
9195/// operations.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009196static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00009197 // Just recurse on the LHS.
9198 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9199
9200 // We want to recurse on the RHS as normal unless we're assigning to
9201 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00009202 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009203 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00009204 E->getOperatorLoc())) {
9205 // Recurse, ignoring any implicit conversions on the RHS.
9206 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
9207 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00009208 }
9209 }
9210
9211 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9212}
9213
John McCall263a48b2010-01-04 23:31:57 +00009214/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009215static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
9216 SourceLocation CContext, unsigned diag,
9217 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00009218 if (pruneControlFlow) {
9219 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9220 S.PDiag(diag)
9221 << SourceType << T << E->getSourceRange()
9222 << SourceRange(CContext));
9223 return;
9224 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00009225 S.Diag(E->getExprLoc(), diag)
9226 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
9227}
9228
Chandler Carruth7f3654f2011-04-05 06:47:57 +00009229/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009230static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
9231 SourceLocation CContext,
9232 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00009233 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00009234}
9235
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +00009236/// Analyze the given compound assignment for the possible losing of
9237/// floating-point precision.
9238static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
9239 assert(isa<CompoundAssignOperator>(E) &&
9240 "Must be compound assignment operation");
9241 // Recurse on the LHS and RHS in here
9242 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9243 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9244
9245 // Now check the outermost expression
9246 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
9247 const auto *RBT = cast<CompoundAssignOperator>(E)
9248 ->getComputationResultType()
9249 ->getAs<BuiltinType>();
9250
9251 // If both source and target are floating points.
9252 if (ResultBT && ResultBT->isFloatingPoint() && RBT && RBT->isFloatingPoint())
9253 // Builtin FP kinds are ordered by increasing FP rank.
9254 if (ResultBT->getKind() < RBT->getKind())
9255 // We don't want to warn for system macro.
9256 if (!S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
9257 // warn about dropping FP rank.
9258 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(),
9259 E->getOperatorLoc(),
9260 diag::warn_impcast_float_result_precision);
9261}
Richard Trieube234c32016-04-21 21:04:55 +00009262
9263/// Diagnose an implicit cast from a floating point value to an integer value.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009264static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
9265 SourceLocation CContext) {
Richard Trieube234c32016-04-21 21:04:55 +00009266 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
Richard Smith51ec0cf2017-02-21 01:17:38 +00009267 const bool PruneWarnings = S.inTemplateInstantiation();
Richard Trieube234c32016-04-21 21:04:55 +00009268
9269 Expr *InnerE = E->IgnoreParenImpCasts();
9270 // We also want to warn on, e.g., "int i = -1.234"
9271 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
9272 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
9273 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
9274
9275 const bool IsLiteral =
9276 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
9277
9278 llvm::APFloat Value(0.0);
9279 bool IsConstant =
9280 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
9281 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00009282 return DiagnoseImpCast(S, E, T, CContext,
9283 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00009284 }
9285
Chandler Carruth016ef402011-04-10 08:36:24 +00009286 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00009287
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00009288 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
9289 T->hasUnsignedIntegerRepresentation());
Richard Trieube234c32016-04-21 21:04:55 +00009290 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
9291 &isExact) == llvm::APFloat::opOK &&
Richard Trieu891f0f12016-04-22 22:14:32 +00009292 isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00009293 if (IsLiteral) return;
9294 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
9295 PruneWarnings);
9296 }
9297
9298 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00009299 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00009300 // Warn on floating point literal to integer.
9301 DiagID = diag::warn_impcast_literal_float_to_integer;
9302 } else if (IntegerValue == 0) {
9303 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
9304 return DiagnoseImpCast(S, E, T, CContext,
9305 diag::warn_impcast_float_integer, PruneWarnings);
9306 }
9307 // Warn on non-zero to zero conversion.
9308 DiagID = diag::warn_impcast_float_to_integer_zero;
9309 } else {
9310 if (IntegerValue.isUnsigned()) {
9311 if (!IntegerValue.isMaxValue()) {
9312 return DiagnoseImpCast(S, E, T, CContext,
9313 diag::warn_impcast_float_integer, PruneWarnings);
9314 }
9315 } else { // IntegerValue.isSigned()
9316 if (!IntegerValue.isMaxSignedValue() &&
9317 !IntegerValue.isMinSignedValue()) {
9318 return DiagnoseImpCast(S, E, T, CContext,
9319 diag::warn_impcast_float_integer, PruneWarnings);
9320 }
9321 }
9322 // Warn on evaluatable floating point expression to integer conversion.
9323 DiagID = diag::warn_impcast_float_to_integer;
9324 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009325
Eli Friedman07185912013-08-29 23:44:43 +00009326 // FIXME: Force the precision of the source value down so we don't print
9327 // digits which are usually useless (we don't really care here if we
9328 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
9329 // would automatically print the shortest representation, but it's a bit
9330 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00009331 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00009332 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
9333 precision = (precision * 59 + 195) / 196;
9334 Value.toString(PrettySourceValue, precision);
9335
David Blaikie9b88cc02012-05-15 17:18:27 +00009336 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00009337 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00009338 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00009339 else
David Blaikie9b88cc02012-05-15 17:18:27 +00009340 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00009341
Richard Trieube234c32016-04-21 21:04:55 +00009342 if (PruneWarnings) {
9343 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9344 S.PDiag(DiagID)
9345 << E->getType() << T.getUnqualifiedType()
9346 << PrettySourceValue << PrettyTargetValue
9347 << E->getSourceRange() << SourceRange(CContext));
9348 } else {
9349 S.Diag(E->getExprLoc(), DiagID)
9350 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
9351 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
9352 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009353}
9354
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009355static std::string PrettyPrintInRange(const llvm::APSInt &Value,
9356 IntRange Range) {
John McCall18a2c2c2010-11-09 22:22:12 +00009357 if (!Range.Width) return "0";
9358
9359 llvm::APSInt ValueInRange = Value;
9360 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00009361 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00009362 return ValueInRange.toString(10);
9363}
9364
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009365static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009366 if (!isa<ImplicitCastExpr>(Ex))
9367 return false;
9368
9369 Expr *InnerE = Ex->IgnoreParenImpCasts();
9370 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
9371 const Type *Source =
9372 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
9373 if (Target->isDependentType())
9374 return false;
9375
9376 const BuiltinType *FloatCandidateBT =
9377 dyn_cast<BuiltinType>(ToBool ? Source : Target);
9378 const Type *BoolCandidateType = ToBool ? Target : Source;
9379
9380 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
9381 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
9382}
9383
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009384static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
9385 SourceLocation CC) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009386 unsigned NumArgs = TheCall->getNumArgs();
9387 for (unsigned i = 0; i < NumArgs; ++i) {
9388 Expr *CurrA = TheCall->getArg(i);
9389 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
9390 continue;
9391
9392 bool IsSwapped = ((i > 0) &&
9393 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
9394 IsSwapped |= ((i < (NumArgs - 1)) &&
9395 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
9396 if (IsSwapped) {
9397 // Warn on this floating-point to bool conversion.
9398 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
9399 CurrA->getType(), CC,
9400 diag::warn_impcast_floating_point_to_bool);
9401 }
9402 }
9403}
9404
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009405static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
9406 SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00009407 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
9408 E->getExprLoc()))
9409 return;
9410
Richard Trieu09d6b802016-01-08 23:35:06 +00009411 // Don't warn on functions which have return type nullptr_t.
9412 if (isa<CallExpr>(E))
9413 return;
9414
Richard Trieu5b993502014-10-15 03:42:06 +00009415 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
9416 const Expr::NullPointerConstantKind NullKind =
9417 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
9418 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
9419 return;
9420
9421 // Return if target type is a safe conversion.
9422 if (T->isAnyPointerType() || T->isBlockPointerType() ||
9423 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
9424 return;
9425
9426 SourceLocation Loc = E->getSourceRange().getBegin();
9427
Richard Trieu0a5e1662016-02-13 00:58:53 +00009428 // Venture through the macro stacks to get to the source of macro arguments.
9429 // The new location is a better location than the complete location that was
9430 // passed in.
George Karpenkov441e8fd2018-02-09 23:30:07 +00009431 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
9432 CC = S.SourceMgr.getTopMacroCallerLoc(CC);
Richard Trieu0a5e1662016-02-13 00:58:53 +00009433
Richard Trieu5b993502014-10-15 03:42:06 +00009434 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00009435 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
9436 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
9437 Loc, S.SourceMgr, S.getLangOpts());
9438 if (MacroName == "NULL")
9439 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00009440 }
9441
9442 // Only warn if the null and context location are in the same macro expansion.
9443 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
9444 return;
9445
9446 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009447 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
Richard Trieu5b993502014-10-15 03:42:06 +00009448 << FixItHint::CreateReplacement(Loc,
9449 S.getFixItZeroLiteralForType(T, Loc));
9450}
9451
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009452static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9453 ObjCArrayLiteral *ArrayLiteral);
9454
9455static void
9456checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9457 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00009458
9459/// Check a single element within a collection literal against the
9460/// target element type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009461static void checkObjCCollectionLiteralElement(Sema &S,
9462 QualType TargetElementType,
9463 Expr *Element,
9464 unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009465 // Skip a bitcast to 'id' or qualified 'id'.
9466 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
9467 if (ICE->getCastKind() == CK_BitCast &&
9468 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
9469 Element = ICE->getSubExpr();
9470 }
9471
9472 QualType ElementType = Element->getType();
9473 ExprResult ElementResult(Element);
9474 if (ElementType->getAs<ObjCObjectPointerType>() &&
9475 S.CheckSingleAssignmentConstraints(TargetElementType,
9476 ElementResult,
9477 false, false)
9478 != Sema::Compatible) {
9479 S.Diag(Element->getLocStart(),
9480 diag::warn_objc_collection_literal_element)
9481 << ElementType << ElementKind << TargetElementType
9482 << Element->getSourceRange();
9483 }
9484
9485 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
9486 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
9487 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
9488 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
9489}
9490
9491/// Check an Objective-C array literal being converted to the given
9492/// target type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009493static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9494 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009495 if (!S.NSArrayDecl)
9496 return;
9497
9498 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9499 if (!TargetObjCPtr)
9500 return;
9501
9502 if (TargetObjCPtr->isUnspecialized() ||
9503 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9504 != S.NSArrayDecl->getCanonicalDecl())
9505 return;
9506
9507 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9508 if (TypeArgs.size() != 1)
9509 return;
9510
9511 QualType TargetElementType = TypeArgs[0];
9512 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
9513 checkObjCCollectionLiteralElement(S, TargetElementType,
9514 ArrayLiteral->getElement(I),
9515 0);
9516 }
9517}
9518
9519/// Check an Objective-C dictionary literal being converted to the given
9520/// target type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009521static void
9522checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9523 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009524 if (!S.NSDictionaryDecl)
9525 return;
9526
9527 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9528 if (!TargetObjCPtr)
9529 return;
9530
9531 if (TargetObjCPtr->isUnspecialized() ||
9532 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9533 != S.NSDictionaryDecl->getCanonicalDecl())
9534 return;
9535
9536 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9537 if (TypeArgs.size() != 2)
9538 return;
9539
9540 QualType TargetKeyType = TypeArgs[0];
9541 QualType TargetObjectType = TypeArgs[1];
9542 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
9543 auto Element = DictionaryLiteral->getKeyValueElement(I);
9544 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
9545 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
9546 }
9547}
9548
Richard Trieufc404c72016-02-05 23:02:38 +00009549// Helper function to filter out cases for constant width constant conversion.
9550// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009551static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
9552 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00009553 // If initializing from a constant, and the constant starts with '0',
9554 // then it is a binary, octal, or hexadecimal. Allow these constants
9555 // to fill all the bits, even if there is a sign change.
9556 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
9557 const char FirstLiteralCharacter =
9558 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
9559 if (FirstLiteralCharacter == '0')
9560 return false;
9561 }
9562
9563 // If the CC location points to a '{', and the type is char, then assume
9564 // assume it is an array initialization.
9565 if (CC.isValid() && T->isCharType()) {
9566 const char FirstContextCharacter =
9567 S.getSourceManager().getCharacterData(CC)[0];
9568 if (FirstContextCharacter == '{')
9569 return false;
9570 }
9571
9572 return true;
9573}
9574
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009575static void
9576CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
9577 bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009578 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00009579
John McCallcc7e5bf2010-05-06 08:58:33 +00009580 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
9581 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
9582 if (Source == Target) return;
9583 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00009584
Chandler Carruthc22845a2011-07-26 05:40:03 +00009585 // If the conversion context location is invalid don't complain. We also
9586 // don't want to emit a warning if the issue occurs from the expansion of
9587 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
9588 // delay this check as long as possible. Once we detect we are in that
9589 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009590 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00009591 return;
9592
Richard Trieu021baa32011-09-23 20:10:00 +00009593 // Diagnose implicit casts to bool.
9594 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
9595 if (isa<StringLiteral>(E))
9596 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00009597 // and expressions, for instance, assert(0 && "error here"), are
9598 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00009599 return DiagnoseImpCast(S, E, T, CC,
9600 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00009601 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
9602 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
9603 // This covers the literal expressions that evaluate to Objective-C
9604 // objects.
9605 return DiagnoseImpCast(S, E, T, CC,
9606 diag::warn_impcast_objective_c_literal_to_bool);
9607 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00009608 if (Source->isPointerType() || Source->canDecayToPointerType()) {
9609 // Warn on pointer to bool conversion that is always true.
9610 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
9611 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00009612 }
Richard Trieu021baa32011-09-23 20:10:00 +00009613 }
John McCall263a48b2010-01-04 23:31:57 +00009614
Douglas Gregor5054cb02015-07-07 03:58:22 +00009615 // Check implicit casts from Objective-C collection literals to specialized
9616 // collection types, e.g., NSArray<NSString *> *.
9617 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
9618 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
9619 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
9620 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
9621
John McCall263a48b2010-01-04 23:31:57 +00009622 // Strip vector types.
9623 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009624 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009625 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009626 return;
John McCallacf0ee52010-10-08 02:01:28 +00009627 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009628 }
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +00009629
Chris Lattneree7286f2011-06-14 04:51:15 +00009630 // If the vector cast is cast between two vectors of the same size, it is
9631 // a bitcast, not a conversion.
9632 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
9633 return;
John McCall263a48b2010-01-04 23:31:57 +00009634
9635 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
9636 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
9637 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00009638 if (auto VecTy = dyn_cast<VectorType>(Target))
9639 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00009640
9641 // Strip complex types.
9642 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009643 if (!isa<ComplexType>(Target)) {
Tim Northover02416372017-08-08 23:18:05 +00009644 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009645 return;
9646
Tim Northover02416372017-08-08 23:18:05 +00009647 return DiagnoseImpCast(S, E, T, CC,
9648 S.getLangOpts().CPlusPlus
9649 ? diag::err_impcast_complex_scalar
9650 : diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009651 }
John McCall263a48b2010-01-04 23:31:57 +00009652
9653 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
9654 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
9655 }
9656
9657 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
9658 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
9659
9660 // If the source is floating point...
9661 if (SourceBT && SourceBT->isFloatingPoint()) {
9662 // ...and the target is floating point...
9663 if (TargetBT && TargetBT->isFloatingPoint()) {
9664 // ...then warn if we're dropping FP rank.
9665
9666 // Builtin FP kinds are ordered by increasing FP rank.
9667 if (SourceBT->getKind() > TargetBT->getKind()) {
9668 // Don't warn about float constants that are precisely
9669 // representable in the target type.
9670 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00009671 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00009672 // Value might be a float, a float vector, or a float complex.
9673 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00009674 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9675 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00009676 return;
9677 }
9678
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009679 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009680 return;
9681
John McCallacf0ee52010-10-08 02:01:28 +00009682 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00009683 }
9684 // ... or possibly if we're increasing rank, too
9685 else if (TargetBT->getKind() > SourceBT->getKind()) {
9686 if (S.SourceMgr.isInSystemMacro(CC))
9687 return;
9688
9689 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00009690 }
9691 return;
9692 }
9693
Richard Trieube234c32016-04-21 21:04:55 +00009694 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00009695 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009696 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009697 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00009698
Richard Trieube234c32016-04-21 21:04:55 +00009699 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00009700 }
John McCall263a48b2010-01-04 23:31:57 +00009701
Richard Smith54894fd2015-12-30 01:06:52 +00009702 // Detect the case where a call result is converted from floating-point to
9703 // to bool, and the final argument to the call is converted from bool, to
9704 // discover this typo:
9705 //
9706 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
9707 //
9708 // FIXME: This is an incredibly special case; is there some more general
9709 // way to detect this class of misplaced-parentheses bug?
9710 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009711 // Check last argument of function call to see if it is an
9712 // implicit cast from a type matching the type the result
9713 // is being cast to.
9714 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00009715 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009716 Expr *LastA = CEx->getArg(NumArgs - 1);
9717 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00009718 if (isa<ImplicitCastExpr>(LastA) &&
9719 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009720 // Warn on this floating-point to bool conversion
9721 DiagnoseImpCast(S, E, T, CC,
9722 diag::warn_impcast_floating_point_to_bool);
9723 }
9724 }
9725 }
John McCall263a48b2010-01-04 23:31:57 +00009726 return;
9727 }
9728
Richard Trieu5b993502014-10-15 03:42:06 +00009729 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00009730
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00009731 S.DiscardMisalignedMemberAddress(Target, E);
9732
David Blaikie9366d2b2012-06-19 21:19:06 +00009733 if (!Source->isIntegerType() || !Target->isIntegerType())
9734 return;
9735
David Blaikie7555b6a2012-05-15 16:56:36 +00009736 // TODO: remove this early return once the false positives for constant->bool
9737 // in templates, macros, etc, are reduced or removed.
9738 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9739 return;
9740
John McCallcc7e5bf2010-05-06 08:58:33 +00009741 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00009742 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00009743
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009744 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00009745 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009746 // TODO: this should happen for bitfield stores, too.
9747 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00009748 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009749 if (S.SourceMgr.isInSystemMacro(CC))
9750 return;
9751
John McCall18a2c2c2010-11-09 22:22:12 +00009752 std::string PrettySourceValue = Value.toString(10);
9753 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009754
Ted Kremenek33ba9952011-10-22 02:37:33 +00009755 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9756 S.PDiag(diag::warn_impcast_integer_precision_constant)
9757 << PrettySourceValue << PrettyTargetValue
9758 << E->getType() << T << E->getSourceRange()
9759 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00009760 return;
9761 }
9762
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009763 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9764 if (S.SourceMgr.isInSystemMacro(CC))
9765 return;
9766
David Blaikie9455da02012-04-12 22:40:54 +00009767 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00009768 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9769 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00009770 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00009771 }
9772
Richard Trieudcb55572016-01-29 23:51:16 +00009773 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9774 SourceRange.NonNegative && Source->isSignedIntegerType()) {
9775 // Warn when doing a signed to signed conversion, warn if the positive
9776 // source value is exactly the width of the target type, which will
9777 // cause a negative value to be stored.
9778
9779 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00009780 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9781 !S.SourceMgr.isInSystemMacro(CC)) {
9782 if (isSameWidthConstantConversion(S, E, T, CC)) {
9783 std::string PrettySourceValue = Value.toString(10);
9784 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00009785
Richard Trieufc404c72016-02-05 23:02:38 +00009786 S.DiagRuntimeBehavior(
9787 E->getExprLoc(), E,
9788 S.PDiag(diag::warn_impcast_integer_precision_constant)
9789 << PrettySourceValue << PrettyTargetValue << E->getType() << T
9790 << E->getSourceRange() << clang::SourceRange(CC));
9791 return;
Richard Trieudcb55572016-01-29 23:51:16 +00009792 }
9793 }
Richard Trieufc404c72016-02-05 23:02:38 +00009794
Richard Trieudcb55572016-01-29 23:51:16 +00009795 // Fall through for non-constants to give a sign conversion warning.
9796 }
9797
John McCallcc7e5bf2010-05-06 08:58:33 +00009798 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9799 (!TargetRange.NonNegative && SourceRange.NonNegative &&
9800 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009801 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009802 return;
9803
John McCallcc7e5bf2010-05-06 08:58:33 +00009804 unsigned DiagID = diag::warn_impcast_integer_sign;
9805
9806 // Traditionally, gcc has warned about this under -Wsign-compare.
9807 // We also want to warn about it in -Wconversion.
9808 // So if -Wconversion is off, use a completely identical diagnostic
9809 // in the sign-compare group.
9810 // The conditional-checking code will
9811 if (ICContext) {
9812 DiagID = diag::warn_impcast_integer_sign_conditional;
9813 *ICContext = true;
9814 }
9815
John McCallacf0ee52010-10-08 02:01:28 +00009816 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00009817 }
9818
Douglas Gregora78f1932011-02-22 02:45:07 +00009819 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00009820 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9821 // type, to give us better diagnostics.
9822 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00009823 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00009824 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9825 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9826 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9827 SourceType = S.Context.getTypeDeclType(Enum);
9828 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9829 }
9830 }
9831
Douglas Gregora78f1932011-02-22 02:45:07 +00009832 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9833 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00009834 if (SourceEnum->getDecl()->hasNameForLinkage() &&
9835 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009836 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009837 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009838 return;
9839
Douglas Gregor364f7db2011-03-12 00:14:31 +00009840 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00009841 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009842 }
John McCall263a48b2010-01-04 23:31:57 +00009843}
9844
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009845static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9846 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009847
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009848static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
9849 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009850 E = E->IgnoreParenImpCasts();
9851
9852 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00009853 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009854
John McCallacf0ee52010-10-08 02:01:28 +00009855 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009856 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009857 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00009858}
9859
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009860static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9861 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00009862 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00009863
9864 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00009865 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9866 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009867
9868 // If -Wconversion would have warned about either of the candidates
9869 // for a signedness conversion to the context type...
9870 if (!Suspicious) return;
9871
9872 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009873 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00009874 return;
9875
John McCallcc7e5bf2010-05-06 08:58:33 +00009876 // ...then check whether it would have warned about either of the
9877 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00009878 if (E->getType() == T) return;
9879
9880 Suspicious = false;
9881 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
9882 E->getType(), CC, &Suspicious);
9883 if (!Suspicious)
9884 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00009885 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009886}
9887
Richard Trieu65724892014-11-15 06:37:39 +00009888/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9889/// Input argument E is a logical expression.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009890static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00009891 if (S.getLangOpts().Bool)
9892 return;
9893 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
9894}
9895
John McCallcc7e5bf2010-05-06 08:58:33 +00009896/// AnalyzeImplicitConversions - Find and report any interesting
9897/// implicit conversions in the given expression. There are a couple
9898/// of competing diagnostics here, -Wconversion and -Wsign-compare.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009899static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
9900 SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00009901 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00009902 Expr *E = OrigE->IgnoreParenImpCasts();
9903
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00009904 if (E->isTypeDependent() || E->isValueDependent())
9905 return;
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +00009906
John McCallcc7e5bf2010-05-06 08:58:33 +00009907 // For conditional operators, we analyze the arguments as if they
9908 // were being fed directly into the output.
9909 if (isa<ConditionalOperator>(E)) {
9910 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00009911 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009912 return;
9913 }
9914
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009915 // Check implicit argument conversions for function calls.
9916 if (CallExpr *Call = dyn_cast<CallExpr>(E))
9917 CheckImplicitArgumentConversions(S, Call, CC);
9918
John McCallcc7e5bf2010-05-06 08:58:33 +00009919 // Go ahead and check any implicit conversions we might have skipped.
9920 // The non-canonical typecheck is just an optimization;
9921 // CheckImplicitConversion will filter out dead implicit conversions.
9922 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009923 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009924
9925 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00009926
9927 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
9928 // The bound subexpressions in a PseudoObjectExpr are not reachable
9929 // as transitive children.
9930 // FIXME: Use a more uniform representation for this.
9931 for (auto *SE : POE->semantics())
9932 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9933 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00009934 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00009935
John McCallcc7e5bf2010-05-06 08:58:33 +00009936 // Skip past explicit casts.
9937 if (isa<ExplicitCastExpr>(E)) {
9938 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00009939 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009940 }
9941
John McCalld2a53122010-11-09 23:24:47 +00009942 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9943 // Do a somewhat different check with comparison operators.
9944 if (BO->isComparisonOp())
9945 return AnalyzeComparison(S, BO);
9946
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009947 // And with simple assignments.
9948 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00009949 return AnalyzeAssignment(S, BO);
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +00009950 // And with compound assignments.
9951 if (BO->isAssignmentOp())
9952 return AnalyzeCompoundAssignment(S, BO);
John McCalld2a53122010-11-09 23:24:47 +00009953 }
John McCallcc7e5bf2010-05-06 08:58:33 +00009954
9955 // These break the otherwise-useful invariant below. Fortunately,
9956 // we don't really need to recurse into them, because any internal
9957 // expressions should have been analyzed already when they were
9958 // built into statements.
9959 if (isa<StmtExpr>(E)) return;
9960
9961 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00009962 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00009963
9964 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00009965 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00009966 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00009967 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00009968 for (Stmt *SubStmt : E->children()) {
9969 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00009970 if (!ChildExpr)
9971 continue;
9972
Richard Trieu955231d2014-01-25 01:10:35 +00009973 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00009974 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00009975 // Ignore checking string literals that are in logical and operators.
9976 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00009977 continue;
9978 AnalyzeImplicitConversions(S, ChildExpr, CC);
9979 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009980
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009981 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00009982 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
9983 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009984 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00009985
9986 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
9987 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009988 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009989 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009990
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009991 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
9992 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00009993 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009994}
9995
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00009996/// Diagnose integer type and any valid implicit conversion to it.
Anastasia Stulova0df4ac32016-11-14 17:39:58 +00009997static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
9998 // Taking into account implicit conversions,
9999 // allow any integer.
10000 if (!E->getType()->isIntegerType()) {
10001 S.Diag(E->getLocStart(),
10002 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
10003 return true;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010004 }
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000010005 // Potentially emit standard warnings for implicit conversions if enabled
10006 // using -Wconversion.
10007 CheckImplicitConversion(S, E, IntT, E->getLocStart());
10008 return false;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010009}
10010
Richard Trieuc1888e02014-06-28 23:25:37 +000010011// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
10012// Returns true when emitting a warning about taking the address of a reference.
10013static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +000010014 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +000010015 E = E->IgnoreParenImpCasts();
10016
10017 const FunctionDecl *FD = nullptr;
10018
10019 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10020 if (!DRE->getDecl()->getType()->isReferenceType())
10021 return false;
10022 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10023 if (!M->getMemberDecl()->getType()->isReferenceType())
10024 return false;
10025 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +000010026 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +000010027 return false;
10028 FD = Call->getDirectCallee();
10029 } else {
10030 return false;
10031 }
10032
10033 SemaRef.Diag(E->getExprLoc(), PD);
10034
10035 // If possible, point to location of function.
10036 if (FD) {
10037 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
10038 }
10039
10040 return true;
10041}
10042
Richard Trieu4cbff5c2014-08-08 22:41:43 +000010043// Returns true if the SourceLocation is expanded from any macro body.
10044// Returns false if the SourceLocation is invalid, is from not in a macro
10045// expansion, or is from expanded from a top-level macro argument.
10046static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
10047 if (Loc.isInvalid())
10048 return false;
10049
10050 while (Loc.isMacroID()) {
10051 if (SM.isMacroBodyExpansion(Loc))
10052 return true;
10053 Loc = SM.getImmediateMacroCallerLoc(Loc);
10054 }
10055
10056 return false;
10057}
10058
Richard Trieu3bb8b562014-02-26 02:36:06 +000010059/// \brief Diagnose pointers that are always non-null.
10060/// \param E the expression containing the pointer
10061/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
10062/// compared to a null pointer
10063/// \param IsEqual True when the comparison is equal to a null pointer
10064/// \param Range Extra SourceRange to highlight in the diagnostic
10065void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
10066 Expr::NullPointerConstantKind NullKind,
10067 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +000010068 if (!E)
10069 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010070
10071 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +000010072 if (E->getExprLoc().isMacroID()) {
10073 const SourceManager &SM = getSourceManager();
10074 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
10075 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +000010076 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +000010077 }
Richard Trieu3bb8b562014-02-26 02:36:06 +000010078 E = E->IgnoreImpCasts();
10079
10080 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
10081
Richard Trieuf7432752014-06-06 21:39:26 +000010082 if (isa<CXXThisExpr>(E)) {
10083 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
10084 : diag::warn_this_bool_conversion;
10085 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
10086 return;
10087 }
10088
Richard Trieu3bb8b562014-02-26 02:36:06 +000010089 bool IsAddressOf = false;
10090
10091 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10092 if (UO->getOpcode() != UO_AddrOf)
10093 return;
10094 IsAddressOf = true;
10095 E = UO->getSubExpr();
10096 }
10097
Richard Trieuc1888e02014-06-28 23:25:37 +000010098 if (IsAddressOf) {
10099 unsigned DiagID = IsCompare
10100 ? diag::warn_address_of_reference_null_compare
10101 : diag::warn_address_of_reference_bool_conversion;
10102 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
10103 << IsEqual;
10104 if (CheckForReference(*this, E, PD)) {
10105 return;
10106 }
10107 }
10108
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010109 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
10110 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +000010111 std::string Str;
10112 llvm::raw_string_ostream S(Str);
10113 E->printPretty(S, nullptr, getPrintingPolicy());
10114 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
10115 : diag::warn_cast_nonnull_to_bool;
10116 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
10117 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010118 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +000010119 };
10120
10121 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
10122 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
10123 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010124 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
10125 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000010126 return;
10127 }
10128 }
10129 }
10130
Richard Trieu3bb8b562014-02-26 02:36:06 +000010131 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +000010132 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010133 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
10134 D = R->getDecl();
10135 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10136 D = M->getMemberDecl();
10137 }
10138
10139 // Weak Decls can be null.
10140 if (!D || D->isWeak())
10141 return;
George Burgess IV850269a2015-12-08 22:02:00 +000010142
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010143 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +000010144 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
10145 if (getCurFunction() &&
10146 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010147 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
10148 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000010149 return;
10150 }
10151
10152 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +000010153 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +000010154 assert(ParamIter != FD->param_end());
10155 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
10156
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010157 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
10158 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010159 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +000010160 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010161 }
George Burgess IV850269a2015-12-08 22:02:00 +000010162
Joel E. Denny81508102018-03-13 14:51:22 +000010163 for (const ParamIdx &ArgNo : NonNull->args()) {
10164 if (ArgNo.getASTIndex() == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010165 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010166 return;
10167 }
George Burgess IV850269a2015-12-08 22:02:00 +000010168 }
10169 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010170 }
10171 }
George Burgess IV850269a2015-12-08 22:02:00 +000010172 }
10173
Richard Trieu3bb8b562014-02-26 02:36:06 +000010174 QualType T = D->getType();
10175 const bool IsArray = T->isArrayType();
10176 const bool IsFunction = T->isFunctionType();
10177
Richard Trieuc1888e02014-06-28 23:25:37 +000010178 // Address of function is used to silence the function warning.
10179 if (IsAddressOf && IsFunction) {
10180 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010181 }
10182
10183 // Found nothing.
10184 if (!IsAddressOf && !IsFunction && !IsArray)
10185 return;
10186
10187 // Pretty print the expression for the diagnostic.
10188 std::string Str;
10189 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +000010190 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +000010191
10192 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
10193 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +000010194 enum {
10195 AddressOf,
10196 FunctionPointer,
10197 ArrayPointer
10198 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010199 if (IsAddressOf)
10200 DiagType = AddressOf;
10201 else if (IsFunction)
10202 DiagType = FunctionPointer;
10203 else if (IsArray)
10204 DiagType = ArrayPointer;
10205 else
10206 llvm_unreachable("Could not determine diagnostic.");
10207 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
10208 << Range << IsEqual;
10209
10210 if (!IsFunction)
10211 return;
10212
10213 // Suggest '&' to silence the function warning.
10214 Diag(E->getExprLoc(), diag::note_function_warning_silence)
10215 << FixItHint::CreateInsertion(E->getLocStart(), "&");
10216
10217 // Check to see if '()' fixit should be emitted.
10218 QualType ReturnType;
10219 UnresolvedSet<4> NonTemplateOverloads;
10220 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
10221 if (ReturnType.isNull())
10222 return;
10223
10224 if (IsCompare) {
10225 // There are two cases here. If there is null constant, the only suggest
10226 // for a pointer return type. If the null is 0, then suggest if the return
10227 // type is a pointer or an integer type.
10228 if (!ReturnType->isPointerType()) {
10229 if (NullKind == Expr::NPCK_ZeroExpression ||
10230 NullKind == Expr::NPCK_ZeroLiteral) {
10231 if (!ReturnType->isIntegerType())
10232 return;
10233 } else {
10234 return;
10235 }
10236 }
10237 } else { // !IsCompare
10238 // For function to bool, only suggest if the function pointer has bool
10239 // return type.
10240 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
10241 return;
10242 }
10243 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +000010244 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +000010245}
10246
John McCallcc7e5bf2010-05-06 08:58:33 +000010247/// Diagnoses "dangerous" implicit conversions within the given
10248/// expression (which is a full expression). Implements -Wconversion
10249/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +000010250///
10251/// \param CC the "context" location of the implicit conversion, i.e.
10252/// the most location of the syntactic entity requiring the implicit
10253/// conversion
10254void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010255 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +000010256 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +000010257 return;
10258
10259 // Don't diagnose for value- or type-dependent expressions.
10260 if (E->isTypeDependent() || E->isValueDependent())
10261 return;
10262
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010263 // Check for array bounds violations in cases where the check isn't triggered
10264 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
10265 // ArraySubscriptExpr is on the RHS of a variable initialization.
10266 CheckArrayAccess(E);
10267
John McCallacf0ee52010-10-08 02:01:28 +000010268 // This is not the right CC for (e.g.) a variable initialization.
10269 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010270}
10271
Richard Trieu65724892014-11-15 06:37:39 +000010272/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10273/// Input argument E is a logical expression.
10274void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
10275 ::CheckBoolLikeConversion(*this, E, CC);
10276}
10277
Richard Smith9f7df0c2017-06-26 23:19:32 +000010278/// Diagnose when expression is an integer constant expression and its evaluation
10279/// results in integer overflow
10280void Sema::CheckForIntOverflow (Expr *E) {
10281 // Use a work list to deal with nested struct initializers.
10282 SmallVector<Expr *, 2> Exprs(1, E);
10283
10284 do {
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010285 Expr *OriginalE = Exprs.pop_back_val();
10286 Expr *E = OriginalE->IgnoreParenCasts();
Richard Smith9f7df0c2017-06-26 23:19:32 +000010287
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010288 if (isa<BinaryOperator>(E)) {
10289 E->EvaluateForOverflow(Context);
Richard Smith9f7df0c2017-06-26 23:19:32 +000010290 continue;
10291 }
10292
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010293 if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
Richard Smith9f7df0c2017-06-26 23:19:32 +000010294 Exprs.append(InitList->inits().begin(), InitList->inits().end());
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010295 else if (isa<ObjCBoxedExpr>(OriginalE))
10296 E->EvaluateForOverflow(Context);
10297 else if (auto Call = dyn_cast<CallExpr>(E))
10298 Exprs.append(Call->arg_begin(), Call->arg_end());
10299 else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
10300 Exprs.append(Message->arg_begin(), Message->arg_end());
Richard Smith9f7df0c2017-06-26 23:19:32 +000010301 } while (!Exprs.empty());
10302}
10303
Richard Smithc406cb72013-01-17 01:17:56 +000010304namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010305
Richard Smithc406cb72013-01-17 01:17:56 +000010306/// \brief Visitor for expressions which looks for unsequenced operations on the
10307/// same object.
10308class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010309 using Base = EvaluatedExprVisitor<SequenceChecker>;
Richard Smithe3dbfe02013-06-30 10:40:20 +000010310
Richard Smithc406cb72013-01-17 01:17:56 +000010311 /// \brief A tree of sequenced regions within an expression. Two regions are
10312 /// unsequenced if one is an ancestor or a descendent of the other. When we
10313 /// finish processing an expression with sequencing, such as a comma
10314 /// expression, we fold its tree nodes into its parent, since they are
10315 /// unsequenced with respect to nodes we will visit later.
10316 class SequenceTree {
10317 struct Value {
10318 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
10319 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +000010320 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +000010321 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010322 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +000010323
10324 public:
10325 /// \brief A region within an expression which may be sequenced with respect
10326 /// to some other region.
10327 class Seq {
Richard Smithc406cb72013-01-17 01:17:56 +000010328 friend class SequenceTree;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010329
10330 unsigned Index = 0;
10331
10332 explicit Seq(unsigned N) : Index(N) {}
10333
Richard Smithc406cb72013-01-17 01:17:56 +000010334 public:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010335 Seq() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010336 };
10337
10338 SequenceTree() { Values.push_back(Value(0)); }
10339 Seq root() const { return Seq(0); }
10340
10341 /// \brief Create a new sequence of operations, which is an unsequenced
10342 /// subset of \p Parent. This sequence of operations is sequenced with
10343 /// respect to other children of \p Parent.
10344 Seq allocate(Seq Parent) {
10345 Values.push_back(Value(Parent.Index));
10346 return Seq(Values.size() - 1);
10347 }
10348
10349 /// \brief Merge a sequence of operations into its parent.
10350 void merge(Seq S) {
10351 Values[S.Index].Merged = true;
10352 }
10353
10354 /// \brief Determine whether two operations are unsequenced. This operation
10355 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
10356 /// should have been merged into its parent as appropriate.
10357 bool isUnsequenced(Seq Cur, Seq Old) {
10358 unsigned C = representative(Cur.Index);
10359 unsigned Target = representative(Old.Index);
10360 while (C >= Target) {
10361 if (C == Target)
10362 return true;
10363 C = Values[C].Parent;
10364 }
10365 return false;
10366 }
10367
10368 private:
10369 /// \brief Pick a representative for a sequence.
10370 unsigned representative(unsigned K) {
10371 if (Values[K].Merged)
10372 // Perform path compression as we go.
10373 return Values[K].Parent = representative(Values[K].Parent);
10374 return K;
10375 }
10376 };
10377
10378 /// An object for which we can track unsequenced uses.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010379 using Object = NamedDecl *;
Richard Smithc406cb72013-01-17 01:17:56 +000010380
10381 /// Different flavors of object usage which we track. We only track the
10382 /// least-sequenced usage of each kind.
10383 enum UsageKind {
10384 /// A read of an object. Multiple unsequenced reads are OK.
10385 UK_Use,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010386
Richard Smithc406cb72013-01-17 01:17:56 +000010387 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +000010388 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +000010389 UK_ModAsValue,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010390
Richard Smithc406cb72013-01-17 01:17:56 +000010391 /// A modification of an object which is not sequenced before the value
10392 /// computation of the expression, such as n++.
10393 UK_ModAsSideEffect,
10394
10395 UK_Count = UK_ModAsSideEffect + 1
10396 };
10397
10398 struct Usage {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010399 Expr *Use = nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000010400 SequenceTree::Seq Seq;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010401
10402 Usage() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010403 };
10404
10405 struct UsageInfo {
Richard Smithc406cb72013-01-17 01:17:56 +000010406 Usage Uses[UK_Count];
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010407
Richard Smithc406cb72013-01-17 01:17:56 +000010408 /// Have we issued a diagnostic for this variable already?
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010409 bool Diagnosed = false;
10410
10411 UsageInfo() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010412 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010413 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
Richard Smithc406cb72013-01-17 01:17:56 +000010414
10415 Sema &SemaRef;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010416
Richard Smithc406cb72013-01-17 01:17:56 +000010417 /// Sequenced regions within the expression.
10418 SequenceTree Tree;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010419
Richard Smithc406cb72013-01-17 01:17:56 +000010420 /// Declaration modifications and references which we have seen.
10421 UsageInfoMap UsageMap;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010422
Richard Smithc406cb72013-01-17 01:17:56 +000010423 /// The region we are currently within.
10424 SequenceTree::Seq Region;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010425
Richard Smithc406cb72013-01-17 01:17:56 +000010426 /// Filled in with declarations which were modified as a side-effect
10427 /// (that is, post-increment operations).
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010428 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
10429
Richard Smithd33f5202013-01-17 23:18:09 +000010430 /// Expressions to check later. We defer checking these to reduce
10431 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010432 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +000010433
10434 /// RAII object wrapping the visitation of a sequenced subexpression of an
10435 /// expression. At the end of this process, the side-effects of the evaluation
10436 /// become sequenced with respect to the value computation of the result, so
10437 /// we downgrade any UK_ModAsSideEffect within the evaluation to
10438 /// UK_ModAsValue.
10439 struct SequencedSubexpression {
10440 SequencedSubexpression(SequenceChecker &Self)
10441 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
10442 Self.ModAsSideEffect = &ModAsSideEffect;
10443 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010444
Richard Smithc406cb72013-01-17 01:17:56 +000010445 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +000010446 for (auto &M : llvm::reverse(ModAsSideEffect)) {
10447 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +000010448 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +000010449 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
10450 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +000010451 }
10452 Self.ModAsSideEffect = OldModAsSideEffect;
10453 }
10454
10455 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010456 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010457 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +000010458 };
10459
Richard Smith40238f02013-06-20 22:21:56 +000010460 /// RAII object wrapping the visitation of a subexpression which we might
10461 /// choose to evaluate as a constant. If any subexpression is evaluated and
10462 /// found to be non-constant, this allows us to suppress the evaluation of
10463 /// the outer expression.
10464 class EvaluationTracker {
10465 public:
10466 EvaluationTracker(SequenceChecker &Self)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010467 : Self(Self), Prev(Self.EvalTracker) {
Richard Smith40238f02013-06-20 22:21:56 +000010468 Self.EvalTracker = this;
10469 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010470
Richard Smith40238f02013-06-20 22:21:56 +000010471 ~EvaluationTracker() {
10472 Self.EvalTracker = Prev;
10473 if (Prev)
10474 Prev->EvalOK &= EvalOK;
10475 }
10476
10477 bool evaluate(const Expr *E, bool &Result) {
10478 if (!EvalOK || E->isValueDependent())
10479 return false;
10480 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
10481 return EvalOK;
10482 }
10483
10484 private:
10485 SequenceChecker &Self;
10486 EvaluationTracker *Prev;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010487 bool EvalOK = true;
10488 } *EvalTracker = nullptr;
Richard Smith40238f02013-06-20 22:21:56 +000010489
Richard Smithc406cb72013-01-17 01:17:56 +000010490 /// \brief Find the object which is produced by the specified expression,
10491 /// if any.
10492 Object getObject(Expr *E, bool Mod) const {
10493 E = E->IgnoreParenCasts();
10494 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10495 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
10496 return getObject(UO->getSubExpr(), Mod);
10497 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10498 if (BO->getOpcode() == BO_Comma)
10499 return getObject(BO->getRHS(), Mod);
10500 if (Mod && BO->isAssignmentOp())
10501 return getObject(BO->getLHS(), Mod);
10502 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10503 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
10504 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
10505 return ME->getMemberDecl();
10506 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10507 // FIXME: If this is a reference, map through to its value.
10508 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +000010509 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000010510 }
10511
10512 /// \brief Note that an object was modified or used by an expression.
10513 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
10514 Usage &U = UI.Uses[UK];
10515 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
10516 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
10517 ModAsSideEffect->push_back(std::make_pair(O, U));
10518 U.Use = Ref;
10519 U.Seq = Region;
10520 }
10521 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010522
Richard Smithc406cb72013-01-17 01:17:56 +000010523 /// \brief Check whether a modification or use conflicts with a prior usage.
10524 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
10525 bool IsModMod) {
10526 if (UI.Diagnosed)
10527 return;
10528
10529 const Usage &U = UI.Uses[OtherKind];
10530 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
10531 return;
10532
10533 Expr *Mod = U.Use;
10534 Expr *ModOrUse = Ref;
10535 if (OtherKind == UK_Use)
10536 std::swap(Mod, ModOrUse);
10537
10538 SemaRef.Diag(Mod->getExprLoc(),
10539 IsModMod ? diag::warn_unsequenced_mod_mod
10540 : diag::warn_unsequenced_mod_use)
10541 << O << SourceRange(ModOrUse->getExprLoc());
10542 UI.Diagnosed = true;
10543 }
10544
10545 void notePreUse(Object O, Expr *Use) {
10546 UsageInfo &U = UsageMap[O];
10547 // Uses conflict with other modifications.
10548 checkUsage(O, U, Use, UK_ModAsValue, false);
10549 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010550
Richard Smithc406cb72013-01-17 01:17:56 +000010551 void notePostUse(Object O, Expr *Use) {
10552 UsageInfo &U = UsageMap[O];
10553 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
10554 addUsage(U, O, Use, UK_Use);
10555 }
10556
10557 void notePreMod(Object O, Expr *Mod) {
10558 UsageInfo &U = UsageMap[O];
10559 // Modifications conflict with other modifications and with uses.
10560 checkUsage(O, U, Mod, UK_ModAsValue, true);
10561 checkUsage(O, U, Mod, UK_Use, false);
10562 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010563
Richard Smithc406cb72013-01-17 01:17:56 +000010564 void notePostMod(Object O, Expr *Use, UsageKind UK) {
10565 UsageInfo &U = UsageMap[O];
10566 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
10567 addUsage(U, O, Use, UK);
10568 }
10569
10570public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010571 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010572 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
Richard Smithc406cb72013-01-17 01:17:56 +000010573 Visit(E);
10574 }
10575
10576 void VisitStmt(Stmt *S) {
10577 // Skip all statements which aren't expressions for now.
10578 }
10579
10580 void VisitExpr(Expr *E) {
10581 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +000010582 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +000010583 }
10584
10585 void VisitCastExpr(CastExpr *E) {
10586 Object O = Object();
10587 if (E->getCastKind() == CK_LValueToRValue)
10588 O = getObject(E->getSubExpr(), false);
10589
10590 if (O)
10591 notePreUse(O, E);
10592 VisitExpr(E);
10593 if (O)
10594 notePostUse(O, E);
10595 }
10596
10597 void VisitBinComma(BinaryOperator *BO) {
10598 // C++11 [expr.comma]p1:
10599 // Every value computation and side effect associated with the left
10600 // expression is sequenced before every value computation and side
10601 // effect associated with the right expression.
10602 SequenceTree::Seq LHS = Tree.allocate(Region);
10603 SequenceTree::Seq RHS = Tree.allocate(Region);
10604 SequenceTree::Seq OldRegion = Region;
10605
10606 {
10607 SequencedSubexpression SeqLHS(*this);
10608 Region = LHS;
10609 Visit(BO->getLHS());
10610 }
10611
10612 Region = RHS;
10613 Visit(BO->getRHS());
10614
10615 Region = OldRegion;
10616
10617 // Forget that LHS and RHS are sequenced. They are both unsequenced
10618 // with respect to other stuff.
10619 Tree.merge(LHS);
10620 Tree.merge(RHS);
10621 }
10622
10623 void VisitBinAssign(BinaryOperator *BO) {
10624 // The modification is sequenced after the value computation of the LHS
10625 // and RHS, so check it before inspecting the operands and update the
10626 // map afterwards.
10627 Object O = getObject(BO->getLHS(), true);
10628 if (!O)
10629 return VisitExpr(BO);
10630
10631 notePreMod(O, BO);
10632
10633 // C++11 [expr.ass]p7:
10634 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
10635 // only once.
10636 //
10637 // Therefore, for a compound assignment operator, O is considered used
10638 // everywhere except within the evaluation of E1 itself.
10639 if (isa<CompoundAssignOperator>(BO))
10640 notePreUse(O, BO);
10641
10642 Visit(BO->getLHS());
10643
10644 if (isa<CompoundAssignOperator>(BO))
10645 notePostUse(O, BO);
10646
10647 Visit(BO->getRHS());
10648
Richard Smith83e37bee2013-06-26 23:16:51 +000010649 // C++11 [expr.ass]p1:
10650 // the assignment is sequenced [...] before the value computation of the
10651 // assignment expression.
10652 // C11 6.5.16/3 has no such rule.
10653 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10654 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010655 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010656
Richard Smithc406cb72013-01-17 01:17:56 +000010657 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
10658 VisitBinAssign(CAO);
10659 }
10660
10661 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10662 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10663 void VisitUnaryPreIncDec(UnaryOperator *UO) {
10664 Object O = getObject(UO->getSubExpr(), true);
10665 if (!O)
10666 return VisitExpr(UO);
10667
10668 notePreMod(O, UO);
10669 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +000010670 // C++11 [expr.pre.incr]p1:
10671 // the expression ++x is equivalent to x+=1
10672 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10673 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010674 }
10675
10676 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10677 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10678 void VisitUnaryPostIncDec(UnaryOperator *UO) {
10679 Object O = getObject(UO->getSubExpr(), true);
10680 if (!O)
10681 return VisitExpr(UO);
10682
10683 notePreMod(O, UO);
10684 Visit(UO->getSubExpr());
10685 notePostMod(O, UO, UK_ModAsSideEffect);
10686 }
10687
10688 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
10689 void VisitBinLOr(BinaryOperator *BO) {
10690 // The side-effects of the LHS of an '&&' are sequenced before the
10691 // value computation of the RHS, and hence before the value computation
10692 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10693 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +000010694 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010695 {
10696 SequencedSubexpression Sequenced(*this);
10697 Visit(BO->getLHS());
10698 }
10699
10700 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010701 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010702 if (!Result)
10703 Visit(BO->getRHS());
10704 } else {
10705 // Check for unsequenced operations in the RHS, treating it as an
10706 // entirely separate evaluation.
10707 //
10708 // FIXME: If there are operations in the RHS which are unsequenced
10709 // with respect to operations outside the RHS, and those operations
10710 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +000010711 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010712 }
Richard Smithc406cb72013-01-17 01:17:56 +000010713 }
10714 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +000010715 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010716 {
10717 SequencedSubexpression Sequenced(*this);
10718 Visit(BO->getLHS());
10719 }
10720
10721 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010722 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010723 if (Result)
10724 Visit(BO->getRHS());
10725 } else {
Richard Smithd33f5202013-01-17 23:18:09 +000010726 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010727 }
Richard Smithc406cb72013-01-17 01:17:56 +000010728 }
10729
10730 // Only visit the condition, unless we can be sure which subexpression will
10731 // be chosen.
10732 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +000010733 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +000010734 {
10735 SequencedSubexpression Sequenced(*this);
10736 Visit(CO->getCond());
10737 }
Richard Smithc406cb72013-01-17 01:17:56 +000010738
10739 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010740 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +000010741 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010742 else {
Richard Smithd33f5202013-01-17 23:18:09 +000010743 WorkList.push_back(CO->getTrueExpr());
10744 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010745 }
Richard Smithc406cb72013-01-17 01:17:56 +000010746 }
10747
Richard Smithe3dbfe02013-06-30 10:40:20 +000010748 void VisitCallExpr(CallExpr *CE) {
10749 // C++11 [intro.execution]p15:
10750 // When calling a function [...], every value computation and side effect
10751 // associated with any argument expression, or with the postfix expression
10752 // designating the called function, is sequenced before execution of every
10753 // expression or statement in the body of the function [and thus before
10754 // the value computation of its result].
10755 SequencedSubexpression Sequenced(*this);
10756 Base::VisitCallExpr(CE);
10757
10758 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10759 }
10760
Richard Smithc406cb72013-01-17 01:17:56 +000010761 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +000010762 // This is a call, so all subexpressions are sequenced before the result.
10763 SequencedSubexpression Sequenced(*this);
10764
Richard Smithc406cb72013-01-17 01:17:56 +000010765 if (!CCE->isListInitialization())
10766 return VisitExpr(CCE);
10767
10768 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010769 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010770 SequenceTree::Seq Parent = Region;
10771 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10772 E = CCE->arg_end();
10773 I != E; ++I) {
10774 Region = Tree.allocate(Parent);
10775 Elts.push_back(Region);
10776 Visit(*I);
10777 }
10778
10779 // Forget that the initializers are sequenced.
10780 Region = Parent;
10781 for (unsigned I = 0; I < Elts.size(); ++I)
10782 Tree.merge(Elts[I]);
10783 }
10784
10785 void VisitInitListExpr(InitListExpr *ILE) {
10786 if (!SemaRef.getLangOpts().CPlusPlus11)
10787 return VisitExpr(ILE);
10788
10789 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010790 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010791 SequenceTree::Seq Parent = Region;
10792 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10793 Expr *E = ILE->getInit(I);
10794 if (!E) continue;
10795 Region = Tree.allocate(Parent);
10796 Elts.push_back(Region);
10797 Visit(E);
10798 }
10799
10800 // Forget that the initializers are sequenced.
10801 Region = Parent;
10802 for (unsigned I = 0; I < Elts.size(); ++I)
10803 Tree.merge(Elts[I]);
10804 }
10805};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010806
10807} // namespace
Richard Smithc406cb72013-01-17 01:17:56 +000010808
10809void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010810 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +000010811 WorkList.push_back(E);
10812 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +000010813 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +000010814 SequenceChecker(*this, Item, WorkList);
10815 }
Richard Smithc406cb72013-01-17 01:17:56 +000010816}
10817
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010818void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10819 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +000010820 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +000010821 if (!E->isInstantiationDependent())
10822 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010823 if (!IsConstexpr && !E->isValueDependent())
Richard Smith9f7df0c2017-06-26 23:19:32 +000010824 CheckForIntOverflow(E);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000010825 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +000010826}
10827
John McCall1f425642010-11-11 03:21:53 +000010828void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10829 FieldDecl *BitField,
10830 Expr *Init) {
10831 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10832}
10833
David Majnemer61a5bbf2015-04-07 22:08:51 +000010834static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
10835 SourceLocation Loc) {
10836 if (!PType->isVariablyModifiedType())
10837 return;
10838 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10839 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10840 return;
10841 }
David Majnemerdf8f73f2015-04-09 19:53:25 +000010842 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10843 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10844 return;
10845 }
David Majnemer61a5bbf2015-04-07 22:08:51 +000010846 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10847 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10848 return;
10849 }
10850
10851 const ArrayType *AT = S.Context.getAsArrayType(PType);
10852 if (!AT)
10853 return;
10854
10855 if (AT->getSizeModifier() != ArrayType::Star) {
10856 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
10857 return;
10858 }
10859
10860 S.Diag(Loc, diag::err_array_star_in_function_definition);
10861}
10862
Mike Stump0c2ec772010-01-21 03:59:47 +000010863/// CheckParmsForFunctionDef - Check that the parameters of the given
10864/// function are appropriate for the definition of a function. This
10865/// takes care of any checks that cannot be performed on the
10866/// declaration itself, e.g., that the types of each of the function
10867/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +000010868bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +000010869 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010870 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +000010871 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010872 // C99 6.7.5.3p4: the parameters in a parameter type list in a
10873 // function declarator that is part of a function definition of
10874 // that function shall not have incomplete type.
10875 //
10876 // This is also C++ [dcl.fct]p6.
10877 if (!Param->isInvalidDecl() &&
10878 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000010879 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010880 Param->setInvalidDecl();
10881 HasInvalidParm = true;
10882 }
10883
10884 // C99 6.9.1p5: If the declarator includes a parameter type list, the
10885 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +000010886 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +000010887 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +000010888 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000010889 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +000010890 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +000010891
10892 // C99 6.7.5.3p12:
10893 // If the function declarator is not part of a definition of that
10894 // function, parameters may have incomplete type and may use the [*]
10895 // notation in their sequences of declarator specifiers to specify
10896 // variable length array types.
10897 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +000010898 // FIXME: This diagnostic should point the '[*]' if source-location
10899 // information is added for it.
10900 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010901
Akira Hatanaka02914dc2018-02-05 20:23:22 +000010902 // If the parameter is a c++ class type and it has to be destructed in the
10903 // callee function, declare the destructor so that it can be called by the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +000010904 // callee function. Do not perform any direct access check on the dtor here.
Akira Hatanaka02914dc2018-02-05 20:23:22 +000010905 if (!Param->isInvalidDecl()) {
10906 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
10907 if (!ClassDecl->isInvalidDecl() &&
10908 !ClassDecl->hasIrrelevantDestructor() &&
10909 !ClassDecl->isDependentContext() &&
10910 Context.isParamDestroyedInCallee(Param->getType())) {
10911 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10912 MarkFunctionReferenced(Param->getLocation(), Destructor);
10913 DiagnoseUseOfDecl(Destructor, Param->getLocation());
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010914 }
10915 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010916 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010917
10918 // Parameters with the pass_object_size attribute only need to be marked
10919 // constant at function definitions. Because we lack information about
10920 // whether we're on a declaration or definition when we're instantiating the
10921 // attribute, we need to check for constness here.
10922 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
10923 if (!Param->getType().isConstQualified())
10924 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10925 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +000010926 }
10927
10928 return HasInvalidParm;
10929}
John McCall2b5c1b22010-08-12 21:44:57 +000010930
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000010931/// A helper function to get the alignment of a Decl referred to by DeclRefExpr
10932/// or MemberExpr.
10933static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
10934 ASTContext &Context) {
10935 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
10936 return Context.getDeclAlign(DRE->getDecl());
10937
10938 if (const auto *ME = dyn_cast<MemberExpr>(E))
10939 return Context.getDeclAlign(ME->getMemberDecl());
10940
10941 return TypeAlign;
10942}
10943
John McCall2b5c1b22010-08-12 21:44:57 +000010944/// CheckCastAlign - Implements -Wcast-align, which warns when a
10945/// pointer cast increases the alignment requirements.
10946void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
10947 // This is actually a lot of work to potentially be doing on every
10948 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010949 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +000010950 return;
10951
10952 // Ignore dependent types.
10953 if (T->isDependentType() || Op->getType()->isDependentType())
10954 return;
10955
10956 // Require that the destination be a pointer type.
10957 const PointerType *DestPtr = T->getAs<PointerType>();
10958 if (!DestPtr) return;
10959
10960 // If the destination has alignment 1, we're done.
10961 QualType DestPointee = DestPtr->getPointeeType();
10962 if (DestPointee->isIncompleteType()) return;
10963 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
10964 if (DestAlign.isOne()) return;
10965
10966 // Require that the source be a pointer type.
10967 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
10968 if (!SrcPtr) return;
10969 QualType SrcPointee = SrcPtr->getPointeeType();
10970
10971 // Whitelist casts from cv void*. We already implicitly
10972 // whitelisted casts to cv void*, since they have alignment 1.
10973 // Also whitelist casts involving incomplete types, which implicitly
10974 // includes 'void'.
10975 if (SrcPointee->isIncompleteType()) return;
10976
10977 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000010978
10979 if (auto *CE = dyn_cast<CastExpr>(Op)) {
10980 if (CE->getCastKind() == CK_ArrayToPointerDecay)
10981 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
10982 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
10983 if (UO->getOpcode() == UO_AddrOf)
10984 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
10985 }
10986
John McCall2b5c1b22010-08-12 21:44:57 +000010987 if (SrcAlign >= DestAlign) return;
10988
10989 Diag(TRange.getBegin(), diag::warn_cast_align)
10990 << Op->getType() << T
10991 << static_cast<unsigned>(SrcAlign.getQuantity())
10992 << static_cast<unsigned>(DestAlign.getQuantity())
10993 << TRange << Op->getSourceRange();
10994}
10995
Chandler Carruth28389f02011-08-05 09:10:50 +000010996/// \brief Check whether this array fits the idiom of a size-one tail padded
10997/// array member of a struct.
10998///
10999/// We avoid emitting out-of-bounds access warnings for such arrays as they are
11000/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +000011001static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +000011002 const NamedDecl *ND) {
11003 if (Size != 1 || !ND) return false;
11004
11005 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
11006 if (!FD) return false;
11007
11008 // Don't consider sizes resulting from macro expansions or template argument
11009 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +000011010
11011 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000011012 while (TInfo) {
11013 TypeLoc TL = TInfo->getTypeLoc();
11014 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +000011015 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
11016 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000011017 TInfo = TDL->getTypeSourceInfo();
11018 continue;
11019 }
David Blaikie6adc78e2013-02-18 22:06:02 +000011020 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
11021 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +000011022 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
11023 return false;
11024 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +000011025 break;
Sean Callanan06a48a62012-05-04 18:22:53 +000011026 }
Chandler Carruth28389f02011-08-05 09:10:50 +000011027
11028 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +000011029 if (!RD) return false;
11030 if (RD->isUnion()) return false;
11031 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
11032 if (!CRD->isStandardLayout()) return false;
11033 }
Chandler Carruth28389f02011-08-05 09:10:50 +000011034
Benjamin Kramer8c543672011-08-06 03:04:42 +000011035 // See if this is the last field decl in the record.
11036 const Decl *D = FD;
11037 while ((D = D->getNextDeclInContext()))
11038 if (isa<FieldDecl>(D))
11039 return false;
11040 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +000011041}
11042
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011043void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011044 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +000011045 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011046 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011047 if (IndexExpr->isValueDependent())
11048 return;
11049
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000011050 const Type *EffectiveType =
11051 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011052 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011053 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011054 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011055 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +000011056 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +000011057
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011058 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +000011059 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +000011060 return;
Richard Smith13f67182011-12-16 19:31:14 +000011061 if (IndexNegated)
11062 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +000011063
Craig Topperc3ec1492014-05-26 06:22:03 +000011064 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +000011065 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011066 ND = DRE->getDecl();
Chandler Carruth28389f02011-08-05 09:10:50 +000011067 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011068 ND = ME->getMemberDecl();
Chandler Carruth126b1552011-08-05 08:07:29 +000011069
Ted Kremeneke4b316c2011-02-23 23:06:04 +000011070 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011071 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +000011072 if (!size.isStrictlyPositive())
11073 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011074
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000011075 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +000011076 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011077 // Make sure we're comparing apples to apples when comparing index to size
11078 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
11079 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +000011080 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +000011081 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011082 if (ptrarith_typesize != array_typesize) {
11083 // There's a cast to a different size type involved
11084 uint64_t ratio = array_typesize / ptrarith_typesize;
11085 // TODO: Be smarter about handling cases where array_typesize is not a
11086 // multiple of ptrarith_typesize
11087 if (ptrarith_typesize * ratio == array_typesize)
11088 size *= llvm::APInt(size.getBitWidth(), ratio);
11089 }
11090 }
11091
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011092 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011093 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011094 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011095 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011096
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011097 // For array subscripting the index must be less than size, but for pointer
11098 // arithmetic also allow the index (offset) to be equal to size since
11099 // computing the next address after the end of the array is legal and
11100 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011101 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +000011102 return;
11103
11104 // Also don't warn for arrays of size 1 which are members of some
11105 // structure. These are often used to approximate flexible arrays in C89
11106 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011107 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +000011108 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011109
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011110 // Suppress the warning if the subscript expression (as identified by the
11111 // ']' location) and the index expression are both from macro expansions
11112 // within a system header.
11113 if (ASE) {
11114 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
11115 ASE->getRBracketLoc());
11116 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
11117 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
11118 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +000011119 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011120 return;
11121 }
11122 }
11123
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011124 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011125 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011126 DiagID = diag::warn_array_index_exceeds_bounds;
11127
11128 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11129 PDiag(DiagID) << index.toString(10, true)
11130 << size.toString(10, true)
11131 << (unsigned)size.getLimitedValue(~0U)
11132 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011133 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011134 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011135 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011136 DiagID = diag::warn_ptr_arith_precedes_bounds;
11137 if (index.isNegative()) index = -index;
11138 }
11139
11140 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11141 PDiag(DiagID) << index.toString(10, true)
11142 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +000011143 }
Chandler Carruth1af88f12011-02-17 21:10:52 +000011144
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000011145 if (!ND) {
11146 // Try harder to find a NamedDecl to point at in the note.
11147 while (const ArraySubscriptExpr *ASE =
11148 dyn_cast<ArraySubscriptExpr>(BaseExpr))
11149 BaseExpr = ASE->getBase()->IgnoreParenCasts();
11150 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011151 ND = DRE->getDecl();
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000011152 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011153 ND = ME->getMemberDecl();
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000011154 }
11155
Chandler Carruth1af88f12011-02-17 21:10:52 +000011156 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011157 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
11158 PDiag(diag::note_array_index_out_of_bounds)
11159 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +000011160}
11161
Ted Kremenekdf26df72011-03-01 18:41:00 +000011162void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011163 int AllowOnePastEnd = 0;
11164 while (expr) {
11165 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +000011166 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011167 case Stmt::ArraySubscriptExprClass: {
11168 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011169 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011170 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +000011171 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011172 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +000011173 case Stmt::OMPArraySectionExprClass: {
11174 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
11175 if (ASE->getLowerBound())
11176 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
11177 /*ASE=*/nullptr, AllowOnePastEnd > 0);
11178 return;
11179 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011180 case Stmt::UnaryOperatorClass: {
11181 // Only unwrap the * and & unary operators
11182 const UnaryOperator *UO = cast<UnaryOperator>(expr);
11183 expr = UO->getSubExpr();
11184 switch (UO->getOpcode()) {
11185 case UO_AddrOf:
11186 AllowOnePastEnd++;
11187 break;
11188 case UO_Deref:
11189 AllowOnePastEnd--;
11190 break;
11191 default:
11192 return;
11193 }
11194 break;
11195 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011196 case Stmt::ConditionalOperatorClass: {
11197 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
11198 if (const Expr *lhs = cond->getLHS())
11199 CheckArrayAccess(lhs);
11200 if (const Expr *rhs = cond->getRHS())
11201 CheckArrayAccess(rhs);
11202 return;
11203 }
Daniel Marjamaki20a209e2017-02-28 14:53:50 +000011204 case Stmt::CXXOperatorCallExprClass: {
11205 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
11206 for (const auto *Arg : OCE->arguments())
11207 CheckArrayAccess(Arg);
11208 return;
11209 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011210 default:
11211 return;
11212 }
Peter Collingbourne91147592011-04-15 00:35:48 +000011213 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011214}
John McCall31168b02011-06-15 23:02:42 +000011215
11216//===--- CHECK: Objective-C retain cycles ----------------------------------//
11217
11218namespace {
John McCall31168b02011-06-15 23:02:42 +000011219
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011220struct RetainCycleOwner {
11221 VarDecl *Variable = nullptr;
11222 SourceRange Range;
11223 SourceLocation Loc;
11224 bool Indirect = false;
11225
11226 RetainCycleOwner() = default;
11227
11228 void setLocsFrom(Expr *e) {
11229 Loc = e->getExprLoc();
11230 Range = e->getSourceRange();
11231 }
11232};
11233
11234} // namespace
John McCall31168b02011-06-15 23:02:42 +000011235
11236/// Consider whether capturing the given variable can possibly lead to
11237/// a retain cycle.
11238static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000011239 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +000011240 // lifetime. In MRR, it's captured strongly if the variable is
11241 // __block and has an appropriate type.
11242 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11243 return false;
11244
11245 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011246 if (ref)
11247 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +000011248 return true;
11249}
11250
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011251static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +000011252 while (true) {
11253 e = e->IgnoreParens();
11254 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
11255 switch (cast->getCastKind()) {
11256 case CK_BitCast:
11257 case CK_LValueBitCast:
11258 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +000011259 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +000011260 e = cast->getSubExpr();
11261 continue;
11262
John McCall31168b02011-06-15 23:02:42 +000011263 default:
11264 return false;
11265 }
11266 }
11267
11268 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
11269 ObjCIvarDecl *ivar = ref->getDecl();
11270 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11271 return false;
11272
11273 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011274 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +000011275 return false;
11276
11277 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
11278 owner.Indirect = true;
11279 return true;
11280 }
11281
11282 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
11283 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
11284 if (!var) return false;
11285 return considerVariable(var, ref, owner);
11286 }
11287
John McCall31168b02011-06-15 23:02:42 +000011288 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
11289 if (member->isArrow()) return false;
11290
11291 // Don't count this as an indirect ownership.
11292 e = member->getBase();
11293 continue;
11294 }
11295
John McCallfe96e0b2011-11-06 09:01:30 +000011296 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
11297 // Only pay attention to pseudo-objects on property references.
11298 ObjCPropertyRefExpr *pre
11299 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
11300 ->IgnoreParens());
11301 if (!pre) return false;
11302 if (pre->isImplicitProperty()) return false;
11303 ObjCPropertyDecl *property = pre->getExplicitProperty();
11304 if (!property->isRetaining() &&
11305 !(property->getPropertyIvarDecl() &&
11306 property->getPropertyIvarDecl()->getType()
11307 .getObjCLifetime() == Qualifiers::OCL_Strong))
11308 return false;
11309
11310 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011311 if (pre->isSuperReceiver()) {
11312 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
11313 if (!owner.Variable)
11314 return false;
11315 owner.Loc = pre->getLocation();
11316 owner.Range = pre->getSourceRange();
11317 return true;
11318 }
John McCallfe96e0b2011-11-06 09:01:30 +000011319 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
11320 ->getSourceExpr());
11321 continue;
11322 }
11323
John McCall31168b02011-06-15 23:02:42 +000011324 // Array ivars?
11325
11326 return false;
11327 }
11328}
11329
11330namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011331
John McCall31168b02011-06-15 23:02:42 +000011332 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011333 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +000011334 VarDecl *Variable;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011335 Expr *Capturer = nullptr;
11336 bool VarWillBeReased = false;
11337
11338 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
11339 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
11340 Context(Context), Variable(variable) {}
John McCall31168b02011-06-15 23:02:42 +000011341
11342 void VisitDeclRefExpr(DeclRefExpr *ref) {
11343 if (ref->getDecl() == Variable && !Capturer)
11344 Capturer = ref;
11345 }
11346
John McCall31168b02011-06-15 23:02:42 +000011347 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
11348 if (Capturer) return;
11349 Visit(ref->getBase());
11350 if (Capturer && ref->isFreeIvar())
11351 Capturer = ref;
11352 }
11353
11354 void VisitBlockExpr(BlockExpr *block) {
11355 // Look inside nested blocks
11356 if (block->getBlockDecl()->capturesVariable(Variable))
11357 Visit(block->getBlockDecl()->getBody());
11358 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +000011359
11360 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
11361 if (Capturer) return;
11362 if (OVE->getSourceExpr())
11363 Visit(OVE->getSourceExpr());
11364 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011365
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011366 void VisitBinaryOperator(BinaryOperator *BinOp) {
11367 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
11368 return;
11369 Expr *LHS = BinOp->getLHS();
11370 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
11371 if (DRE->getDecl() != Variable)
11372 return;
11373 if (Expr *RHS = BinOp->getRHS()) {
11374 RHS = RHS->IgnoreParenCasts();
11375 llvm::APSInt Value;
11376 VarWillBeReased =
11377 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
11378 }
11379 }
11380 }
John McCall31168b02011-06-15 23:02:42 +000011381 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011382
11383} // namespace
John McCall31168b02011-06-15 23:02:42 +000011384
11385/// Check whether the given argument is a block which captures a
11386/// variable.
11387static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
11388 assert(owner.Variable && owner.Loc.isValid());
11389
11390 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000011391
11392 // Look through [^{...} copy] and Block_copy(^{...}).
11393 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
11394 Selector Cmd = ME->getSelector();
11395 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
11396 e = ME->getInstanceReceiver();
11397 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000011398 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000011399 e = e->IgnoreParenCasts();
11400 }
11401 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
11402 if (CE->getNumArgs() == 1) {
11403 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000011404 if (Fn) {
11405 const IdentifierInfo *FnI = Fn->getIdentifier();
11406 if (FnI && FnI->isStr("_Block_copy")) {
11407 e = CE->getArg(0)->IgnoreParenCasts();
11408 }
11409 }
Jordan Rose67e887c2012-09-17 17:54:30 +000011410 }
11411 }
11412
John McCall31168b02011-06-15 23:02:42 +000011413 BlockExpr *block = dyn_cast<BlockExpr>(e);
11414 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000011415 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000011416
11417 FindCaptureVisitor visitor(S.Context, owner.Variable);
11418 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011419 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000011420}
11421
11422static void diagnoseRetainCycle(Sema &S, Expr *capturer,
11423 RetainCycleOwner &owner) {
11424 assert(capturer);
11425 assert(owner.Variable && owner.Loc.isValid());
11426
11427 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
11428 << owner.Variable << capturer->getSourceRange();
11429 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
11430 << owner.Indirect << owner.Range;
11431}
11432
11433/// Check for a keyword selector that starts with the word 'add' or
11434/// 'set'.
11435static bool isSetterLikeSelector(Selector sel) {
11436 if (sel.isUnarySelector()) return false;
11437
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011438 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000011439 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011440 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000011441 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011442 else if (str.startswith("add")) {
11443 // Specially whitelist 'addOperationWithBlock:'.
11444 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
11445 return false;
11446 str = str.substr(3);
11447 }
John McCall31168b02011-06-15 23:02:42 +000011448 else
11449 return false;
11450
11451 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000011452 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000011453}
11454
Benjamin Kramer3a743452015-03-09 15:03:32 +000011455static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
11456 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011457 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
11458 Message->getReceiverInterface(),
11459 NSAPI::ClassId_NSMutableArray);
11460 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011461 return None;
11462 }
11463
11464 Selector Sel = Message->getSelector();
11465
11466 Optional<NSAPI::NSArrayMethodKind> MKOpt =
11467 S.NSAPIObj->getNSArrayMethodKind(Sel);
11468 if (!MKOpt) {
11469 return None;
11470 }
11471
11472 NSAPI::NSArrayMethodKind MK = *MKOpt;
11473
11474 switch (MK) {
11475 case NSAPI::NSMutableArr_addObject:
11476 case NSAPI::NSMutableArr_insertObjectAtIndex:
11477 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
11478 return 0;
11479 case NSAPI::NSMutableArr_replaceObjectAtIndex:
11480 return 1;
11481
11482 default:
11483 return None;
11484 }
11485
11486 return None;
11487}
11488
11489static
11490Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
11491 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011492 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
11493 Message->getReceiverInterface(),
11494 NSAPI::ClassId_NSMutableDictionary);
11495 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011496 return None;
11497 }
11498
11499 Selector Sel = Message->getSelector();
11500
11501 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
11502 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
11503 if (!MKOpt) {
11504 return None;
11505 }
11506
11507 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
11508
11509 switch (MK) {
11510 case NSAPI::NSMutableDict_setObjectForKey:
11511 case NSAPI::NSMutableDict_setValueForKey:
11512 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
11513 return 0;
11514
11515 default:
11516 return None;
11517 }
11518
11519 return None;
11520}
11521
11522static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011523 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
11524 Message->getReceiverInterface(),
11525 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000011526
Alex Denisov5dfac812015-08-06 04:51:14 +000011527 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
11528 Message->getReceiverInterface(),
11529 NSAPI::ClassId_NSMutableOrderedSet);
11530 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011531 return None;
11532 }
11533
11534 Selector Sel = Message->getSelector();
11535
11536 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
11537 if (!MKOpt) {
11538 return None;
11539 }
11540
11541 NSAPI::NSSetMethodKind MK = *MKOpt;
11542
11543 switch (MK) {
11544 case NSAPI::NSMutableSet_addObject:
11545 case NSAPI::NSOrderedSet_setObjectAtIndex:
11546 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
11547 case NSAPI::NSOrderedSet_insertObjectAtIndex:
11548 return 0;
11549 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
11550 return 1;
11551 }
11552
11553 return None;
11554}
11555
11556void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
11557 if (!Message->isInstanceMessage()) {
11558 return;
11559 }
11560
11561 Optional<int> ArgOpt;
11562
11563 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
11564 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
11565 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
11566 return;
11567 }
11568
11569 int ArgIndex = *ArgOpt;
11570
Alex Denisove1d882c2015-03-04 17:55:52 +000011571 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
11572 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
11573 Arg = OE->getSourceExpr()->IgnoreImpCasts();
11574 }
11575
Alex Denisov5dfac812015-08-06 04:51:14 +000011576 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011577 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011578 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011579 Diag(Message->getSourceRange().getBegin(),
11580 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000011581 << ArgRE->getDecl() << StringRef("'super'");
Alex Denisove1d882c2015-03-04 17:55:52 +000011582 }
11583 }
Alex Denisov5dfac812015-08-06 04:51:14 +000011584 } else {
11585 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
11586
11587 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
11588 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
11589 }
11590
11591 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
11592 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11593 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
11594 ValueDecl *Decl = ReceiverRE->getDecl();
11595 Diag(Message->getSourceRange().getBegin(),
11596 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000011597 << Decl << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000011598 if (!ArgRE->isObjCSelfExpr()) {
11599 Diag(Decl->getLocation(),
11600 diag::note_objc_circular_container_declared_here)
Richard Trieub4025802018-03-28 04:16:13 +000011601 << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000011602 }
11603 }
11604 }
11605 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
11606 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
11607 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
11608 ObjCIvarDecl *Decl = IvarRE->getDecl();
11609 Diag(Message->getSourceRange().getBegin(),
11610 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000011611 << Decl << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000011612 Diag(Decl->getLocation(),
11613 diag::note_objc_circular_container_declared_here)
Richard Trieub4025802018-03-28 04:16:13 +000011614 << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000011615 }
Alex Denisove1d882c2015-03-04 17:55:52 +000011616 }
11617 }
11618 }
Alex Denisove1d882c2015-03-04 17:55:52 +000011619}
11620
John McCall31168b02011-06-15 23:02:42 +000011621/// Check a message send to see if it's likely to cause a retain cycle.
11622void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
11623 // Only check instance methods whose selector looks like a setter.
11624 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
11625 return;
11626
11627 // Try to find a variable that the receiver is strongly owned by.
11628 RetainCycleOwner owner;
11629 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011630 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000011631 return;
11632 } else {
11633 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
11634 owner.Variable = getCurMethodDecl()->getSelfDecl();
11635 owner.Loc = msg->getSuperLoc();
11636 owner.Range = msg->getSuperLoc();
11637 }
11638
11639 // Check whether the receiver is captured by any of the arguments.
Alex Lorenz42a97a92017-11-17 20:44:25 +000011640 const ObjCMethodDecl *MD = msg->getMethodDecl();
11641 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
11642 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
11643 // noescape blocks should not be retained by the method.
11644 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
11645 continue;
John McCall31168b02011-06-15 23:02:42 +000011646 return diagnoseRetainCycle(*this, capturer, owner);
Alex Lorenz42a97a92017-11-17 20:44:25 +000011647 }
11648 }
John McCall31168b02011-06-15 23:02:42 +000011649}
11650
11651/// Check a property assign to see if it's likely to cause a retain cycle.
11652void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
11653 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011654 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000011655 return;
11656
11657 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
11658 diagnoseRetainCycle(*this, capturer, owner);
11659}
11660
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011661void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
11662 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000011663 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011664 return;
11665
11666 // Because we don't have an expression for the variable, we have to set the
11667 // location explicitly here.
11668 Owner.Loc = Var->getLocation();
11669 Owner.Range = Var->getSourceRange();
11670
11671 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
11672 diagnoseRetainCycle(*this, Capturer, Owner);
11673}
11674
Ted Kremenek9304da92012-12-21 08:04:28 +000011675static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
11676 Expr *RHS, bool isProperty) {
11677 // Check if RHS is an Objective-C object literal, which also can get
11678 // immediately zapped in a weak reference. Note that we explicitly
11679 // allow ObjCStringLiterals, since those are designed to never really die.
11680 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011681
Ted Kremenek64873352012-12-21 22:46:35 +000011682 // This enum needs to match with the 'select' in
11683 // warn_objc_arc_literal_assign (off-by-1).
11684 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
11685 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
11686 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011687
11688 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000011689 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000011690 << (isProperty ? 0 : 1)
11691 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011692
11693 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000011694}
11695
Ted Kremenekc1f014a2012-12-21 19:45:30 +000011696static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
11697 Qualifiers::ObjCLifetime LT,
11698 Expr *RHS, bool isProperty) {
11699 // Strip off any implicit cast added to get to the one ARC-specific.
11700 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11701 if (cast->getCastKind() == CK_ARCConsumeObject) {
11702 S.Diag(Loc, diag::warn_arc_retained_assign)
11703 << (LT == Qualifiers::OCL_ExplicitNone)
11704 << (isProperty ? 0 : 1)
11705 << RHS->getSourceRange();
11706 return true;
11707 }
11708 RHS = cast->getSubExpr();
11709 }
11710
11711 if (LT == Qualifiers::OCL_Weak &&
11712 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
11713 return true;
11714
11715 return false;
11716}
11717
Ted Kremenekb36234d2012-12-21 08:04:20 +000011718bool Sema::checkUnsafeAssigns(SourceLocation Loc,
11719 QualType LHS, Expr *RHS) {
11720 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
11721
11722 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
11723 return false;
11724
11725 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
11726 return true;
11727
11728 return false;
11729}
11730
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011731void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
11732 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011733 QualType LHSType;
11734 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000011735 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011736 ObjCPropertyRefExpr *PRE
11737 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11738 if (PRE && !PRE->isImplicitProperty()) {
11739 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11740 if (PD)
11741 LHSType = PD->getType();
11742 }
11743
11744 if (LHSType.isNull())
11745 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000011746
11747 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
11748
11749 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011750 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000011751 getCurFunction()->markSafeWeakUse(LHS);
11752 }
11753
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011754 if (checkUnsafeAssigns(Loc, LHSType, RHS))
11755 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000011756
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011757 // FIXME. Check for other life times.
11758 if (LT != Qualifiers::OCL_None)
11759 return;
11760
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011761 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011762 if (PRE->isImplicitProperty())
11763 return;
11764 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11765 if (!PD)
11766 return;
11767
Bill Wendling44426052012-12-20 19:22:21 +000011768 unsigned Attributes = PD->getPropertyAttributes();
11769 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011770 // when 'assign' attribute was not explicitly specified
11771 // by user, ignore it and rely on property type itself
11772 // for lifetime info.
11773 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11774 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11775 LHSType->isObjCRetainableType())
11776 return;
11777
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011778 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000011779 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011780 Diag(Loc, diag::warn_arc_retained_property_assign)
11781 << RHS->getSourceRange();
11782 return;
11783 }
11784 RHS = cast->getSubExpr();
11785 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011786 }
Bill Wendling44426052012-12-20 19:22:21 +000011787 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000011788 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11789 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000011790 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011791 }
11792}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011793
11794//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11795
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011796static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11797 SourceLocation StmtLoc,
11798 const NullStmt *Body) {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011799 // Do not warn if the body is a macro that expands to nothing, e.g:
11800 //
11801 // #define CALL(x)
11802 // if (condition)
11803 // CALL(0);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011804 if (Body->hasLeadingEmptyMacro())
11805 return false;
11806
11807 // Get line numbers of statement and body.
11808 bool StmtLineInvalid;
Hans Wennborg95419752017-11-20 17:38:16 +000011809 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011810 &StmtLineInvalid);
11811 if (StmtLineInvalid)
11812 return false;
11813
11814 bool BodyLineInvalid;
11815 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11816 &BodyLineInvalid);
11817 if (BodyLineInvalid)
11818 return false;
11819
11820 // Warn if null statement and body are on the same line.
11821 if (StmtLine != BodyLine)
11822 return false;
11823
11824 return true;
11825}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011826
11827void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
11828 const Stmt *Body,
11829 unsigned DiagID) {
11830 // Since this is a syntactic check, don't emit diagnostic for template
11831 // instantiations, this just adds noise.
11832 if (CurrentInstantiationScope)
11833 return;
11834
11835 // The body should be a null statement.
11836 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11837 if (!NBody)
11838 return;
11839
11840 // Do the usual checks.
11841 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11842 return;
11843
11844 Diag(NBody->getSemiLoc(), DiagID);
11845 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11846}
11847
11848void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
11849 const Stmt *PossibleBody) {
11850 assert(!CurrentInstantiationScope); // Ensured by caller
11851
11852 SourceLocation StmtLoc;
11853 const Stmt *Body;
11854 unsigned DiagID;
11855 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11856 StmtLoc = FS->getRParenLoc();
11857 Body = FS->getBody();
11858 DiagID = diag::warn_empty_for_body;
11859 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11860 StmtLoc = WS->getCond()->getSourceRange().getEnd();
11861 Body = WS->getBody();
11862 DiagID = diag::warn_empty_while_body;
11863 } else
11864 return; // Neither `for' nor `while'.
11865
11866 // The body should be a null statement.
11867 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11868 if (!NBody)
11869 return;
11870
11871 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011872 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011873 return;
11874
11875 // Do the usual checks.
11876 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11877 return;
11878
11879 // `for(...);' and `while(...);' are popular idioms, so in order to keep
11880 // noise level low, emit diagnostics only if for/while is followed by a
11881 // CompoundStmt, e.g.:
11882 // for (int i = 0; i < n; i++);
11883 // {
11884 // a(i);
11885 // }
11886 // or if for/while is followed by a statement with more indentation
11887 // than for/while itself:
11888 // for (int i = 0; i < n; i++);
11889 // a(i);
11890 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
11891 if (!ProbableTypo) {
11892 bool BodyColInvalid;
11893 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
11894 PossibleBody->getLocStart(),
11895 &BodyColInvalid);
11896 if (BodyColInvalid)
11897 return;
11898
11899 bool StmtColInvalid;
11900 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
11901 S->getLocStart(),
11902 &StmtColInvalid);
11903 if (StmtColInvalid)
11904 return;
11905
11906 if (BodyCol > StmtCol)
11907 ProbableTypo = true;
11908 }
11909
11910 if (ProbableTypo) {
11911 Diag(NBody->getSemiLoc(), DiagID);
11912 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11913 }
11914}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011915
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011916//===--- CHECK: Warn on self move with std::move. -------------------------===//
11917
11918/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
11919void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
11920 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011921 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11922 return;
11923
Richard Smith51ec0cf2017-02-21 01:17:38 +000011924 if (inTemplateInstantiation())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011925 return;
11926
11927 // Strip parens and casts away.
11928 LHSExpr = LHSExpr->IgnoreParenImpCasts();
11929 RHSExpr = RHSExpr->IgnoreParenImpCasts();
11930
11931 // Check for a call expression
11932 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
11933 if (!CE || CE->getNumArgs() != 1)
11934 return;
11935
11936 // Check for a call to std::move
Nico Weberb688d132017-09-28 16:16:39 +000011937 if (!CE->isCallToStdMove())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011938 return;
11939
11940 // Get argument from std::move
11941 RHSExpr = CE->getArg(0);
11942
11943 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11944 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11945
11946 // Two DeclRefExpr's, check that the decls are the same.
11947 if (LHSDeclRef && RHSDeclRef) {
11948 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11949 return;
11950 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11951 RHSDeclRef->getDecl()->getCanonicalDecl())
11952 return;
11953
11954 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11955 << LHSExpr->getSourceRange()
11956 << RHSExpr->getSourceRange();
11957 return;
11958 }
11959
11960 // Member variables require a different approach to check for self moves.
11961 // MemberExpr's are the same if every nested MemberExpr refers to the same
11962 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
11963 // the base Expr's are CXXThisExpr's.
11964 const Expr *LHSBase = LHSExpr;
11965 const Expr *RHSBase = RHSExpr;
11966 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
11967 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
11968 if (!LHSME || !RHSME)
11969 return;
11970
11971 while (LHSME && RHSME) {
11972 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
11973 RHSME->getMemberDecl()->getCanonicalDecl())
11974 return;
11975
11976 LHSBase = LHSME->getBase();
11977 RHSBase = RHSME->getBase();
11978 LHSME = dyn_cast<MemberExpr>(LHSBase);
11979 RHSME = dyn_cast<MemberExpr>(RHSBase);
11980 }
11981
11982 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
11983 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
11984 if (LHSDeclRef && RHSDeclRef) {
11985 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11986 return;
11987 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11988 RHSDeclRef->getDecl()->getCanonicalDecl())
11989 return;
11990
11991 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11992 << LHSExpr->getSourceRange()
11993 << RHSExpr->getSourceRange();
11994 return;
11995 }
11996
11997 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
11998 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11999 << LHSExpr->getSourceRange()
12000 << RHSExpr->getSourceRange();
12001}
12002
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012003//===--- Layout compatibility ----------------------------------------------//
12004
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012005static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012006
12007/// \brief Check if two enumeration types are layout-compatible.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012008static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012009 // C++11 [dcl.enum] p8:
12010 // Two enumeration types are layout-compatible if they have the same
12011 // underlying type.
12012 return ED1->isComplete() && ED2->isComplete() &&
12013 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
12014}
12015
12016/// \brief Check if two fields are layout-compatible.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012017static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
12018 FieldDecl *Field2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012019 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
12020 return false;
12021
12022 if (Field1->isBitField() != Field2->isBitField())
12023 return false;
12024
12025 if (Field1->isBitField()) {
12026 // Make sure that the bit-fields are the same length.
12027 unsigned Bits1 = Field1->getBitWidthValue(C);
12028 unsigned Bits2 = Field2->getBitWidthValue(C);
12029
12030 if (Bits1 != Bits2)
12031 return false;
12032 }
12033
12034 return true;
12035}
12036
12037/// \brief Check if two standard-layout structs are layout-compatible.
12038/// (C++11 [class.mem] p17)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012039static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
12040 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012041 // If both records are C++ classes, check that base classes match.
12042 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
12043 // If one of records is a CXXRecordDecl we are in C++ mode,
12044 // thus the other one is a CXXRecordDecl, too.
12045 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
12046 // Check number of base classes.
12047 if (D1CXX->getNumBases() != D2CXX->getNumBases())
12048 return false;
12049
12050 // Check the base classes.
12051 for (CXXRecordDecl::base_class_const_iterator
12052 Base1 = D1CXX->bases_begin(),
12053 BaseEnd1 = D1CXX->bases_end(),
12054 Base2 = D2CXX->bases_begin();
12055 Base1 != BaseEnd1;
12056 ++Base1, ++Base2) {
12057 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
12058 return false;
12059 }
12060 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
12061 // If only RD2 is a C++ class, it should have zero base classes.
12062 if (D2CXX->getNumBases() > 0)
12063 return false;
12064 }
12065
12066 // Check the fields.
12067 RecordDecl::field_iterator Field2 = RD2->field_begin(),
12068 Field2End = RD2->field_end(),
12069 Field1 = RD1->field_begin(),
12070 Field1End = RD1->field_end();
12071 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
12072 if (!isLayoutCompatible(C, *Field1, *Field2))
12073 return false;
12074 }
12075 if (Field1 != Field1End || Field2 != Field2End)
12076 return false;
12077
12078 return true;
12079}
12080
12081/// \brief Check if two standard-layout unions are layout-compatible.
12082/// (C++11 [class.mem] p18)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012083static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
12084 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012085 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012086 for (auto *Field2 : RD2->fields())
12087 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012088
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012089 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012090 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
12091 I = UnmatchedFields.begin(),
12092 E = UnmatchedFields.end();
12093
12094 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012095 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012096 bool Result = UnmatchedFields.erase(*I);
12097 (void) Result;
12098 assert(Result);
12099 break;
12100 }
12101 }
12102 if (I == E)
12103 return false;
12104 }
12105
12106 return UnmatchedFields.empty();
12107}
12108
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012109static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
12110 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012111 if (RD1->isUnion() != RD2->isUnion())
12112 return false;
12113
12114 if (RD1->isUnion())
12115 return isLayoutCompatibleUnion(C, RD1, RD2);
12116 else
12117 return isLayoutCompatibleStruct(C, RD1, RD2);
12118}
12119
12120/// \brief Check if two types are layout-compatible in C++11 sense.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012121static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012122 if (T1.isNull() || T2.isNull())
12123 return false;
12124
12125 // C++11 [basic.types] p11:
12126 // If two types T1 and T2 are the same type, then T1 and T2 are
12127 // layout-compatible types.
12128 if (C.hasSameType(T1, T2))
12129 return true;
12130
12131 T1 = T1.getCanonicalType().getUnqualifiedType();
12132 T2 = T2.getCanonicalType().getUnqualifiedType();
12133
12134 const Type::TypeClass TC1 = T1->getTypeClass();
12135 const Type::TypeClass TC2 = T2->getTypeClass();
12136
12137 if (TC1 != TC2)
12138 return false;
12139
12140 if (TC1 == Type::Enum) {
12141 return isLayoutCompatible(C,
12142 cast<EnumType>(T1)->getDecl(),
12143 cast<EnumType>(T2)->getDecl());
12144 } else if (TC1 == Type::Record) {
12145 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
12146 return false;
12147
12148 return isLayoutCompatible(C,
12149 cast<RecordType>(T1)->getDecl(),
12150 cast<RecordType>(T2)->getDecl());
12151 }
12152
12153 return false;
12154}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012155
12156//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
12157
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012158/// \brief Given a type tag expression find the type tag itself.
12159///
12160/// \param TypeExpr Type tag expression, as it appears in user's code.
12161///
12162/// \param VD Declaration of an identifier that appears in a type tag.
12163///
12164/// \param MagicValue Type tag magic value.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012165static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
12166 const ValueDecl **VD, uint64_t *MagicValue) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012167 while(true) {
12168 if (!TypeExpr)
12169 return false;
12170
12171 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
12172
12173 switch (TypeExpr->getStmtClass()) {
12174 case Stmt::UnaryOperatorClass: {
12175 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
12176 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
12177 TypeExpr = UO->getSubExpr();
12178 continue;
12179 }
12180 return false;
12181 }
12182
12183 case Stmt::DeclRefExprClass: {
12184 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
12185 *VD = DRE->getDecl();
12186 return true;
12187 }
12188
12189 case Stmt::IntegerLiteralClass: {
12190 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
12191 llvm::APInt MagicValueAPInt = IL->getValue();
12192 if (MagicValueAPInt.getActiveBits() <= 64) {
12193 *MagicValue = MagicValueAPInt.getZExtValue();
12194 return true;
12195 } else
12196 return false;
12197 }
12198
12199 case Stmt::BinaryConditionalOperatorClass:
12200 case Stmt::ConditionalOperatorClass: {
12201 const AbstractConditionalOperator *ACO =
12202 cast<AbstractConditionalOperator>(TypeExpr);
12203 bool Result;
12204 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
12205 if (Result)
12206 TypeExpr = ACO->getTrueExpr();
12207 else
12208 TypeExpr = ACO->getFalseExpr();
12209 continue;
12210 }
12211 return false;
12212 }
12213
12214 case Stmt::BinaryOperatorClass: {
12215 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
12216 if (BO->getOpcode() == BO_Comma) {
12217 TypeExpr = BO->getRHS();
12218 continue;
12219 }
12220 return false;
12221 }
12222
12223 default:
12224 return false;
12225 }
12226 }
12227}
12228
12229/// \brief Retrieve the C type corresponding to type tag TypeExpr.
12230///
12231/// \param TypeExpr Expression that specifies a type tag.
12232///
12233/// \param MagicValues Registered magic values.
12234///
12235/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
12236/// kind.
12237///
12238/// \param TypeInfo Information about the corresponding C type.
12239///
12240/// \returns true if the corresponding C type was found.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012241static bool GetMatchingCType(
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012242 const IdentifierInfo *ArgumentKind,
12243 const Expr *TypeExpr, const ASTContext &Ctx,
12244 const llvm::DenseMap<Sema::TypeTagMagicValue,
12245 Sema::TypeTagData> *MagicValues,
12246 bool &FoundWrongKind,
12247 Sema::TypeTagData &TypeInfo) {
12248 FoundWrongKind = false;
12249
12250 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000012251 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012252
12253 uint64_t MagicValue;
12254
12255 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
12256 return false;
12257
12258 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000012259 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012260 if (I->getArgumentKind() != ArgumentKind) {
12261 FoundWrongKind = true;
12262 return false;
12263 }
12264 TypeInfo.Type = I->getMatchingCType();
12265 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
12266 TypeInfo.MustBeNull = I->getMustBeNull();
12267 return true;
12268 }
12269 return false;
12270 }
12271
12272 if (!MagicValues)
12273 return false;
12274
12275 llvm::DenseMap<Sema::TypeTagMagicValue,
12276 Sema::TypeTagData>::const_iterator I =
12277 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
12278 if (I == MagicValues->end())
12279 return false;
12280
12281 TypeInfo = I->second;
12282 return true;
12283}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012284
12285void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
12286 uint64_t MagicValue, QualType Type,
12287 bool LayoutCompatible,
12288 bool MustBeNull) {
12289 if (!TypeTagForDatatypeMagicValues)
12290 TypeTagForDatatypeMagicValues.reset(
12291 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
12292
12293 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
12294 (*TypeTagForDatatypeMagicValues)[Magic] =
12295 TypeTagData(Type, LayoutCompatible, MustBeNull);
12296}
12297
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012298static bool IsSameCharType(QualType T1, QualType T2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012299 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
12300 if (!BT1)
12301 return false;
12302
12303 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
12304 if (!BT2)
12305 return false;
12306
12307 BuiltinType::Kind T1Kind = BT1->getKind();
12308 BuiltinType::Kind T2Kind = BT2->getKind();
12309
12310 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
12311 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
12312 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
12313 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
12314}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012315
12316void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012317 const ArrayRef<const Expr *> ExprArgs,
12318 SourceLocation CallSiteLoc) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012319 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
12320 bool IsPointerAttr = Attr->getIsPointer();
12321
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012322 // Retrieve the argument representing the 'type_tag'.
Joel E. Denny81508102018-03-13 14:51:22 +000012323 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
12324 if (TypeTagIdxAST >= ExprArgs.size()) {
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012325 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
Joel E. Denny81508102018-03-13 14:51:22 +000012326 << 0 << Attr->getTypeTagIdx().getSourceIndex();
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012327 return;
12328 }
Joel E. Denny81508102018-03-13 14:51:22 +000012329 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012330 bool FoundWrongKind;
12331 TypeTagData TypeInfo;
12332 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
12333 TypeTagForDatatypeMagicValues.get(),
12334 FoundWrongKind, TypeInfo)) {
12335 if (FoundWrongKind)
12336 Diag(TypeTagExpr->getExprLoc(),
12337 diag::warn_type_tag_for_datatype_wrong_kind)
12338 << TypeTagExpr->getSourceRange();
12339 return;
12340 }
12341
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012342 // Retrieve the argument representing the 'arg_idx'.
Joel E. Denny81508102018-03-13 14:51:22 +000012343 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
12344 if (ArgumentIdxAST >= ExprArgs.size()) {
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012345 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
Joel E. Denny81508102018-03-13 14:51:22 +000012346 << 1 << Attr->getArgumentIdx().getSourceIndex();
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012347 return;
12348 }
Joel E. Denny81508102018-03-13 14:51:22 +000012349 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012350 if (IsPointerAttr) {
12351 // Skip implicit cast of pointer to `void *' (as a function argument).
12352 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000012353 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000012354 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012355 ArgumentExpr = ICE->getSubExpr();
12356 }
12357 QualType ArgumentType = ArgumentExpr->getType();
12358
12359 // Passing a `void*' pointer shouldn't trigger a warning.
12360 if (IsPointerAttr && ArgumentType->isVoidPointerType())
12361 return;
12362
12363 if (TypeInfo.MustBeNull) {
12364 // Type tag with matching void type requires a null pointer.
12365 if (!ArgumentExpr->isNullPointerConstant(Context,
12366 Expr::NPC_ValueDependentIsNotNull)) {
12367 Diag(ArgumentExpr->getExprLoc(),
12368 diag::warn_type_safety_null_pointer_required)
12369 << ArgumentKind->getName()
12370 << ArgumentExpr->getSourceRange()
12371 << TypeTagExpr->getSourceRange();
12372 }
12373 return;
12374 }
12375
12376 QualType RequiredType = TypeInfo.Type;
12377 if (IsPointerAttr)
12378 RequiredType = Context.getPointerType(RequiredType);
12379
12380 bool mismatch = false;
12381 if (!TypeInfo.LayoutCompatible) {
12382 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
12383
12384 // C++11 [basic.fundamental] p1:
12385 // Plain char, signed char, and unsigned char are three distinct types.
12386 //
12387 // But we treat plain `char' as equivalent to `signed char' or `unsigned
12388 // char' depending on the current char signedness mode.
12389 if (mismatch)
12390 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
12391 RequiredType->getPointeeType())) ||
12392 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
12393 mismatch = false;
12394 } else
12395 if (IsPointerAttr)
12396 mismatch = !isLayoutCompatible(Context,
12397 ArgumentType->getPointeeType(),
12398 RequiredType->getPointeeType());
12399 else
12400 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
12401
12402 if (mismatch)
12403 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000012404 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012405 << TypeInfo.LayoutCompatible << RequiredType
12406 << ArgumentExpr->getSourceRange()
12407 << TypeTagExpr->getSourceRange();
12408}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012409
12410void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
12411 CharUnits Alignment) {
12412 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
12413}
12414
12415void Sema::DiagnoseMisalignedMembers() {
12416 for (MisalignedMember &m : MisalignedMembers) {
Alex Lorenz014181e2016-10-05 09:27:48 +000012417 const NamedDecl *ND = m.RD;
12418 if (ND->getName().empty()) {
12419 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
12420 ND = TD;
12421 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012422 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
Alex Lorenz014181e2016-10-05 09:27:48 +000012423 << m.MD << ND << m.E->getSourceRange();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012424 }
12425 MisalignedMembers.clear();
12426}
12427
12428void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012429 E = E->IgnoreParens();
12430 if (!T->isPointerType() && !T->isIntegerType())
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012431 return;
12432 if (isa<UnaryOperator>(E) &&
12433 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
12434 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12435 if (isa<MemberExpr>(Op)) {
12436 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
12437 MisalignedMember(Op));
12438 if (MA != MisalignedMembers.end() &&
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012439 (T->isIntegerType() ||
Roger Ferrer Ibanezd80d6c52017-12-07 09:23:50 +000012440 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
12441 Context.getTypeAlignInChars(
12442 T->getPointeeType()) <= MA->Alignment))))
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012443 MisalignedMembers.erase(MA);
12444 }
12445 }
12446}
12447
12448void Sema::RefersToMemberWithReducedAlignment(
12449 Expr *E,
Benjamin Kramera8c3e672016-12-12 14:41:19 +000012450 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
12451 Action) {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012452 const auto *ME = dyn_cast<MemberExpr>(E);
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012453 if (!ME)
12454 return;
12455
Roger Ferrer Ibanez9f963472017-03-13 13:18:21 +000012456 // No need to check expressions with an __unaligned-qualified type.
12457 if (E->getType().getQualifiers().hasUnaligned())
12458 return;
12459
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012460 // For a chain of MemberExpr like "a.b.c.d" this list
12461 // will keep FieldDecl's like [d, c, b].
12462 SmallVector<FieldDecl *, 4> ReverseMemberChain;
12463 const MemberExpr *TopME = nullptr;
12464 bool AnyIsPacked = false;
12465 do {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012466 QualType BaseType = ME->getBase()->getType();
12467 if (ME->isArrow())
12468 BaseType = BaseType->getPointeeType();
12469 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
Olivier Goffart67049f02017-07-07 09:38:59 +000012470 if (RD->isInvalidDecl())
12471 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012472
12473 ValueDecl *MD = ME->getMemberDecl();
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012474 auto *FD = dyn_cast<FieldDecl>(MD);
12475 // We do not care about non-data members.
12476 if (!FD || FD->isInvalidDecl())
12477 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012478
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012479 AnyIsPacked =
12480 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
12481 ReverseMemberChain.push_back(FD);
12482
12483 TopME = ME;
12484 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
12485 } while (ME);
12486 assert(TopME && "We did not compute a topmost MemberExpr!");
12487
12488 // Not the scope of this diagnostic.
12489 if (!AnyIsPacked)
12490 return;
12491
12492 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
12493 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
12494 // TODO: The innermost base of the member expression may be too complicated.
12495 // For now, just disregard these cases. This is left for future
12496 // improvement.
12497 if (!DRE && !isa<CXXThisExpr>(TopBase))
12498 return;
12499
12500 // Alignment expected by the whole expression.
12501 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
12502
12503 // No need to do anything else with this case.
12504 if (ExpectedAlignment.isOne())
12505 return;
12506
12507 // Synthesize offset of the whole access.
12508 CharUnits Offset;
12509 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
12510 I++) {
12511 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
12512 }
12513
12514 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
12515 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
12516 ReverseMemberChain.back()->getParent()->getTypeForDecl());
12517
12518 // The base expression of the innermost MemberExpr may give
12519 // stronger guarantees than the class containing the member.
12520 if (DRE && !TopME->isArrow()) {
12521 const ValueDecl *VD = DRE->getDecl();
12522 if (!VD->getType()->isReferenceType())
12523 CompleteObjectAlignment =
12524 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
12525 }
12526
12527 // Check if the synthesized offset fulfills the alignment.
12528 if (Offset % ExpectedAlignment != 0 ||
12529 // It may fulfill the offset it but the effective alignment may still be
12530 // lower than the expected expression alignment.
12531 CompleteObjectAlignment < ExpectedAlignment) {
12532 // If this happens, we want to determine a sensible culprit of this.
12533 // Intuitively, watching the chain of member expressions from right to
12534 // left, we start with the required alignment (as required by the field
12535 // type) but some packed attribute in that chain has reduced the alignment.
12536 // It may happen that another packed structure increases it again. But if
12537 // we are here such increase has not been enough. So pointing the first
12538 // FieldDecl that either is packed or else its RecordDecl is,
12539 // seems reasonable.
12540 FieldDecl *FD = nullptr;
12541 CharUnits Alignment;
12542 for (FieldDecl *FDI : ReverseMemberChain) {
12543 if (FDI->hasAttr<PackedAttr>() ||
12544 FDI->getParent()->hasAttr<PackedAttr>()) {
12545 FD = FDI;
12546 Alignment = std::min(
12547 Context.getTypeAlignInChars(FD->getType()),
12548 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
12549 break;
12550 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012551 }
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012552 assert(FD && "We did not find a packed FieldDecl!");
12553 Action(E, FD->getParent(), FD, Alignment);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012554 }
12555}
12556
12557void Sema::CheckAddressOfPackedMember(Expr *rhs) {
12558 using namespace std::placeholders;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012559
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012560 RefersToMemberWithReducedAlignment(
12561 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
12562 _2, _3, _4));
12563}