blob: e662a5c8b977c48531c4056f52acfa8f9110c31f [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());
121
122 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,
227 CallExpr *TheCall, unsigned SizeIdx,
228 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:
1100 case Builtin::BI__builtin_operator_delete:
1101 if (!getLangOpts().CPlusPlus) {
1102 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
1103 << (BuiltinID == Builtin::BI__builtin_operator_new
1104 ? "__builtin_operator_new"
1105 : "__builtin_operator_delete")
1106 << "C++";
1107 return ExprError();
1108 }
1109 // CodeGen assumes it can find the global new and delete to call,
1110 // so ensure that they are declared.
1111 DeclareGlobalNewDelete();
1112 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001113
1114 // check secure string manipulation functions where overflows
1115 // are detectable at compile time
1116 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001117 case Builtin::BI__builtin___memmove_chk:
1118 case Builtin::BI__builtin___memset_chk:
1119 case Builtin::BI__builtin___strlcat_chk:
1120 case Builtin::BI__builtin___strlcpy_chk:
1121 case Builtin::BI__builtin___strncat_chk:
1122 case Builtin::BI__builtin___strncpy_chk:
1123 case Builtin::BI__builtin___stpncpy_chk:
1124 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
1125 break;
Steven Wu566c14e2014-09-24 04:37:33 +00001126 case Builtin::BI__builtin___memccpy_chk:
1127 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
1128 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001129 case Builtin::BI__builtin___snprintf_chk:
1130 case Builtin::BI__builtin___vsnprintf_chk:
1131 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
1132 break;
Peter Collingbournef7706832014-12-12 23:41:25 +00001133 case Builtin::BI__builtin_call_with_static_chain:
1134 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1135 return ExprError();
1136 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001137 case Builtin::BI__exception_code:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001138 case Builtin::BI_exception_code:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001139 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1140 diag::err_seh___except_block))
1141 return ExprError();
1142 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001143 case Builtin::BI__exception_info:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001144 case Builtin::BI_exception_info:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001145 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1146 diag::err_seh___except_filter))
1147 return ExprError();
1148 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +00001149 case Builtin::BI__GetExceptionInfo:
1150 if (checkArgCount(*this, TheCall, 1))
1151 return ExprError();
1152
1153 if (CheckCXXThrowOperand(
1154 TheCall->getLocStart(),
1155 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1156 TheCall))
1157 return ExprError();
1158
1159 TheCall->setType(Context.VoidPtrTy);
1160 break;
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +00001161 // OpenCL v2.0, s6.13.16 - Pipe functions
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001162 case Builtin::BIread_pipe:
1163 case Builtin::BIwrite_pipe:
1164 // Since those two functions are declared with var args, we need a semantic
1165 // check for the argument.
1166 if (SemaBuiltinRWPipe(*this, TheCall))
1167 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001168 TheCall->setType(Context.IntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001169 break;
1170 case Builtin::BIreserve_read_pipe:
1171 case Builtin::BIreserve_write_pipe:
1172 case Builtin::BIwork_group_reserve_read_pipe:
1173 case Builtin::BIwork_group_reserve_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001174 if (SemaBuiltinReserveRWPipe(*this, TheCall))
1175 return ExprError();
Joey Gouly84ae3362017-07-31 15:15:59 +00001176 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001177 case Builtin::BIsub_group_reserve_read_pipe:
1178 case Builtin::BIsub_group_reserve_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001179 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1180 SemaBuiltinReserveRWPipe(*this, TheCall))
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001181 return ExprError();
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001182 break;
1183 case Builtin::BIcommit_read_pipe:
1184 case Builtin::BIcommit_write_pipe:
1185 case Builtin::BIwork_group_commit_read_pipe:
1186 case Builtin::BIwork_group_commit_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001187 if (SemaBuiltinCommitRWPipe(*this, TheCall))
1188 return ExprError();
1189 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001190 case Builtin::BIsub_group_commit_read_pipe:
1191 case Builtin::BIsub_group_commit_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001192 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1193 SemaBuiltinCommitRWPipe(*this, TheCall))
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001194 return ExprError();
1195 break;
1196 case Builtin::BIget_pipe_num_packets:
1197 case Builtin::BIget_pipe_max_packets:
1198 if (SemaBuiltinPipePackets(*this, TheCall))
1199 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001200 TheCall->setType(Context.UnsignedIntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001201 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +00001202 case Builtin::BIto_global:
1203 case Builtin::BIto_local:
1204 case Builtin::BIto_private:
1205 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1206 return ExprError();
1207 break;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001208 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1209 case Builtin::BIenqueue_kernel:
1210 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1211 return ExprError();
1212 break;
1213 case Builtin::BIget_kernel_work_group_size:
1214 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1215 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1216 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001217 break;
Joey Goulyfa76b492017-08-01 13:27:09 +00001218 break;
1219 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1220 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1221 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1222 return ExprError();
1223 break;
Mehdi Amini06d367c2016-10-24 20:39:34 +00001224 case Builtin::BI__builtin_os_log_format:
1225 case Builtin::BI__builtin_os_log_format_buffer_size:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00001226 if (SemaBuiltinOSLogFormat(TheCall))
Mehdi Amini06d367c2016-10-24 20:39:34 +00001227 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001228 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001229 }
Richard Smith760520b2014-06-03 23:27:44 +00001230
Nate Begeman4904e322010-06-08 02:47:44 +00001231 // Since the target specific builtins for each arch overlap, only check those
1232 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +00001233 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001234 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +00001235 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001236 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001237 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001238 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001239 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1240 return ExprError();
1241 break;
Tim Northover25e8a672014-05-24 12:51:25 +00001242 case llvm::Triple::aarch64:
1243 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +00001244 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +00001245 return ExprError();
1246 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001247 case llvm::Triple::mips:
1248 case llvm::Triple::mipsel:
1249 case llvm::Triple::mips64:
1250 case llvm::Triple::mips64el:
1251 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1252 return ExprError();
1253 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001254 case llvm::Triple::systemz:
1255 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1256 return ExprError();
1257 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001258 case llvm::Triple::x86:
1259 case llvm::Triple::x86_64:
1260 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1261 return ExprError();
1262 break;
Kit Bartone50adcb2015-03-30 19:40:59 +00001263 case llvm::Triple::ppc:
1264 case llvm::Triple::ppc64:
1265 case llvm::Triple::ppc64le:
1266 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1267 return ExprError();
1268 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001269 default:
1270 break;
1271 }
1272 }
1273
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001274 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +00001275}
1276
Nate Begeman91e1fea2010-06-14 05:21:25 +00001277// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +00001278static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +00001279 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +00001280 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +00001281 switch (Type.getEltType()) {
1282 case NeonTypeFlags::Int8:
1283 case NeonTypeFlags::Poly8:
1284 return shift ? 7 : (8 << IsQuad) - 1;
1285 case NeonTypeFlags::Int16:
1286 case NeonTypeFlags::Poly16:
1287 return shift ? 15 : (4 << IsQuad) - 1;
1288 case NeonTypeFlags::Int32:
1289 return shift ? 31 : (2 << IsQuad) - 1;
1290 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +00001291 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +00001292 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001293 case NeonTypeFlags::Poly128:
1294 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +00001295 case NeonTypeFlags::Float16:
1296 assert(!shift && "cannot shift float types!");
1297 return (4 << IsQuad) - 1;
1298 case NeonTypeFlags::Float32:
1299 assert(!shift && "cannot shift float types!");
1300 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001301 case NeonTypeFlags::Float64:
1302 assert(!shift && "cannot shift float types!");
1303 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +00001304 }
David Blaikie8a40f702012-01-17 06:56:22 +00001305 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +00001306}
1307
Bob Wilsone4d77232011-11-08 05:04:11 +00001308/// getNeonEltType - Return the QualType corresponding to the elements of
1309/// the vector type specified by the NeonTypeFlags. This is used to check
1310/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +00001311static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +00001312 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +00001313 switch (Flags.getEltType()) {
1314 case NeonTypeFlags::Int8:
1315 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1316 case NeonTypeFlags::Int16:
1317 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1318 case NeonTypeFlags::Int32:
1319 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1320 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +00001321 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +00001322 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1323 else
1324 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1325 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001326 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +00001327 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001328 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +00001329 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +00001330 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +00001331 if (IsInt64Long)
1332 return Context.UnsignedLongTy;
1333 else
1334 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001335 case NeonTypeFlags::Poly128:
1336 break;
Bob Wilsone4d77232011-11-08 05:04:11 +00001337 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +00001338 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001339 case NeonTypeFlags::Float32:
1340 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +00001341 case NeonTypeFlags::Float64:
1342 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001343 }
David Blaikie8a40f702012-01-17 06:56:22 +00001344 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +00001345}
1346
Tim Northover12670412014-02-19 10:37:05 +00001347bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +00001348 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +00001349 uint64_t mask = 0;
1350 unsigned TV = 0;
1351 int PtrArgNum = -1;
1352 bool HasConstPtr = false;
1353 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +00001354#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001355#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +00001356#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001357 }
1358
1359 // For NEON intrinsics which are overloaded on vector element type, validate
1360 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +00001361 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001362 if (mask) {
1363 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1364 return true;
1365
1366 TV = Result.getLimitedValue(64);
1367 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1368 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +00001369 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +00001370 }
1371
1372 if (PtrArgNum >= 0) {
1373 // Check that pointer arguments have the specified type.
1374 Expr *Arg = TheCall->getArg(PtrArgNum);
1375 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1376 Arg = ICE->getSubExpr();
1377 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1378 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +00001379
Tim Northovera2ee4332014-03-29 15:09:45 +00001380 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Joerg Sonnenberger47006c52017-01-09 11:40:41 +00001381 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1382 Arch == llvm::Triple::aarch64_be;
Tim Northovera2ee4332014-03-29 15:09:45 +00001383 bool IsInt64Long =
1384 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1385 QualType EltTy =
1386 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +00001387 if (HasConstPtr)
1388 EltTy = EltTy.withConst();
1389 QualType LHSTy = Context.getPointerType(EltTy);
1390 AssignConvertType ConvTy;
1391 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1392 if (RHS.isInvalid())
1393 return true;
1394 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1395 RHS.get(), AA_Assigning))
1396 return true;
1397 }
1398
1399 // For NEON intrinsics which take an immediate value as part of the
1400 // instruction, range check them here.
1401 unsigned i = 0, l = 0, u = 0;
1402 switch (BuiltinID) {
1403 default:
1404 return false;
Tim Northover12670412014-02-19 10:37:05 +00001405#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001406#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +00001407#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001408 }
Tim Northover2fe823a2013-08-01 09:23:19 +00001409
Richard Sandiford28940af2014-04-16 08:47:51 +00001410 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +00001411}
1412
Tim Northovera2ee4332014-03-29 15:09:45 +00001413bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1414 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +00001415 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001416 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +00001417 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001418 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +00001419 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001420 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1421 BuiltinID == AArch64::BI__builtin_arm_strex ||
1422 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +00001423 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +00001424 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001425 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1426 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1427 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +00001428
1429 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1430
1431 // Ensure that we have the proper number of arguments.
1432 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1433 return true;
1434
1435 // Inspect the pointer argument of the atomic builtin. This should always be
1436 // a pointer type, whose element is an integral scalar or pointer type.
1437 // Because it is a pointer type, we don't have to worry about any implicit
1438 // casts here.
1439 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1440 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1441 if (PointerArgRes.isInvalid())
1442 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001443 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001444
1445 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1446 if (!pointerType) {
1447 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1448 << PointerArg->getType() << PointerArg->getSourceRange();
1449 return true;
1450 }
1451
1452 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1453 // task is to insert the appropriate casts into the AST. First work out just
1454 // what the appropriate type is.
1455 QualType ValType = pointerType->getPointeeType();
1456 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1457 if (IsLdrex)
1458 AddrType.addConst();
1459
1460 // Issue a warning if the cast is dodgy.
1461 CastKind CastNeeded = CK_NoOp;
1462 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1463 CastNeeded = CK_BitCast;
1464 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1465 << PointerArg->getType()
1466 << Context.getPointerType(AddrType)
1467 << AA_Passing << PointerArg->getSourceRange();
1468 }
1469
1470 // Finally, do the cast and replace the argument with the corrected version.
1471 AddrType = Context.getPointerType(AddrType);
1472 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1473 if (PointerArgRes.isInvalid())
1474 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001475 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001476
1477 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1478
1479 // In general, we allow ints, floats and pointers to be loaded and stored.
1480 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1481 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1482 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1483 << PointerArg->getType() << PointerArg->getSourceRange();
1484 return true;
1485 }
1486
1487 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001488 if (Context.getTypeSize(ValType) > MaxWidth) {
1489 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +00001490 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1491 << PointerArg->getType() << PointerArg->getSourceRange();
1492 return true;
1493 }
1494
1495 switch (ValType.getObjCLifetime()) {
1496 case Qualifiers::OCL_None:
1497 case Qualifiers::OCL_ExplicitNone:
1498 // okay
1499 break;
1500
1501 case Qualifiers::OCL_Weak:
1502 case Qualifiers::OCL_Strong:
1503 case Qualifiers::OCL_Autoreleasing:
1504 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1505 << ValType << PointerArg->getSourceRange();
1506 return true;
1507 }
1508
Tim Northover6aacd492013-07-16 09:47:53 +00001509 if (IsLdrex) {
1510 TheCall->setType(ValType);
1511 return false;
1512 }
1513
1514 // Initialize the argument to be stored.
1515 ExprResult ValArg = TheCall->getArg(0);
1516 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1517 Context, ValType, /*consume*/ false);
1518 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1519 if (ValArg.isInvalid())
1520 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001521 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001522
1523 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1524 // but the custom checker bypasses all default analysis.
1525 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001526 return false;
1527}
1528
Nate Begeman4904e322010-06-08 02:47:44 +00001529bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover6aacd492013-07-16 09:47:53 +00001530 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001531 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1532 BuiltinID == ARM::BI__builtin_arm_strex ||
1533 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001534 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001535 }
1536
Yi Kong26d104a2014-08-13 19:18:14 +00001537 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1538 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1539 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1540 }
1541
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001542 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1543 BuiltinID == ARM::BI__builtin_arm_wsr64)
1544 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1545
1546 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1547 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1548 BuiltinID == ARM::BI__builtin_arm_wsr ||
1549 BuiltinID == ARM::BI__builtin_arm_wsrp)
1550 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1551
Tim Northover12670412014-02-19 10:37:05 +00001552 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1553 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001554
Yi Kong4efadfb2014-07-03 16:01:25 +00001555 // For intrinsics which take an immediate value as part of the instruction,
1556 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +00001557 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +00001558 switch (BuiltinID) {
1559 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +00001560 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1561 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +00001562 case ARM::BI__builtin_arm_vcvtr_f:
1563 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +00001564 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001565 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001566 case ARM::BI__builtin_arm_isb:
1567 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001568 }
Nate Begemand773fe62010-06-13 04:47:52 +00001569
Nate Begemanf568b072010-08-03 21:32:34 +00001570 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +00001571 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001572}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001573
Tim Northover573cbee2014-05-24 12:52:07 +00001574bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001575 CallExpr *TheCall) {
Tim Northover573cbee2014-05-24 12:52:07 +00001576 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001577 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1578 BuiltinID == AArch64::BI__builtin_arm_strex ||
1579 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001580 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1581 }
1582
Yi Konga5548432014-08-13 19:18:20 +00001583 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1584 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1585 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1586 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1587 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1588 }
1589
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001590 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1591 BuiltinID == AArch64::BI__builtin_arm_wsr64)
Tim Northover54e50002016-04-13 17:08:55 +00001592 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001593
1594 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1595 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1596 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1597 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1598 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1599
Tim Northovera2ee4332014-03-29 15:09:45 +00001600 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1601 return true;
1602
Yi Kong19a29ac2014-07-17 10:52:06 +00001603 // For intrinsics which take an immediate value as part of the instruction,
1604 // range check them here.
1605 unsigned i = 0, l = 0, u = 0;
1606 switch (BuiltinID) {
1607 default: return false;
1608 case AArch64::BI__builtin_arm_dmb:
1609 case AArch64::BI__builtin_arm_dsb:
1610 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1611 }
1612
Yi Kong19a29ac2014-07-17 10:52:06 +00001613 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001614}
1615
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001616// CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1617// intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1618// ordering for DSP is unspecified. MSA is ordered by the data format used
1619// by the underlying instruction i.e., df/m, df/n and then by size.
1620//
1621// FIXME: The size tests here should instead be tablegen'd along with the
1622// definitions from include/clang/Basic/BuiltinsMips.def.
1623// FIXME: GCC is strict on signedness for some of these intrinsics, we should
1624// be too.
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001625bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001626 unsigned i = 0, l = 0, u = 0, m = 0;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001627 switch (BuiltinID) {
1628 default: return false;
1629 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1630 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00001631 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1632 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1633 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1634 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1635 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001636 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1637 // df/m field.
1638 // These intrinsics take an unsigned 3 bit immediate.
1639 case Mips::BI__builtin_msa_bclri_b:
1640 case Mips::BI__builtin_msa_bnegi_b:
1641 case Mips::BI__builtin_msa_bseti_b:
1642 case Mips::BI__builtin_msa_sat_s_b:
1643 case Mips::BI__builtin_msa_sat_u_b:
1644 case Mips::BI__builtin_msa_slli_b:
1645 case Mips::BI__builtin_msa_srai_b:
1646 case Mips::BI__builtin_msa_srari_b:
1647 case Mips::BI__builtin_msa_srli_b:
1648 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1649 case Mips::BI__builtin_msa_binsli_b:
1650 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1651 // These intrinsics take an unsigned 4 bit immediate.
1652 case Mips::BI__builtin_msa_bclri_h:
1653 case Mips::BI__builtin_msa_bnegi_h:
1654 case Mips::BI__builtin_msa_bseti_h:
1655 case Mips::BI__builtin_msa_sat_s_h:
1656 case Mips::BI__builtin_msa_sat_u_h:
1657 case Mips::BI__builtin_msa_slli_h:
1658 case Mips::BI__builtin_msa_srai_h:
1659 case Mips::BI__builtin_msa_srari_h:
1660 case Mips::BI__builtin_msa_srli_h:
1661 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1662 case Mips::BI__builtin_msa_binsli_h:
1663 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
1664 // These intrinsics take an unsigned 5 bit immedate.
1665 // The first block of intrinsics actually have an unsigned 5 bit field,
1666 // not a df/n field.
1667 case Mips::BI__builtin_msa_clei_u_b:
1668 case Mips::BI__builtin_msa_clei_u_h:
1669 case Mips::BI__builtin_msa_clei_u_w:
1670 case Mips::BI__builtin_msa_clei_u_d:
1671 case Mips::BI__builtin_msa_clti_u_b:
1672 case Mips::BI__builtin_msa_clti_u_h:
1673 case Mips::BI__builtin_msa_clti_u_w:
1674 case Mips::BI__builtin_msa_clti_u_d:
1675 case Mips::BI__builtin_msa_maxi_u_b:
1676 case Mips::BI__builtin_msa_maxi_u_h:
1677 case Mips::BI__builtin_msa_maxi_u_w:
1678 case Mips::BI__builtin_msa_maxi_u_d:
1679 case Mips::BI__builtin_msa_mini_u_b:
1680 case Mips::BI__builtin_msa_mini_u_h:
1681 case Mips::BI__builtin_msa_mini_u_w:
1682 case Mips::BI__builtin_msa_mini_u_d:
1683 case Mips::BI__builtin_msa_addvi_b:
1684 case Mips::BI__builtin_msa_addvi_h:
1685 case Mips::BI__builtin_msa_addvi_w:
1686 case Mips::BI__builtin_msa_addvi_d:
1687 case Mips::BI__builtin_msa_bclri_w:
1688 case Mips::BI__builtin_msa_bnegi_w:
1689 case Mips::BI__builtin_msa_bseti_w:
1690 case Mips::BI__builtin_msa_sat_s_w:
1691 case Mips::BI__builtin_msa_sat_u_w:
1692 case Mips::BI__builtin_msa_slli_w:
1693 case Mips::BI__builtin_msa_srai_w:
1694 case Mips::BI__builtin_msa_srari_w:
1695 case Mips::BI__builtin_msa_srli_w:
1696 case Mips::BI__builtin_msa_srlri_w:
1697 case Mips::BI__builtin_msa_subvi_b:
1698 case Mips::BI__builtin_msa_subvi_h:
1699 case Mips::BI__builtin_msa_subvi_w:
1700 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1701 case Mips::BI__builtin_msa_binsli_w:
1702 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1703 // These intrinsics take an unsigned 6 bit immediate.
1704 case Mips::BI__builtin_msa_bclri_d:
1705 case Mips::BI__builtin_msa_bnegi_d:
1706 case Mips::BI__builtin_msa_bseti_d:
1707 case Mips::BI__builtin_msa_sat_s_d:
1708 case Mips::BI__builtin_msa_sat_u_d:
1709 case Mips::BI__builtin_msa_slli_d:
1710 case Mips::BI__builtin_msa_srai_d:
1711 case Mips::BI__builtin_msa_srari_d:
1712 case Mips::BI__builtin_msa_srli_d:
1713 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1714 case Mips::BI__builtin_msa_binsli_d:
1715 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1716 // These intrinsics take a signed 5 bit immediate.
1717 case Mips::BI__builtin_msa_ceqi_b:
1718 case Mips::BI__builtin_msa_ceqi_h:
1719 case Mips::BI__builtin_msa_ceqi_w:
1720 case Mips::BI__builtin_msa_ceqi_d:
1721 case Mips::BI__builtin_msa_clti_s_b:
1722 case Mips::BI__builtin_msa_clti_s_h:
1723 case Mips::BI__builtin_msa_clti_s_w:
1724 case Mips::BI__builtin_msa_clti_s_d:
1725 case Mips::BI__builtin_msa_clei_s_b:
1726 case Mips::BI__builtin_msa_clei_s_h:
1727 case Mips::BI__builtin_msa_clei_s_w:
1728 case Mips::BI__builtin_msa_clei_s_d:
1729 case Mips::BI__builtin_msa_maxi_s_b:
1730 case Mips::BI__builtin_msa_maxi_s_h:
1731 case Mips::BI__builtin_msa_maxi_s_w:
1732 case Mips::BI__builtin_msa_maxi_s_d:
1733 case Mips::BI__builtin_msa_mini_s_b:
1734 case Mips::BI__builtin_msa_mini_s_h:
1735 case Mips::BI__builtin_msa_mini_s_w:
1736 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
1737 // These intrinsics take an unsigned 8 bit immediate.
1738 case Mips::BI__builtin_msa_andi_b:
1739 case Mips::BI__builtin_msa_nori_b:
1740 case Mips::BI__builtin_msa_ori_b:
1741 case Mips::BI__builtin_msa_shf_b:
1742 case Mips::BI__builtin_msa_shf_h:
1743 case Mips::BI__builtin_msa_shf_w:
1744 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
1745 case Mips::BI__builtin_msa_bseli_b:
1746 case Mips::BI__builtin_msa_bmnzi_b:
1747 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
1748 // df/n format
1749 // These intrinsics take an unsigned 4 bit immediate.
1750 case Mips::BI__builtin_msa_copy_s_b:
1751 case Mips::BI__builtin_msa_copy_u_b:
1752 case Mips::BI__builtin_msa_insve_b:
1753 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001754 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
1755 // These intrinsics take an unsigned 3 bit immediate.
1756 case Mips::BI__builtin_msa_copy_s_h:
1757 case Mips::BI__builtin_msa_copy_u_h:
1758 case Mips::BI__builtin_msa_insve_h:
1759 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001760 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1761 // These intrinsics take an unsigned 2 bit immediate.
1762 case Mips::BI__builtin_msa_copy_s_w:
1763 case Mips::BI__builtin_msa_copy_u_w:
1764 case Mips::BI__builtin_msa_insve_w:
1765 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001766 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1767 // These intrinsics take an unsigned 1 bit immediate.
1768 case Mips::BI__builtin_msa_copy_s_d:
1769 case Mips::BI__builtin_msa_copy_u_d:
1770 case Mips::BI__builtin_msa_insve_d:
1771 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001772 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1773 // Memory offsets and immediate loads.
1774 // These intrinsics take a signed 10 bit immediate.
Petar Jovanovic9b8b9e82017-03-31 16:16:43 +00001775 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001776 case Mips::BI__builtin_msa_ldi_h:
1777 case Mips::BI__builtin_msa_ldi_w:
1778 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1779 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1780 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1781 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1782 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1783 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1784 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1785 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1786 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001787 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001788
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001789 if (!m)
1790 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1791
1792 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1793 SemaBuiltinConstantArgMultiple(TheCall, i, m);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001794}
1795
Kit Bartone50adcb2015-03-30 19:40:59 +00001796bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1797 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00001798 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1799 BuiltinID == PPC::BI__builtin_divdeu ||
1800 BuiltinID == PPC::BI__builtin_bpermd;
1801 bool IsTarget64Bit = Context.getTargetInfo()
1802 .getTypeWidth(Context
1803 .getTargetInfo()
1804 .getIntPtrType()) == 64;
1805 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1806 BuiltinID == PPC::BI__builtin_divweu ||
1807 BuiltinID == PPC::BI__builtin_divde ||
1808 BuiltinID == PPC::BI__builtin_divdeu;
1809
1810 if (Is64BitBltin && !IsTarget64Bit)
1811 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1812 << TheCall->getSourceRange();
1813
1814 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1815 (BuiltinID == PPC::BI__builtin_bpermd &&
1816 !Context.getTargetInfo().hasFeature("bpermd")))
1817 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1818 << TheCall->getSourceRange();
1819
Kit Bartone50adcb2015-03-30 19:40:59 +00001820 switch (BuiltinID) {
1821 default: return false;
1822 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1823 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1824 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1825 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1826 case PPC::BI__builtin_tbegin:
1827 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1828 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1829 case PPC::BI__builtin_tabortwc:
1830 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1831 case PPC::BI__builtin_tabortwci:
1832 case PPC::BI__builtin_tabortdci:
1833 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1834 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
Tony Jiangbbc48e92017-05-24 15:13:32 +00001835 case PPC::BI__builtin_vsx_xxpermdi:
Tony Jiang9aa2c032017-05-24 15:54:13 +00001836 case PPC::BI__builtin_vsx_xxsldwi:
Tony Jiangbbc48e92017-05-24 15:13:32 +00001837 return SemaBuiltinVSX(TheCall);
Kit Bartone50adcb2015-03-30 19:40:59 +00001838 }
1839 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1840}
1841
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001842bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1843 CallExpr *TheCall) {
1844 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1845 Expr *Arg = TheCall->getArg(0);
1846 llvm::APSInt AbortCode(32);
1847 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1848 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1849 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1850 << Arg->getSourceRange();
1851 }
1852
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001853 // For intrinsics which take an immediate value as part of the instruction,
1854 // range check them here.
1855 unsigned i = 0, l = 0, u = 0;
1856 switch (BuiltinID) {
1857 default: return false;
1858 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1859 case SystemZ::BI__builtin_s390_verimb:
1860 case SystemZ::BI__builtin_s390_verimh:
1861 case SystemZ::BI__builtin_s390_verimf:
1862 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1863 case SystemZ::BI__builtin_s390_vfaeb:
1864 case SystemZ::BI__builtin_s390_vfaeh:
1865 case SystemZ::BI__builtin_s390_vfaef:
1866 case SystemZ::BI__builtin_s390_vfaebs:
1867 case SystemZ::BI__builtin_s390_vfaehs:
1868 case SystemZ::BI__builtin_s390_vfaefs:
1869 case SystemZ::BI__builtin_s390_vfaezb:
1870 case SystemZ::BI__builtin_s390_vfaezh:
1871 case SystemZ::BI__builtin_s390_vfaezf:
1872 case SystemZ::BI__builtin_s390_vfaezbs:
1873 case SystemZ::BI__builtin_s390_vfaezhs:
1874 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00001875 case SystemZ::BI__builtin_s390_vfisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001876 case SystemZ::BI__builtin_s390_vfidb:
1877 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1878 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00001879 case SystemZ::BI__builtin_s390_vftcisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001880 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1881 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1882 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1883 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1884 case SystemZ::BI__builtin_s390_vstrcb:
1885 case SystemZ::BI__builtin_s390_vstrch:
1886 case SystemZ::BI__builtin_s390_vstrcf:
1887 case SystemZ::BI__builtin_s390_vstrczb:
1888 case SystemZ::BI__builtin_s390_vstrczh:
1889 case SystemZ::BI__builtin_s390_vstrczf:
1890 case SystemZ::BI__builtin_s390_vstrcbs:
1891 case SystemZ::BI__builtin_s390_vstrchs:
1892 case SystemZ::BI__builtin_s390_vstrcfs:
1893 case SystemZ::BI__builtin_s390_vstrczbs:
1894 case SystemZ::BI__builtin_s390_vstrczhs:
1895 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00001896 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
1897 case SystemZ::BI__builtin_s390_vfminsb:
1898 case SystemZ::BI__builtin_s390_vfmaxsb:
1899 case SystemZ::BI__builtin_s390_vfmindb:
1900 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001901 }
1902 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001903}
1904
Craig Topper5ba2c502015-11-07 08:08:31 +00001905/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1906/// This checks that the target supports __builtin_cpu_supports and
1907/// that the string argument is constant and valid.
1908static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1909 Expr *Arg = TheCall->getArg(0);
1910
1911 // Check if the argument is a string literal.
1912 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1913 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1914 << Arg->getSourceRange();
1915
1916 // Check the contents of the string.
1917 StringRef Feature =
1918 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1919 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1920 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1921 << Arg->getSourceRange();
1922 return false;
1923}
1924
Craig Topper699ae0c2017-08-10 20:28:30 +00001925/// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
1926/// This checks that the target supports __builtin_cpu_is and
1927/// that the string argument is constant and valid.
1928static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
1929 Expr *Arg = TheCall->getArg(0);
1930
1931 // Check if the argument is a string literal.
1932 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1933 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1934 << Arg->getSourceRange();
1935
1936 // Check the contents of the string.
1937 StringRef Feature =
1938 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1939 if (!S.Context.getTargetInfo().validateCpuIs(Feature))
1940 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is)
1941 << Arg->getSourceRange();
1942 return false;
1943}
1944
Craig Toppera7e253e2016-09-23 04:48:31 +00001945// Check if the rounding mode is legal.
1946bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
1947 // Indicates if this instruction has rounding control or just SAE.
1948 bool HasRC = false;
1949
1950 unsigned ArgNum = 0;
1951 switch (BuiltinID) {
1952 default:
1953 return false;
1954 case X86::BI__builtin_ia32_vcvttsd2si32:
1955 case X86::BI__builtin_ia32_vcvttsd2si64:
1956 case X86::BI__builtin_ia32_vcvttsd2usi32:
1957 case X86::BI__builtin_ia32_vcvttsd2usi64:
1958 case X86::BI__builtin_ia32_vcvttss2si32:
1959 case X86::BI__builtin_ia32_vcvttss2si64:
1960 case X86::BI__builtin_ia32_vcvttss2usi32:
1961 case X86::BI__builtin_ia32_vcvttss2usi64:
1962 ArgNum = 1;
1963 break;
1964 case X86::BI__builtin_ia32_cvtps2pd512_mask:
1965 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1966 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1967 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1968 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1969 case X86::BI__builtin_ia32_cvttps2dq512_mask:
1970 case X86::BI__builtin_ia32_cvttps2qq512_mask:
1971 case X86::BI__builtin_ia32_cvttps2udq512_mask:
1972 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1973 case X86::BI__builtin_ia32_exp2pd_mask:
1974 case X86::BI__builtin_ia32_exp2ps_mask:
1975 case X86::BI__builtin_ia32_getexppd512_mask:
1976 case X86::BI__builtin_ia32_getexpps512_mask:
1977 case X86::BI__builtin_ia32_rcp28pd_mask:
1978 case X86::BI__builtin_ia32_rcp28ps_mask:
1979 case X86::BI__builtin_ia32_rsqrt28pd_mask:
1980 case X86::BI__builtin_ia32_rsqrt28ps_mask:
1981 case X86::BI__builtin_ia32_vcomisd:
1982 case X86::BI__builtin_ia32_vcomiss:
1983 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1984 ArgNum = 3;
1985 break;
1986 case X86::BI__builtin_ia32_cmppd512_mask:
1987 case X86::BI__builtin_ia32_cmpps512_mask:
1988 case X86::BI__builtin_ia32_cmpsd_mask:
1989 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001990 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00001991 case X86::BI__builtin_ia32_getexpsd128_round_mask:
1992 case X86::BI__builtin_ia32_getexpss128_round_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001993 case X86::BI__builtin_ia32_maxpd512_mask:
1994 case X86::BI__builtin_ia32_maxps512_mask:
1995 case X86::BI__builtin_ia32_maxsd_round_mask:
1996 case X86::BI__builtin_ia32_maxss_round_mask:
1997 case X86::BI__builtin_ia32_minpd512_mask:
1998 case X86::BI__builtin_ia32_minps512_mask:
1999 case X86::BI__builtin_ia32_minsd_round_mask:
2000 case X86::BI__builtin_ia32_minss_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00002001 case X86::BI__builtin_ia32_rcp28sd_round_mask:
2002 case X86::BI__builtin_ia32_rcp28ss_round_mask:
2003 case X86::BI__builtin_ia32_reducepd512_mask:
2004 case X86::BI__builtin_ia32_reduceps512_mask:
2005 case X86::BI__builtin_ia32_rndscalepd_mask:
2006 case X86::BI__builtin_ia32_rndscaleps_mask:
2007 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
2008 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
2009 ArgNum = 4;
2010 break;
2011 case X86::BI__builtin_ia32_fixupimmpd512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002012 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002013 case X86::BI__builtin_ia32_fixupimmps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002014 case X86::BI__builtin_ia32_fixupimmps512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002015 case X86::BI__builtin_ia32_fixupimmsd_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002016 case X86::BI__builtin_ia32_fixupimmsd_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002017 case X86::BI__builtin_ia32_fixupimmss_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002018 case X86::BI__builtin_ia32_fixupimmss_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002019 case X86::BI__builtin_ia32_rangepd512_mask:
2020 case X86::BI__builtin_ia32_rangeps512_mask:
2021 case X86::BI__builtin_ia32_rangesd128_round_mask:
2022 case X86::BI__builtin_ia32_rangess128_round_mask:
2023 case X86::BI__builtin_ia32_reducesd_mask:
2024 case X86::BI__builtin_ia32_reducess_mask:
2025 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2026 case X86::BI__builtin_ia32_rndscaless_round_mask:
2027 ArgNum = 5;
2028 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00002029 case X86::BI__builtin_ia32_vcvtsd2si64:
2030 case X86::BI__builtin_ia32_vcvtsd2si32:
2031 case X86::BI__builtin_ia32_vcvtsd2usi32:
2032 case X86::BI__builtin_ia32_vcvtsd2usi64:
2033 case X86::BI__builtin_ia32_vcvtss2si32:
2034 case X86::BI__builtin_ia32_vcvtss2si64:
2035 case X86::BI__builtin_ia32_vcvtss2usi32:
2036 case X86::BI__builtin_ia32_vcvtss2usi64:
2037 ArgNum = 1;
2038 HasRC = true;
2039 break;
Craig Topper8e066312016-11-07 07:01:09 +00002040 case X86::BI__builtin_ia32_cvtsi2sd64:
2041 case X86::BI__builtin_ia32_cvtsi2ss32:
2042 case X86::BI__builtin_ia32_cvtsi2ss64:
Craig Topper7609f1c2016-10-01 21:03:50 +00002043 case X86::BI__builtin_ia32_cvtusi2sd64:
2044 case X86::BI__builtin_ia32_cvtusi2ss32:
2045 case X86::BI__builtin_ia32_cvtusi2ss64:
2046 ArgNum = 2;
2047 HasRC = true;
2048 break;
2049 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
2050 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
2051 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
2052 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
2053 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
2054 case X86::BI__builtin_ia32_cvtps2qq512_mask:
2055 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
2056 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
2057 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
2058 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
2059 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002060 case X86::BI__builtin_ia32_sqrtpd512_mask:
2061 case X86::BI__builtin_ia32_sqrtps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002062 ArgNum = 3;
2063 HasRC = true;
2064 break;
2065 case X86::BI__builtin_ia32_addpd512_mask:
2066 case X86::BI__builtin_ia32_addps512_mask:
2067 case X86::BI__builtin_ia32_divpd512_mask:
2068 case X86::BI__builtin_ia32_divps512_mask:
2069 case X86::BI__builtin_ia32_mulpd512_mask:
2070 case X86::BI__builtin_ia32_mulps512_mask:
2071 case X86::BI__builtin_ia32_subpd512_mask:
2072 case X86::BI__builtin_ia32_subps512_mask:
2073 case X86::BI__builtin_ia32_addss_round_mask:
2074 case X86::BI__builtin_ia32_addsd_round_mask:
2075 case X86::BI__builtin_ia32_divss_round_mask:
2076 case X86::BI__builtin_ia32_divsd_round_mask:
2077 case X86::BI__builtin_ia32_mulss_round_mask:
2078 case X86::BI__builtin_ia32_mulsd_round_mask:
2079 case X86::BI__builtin_ia32_subss_round_mask:
2080 case X86::BI__builtin_ia32_subsd_round_mask:
2081 case X86::BI__builtin_ia32_scalefpd512_mask:
2082 case X86::BI__builtin_ia32_scalefps512_mask:
2083 case X86::BI__builtin_ia32_scalefsd_round_mask:
2084 case X86::BI__builtin_ia32_scalefss_round_mask:
2085 case X86::BI__builtin_ia32_getmantpd512_mask:
2086 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002087 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
2088 case X86::BI__builtin_ia32_sqrtsd_round_mask:
2089 case X86::BI__builtin_ia32_sqrtss_round_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002090 case X86::BI__builtin_ia32_vfmaddpd512_mask:
2091 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
2092 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
2093 case X86::BI__builtin_ia32_vfmaddps512_mask:
2094 case X86::BI__builtin_ia32_vfmaddps512_mask3:
2095 case X86::BI__builtin_ia32_vfmaddps512_maskz:
2096 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
2097 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
2098 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
2099 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
2100 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
2101 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
2102 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
2103 case X86::BI__builtin_ia32_vfmsubps512_mask3:
2104 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
2105 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
2106 case X86::BI__builtin_ia32_vfnmaddpd512_mask:
2107 case X86::BI__builtin_ia32_vfnmaddps512_mask:
2108 case X86::BI__builtin_ia32_vfnmsubpd512_mask:
2109 case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
2110 case X86::BI__builtin_ia32_vfnmsubps512_mask:
2111 case X86::BI__builtin_ia32_vfnmsubps512_mask3:
2112 case X86::BI__builtin_ia32_vfmaddsd3_mask:
2113 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
2114 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
2115 case X86::BI__builtin_ia32_vfmaddss3_mask:
2116 case X86::BI__builtin_ia32_vfmaddss3_maskz:
2117 case X86::BI__builtin_ia32_vfmaddss3_mask3:
2118 ArgNum = 4;
2119 HasRC = true;
2120 break;
2121 case X86::BI__builtin_ia32_getmantsd_round_mask:
2122 case X86::BI__builtin_ia32_getmantss_round_mask:
2123 ArgNum = 5;
2124 HasRC = true;
2125 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00002126 }
2127
2128 llvm::APSInt Result;
2129
2130 // We can't check the value of a dependent argument.
2131 Expr *Arg = TheCall->getArg(ArgNum);
2132 if (Arg->isTypeDependent() || Arg->isValueDependent())
2133 return false;
2134
2135 // Check constant-ness first.
2136 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2137 return true;
2138
2139 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
2140 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
2141 // combined with ROUND_NO_EXC.
2142 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
2143 Result == 8/*ROUND_NO_EXC*/ ||
2144 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
2145 return false;
2146
2147 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
2148 << Arg->getSourceRange();
2149}
2150
Craig Topperdf5beb22017-03-13 17:16:50 +00002151// Check if the gather/scatter scale is legal.
2152bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
2153 CallExpr *TheCall) {
2154 unsigned ArgNum = 0;
2155 switch (BuiltinID) {
2156 default:
2157 return false;
2158 case X86::BI__builtin_ia32_gatherpfdpd:
2159 case X86::BI__builtin_ia32_gatherpfdps:
2160 case X86::BI__builtin_ia32_gatherpfqpd:
2161 case X86::BI__builtin_ia32_gatherpfqps:
2162 case X86::BI__builtin_ia32_scatterpfdpd:
2163 case X86::BI__builtin_ia32_scatterpfdps:
2164 case X86::BI__builtin_ia32_scatterpfqpd:
2165 case X86::BI__builtin_ia32_scatterpfqps:
2166 ArgNum = 3;
2167 break;
2168 case X86::BI__builtin_ia32_gatherd_pd:
2169 case X86::BI__builtin_ia32_gatherd_pd256:
2170 case X86::BI__builtin_ia32_gatherq_pd:
2171 case X86::BI__builtin_ia32_gatherq_pd256:
2172 case X86::BI__builtin_ia32_gatherd_ps:
2173 case X86::BI__builtin_ia32_gatherd_ps256:
2174 case X86::BI__builtin_ia32_gatherq_ps:
2175 case X86::BI__builtin_ia32_gatherq_ps256:
2176 case X86::BI__builtin_ia32_gatherd_q:
2177 case X86::BI__builtin_ia32_gatherd_q256:
2178 case X86::BI__builtin_ia32_gatherq_q:
2179 case X86::BI__builtin_ia32_gatherq_q256:
2180 case X86::BI__builtin_ia32_gatherd_d:
2181 case X86::BI__builtin_ia32_gatherd_d256:
2182 case X86::BI__builtin_ia32_gatherq_d:
2183 case X86::BI__builtin_ia32_gatherq_d256:
2184 case X86::BI__builtin_ia32_gather3div2df:
2185 case X86::BI__builtin_ia32_gather3div2di:
2186 case X86::BI__builtin_ia32_gather3div4df:
2187 case X86::BI__builtin_ia32_gather3div4di:
2188 case X86::BI__builtin_ia32_gather3div4sf:
2189 case X86::BI__builtin_ia32_gather3div4si:
2190 case X86::BI__builtin_ia32_gather3div8sf:
2191 case X86::BI__builtin_ia32_gather3div8si:
2192 case X86::BI__builtin_ia32_gather3siv2df:
2193 case X86::BI__builtin_ia32_gather3siv2di:
2194 case X86::BI__builtin_ia32_gather3siv4df:
2195 case X86::BI__builtin_ia32_gather3siv4di:
2196 case X86::BI__builtin_ia32_gather3siv4sf:
2197 case X86::BI__builtin_ia32_gather3siv4si:
2198 case X86::BI__builtin_ia32_gather3siv8sf:
2199 case X86::BI__builtin_ia32_gather3siv8si:
2200 case X86::BI__builtin_ia32_gathersiv8df:
2201 case X86::BI__builtin_ia32_gathersiv16sf:
2202 case X86::BI__builtin_ia32_gatherdiv8df:
2203 case X86::BI__builtin_ia32_gatherdiv16sf:
2204 case X86::BI__builtin_ia32_gathersiv8di:
2205 case X86::BI__builtin_ia32_gathersiv16si:
2206 case X86::BI__builtin_ia32_gatherdiv8di:
2207 case X86::BI__builtin_ia32_gatherdiv16si:
2208 case X86::BI__builtin_ia32_scatterdiv2df:
2209 case X86::BI__builtin_ia32_scatterdiv2di:
2210 case X86::BI__builtin_ia32_scatterdiv4df:
2211 case X86::BI__builtin_ia32_scatterdiv4di:
2212 case X86::BI__builtin_ia32_scatterdiv4sf:
2213 case X86::BI__builtin_ia32_scatterdiv4si:
2214 case X86::BI__builtin_ia32_scatterdiv8sf:
2215 case X86::BI__builtin_ia32_scatterdiv8si:
2216 case X86::BI__builtin_ia32_scattersiv2df:
2217 case X86::BI__builtin_ia32_scattersiv2di:
2218 case X86::BI__builtin_ia32_scattersiv4df:
2219 case X86::BI__builtin_ia32_scattersiv4di:
2220 case X86::BI__builtin_ia32_scattersiv4sf:
2221 case X86::BI__builtin_ia32_scattersiv4si:
2222 case X86::BI__builtin_ia32_scattersiv8sf:
2223 case X86::BI__builtin_ia32_scattersiv8si:
2224 case X86::BI__builtin_ia32_scattersiv8df:
2225 case X86::BI__builtin_ia32_scattersiv16sf:
2226 case X86::BI__builtin_ia32_scatterdiv8df:
2227 case X86::BI__builtin_ia32_scatterdiv16sf:
2228 case X86::BI__builtin_ia32_scattersiv8di:
2229 case X86::BI__builtin_ia32_scattersiv16si:
2230 case X86::BI__builtin_ia32_scatterdiv8di:
2231 case X86::BI__builtin_ia32_scatterdiv16si:
2232 ArgNum = 4;
2233 break;
2234 }
2235
2236 llvm::APSInt Result;
2237
2238 // We can't check the value of a dependent argument.
2239 Expr *Arg = TheCall->getArg(ArgNum);
2240 if (Arg->isTypeDependent() || Arg->isValueDependent())
2241 return false;
2242
2243 // Check constant-ness first.
2244 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2245 return true;
2246
2247 if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
2248 return false;
2249
2250 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
2251 << Arg->getSourceRange();
2252}
2253
Craig Topperf0ddc892016-09-23 04:48:27 +00002254bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2255 if (BuiltinID == X86::BI__builtin_cpu_supports)
2256 return SemaBuiltinCpuSupports(*this, TheCall);
2257
Craig Topper699ae0c2017-08-10 20:28:30 +00002258 if (BuiltinID == X86::BI__builtin_cpu_is)
2259 return SemaBuiltinCpuIs(*this, TheCall);
2260
Craig Toppera7e253e2016-09-23 04:48:31 +00002261 // If the intrinsic has rounding or SAE make sure its valid.
2262 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2263 return true;
2264
Craig Topperdf5beb22017-03-13 17:16:50 +00002265 // If the intrinsic has a gather/scatter scale immediate make sure its valid.
2266 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
2267 return true;
2268
Craig Topperf0ddc892016-09-23 04:48:27 +00002269 // For intrinsics which take an immediate value as part of the instruction,
2270 // range check them here.
2271 int i = 0, l = 0, u = 0;
2272 switch (BuiltinID) {
2273 default:
2274 return false;
Richard Trieucc3949d2016-02-18 22:34:54 +00002275 case X86::BI_mm_prefetch:
Craig Topper39c87102016-05-18 03:18:12 +00002276 i = 1; l = 0; u = 3;
2277 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00002278 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper39c87102016-05-18 03:18:12 +00002279 case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2280 case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2281 case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2282 case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002283 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002284 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00002285 case X86::BI__builtin_ia32_vpermil2pd:
2286 case X86::BI__builtin_ia32_vpermil2pd256:
2287 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00002288 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00002289 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002290 break;
Craig Topper95b0d732015-01-25 23:30:05 +00002291 case X86::BI__builtin_ia32_cmpb128_mask:
2292 case X86::BI__builtin_ia32_cmpw128_mask:
2293 case X86::BI__builtin_ia32_cmpd128_mask:
2294 case X86::BI__builtin_ia32_cmpq128_mask:
2295 case X86::BI__builtin_ia32_cmpb256_mask:
2296 case X86::BI__builtin_ia32_cmpw256_mask:
2297 case X86::BI__builtin_ia32_cmpd256_mask:
2298 case X86::BI__builtin_ia32_cmpq256_mask:
2299 case X86::BI__builtin_ia32_cmpb512_mask:
2300 case X86::BI__builtin_ia32_cmpw512_mask:
2301 case X86::BI__builtin_ia32_cmpd512_mask:
2302 case X86::BI__builtin_ia32_cmpq512_mask:
2303 case X86::BI__builtin_ia32_ucmpb128_mask:
2304 case X86::BI__builtin_ia32_ucmpw128_mask:
2305 case X86::BI__builtin_ia32_ucmpd128_mask:
2306 case X86::BI__builtin_ia32_ucmpq128_mask:
2307 case X86::BI__builtin_ia32_ucmpb256_mask:
2308 case X86::BI__builtin_ia32_ucmpw256_mask:
2309 case X86::BI__builtin_ia32_ucmpd256_mask:
2310 case X86::BI__builtin_ia32_ucmpq256_mask:
2311 case X86::BI__builtin_ia32_ucmpb512_mask:
2312 case X86::BI__builtin_ia32_ucmpw512_mask:
2313 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00002314 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00002315 case X86::BI__builtin_ia32_vpcomub:
2316 case X86::BI__builtin_ia32_vpcomuw:
2317 case X86::BI__builtin_ia32_vpcomud:
2318 case X86::BI__builtin_ia32_vpcomuq:
2319 case X86::BI__builtin_ia32_vpcomb:
2320 case X86::BI__builtin_ia32_vpcomw:
2321 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00002322 case X86::BI__builtin_ia32_vpcomq:
Craig Topper39c87102016-05-18 03:18:12 +00002323 i = 2; l = 0; u = 7;
2324 break;
2325 case X86::BI__builtin_ia32_roundps:
2326 case X86::BI__builtin_ia32_roundpd:
2327 case X86::BI__builtin_ia32_roundps256:
2328 case X86::BI__builtin_ia32_roundpd256:
Craig Topper39c87102016-05-18 03:18:12 +00002329 i = 1; l = 0; u = 15;
2330 break;
2331 case X86::BI__builtin_ia32_roundss:
2332 case X86::BI__builtin_ia32_roundsd:
2333 case X86::BI__builtin_ia32_rangepd128_mask:
2334 case X86::BI__builtin_ia32_rangepd256_mask:
2335 case X86::BI__builtin_ia32_rangepd512_mask:
2336 case X86::BI__builtin_ia32_rangeps128_mask:
2337 case X86::BI__builtin_ia32_rangeps256_mask:
2338 case X86::BI__builtin_ia32_rangeps512_mask:
2339 case X86::BI__builtin_ia32_getmantsd_round_mask:
2340 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002341 i = 2; l = 0; u = 15;
2342 break;
2343 case X86::BI__builtin_ia32_cmpps:
2344 case X86::BI__builtin_ia32_cmpss:
2345 case X86::BI__builtin_ia32_cmppd:
2346 case X86::BI__builtin_ia32_cmpsd:
2347 case X86::BI__builtin_ia32_cmpps256:
2348 case X86::BI__builtin_ia32_cmppd256:
2349 case X86::BI__builtin_ia32_cmpps128_mask:
2350 case X86::BI__builtin_ia32_cmppd128_mask:
2351 case X86::BI__builtin_ia32_cmpps256_mask:
2352 case X86::BI__builtin_ia32_cmppd256_mask:
2353 case X86::BI__builtin_ia32_cmpps512_mask:
2354 case X86::BI__builtin_ia32_cmppd512_mask:
2355 case X86::BI__builtin_ia32_cmpsd_mask:
2356 case X86::BI__builtin_ia32_cmpss_mask:
2357 i = 2; l = 0; u = 31;
2358 break;
2359 case X86::BI__builtin_ia32_xabort:
2360 i = 0; l = -128; u = 255;
2361 break;
2362 case X86::BI__builtin_ia32_pshufw:
2363 case X86::BI__builtin_ia32_aeskeygenassist128:
2364 i = 1; l = -128; u = 255;
2365 break;
2366 case X86::BI__builtin_ia32_vcvtps2ph:
Craig Topper23a30222017-11-08 04:54:26 +00002367 case X86::BI__builtin_ia32_vcvtps2ph_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002368 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper23a30222017-11-08 04:54:26 +00002369 case X86::BI__builtin_ia32_vcvtps2ph256_mask:
2370 case X86::BI__builtin_ia32_vcvtps2ph512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002371 case X86::BI__builtin_ia32_rndscaleps_128_mask:
2372 case X86::BI__builtin_ia32_rndscalepd_128_mask:
2373 case X86::BI__builtin_ia32_rndscaleps_256_mask:
2374 case X86::BI__builtin_ia32_rndscalepd_256_mask:
2375 case X86::BI__builtin_ia32_rndscaleps_mask:
2376 case X86::BI__builtin_ia32_rndscalepd_mask:
2377 case X86::BI__builtin_ia32_reducepd128_mask:
2378 case X86::BI__builtin_ia32_reducepd256_mask:
2379 case X86::BI__builtin_ia32_reducepd512_mask:
2380 case X86::BI__builtin_ia32_reduceps128_mask:
2381 case X86::BI__builtin_ia32_reduceps256_mask:
2382 case X86::BI__builtin_ia32_reduceps512_mask:
2383 case X86::BI__builtin_ia32_prold512_mask:
2384 case X86::BI__builtin_ia32_prolq512_mask:
2385 case X86::BI__builtin_ia32_prold128_mask:
2386 case X86::BI__builtin_ia32_prold256_mask:
2387 case X86::BI__builtin_ia32_prolq128_mask:
2388 case X86::BI__builtin_ia32_prolq256_mask:
2389 case X86::BI__builtin_ia32_prord128_mask:
2390 case X86::BI__builtin_ia32_prord256_mask:
2391 case X86::BI__builtin_ia32_prorq128_mask:
2392 case X86::BI__builtin_ia32_prorq256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002393 case X86::BI__builtin_ia32_fpclasspd128_mask:
2394 case X86::BI__builtin_ia32_fpclasspd256_mask:
2395 case X86::BI__builtin_ia32_fpclassps128_mask:
2396 case X86::BI__builtin_ia32_fpclassps256_mask:
2397 case X86::BI__builtin_ia32_fpclassps512_mask:
2398 case X86::BI__builtin_ia32_fpclasspd512_mask:
2399 case X86::BI__builtin_ia32_fpclasssd_mask:
2400 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002401 i = 1; l = 0; u = 255;
2402 break;
2403 case X86::BI__builtin_ia32_palignr:
2404 case X86::BI__builtin_ia32_insertps128:
2405 case X86::BI__builtin_ia32_dpps:
2406 case X86::BI__builtin_ia32_dppd:
2407 case X86::BI__builtin_ia32_dpps256:
2408 case X86::BI__builtin_ia32_mpsadbw128:
2409 case X86::BI__builtin_ia32_mpsadbw256:
2410 case X86::BI__builtin_ia32_pcmpistrm128:
2411 case X86::BI__builtin_ia32_pcmpistri128:
2412 case X86::BI__builtin_ia32_pcmpistria128:
2413 case X86::BI__builtin_ia32_pcmpistric128:
2414 case X86::BI__builtin_ia32_pcmpistrio128:
2415 case X86::BI__builtin_ia32_pcmpistris128:
2416 case X86::BI__builtin_ia32_pcmpistriz128:
2417 case X86::BI__builtin_ia32_pclmulqdq128:
2418 case X86::BI__builtin_ia32_vperm2f128_pd256:
2419 case X86::BI__builtin_ia32_vperm2f128_ps256:
2420 case X86::BI__builtin_ia32_vperm2f128_si256:
2421 case X86::BI__builtin_ia32_permti256:
2422 i = 2; l = -128; u = 255;
2423 break;
2424 case X86::BI__builtin_ia32_palignr128:
2425 case X86::BI__builtin_ia32_palignr256:
Craig Topper39c87102016-05-18 03:18:12 +00002426 case X86::BI__builtin_ia32_palignr512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002427 case X86::BI__builtin_ia32_vcomisd:
2428 case X86::BI__builtin_ia32_vcomiss:
2429 case X86::BI__builtin_ia32_shuf_f32x4_mask:
2430 case X86::BI__builtin_ia32_shuf_f64x2_mask:
2431 case X86::BI__builtin_ia32_shuf_i32x4_mask:
2432 case X86::BI__builtin_ia32_shuf_i64x2_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002433 case X86::BI__builtin_ia32_dbpsadbw128_mask:
2434 case X86::BI__builtin_ia32_dbpsadbw256_mask:
2435 case X86::BI__builtin_ia32_dbpsadbw512_mask:
2436 i = 2; l = 0; u = 255;
2437 break;
2438 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2439 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2440 case X86::BI__builtin_ia32_fixupimmps512_mask:
2441 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2442 case X86::BI__builtin_ia32_fixupimmsd_mask:
2443 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2444 case X86::BI__builtin_ia32_fixupimmss_mask:
2445 case X86::BI__builtin_ia32_fixupimmss_maskz:
2446 case X86::BI__builtin_ia32_fixupimmpd128_mask:
2447 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2448 case X86::BI__builtin_ia32_fixupimmpd256_mask:
2449 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2450 case X86::BI__builtin_ia32_fixupimmps128_mask:
2451 case X86::BI__builtin_ia32_fixupimmps128_maskz:
2452 case X86::BI__builtin_ia32_fixupimmps256_mask:
2453 case X86::BI__builtin_ia32_fixupimmps256_maskz:
2454 case X86::BI__builtin_ia32_pternlogd512_mask:
2455 case X86::BI__builtin_ia32_pternlogd512_maskz:
2456 case X86::BI__builtin_ia32_pternlogq512_mask:
2457 case X86::BI__builtin_ia32_pternlogq512_maskz:
2458 case X86::BI__builtin_ia32_pternlogd128_mask:
2459 case X86::BI__builtin_ia32_pternlogd128_maskz:
2460 case X86::BI__builtin_ia32_pternlogd256_mask:
2461 case X86::BI__builtin_ia32_pternlogd256_maskz:
2462 case X86::BI__builtin_ia32_pternlogq128_mask:
2463 case X86::BI__builtin_ia32_pternlogq128_maskz:
2464 case X86::BI__builtin_ia32_pternlogq256_mask:
2465 case X86::BI__builtin_ia32_pternlogq256_maskz:
2466 i = 3; l = 0; u = 255;
2467 break;
Craig Topper9625db02017-03-12 22:19:10 +00002468 case X86::BI__builtin_ia32_gatherpfdpd:
2469 case X86::BI__builtin_ia32_gatherpfdps:
2470 case X86::BI__builtin_ia32_gatherpfqpd:
2471 case X86::BI__builtin_ia32_gatherpfqps:
2472 case X86::BI__builtin_ia32_scatterpfdpd:
2473 case X86::BI__builtin_ia32_scatterpfdps:
2474 case X86::BI__builtin_ia32_scatterpfqpd:
2475 case X86::BI__builtin_ia32_scatterpfqps:
Craig Topperf771f79b2017-03-31 17:22:30 +00002476 i = 4; l = 2; u = 3;
Craig Topper9625db02017-03-12 22:19:10 +00002477 break;
Craig Topper39c87102016-05-18 03:18:12 +00002478 case X86::BI__builtin_ia32_pcmpestrm128:
2479 case X86::BI__builtin_ia32_pcmpestri128:
2480 case X86::BI__builtin_ia32_pcmpestria128:
2481 case X86::BI__builtin_ia32_pcmpestric128:
2482 case X86::BI__builtin_ia32_pcmpestrio128:
2483 case X86::BI__builtin_ia32_pcmpestris128:
2484 case X86::BI__builtin_ia32_pcmpestriz128:
2485 i = 4; l = -128; u = 255;
2486 break;
2487 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2488 case X86::BI__builtin_ia32_rndscaless_round_mask:
2489 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00002490 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002491 }
Craig Topperdd84ec52014-12-27 07:00:08 +00002492 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002493}
2494
Richard Smith55ce3522012-06-25 20:30:08 +00002495/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2496/// parameter with the FormatAttr's correct format_idx and firstDataArg.
2497/// Returns true when the format fits the function and the FormatStringInfo has
2498/// been populated.
2499bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2500 FormatStringInfo *FSI) {
2501 FSI->HasVAListArg = Format->getFirstArg() == 0;
2502 FSI->FormatIdx = Format->getFormatIdx() - 1;
2503 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002504
Richard Smith55ce3522012-06-25 20:30:08 +00002505 // The way the format attribute works in GCC, the implicit this argument
2506 // of member functions is counted. However, it doesn't appear in our own
2507 // lists, so decrement format_idx in that case.
2508 if (IsCXXMember) {
2509 if(FSI->FormatIdx == 0)
2510 return false;
2511 --FSI->FormatIdx;
2512 if (FSI->FirstDataArg != 0)
2513 --FSI->FirstDataArg;
2514 }
2515 return true;
2516}
Mike Stump11289f42009-09-09 15:08:12 +00002517
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002518/// Checks if a the given expression evaluates to null.
2519///
2520/// \brief Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00002521static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002522 // If the expression has non-null type, it doesn't evaluate to null.
2523 if (auto nullability
2524 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2525 if (*nullability == NullabilityKind::NonNull)
2526 return false;
2527 }
2528
Ted Kremeneka146db32014-01-17 06:24:47 +00002529 // As a special case, transparent unions initialized with zero are
2530 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002531 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00002532 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2533 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002534 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00002535 if (const InitListExpr *ILE =
2536 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002537 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00002538 }
2539
2540 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00002541 return (!Expr->isValueDependent() &&
2542 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2543 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002544}
2545
2546static void CheckNonNullArgument(Sema &S,
2547 const Expr *ArgExpr,
2548 SourceLocation CallSiteLoc) {
2549 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00002550 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2551 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00002552}
2553
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002554bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2555 FormatStringInfo FSI;
2556 if ((GetFormatStringType(Format) == FST_NSString) &&
2557 getFormatStringInfo(Format, false, &FSI)) {
2558 Idx = FSI.FormatIdx;
2559 return true;
2560 }
2561 return false;
2562}
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002563
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002564/// \brief Diagnose use of %s directive in an NSString which is being passed
2565/// as formatting string to formatting method.
2566static void
2567DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2568 const NamedDecl *FDecl,
2569 Expr **Args,
2570 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002571 unsigned Idx = 0;
2572 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002573 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2574 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002575 Idx = 2;
2576 Format = true;
2577 }
2578 else
2579 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2580 if (S.GetFormatNSStringIdx(I, Idx)) {
2581 Format = true;
2582 break;
2583 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002584 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002585 if (!Format || NumArgs <= Idx)
2586 return;
2587 const Expr *FormatExpr = Args[Idx];
2588 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2589 FormatExpr = CSCE->getSubExpr();
2590 const StringLiteral *FormatString;
2591 if (const ObjCStringLiteral *OSL =
2592 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2593 FormatString = OSL->getString();
2594 else
2595 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2596 if (!FormatString)
2597 return;
2598 if (S.FormatStringHasSArg(FormatString)) {
2599 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2600 << "%s" << 1 << 1;
2601 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2602 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002603 }
2604}
2605
Douglas Gregorb4866e82015-06-19 18:13:19 +00002606/// Determine whether the given type has a non-null nullability annotation.
2607static bool isNonNullType(ASTContext &ctx, QualType type) {
2608 if (auto nullability = type->getNullability(ctx))
2609 return *nullability == NullabilityKind::NonNull;
2610
2611 return false;
2612}
2613
Ted Kremenek2bc73332014-01-17 06:24:43 +00002614static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00002615 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002616 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00002617 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00002618 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002619 assert((FDecl || Proto) && "Need a function declaration or prototype");
2620
Ted Kremenek9aedc152014-01-17 06:24:56 +00002621 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00002622 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00002623 if (FDecl) {
2624 // Handle the nonnull attribute on the function/method declaration itself.
2625 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2626 if (!NonNull->args_size()) {
2627 // Easy case: all pointer arguments are nonnull.
2628 for (const auto *Arg : Args)
2629 if (S.isValidPointerAttrType(Arg->getType()))
2630 CheckNonNullArgument(S, Arg, CallSiteLoc);
2631 return;
2632 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002633
Douglas Gregorb4866e82015-06-19 18:13:19 +00002634 for (unsigned Val : NonNull->args()) {
2635 if (Val >= Args.size())
2636 continue;
2637 if (NonNullArgs.empty())
2638 NonNullArgs.resize(Args.size());
2639 NonNullArgs.set(Val);
2640 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002641 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002642 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002643
Douglas Gregorb4866e82015-06-19 18:13:19 +00002644 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2645 // Handle the nonnull attribute on the parameters of the
2646 // function/method.
2647 ArrayRef<ParmVarDecl*> parms;
2648 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2649 parms = FD->parameters();
2650 else
2651 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2652
2653 unsigned ParamIndex = 0;
2654 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2655 I != E; ++I, ++ParamIndex) {
2656 const ParmVarDecl *PVD = *I;
2657 if (PVD->hasAttr<NonNullAttr>() ||
2658 isNonNullType(S.Context, PVD->getType())) {
2659 if (NonNullArgs.empty())
2660 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00002661
Douglas Gregorb4866e82015-06-19 18:13:19 +00002662 NonNullArgs.set(ParamIndex);
2663 }
2664 }
2665 } else {
2666 // If we have a non-function, non-method declaration but no
2667 // function prototype, try to dig out the function prototype.
2668 if (!Proto) {
2669 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2670 QualType type = VD->getType().getNonReferenceType();
2671 if (auto pointerType = type->getAs<PointerType>())
2672 type = pointerType->getPointeeType();
2673 else if (auto blockType = type->getAs<BlockPointerType>())
2674 type = blockType->getPointeeType();
2675 // FIXME: data member pointers?
2676
2677 // Dig out the function prototype, if there is one.
2678 Proto = type->getAs<FunctionProtoType>();
2679 }
2680 }
2681
2682 // Fill in non-null argument information from the nullability
2683 // information on the parameter types (if we have them).
2684 if (Proto) {
2685 unsigned Index = 0;
2686 for (auto paramType : Proto->getParamTypes()) {
2687 if (isNonNullType(S.Context, paramType)) {
2688 if (NonNullArgs.empty())
2689 NonNullArgs.resize(Args.size());
2690
2691 NonNullArgs.set(Index);
2692 }
2693
2694 ++Index;
2695 }
2696 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002697 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002698
Douglas Gregorb4866e82015-06-19 18:13:19 +00002699 // Check for non-null arguments.
2700 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2701 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00002702 if (NonNullArgs[ArgIndex])
2703 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00002704 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002705}
2706
Richard Smith55ce3522012-06-25 20:30:08 +00002707/// Handles the checks for format strings, non-POD arguments to vararg
George Burgess IVce6284b2017-01-28 02:19:40 +00002708/// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
2709/// attributes.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002710void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
George Burgess IVce6284b2017-01-28 02:19:40 +00002711 const Expr *ThisArg, ArrayRef<const Expr *> Args,
2712 bool IsMemberFunction, SourceLocation Loc,
2713 SourceRange Range, VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00002714 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00002715 if (CurContext->isDependentContext())
2716 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00002717
Ted Kremenekb8176da2010-09-09 04:33:05 +00002718 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00002719 llvm::SmallBitVector CheckedVarArgs;
2720 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002721 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002722 // Only create vector if there are format attributes.
2723 CheckedVarArgs.resize(Args.size());
2724
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002725 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00002726 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002727 }
Richard Smithd7293d72013-08-05 18:49:43 +00002728 }
Richard Smith55ce3522012-06-25 20:30:08 +00002729
2730 // Refuse POD arguments that weren't caught by the format string
2731 // checks above.
Richard Smith836de6b2016-12-19 23:59:34 +00002732 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
2733 if (CallType != VariadicDoesNotApply &&
2734 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002735 unsigned NumParams = Proto ? Proto->getNumParams()
2736 : FDecl && isa<FunctionDecl>(FDecl)
2737 ? cast<FunctionDecl>(FDecl)->getNumParams()
2738 : FDecl && isa<ObjCMethodDecl>(FDecl)
2739 ? cast<ObjCMethodDecl>(FDecl)->param_size()
2740 : 0;
2741
Alp Toker9cacbab2014-01-20 20:26:09 +00002742 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002743 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00002744 if (const Expr *Arg = Args[ArgIdx]) {
2745 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2746 checkVariadicArgument(Arg, CallType);
2747 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002748 }
Richard Smithd7293d72013-08-05 18:49:43 +00002749 }
Mike Stump11289f42009-09-09 15:08:12 +00002750
Douglas Gregorb4866e82015-06-19 18:13:19 +00002751 if (FDecl || Proto) {
2752 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002753
Richard Trieu41bc0992013-06-22 00:20:41 +00002754 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002755 if (FDecl) {
2756 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2757 CheckArgumentWithTypeTag(I, Args.data());
2758 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002759 }
George Burgess IVce6284b2017-01-28 02:19:40 +00002760
2761 if (FD)
2762 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
Richard Smith55ce3522012-06-25 20:30:08 +00002763}
2764
2765/// CheckConstructorCall - Check a constructor call for correctness and safety
2766/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002767void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2768 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002769 const FunctionProtoType *Proto,
2770 SourceLocation Loc) {
2771 VariadicCallType CallType =
2772 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
George Burgess IVce6284b2017-01-28 02:19:40 +00002773 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
2774 Loc, SourceRange(), CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00002775}
2776
2777/// CheckFunctionCall - Check a direct function call for various correctness
2778/// and safety properties not strictly enforced by the C type system.
2779bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2780 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002781 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2782 isa<CXXMethodDecl>(FDecl);
2783 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2784 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00002785 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2786 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00002787 Expr** Args = TheCall->getArgs();
2788 unsigned NumArgs = TheCall->getNumArgs();
George Burgess IVce6284b2017-01-28 02:19:40 +00002789
2790 Expr *ImplicitThis = nullptr;
Eli Friedmanadf42182012-10-11 00:34:15 +00002791 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002792 // If this is a call to a member operator, hide the first argument
2793 // from checkCall.
2794 // FIXME: Our choice of AST representation here is less than ideal.
George Burgess IVce6284b2017-01-28 02:19:40 +00002795 ImplicitThis = Args[0];
Eli Friedman726d11c2012-10-11 00:30:58 +00002796 ++Args;
2797 --NumArgs;
George Burgess IVce6284b2017-01-28 02:19:40 +00002798 } else if (IsMemberFunction)
2799 ImplicitThis =
2800 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
2801
2802 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00002803 IsMemberFunction, TheCall->getRParenLoc(),
2804 TheCall->getCallee()->getSourceRange(), CallType);
2805
2806 IdentifierInfo *FnInfo = FDecl->getIdentifier();
2807 // None of the checks below are needed for functions that don't have
2808 // simple names (e.g., C++ conversion functions).
2809 if (!FnInfo)
2810 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002811
Richard Trieua7f30b12016-12-06 01:42:28 +00002812 CheckAbsoluteValueFunction(TheCall, FDecl);
2813 CheckMaxUnsignedZero(TheCall, FDecl);
Richard Trieu67c00712016-12-05 23:41:46 +00002814
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002815 if (getLangOpts().ObjC1)
2816 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00002817
Anna Zaks22122702012-01-17 00:37:07 +00002818 unsigned CMId = FDecl->getMemoryFunctionKind();
2819 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00002820 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00002821
Anna Zaks201d4892012-01-13 21:52:01 +00002822 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00002823 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00002824 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00002825 else if (CMId == Builtin::BIstrncat)
2826 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00002827 else
Anna Zaks22122702012-01-17 00:37:07 +00002828 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002829
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002830 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00002831}
2832
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002833bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00002834 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00002835 VariadicCallType CallType =
2836 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002837
George Burgess IVce6284b2017-01-28 02:19:40 +00002838 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
2839 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002840 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002841
2842 return false;
2843}
2844
Richard Trieu664c4c62013-06-20 21:03:13 +00002845bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2846 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00002847 QualType Ty;
2848 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002849 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002850 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002851 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002852 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002853 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002854
Douglas Gregorb4866e82015-06-19 18:13:19 +00002855 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2856 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002857 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002858
Richard Trieu664c4c62013-06-20 21:03:13 +00002859 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00002860 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00002861 CallType = VariadicDoesNotApply;
2862 } else if (Ty->isBlockPointerType()) {
2863 CallType = VariadicBlock;
2864 } else { // Ty->isFunctionPointerType()
2865 CallType = VariadicFunction;
2866 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002867
George Burgess IVce6284b2017-01-28 02:19:40 +00002868 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002869 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2870 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00002871 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00002872
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002873 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00002874}
2875
Richard Trieu41bc0992013-06-22 00:20:41 +00002876/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2877/// such as function pointers returned from functions.
2878bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002879 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00002880 TheCall->getCallee());
George Burgess IVce6284b2017-01-28 02:19:40 +00002881 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00002882 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002883 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00002884 TheCall->getCallee()->getSourceRange(), CallType);
2885
2886 return false;
2887}
2888
Tim Northovere94a34c2014-03-11 10:49:14 +00002889static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00002890 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00002891 return false;
2892
JF Bastiendda2cb12016-04-18 18:01:49 +00002893 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00002894 switch (Op) {
2895 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00002896 case AtomicExpr::AO__opencl_atomic_init:
Tim Northovere94a34c2014-03-11 10:49:14 +00002897 llvm_unreachable("There is no ordering argument for an init");
2898
2899 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00002900 case AtomicExpr::AO__opencl_atomic_load:
Tim Northovere94a34c2014-03-11 10:49:14 +00002901 case AtomicExpr::AO__atomic_load_n:
2902 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00002903 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2904 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002905
2906 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00002907 case AtomicExpr::AO__opencl_atomic_store:
Tim Northovere94a34c2014-03-11 10:49:14 +00002908 case AtomicExpr::AO__atomic_store:
2909 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00002910 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2911 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2912 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002913
2914 default:
2915 return true;
2916 }
2917}
2918
Richard Smithfeea8832012-04-12 05:08:17 +00002919ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2920 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002921 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2922 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002923
Yaxun Liu39195062017-08-04 18:16:31 +00002924 // All the non-OpenCL operations take one of the following forms.
2925 // The OpenCL operations take the __c11 forms with one extra argument for
2926 // synchronization scope.
Richard Smithfeea8832012-04-12 05:08:17 +00002927 enum {
2928 // C __c11_atomic_init(A *, C)
2929 Init,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002930
Richard Smithfeea8832012-04-12 05:08:17 +00002931 // C __c11_atomic_load(A *, int)
2932 Load,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002933
Richard Smithfeea8832012-04-12 05:08:17 +00002934 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00002935 LoadCopy,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002936
Eric Fiselier8d662442016-03-30 23:39:56 +00002937 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00002938 Copy,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002939
Richard Smithfeea8832012-04-12 05:08:17 +00002940 // C __c11_atomic_add(A *, M, int)
2941 Arithmetic,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002942
Richard Smithfeea8832012-04-12 05:08:17 +00002943 // C __atomic_exchange_n(A *, CP, int)
2944 Xchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002945
Richard Smithfeea8832012-04-12 05:08:17 +00002946 // void __atomic_exchange(A *, C *, CP, int)
2947 GNUXchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002948
Richard Smithfeea8832012-04-12 05:08:17 +00002949 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2950 C11CmpXchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002951
Richard Smithfeea8832012-04-12 05:08:17 +00002952 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2953 GNUCmpXchg
2954 } Form = Init;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002955
Yaxun Liu39195062017-08-04 18:16:31 +00002956 const unsigned NumForm = GNUCmpXchg + 1;
Eric Fiselier8d662442016-03-30 23:39:56 +00002957 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2958 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00002959 // where:
2960 // C is an appropriate type,
2961 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2962 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2963 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2964 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002965
Yaxun Liu39195062017-08-04 18:16:31 +00002966 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
2967 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
2968 "need to update code for modified forms");
Gabor Horvath98bd0982015-03-16 09:59:54 +00002969 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2970 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2971 AtomicExpr::AO__atomic_load,
2972 "need to update code for modified C11 atomics");
Yaxun Liu39195062017-08-04 18:16:31 +00002973 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
2974 Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
2975 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
2976 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
2977 IsOpenCL;
Richard Smithfeea8832012-04-12 05:08:17 +00002978 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2979 Op == AtomicExpr::AO__atomic_store_n ||
2980 Op == AtomicExpr::AO__atomic_exchange_n ||
2981 Op == AtomicExpr::AO__atomic_compare_exchange_n;
2982 bool IsAddSub = false;
2983
2984 switch (Op) {
2985 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00002986 case AtomicExpr::AO__opencl_atomic_init:
Richard Smithfeea8832012-04-12 05:08:17 +00002987 Form = Init;
2988 break;
2989
2990 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00002991 case AtomicExpr::AO__opencl_atomic_load:
Richard Smithfeea8832012-04-12 05:08:17 +00002992 case AtomicExpr::AO__atomic_load_n:
2993 Form = Load;
2994 break;
2995
Richard Smithfeea8832012-04-12 05:08:17 +00002996 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00002997 Form = LoadCopy;
2998 break;
2999
3000 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00003001 case AtomicExpr::AO__opencl_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00003002 case AtomicExpr::AO__atomic_store:
3003 case AtomicExpr::AO__atomic_store_n:
3004 Form = Copy;
3005 break;
3006
3007 case AtomicExpr::AO__c11_atomic_fetch_add:
3008 case AtomicExpr::AO__c11_atomic_fetch_sub:
Yaxun Liu39195062017-08-04 18:16:31 +00003009 case AtomicExpr::AO__opencl_atomic_fetch_add:
3010 case AtomicExpr::AO__opencl_atomic_fetch_sub:
3011 case AtomicExpr::AO__opencl_atomic_fetch_min:
3012 case AtomicExpr::AO__opencl_atomic_fetch_max:
Richard Smithfeea8832012-04-12 05:08:17 +00003013 case AtomicExpr::AO__atomic_fetch_add:
3014 case AtomicExpr::AO__atomic_fetch_sub:
3015 case AtomicExpr::AO__atomic_add_fetch:
3016 case AtomicExpr::AO__atomic_sub_fetch:
3017 IsAddSub = true;
3018 // Fall through.
3019 case AtomicExpr::AO__c11_atomic_fetch_and:
3020 case AtomicExpr::AO__c11_atomic_fetch_or:
3021 case AtomicExpr::AO__c11_atomic_fetch_xor:
Yaxun Liu39195062017-08-04 18:16:31 +00003022 case AtomicExpr::AO__opencl_atomic_fetch_and:
3023 case AtomicExpr::AO__opencl_atomic_fetch_or:
3024 case AtomicExpr::AO__opencl_atomic_fetch_xor:
Richard Smithfeea8832012-04-12 05:08:17 +00003025 case AtomicExpr::AO__atomic_fetch_and:
3026 case AtomicExpr::AO__atomic_fetch_or:
3027 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00003028 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00003029 case AtomicExpr::AO__atomic_and_fetch:
3030 case AtomicExpr::AO__atomic_or_fetch:
3031 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00003032 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00003033 Form = Arithmetic;
3034 break;
3035
3036 case AtomicExpr::AO__c11_atomic_exchange:
Yaxun Liu39195062017-08-04 18:16:31 +00003037 case AtomicExpr::AO__opencl_atomic_exchange:
Richard Smithfeea8832012-04-12 05:08:17 +00003038 case AtomicExpr::AO__atomic_exchange_n:
3039 Form = Xchg;
3040 break;
3041
3042 case AtomicExpr::AO__atomic_exchange:
3043 Form = GNUXchg;
3044 break;
3045
3046 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3047 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
Yaxun Liu39195062017-08-04 18:16:31 +00003048 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
3049 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
Richard Smithfeea8832012-04-12 05:08:17 +00003050 Form = C11CmpXchg;
3051 break;
3052
3053 case AtomicExpr::AO__atomic_compare_exchange:
3054 case AtomicExpr::AO__atomic_compare_exchange_n:
3055 Form = GNUCmpXchg;
3056 break;
3057 }
3058
Yaxun Liu39195062017-08-04 18:16:31 +00003059 unsigned AdjustedNumArgs = NumArgs[Form];
3060 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
3061 ++AdjustedNumArgs;
Richard Smithfeea8832012-04-12 05:08:17 +00003062 // Check we have the right number of arguments.
Yaxun Liu39195062017-08-04 18:16:31 +00003063 if (TheCall->getNumArgs() < AdjustedNumArgs) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003064 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Yaxun Liu39195062017-08-04 18:16:31 +00003065 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003066 << TheCall->getCallee()->getSourceRange();
3067 return ExprError();
Yaxun Liu39195062017-08-04 18:16:31 +00003068 } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
3069 Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003070 diag::err_typecheck_call_too_many_args)
Yaxun Liu39195062017-08-04 18:16:31 +00003071 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003072 << TheCall->getCallee()->getSourceRange();
3073 return ExprError();
3074 }
3075
Richard Smithfeea8832012-04-12 05:08:17 +00003076 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003077 Expr *Ptr = TheCall->getArg(0);
George Burgess IV92b43a42016-07-21 03:28:13 +00003078 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
3079 if (ConvertedPtr.isInvalid())
3080 return ExprError();
3081
3082 Ptr = ConvertedPtr.get();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003083 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
3084 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00003085 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003086 << Ptr->getType() << Ptr->getSourceRange();
3087 return ExprError();
3088 }
3089
Richard Smithfeea8832012-04-12 05:08:17 +00003090 // For a __c11 builtin, this should be a pointer to an _Atomic type.
3091 QualType AtomTy = pointerType->getPointeeType(); // 'A'
3092 QualType ValType = AtomTy; // 'C'
3093 if (IsC11) {
3094 if (!AtomTy->isAtomicType()) {
3095 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
3096 << Ptr->getType() << Ptr->getSourceRange();
3097 return ExprError();
3098 }
Yaxun Liu39195062017-08-04 18:16:31 +00003099 if (AtomTy.isConstQualified() ||
3100 AtomTy.getAddressSpace() == LangAS::opencl_constant) {
Richard Smithe00921a2012-09-15 06:09:58 +00003101 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
Yaxun Liu39195062017-08-04 18:16:31 +00003102 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
3103 << Ptr->getSourceRange();
Richard Smithe00921a2012-09-15 06:09:58 +00003104 return ExprError();
3105 }
Richard Smithfeea8832012-04-12 05:08:17 +00003106 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00003107 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00003108 if (ValType.isConstQualified()) {
3109 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
3110 << Ptr->getType() << Ptr->getSourceRange();
3111 return ExprError();
3112 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003113 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003114
Richard Smithfeea8832012-04-12 05:08:17 +00003115 // For an arithmetic operation, the implied arithmetic must be well-formed.
3116 if (Form == Arithmetic) {
3117 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
3118 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
3119 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3120 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3121 return ExprError();
3122 }
3123 if (!IsAddSub && !ValType->isIntegerType()) {
3124 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
3125 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3126 return ExprError();
3127 }
David Majnemere85cff82015-01-28 05:48:06 +00003128 if (IsC11 && ValType->isPointerType() &&
3129 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
3130 diag::err_incomplete_type)) {
3131 return ExprError();
3132 }
Richard Smithfeea8832012-04-12 05:08:17 +00003133 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
3134 // For __atomic_*_n operations, the value type must be a scalar integral or
3135 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003136 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00003137 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3138 return ExprError();
3139 }
3140
Eli Friedmanaa769812013-09-11 03:49:34 +00003141 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
3142 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00003143 // For GNU atomics, require a trivially-copyable type. This is not part of
3144 // the GNU atomics specification, but we enforce it for sanity.
3145 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003146 << Ptr->getType() << Ptr->getSourceRange();
3147 return ExprError();
3148 }
3149
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003150 switch (ValType.getObjCLifetime()) {
3151 case Qualifiers::OCL_None:
3152 case Qualifiers::OCL_ExplicitNone:
3153 // okay
3154 break;
3155
3156 case Qualifiers::OCL_Weak:
3157 case Qualifiers::OCL_Strong:
3158 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00003159 // FIXME: Can this happen? By this point, ValType should be known
3160 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003161 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3162 << ValType << Ptr->getSourceRange();
3163 return ExprError();
3164 }
3165
David Majnemerc6eb6502015-06-03 00:26:35 +00003166 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
3167 // volatile-ness of the pointee-type inject itself into the result or the
Eric Fiselier8d662442016-03-30 23:39:56 +00003168 // other operands. Similarly atomic_load can take a pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00003169 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00003170 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003171 QualType ResultType = ValType;
Yaxun Liu39195062017-08-04 18:16:31 +00003172 if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
3173 Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003174 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00003175 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003176 ResultType = Context.BoolTy;
3177
Richard Smithfeea8832012-04-12 05:08:17 +00003178 // The type of a parameter passed 'by value'. In the GNU atomics, such
3179 // arguments are actually passed as pointers.
3180 QualType ByValType = ValType; // 'CP'
3181 if (!IsC11 && !IsN)
3182 ByValType = Ptr->getType();
3183
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003184 // The first argument --- the pointer --- has a fixed type; we
3185 // deduce the types of the rest of the arguments accordingly. Walk
3186 // the remaining arguments, converting them to the deduced value type.
Yaxun Liu39195062017-08-04 18:16:31 +00003187 for (unsigned i = 1; i != TheCall->getNumArgs(); ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003188 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00003189 if (i < NumVals[Form] + 1) {
3190 switch (i) {
3191 case 1:
3192 // The second argument is the non-atomic operand. For arithmetic, this
3193 // is always passed by value, and for a compare_exchange it is always
3194 // passed by address. For the rest, GNU uses by-address and C11 uses
3195 // by-value.
3196 assert(Form != Load);
3197 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
3198 Ty = ValType;
3199 else if (Form == Copy || Form == Xchg)
3200 Ty = ByValType;
3201 else if (Form == Arithmetic)
3202 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003203 else {
3204 Expr *ValArg = TheCall->getArg(i);
Alex Lorenz67522152016-11-23 16:57:03 +00003205 // Treat this argument as _Nonnull as we want to show a warning if
3206 // NULL is passed into it.
3207 CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
Alexander Richardson6d989432017-10-15 18:48:14 +00003208 LangAS AS = LangAS::Default;
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003209 // Keep address space of non-atomic pointer type.
3210 if (const PointerType *PtrTy =
3211 ValArg->getType()->getAs<PointerType>()) {
3212 AS = PtrTy->getPointeeType().getAddressSpace();
3213 }
3214 Ty = Context.getPointerType(
3215 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
3216 }
Richard Smithfeea8832012-04-12 05:08:17 +00003217 break;
3218 case 2:
3219 // The third argument to compare_exchange / GNU exchange is a
3220 // (pointer to a) desired value.
3221 Ty = ByValType;
3222 break;
3223 case 3:
3224 // The fourth argument to GNU compare_exchange is a 'weak' flag.
3225 Ty = Context.BoolTy;
3226 break;
3227 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003228 } else {
Yaxun Liu39195062017-08-04 18:16:31 +00003229 // The order(s) and scope are always converted to int.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003230 Ty = Context.IntTy;
3231 }
Richard Smithfeea8832012-04-12 05:08:17 +00003232
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003233 InitializedEntity Entity =
3234 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00003235 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003236 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3237 if (Arg.isInvalid())
3238 return true;
3239 TheCall->setArg(i, Arg.get());
3240 }
3241
Richard Smithfeea8832012-04-12 05:08:17 +00003242 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003243 SmallVector<Expr*, 5> SubExprs;
3244 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00003245 switch (Form) {
3246 case Init:
3247 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00003248 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003249 break;
3250 case Load:
3251 SubExprs.push_back(TheCall->getArg(1)); // Order
3252 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00003253 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00003254 case Copy:
3255 case Arithmetic:
3256 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003257 SubExprs.push_back(TheCall->getArg(2)); // Order
3258 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003259 break;
3260 case GNUXchg:
3261 // Note, AtomicExpr::getVal2() has a special case for this atomic.
3262 SubExprs.push_back(TheCall->getArg(3)); // Order
3263 SubExprs.push_back(TheCall->getArg(1)); // Val1
3264 SubExprs.push_back(TheCall->getArg(2)); // Val2
3265 break;
3266 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003267 SubExprs.push_back(TheCall->getArg(3)); // Order
3268 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003269 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00003270 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00003271 break;
3272 case GNUCmpXchg:
3273 SubExprs.push_back(TheCall->getArg(4)); // Order
3274 SubExprs.push_back(TheCall->getArg(1)); // Val1
3275 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
3276 SubExprs.push_back(TheCall->getArg(2)); // Val2
3277 SubExprs.push_back(TheCall->getArg(3)); // Weak
3278 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003279 }
Tim Northovere94a34c2014-03-11 10:49:14 +00003280
3281 if (SubExprs.size() >= 2 && Form != Init) {
3282 llvm::APSInt Result(32);
3283 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
3284 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00003285 Diag(SubExprs[1]->getLocStart(),
3286 diag::warn_atomic_op_has_invalid_memory_order)
3287 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00003288 }
3289
Yaxun Liu30d652a2017-08-15 16:02:49 +00003290 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
3291 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
3292 llvm::APSInt Result(32);
3293 if (Scope->isIntegerConstantExpr(Result, Context) &&
3294 !ScopeModel->isValid(Result.getZExtValue())) {
3295 Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope)
3296 << Scope->getSourceRange();
3297 }
3298 SubExprs.push_back(Scope);
3299 }
3300
Fariborz Jahanian615de762013-05-28 17:37:39 +00003301 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
3302 SubExprs, ResultType, Op,
3303 TheCall->getRParenLoc());
3304
3305 if ((Op == AtomicExpr::AO__c11_atomic_load ||
Yaxun Liu39195062017-08-04 18:16:31 +00003306 Op == AtomicExpr::AO__c11_atomic_store ||
3307 Op == AtomicExpr::AO__opencl_atomic_load ||
3308 Op == AtomicExpr::AO__opencl_atomic_store ) &&
Fariborz Jahanian615de762013-05-28 17:37:39 +00003309 Context.AtomicUsesUnsupportedLibcall(AE))
Yaxun Liu39195062017-08-04 18:16:31 +00003310 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib)
3311 << ((Op == AtomicExpr::AO__c11_atomic_load ||
3312 Op == AtomicExpr::AO__opencl_atomic_load)
3313 ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003314
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003315 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003316}
3317
John McCall29ad95b2011-08-27 01:09:30 +00003318/// checkBuiltinArgument - Given a call to a builtin function, perform
3319/// normal type-checking on the given argument, updating the call in
3320/// place. This is useful when a builtin function requires custom
3321/// type-checking for some of its arguments but not necessarily all of
3322/// them.
3323///
3324/// Returns true on error.
3325static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
3326 FunctionDecl *Fn = E->getDirectCallee();
3327 assert(Fn && "builtin call without direct callee!");
3328
3329 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
3330 InitializedEntity Entity =
3331 InitializedEntity::InitializeParameter(S.Context, Param);
3332
3333 ExprResult Arg = E->getArg(0);
3334 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3335 if (Arg.isInvalid())
3336 return true;
3337
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003338 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00003339 return false;
3340}
3341
Chris Lattnerdc046542009-05-08 06:58:22 +00003342/// SemaBuiltinAtomicOverloaded - We have a call to a function like
3343/// __sync_fetch_and_add, which is an overloaded function based on the pointer
3344/// type of its first argument. The main ActOnCallExpr routines have already
3345/// promoted the types of arguments because all of these calls are prototyped as
3346/// void(...).
3347///
3348/// This function goes through and does final semantic checking for these
3349/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00003350ExprResult
3351Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003352 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00003353 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3354 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3355
3356 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003357 if (TheCall->getNumArgs() < 1) {
3358 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3359 << 0 << 1 << TheCall->getNumArgs()
3360 << TheCall->getCallee()->getSourceRange();
3361 return ExprError();
3362 }
Mike Stump11289f42009-09-09 15:08:12 +00003363
Chris Lattnerdc046542009-05-08 06:58:22 +00003364 // Inspect the first argument of the atomic builtin. This should always be
3365 // a pointer type, whose element is an integral scalar or pointer type.
3366 // Because it is a pointer type, we don't have to worry about any implicit
3367 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003368 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00003369 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00003370 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3371 if (FirstArgResult.isInvalid())
3372 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003373 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00003374 TheCall->setArg(0, FirstArg);
3375
John McCall31168b02011-06-15 23:02:42 +00003376 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3377 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003378 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3379 << FirstArg->getType() << FirstArg->getSourceRange();
3380 return ExprError();
3381 }
Mike Stump11289f42009-09-09 15:08:12 +00003382
John McCall31168b02011-06-15 23:02:42 +00003383 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00003384 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003385 !ValType->isBlockPointerType()) {
3386 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3387 << FirstArg->getType() << FirstArg->getSourceRange();
3388 return ExprError();
3389 }
Chris Lattnerdc046542009-05-08 06:58:22 +00003390
John McCall31168b02011-06-15 23:02:42 +00003391 switch (ValType.getObjCLifetime()) {
3392 case Qualifiers::OCL_None:
3393 case Qualifiers::OCL_ExplicitNone:
3394 // okay
3395 break;
3396
3397 case Qualifiers::OCL_Weak:
3398 case Qualifiers::OCL_Strong:
3399 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00003400 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00003401 << ValType << FirstArg->getSourceRange();
3402 return ExprError();
3403 }
3404
John McCallb50451a2011-10-05 07:41:44 +00003405 // Strip any qualifiers off ValType.
3406 ValType = ValType.getUnqualifiedType();
3407
Chandler Carruth3973af72010-07-18 20:54:12 +00003408 // The majority of builtins return a value, but a few have special return
3409 // types, so allow them to override appropriately below.
3410 QualType ResultType = ValType;
3411
Chris Lattnerdc046542009-05-08 06:58:22 +00003412 // We need to figure out which concrete builtin this maps onto. For example,
3413 // __sync_fetch_and_add with a 2 byte object turns into
3414 // __sync_fetch_and_add_2.
3415#define BUILTIN_ROW(x) \
3416 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3417 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00003418
Chris Lattnerdc046542009-05-08 06:58:22 +00003419 static const unsigned BuiltinIndices[][5] = {
3420 BUILTIN_ROW(__sync_fetch_and_add),
3421 BUILTIN_ROW(__sync_fetch_and_sub),
3422 BUILTIN_ROW(__sync_fetch_and_or),
3423 BUILTIN_ROW(__sync_fetch_and_and),
3424 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00003425 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00003426
Chris Lattnerdc046542009-05-08 06:58:22 +00003427 BUILTIN_ROW(__sync_add_and_fetch),
3428 BUILTIN_ROW(__sync_sub_and_fetch),
3429 BUILTIN_ROW(__sync_and_and_fetch),
3430 BUILTIN_ROW(__sync_or_and_fetch),
3431 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00003432 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00003433
Chris Lattnerdc046542009-05-08 06:58:22 +00003434 BUILTIN_ROW(__sync_val_compare_and_swap),
3435 BUILTIN_ROW(__sync_bool_compare_and_swap),
3436 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00003437 BUILTIN_ROW(__sync_lock_release),
3438 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00003439 };
Mike Stump11289f42009-09-09 15:08:12 +00003440#undef BUILTIN_ROW
3441
Chris Lattnerdc046542009-05-08 06:58:22 +00003442 // Determine the index of the size.
3443 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00003444 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00003445 case 1: SizeIndex = 0; break;
3446 case 2: SizeIndex = 1; break;
3447 case 4: SizeIndex = 2; break;
3448 case 8: SizeIndex = 3; break;
3449 case 16: SizeIndex = 4; break;
3450 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003451 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3452 << FirstArg->getType() << FirstArg->getSourceRange();
3453 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00003454 }
Mike Stump11289f42009-09-09 15:08:12 +00003455
Chris Lattnerdc046542009-05-08 06:58:22 +00003456 // Each of these builtins has one pointer argument, followed by some number of
3457 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3458 // that we ignore. Find out which row of BuiltinIndices to read from as well
3459 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00003460 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00003461 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00003462 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00003463 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00003464 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00003465 case Builtin::BI__sync_fetch_and_add:
3466 case Builtin::BI__sync_fetch_and_add_1:
3467 case Builtin::BI__sync_fetch_and_add_2:
3468 case Builtin::BI__sync_fetch_and_add_4:
3469 case Builtin::BI__sync_fetch_and_add_8:
3470 case Builtin::BI__sync_fetch_and_add_16:
3471 BuiltinIndex = 0;
3472 break;
3473
3474 case Builtin::BI__sync_fetch_and_sub:
3475 case Builtin::BI__sync_fetch_and_sub_1:
3476 case Builtin::BI__sync_fetch_and_sub_2:
3477 case Builtin::BI__sync_fetch_and_sub_4:
3478 case Builtin::BI__sync_fetch_and_sub_8:
3479 case Builtin::BI__sync_fetch_and_sub_16:
3480 BuiltinIndex = 1;
3481 break;
3482
3483 case Builtin::BI__sync_fetch_and_or:
3484 case Builtin::BI__sync_fetch_and_or_1:
3485 case Builtin::BI__sync_fetch_and_or_2:
3486 case Builtin::BI__sync_fetch_and_or_4:
3487 case Builtin::BI__sync_fetch_and_or_8:
3488 case Builtin::BI__sync_fetch_and_or_16:
3489 BuiltinIndex = 2;
3490 break;
3491
3492 case Builtin::BI__sync_fetch_and_and:
3493 case Builtin::BI__sync_fetch_and_and_1:
3494 case Builtin::BI__sync_fetch_and_and_2:
3495 case Builtin::BI__sync_fetch_and_and_4:
3496 case Builtin::BI__sync_fetch_and_and_8:
3497 case Builtin::BI__sync_fetch_and_and_16:
3498 BuiltinIndex = 3;
3499 break;
Mike Stump11289f42009-09-09 15:08:12 +00003500
Douglas Gregor73722482011-11-28 16:30:08 +00003501 case Builtin::BI__sync_fetch_and_xor:
3502 case Builtin::BI__sync_fetch_and_xor_1:
3503 case Builtin::BI__sync_fetch_and_xor_2:
3504 case Builtin::BI__sync_fetch_and_xor_4:
3505 case Builtin::BI__sync_fetch_and_xor_8:
3506 case Builtin::BI__sync_fetch_and_xor_16:
3507 BuiltinIndex = 4;
3508 break;
3509
Hal Finkeld2208b52014-10-02 20:53:50 +00003510 case Builtin::BI__sync_fetch_and_nand:
3511 case Builtin::BI__sync_fetch_and_nand_1:
3512 case Builtin::BI__sync_fetch_and_nand_2:
3513 case Builtin::BI__sync_fetch_and_nand_4:
3514 case Builtin::BI__sync_fetch_and_nand_8:
3515 case Builtin::BI__sync_fetch_and_nand_16:
3516 BuiltinIndex = 5;
3517 WarnAboutSemanticsChange = true;
3518 break;
3519
Douglas Gregor73722482011-11-28 16:30:08 +00003520 case Builtin::BI__sync_add_and_fetch:
3521 case Builtin::BI__sync_add_and_fetch_1:
3522 case Builtin::BI__sync_add_and_fetch_2:
3523 case Builtin::BI__sync_add_and_fetch_4:
3524 case Builtin::BI__sync_add_and_fetch_8:
3525 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003526 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00003527 break;
3528
3529 case Builtin::BI__sync_sub_and_fetch:
3530 case Builtin::BI__sync_sub_and_fetch_1:
3531 case Builtin::BI__sync_sub_and_fetch_2:
3532 case Builtin::BI__sync_sub_and_fetch_4:
3533 case Builtin::BI__sync_sub_and_fetch_8:
3534 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003535 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00003536 break;
3537
3538 case Builtin::BI__sync_and_and_fetch:
3539 case Builtin::BI__sync_and_and_fetch_1:
3540 case Builtin::BI__sync_and_and_fetch_2:
3541 case Builtin::BI__sync_and_and_fetch_4:
3542 case Builtin::BI__sync_and_and_fetch_8:
3543 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003544 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00003545 break;
3546
3547 case Builtin::BI__sync_or_and_fetch:
3548 case Builtin::BI__sync_or_and_fetch_1:
3549 case Builtin::BI__sync_or_and_fetch_2:
3550 case Builtin::BI__sync_or_and_fetch_4:
3551 case Builtin::BI__sync_or_and_fetch_8:
3552 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003553 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00003554 break;
3555
3556 case Builtin::BI__sync_xor_and_fetch:
3557 case Builtin::BI__sync_xor_and_fetch_1:
3558 case Builtin::BI__sync_xor_and_fetch_2:
3559 case Builtin::BI__sync_xor_and_fetch_4:
3560 case Builtin::BI__sync_xor_and_fetch_8:
3561 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003562 BuiltinIndex = 10;
3563 break;
3564
3565 case Builtin::BI__sync_nand_and_fetch:
3566 case Builtin::BI__sync_nand_and_fetch_1:
3567 case Builtin::BI__sync_nand_and_fetch_2:
3568 case Builtin::BI__sync_nand_and_fetch_4:
3569 case Builtin::BI__sync_nand_and_fetch_8:
3570 case Builtin::BI__sync_nand_and_fetch_16:
3571 BuiltinIndex = 11;
3572 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00003573 break;
Mike Stump11289f42009-09-09 15:08:12 +00003574
Chris Lattnerdc046542009-05-08 06:58:22 +00003575 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003576 case Builtin::BI__sync_val_compare_and_swap_1:
3577 case Builtin::BI__sync_val_compare_and_swap_2:
3578 case Builtin::BI__sync_val_compare_and_swap_4:
3579 case Builtin::BI__sync_val_compare_and_swap_8:
3580 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003581 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00003582 NumFixed = 2;
3583 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003584
Chris Lattnerdc046542009-05-08 06:58:22 +00003585 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003586 case Builtin::BI__sync_bool_compare_and_swap_1:
3587 case Builtin::BI__sync_bool_compare_and_swap_2:
3588 case Builtin::BI__sync_bool_compare_and_swap_4:
3589 case Builtin::BI__sync_bool_compare_and_swap_8:
3590 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003591 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00003592 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00003593 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003594 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003595
3596 case Builtin::BI__sync_lock_test_and_set:
3597 case Builtin::BI__sync_lock_test_and_set_1:
3598 case Builtin::BI__sync_lock_test_and_set_2:
3599 case Builtin::BI__sync_lock_test_and_set_4:
3600 case Builtin::BI__sync_lock_test_and_set_8:
3601 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003602 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00003603 break;
3604
Chris Lattnerdc046542009-05-08 06:58:22 +00003605 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00003606 case Builtin::BI__sync_lock_release_1:
3607 case Builtin::BI__sync_lock_release_2:
3608 case Builtin::BI__sync_lock_release_4:
3609 case Builtin::BI__sync_lock_release_8:
3610 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003611 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00003612 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00003613 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003614 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003615
3616 case Builtin::BI__sync_swap:
3617 case Builtin::BI__sync_swap_1:
3618 case Builtin::BI__sync_swap_2:
3619 case Builtin::BI__sync_swap_4:
3620 case Builtin::BI__sync_swap_8:
3621 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003622 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00003623 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00003624 }
Mike Stump11289f42009-09-09 15:08:12 +00003625
Chris Lattnerdc046542009-05-08 06:58:22 +00003626 // Now that we know how many fixed arguments we expect, first check that we
3627 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003628 if (TheCall->getNumArgs() < 1+NumFixed) {
3629 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3630 << 0 << 1+NumFixed << TheCall->getNumArgs()
3631 << TheCall->getCallee()->getSourceRange();
3632 return ExprError();
3633 }
Mike Stump11289f42009-09-09 15:08:12 +00003634
Hal Finkeld2208b52014-10-02 20:53:50 +00003635 if (WarnAboutSemanticsChange) {
3636 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3637 << TheCall->getCallee()->getSourceRange();
3638 }
3639
Chris Lattner5b9241b2009-05-08 15:36:58 +00003640 // Get the decl for the concrete builtin from this, we can tell what the
3641 // concrete integer type we should convert to is.
3642 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Mehdi Amini7186a432016-10-11 19:04:24 +00003643 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003644 FunctionDecl *NewBuiltinDecl;
3645 if (NewBuiltinID == BuiltinID)
3646 NewBuiltinDecl = FDecl;
3647 else {
3648 // Perform builtin lookup to avoid redeclaring it.
3649 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3650 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3651 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3652 assert(Res.getFoundDecl());
3653 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00003654 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003655 return ExprError();
3656 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003657
John McCallcf142162010-08-07 06:22:56 +00003658 // The first argument --- the pointer --- has a fixed type; we
3659 // deduce the types of the rest of the arguments accordingly. Walk
3660 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00003661 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00003662 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00003663
Chris Lattnerdc046542009-05-08 06:58:22 +00003664 // GCC does an implicit conversion to the pointer or integer ValType. This
3665 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00003666 // Initialize the argument.
3667 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3668 ValType, /*consume*/ false);
3669 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00003670 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003671 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003672
Chris Lattnerdc046542009-05-08 06:58:22 +00003673 // Okay, we have something that *can* be converted to the right type. Check
3674 // to see if there is a potentially weird extension going on here. This can
3675 // happen when you do an atomic operation on something like an char* and
3676 // pass in 42. The 42 gets converted to char. This is even more strange
3677 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00003678 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003679 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00003680 }
Mike Stump11289f42009-09-09 15:08:12 +00003681
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003682 ASTContext& Context = this->getASTContext();
3683
3684 // Create a new DeclRefExpr to refer to the new decl.
3685 DeclRefExpr* NewDRE = DeclRefExpr::Create(
3686 Context,
3687 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00003688 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003689 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00003690 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003691 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00003692 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003693 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00003694
Chris Lattnerdc046542009-05-08 06:58:22 +00003695 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00003696 // FIXME: This loses syntactic information.
3697 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3698 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3699 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003700 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00003701
Chandler Carruthbc8cab12010-07-18 07:23:17 +00003702 // Change the result type of the call to match the original value type. This
3703 // is arbitrary, but the codegen for these builtins ins design to handle it
3704 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00003705 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003706
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003707 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00003708}
3709
Michael Zolotukhin84df1232015-09-08 23:52:33 +00003710/// SemaBuiltinNontemporalOverloaded - We have a call to
3711/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3712/// overloaded function based on the pointer type of its last argument.
3713///
3714/// This function goes through and does final semantic checking for these
3715/// builtins.
3716ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3717 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3718 DeclRefExpr *DRE =
3719 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3720 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3721 unsigned BuiltinID = FDecl->getBuiltinID();
3722 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3723 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3724 "Unexpected nontemporal load/store builtin!");
3725 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3726 unsigned numArgs = isStore ? 2 : 1;
3727
3728 // Ensure that we have the proper number of arguments.
3729 if (checkArgCount(*this, TheCall, numArgs))
3730 return ExprError();
3731
3732 // Inspect the last argument of the nontemporal builtin. This should always
3733 // be a pointer type, from which we imply the type of the memory access.
3734 // Because it is a pointer type, we don't have to worry about any implicit
3735 // casts here.
3736 Expr *PointerArg = TheCall->getArg(numArgs - 1);
3737 ExprResult PointerArgResult =
3738 DefaultFunctionArrayLvalueConversion(PointerArg);
3739
3740 if (PointerArgResult.isInvalid())
3741 return ExprError();
3742 PointerArg = PointerArgResult.get();
3743 TheCall->setArg(numArgs - 1, PointerArg);
3744
3745 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3746 if (!pointerType) {
3747 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3748 << PointerArg->getType() << PointerArg->getSourceRange();
3749 return ExprError();
3750 }
3751
3752 QualType ValType = pointerType->getPointeeType();
3753
3754 // Strip any qualifiers off ValType.
3755 ValType = ValType.getUnqualifiedType();
3756 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3757 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3758 !ValType->isVectorType()) {
3759 Diag(DRE->getLocStart(),
3760 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3761 << PointerArg->getType() << PointerArg->getSourceRange();
3762 return ExprError();
3763 }
3764
3765 if (!isStore) {
3766 TheCall->setType(ValType);
3767 return TheCallResult;
3768 }
3769
3770 ExprResult ValArg = TheCall->getArg(0);
3771 InitializedEntity Entity = InitializedEntity::InitializeParameter(
3772 Context, ValType, /*consume*/ false);
3773 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3774 if (ValArg.isInvalid())
3775 return ExprError();
3776
3777 TheCall->setArg(0, ValArg.get());
3778 TheCall->setType(Context.VoidTy);
3779 return TheCallResult;
3780}
3781
Chris Lattner6436fb62009-02-18 06:01:06 +00003782/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00003783/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00003784/// Note: It might also make sense to do the UTF-16 conversion here (would
3785/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00003786bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00003787 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00003788 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3789
Douglas Gregorfb65e592011-07-27 05:40:30 +00003790 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003791 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3792 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00003793 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00003794 }
Mike Stump11289f42009-09-09 15:08:12 +00003795
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003796 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003797 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003798 unsigned NumBytes = String.size();
Justin Lebar90910552016-09-30 00:38:45 +00003799 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3800 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3801 llvm::UTF16 *ToPtr = &ToBuf[0];
3802
3803 llvm::ConversionResult Result =
3804 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3805 ToPtr + NumBytes, llvm::strictConversion);
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003806 // Check for conversion failure.
Justin Lebar90910552016-09-30 00:38:45 +00003807 if (Result != llvm::conversionOK)
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003808 Diag(Arg->getLocStart(),
3809 diag::warn_cfstring_truncated) << Arg->getSourceRange();
3810 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00003811 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003812}
3813
Mehdi Amini06d367c2016-10-24 20:39:34 +00003814/// CheckObjCString - Checks that the format string argument to the os_log()
3815/// and os_trace() functions is correct, and converts it to const char *.
3816ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3817 Arg = Arg->IgnoreParenCasts();
3818 auto *Literal = dyn_cast<StringLiteral>(Arg);
3819 if (!Literal) {
3820 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3821 Literal = ObjcLiteral->getString();
3822 }
3823 }
3824
3825 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3826 return ExprError(
3827 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3828 << Arg->getSourceRange());
3829 }
3830
3831 ExprResult Result(Literal);
3832 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3833 InitializedEntity Entity =
3834 InitializedEntity::InitializeParameter(Context, ResultTy, false);
3835 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3836 return Result;
3837}
3838
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003839/// Check that the user is calling the appropriate va_start builtin for the
3840/// target and calling convention.
3841static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
3842 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
3843 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
Martin Storsjo022e7822017-07-17 20:49:45 +00003844 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003845 bool IsWindows = TT.isOSWindows();
Martin Storsjo022e7822017-07-17 20:49:45 +00003846 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
3847 if (IsX64 || IsAArch64) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003848 CallingConv CC = CC_C;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003849 if (const FunctionDecl *FD = S.getCurFunctionDecl())
3850 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3851 if (IsMSVAStart) {
3852 // Don't allow this in System V ABI functions.
Martin Storsjo022e7822017-07-17 20:49:45 +00003853 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003854 return S.Diag(Fn->getLocStart(),
3855 diag::err_ms_va_start_used_in_sysv_function);
3856 } else {
Martin Storsjo022e7822017-07-17 20:49:45 +00003857 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003858 // On x64 Windows, don't allow this in System V ABI functions.
3859 // (Yes, that means there's no corresponding way to support variadic
3860 // System V ABI functions on Windows.)
3861 if ((IsWindows && CC == CC_X86_64SysV) ||
Martin Storsjo022e7822017-07-17 20:49:45 +00003862 (!IsWindows && CC == CC_Win64))
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003863 return S.Diag(Fn->getLocStart(),
3864 diag::err_va_start_used_in_wrong_abi_function)
3865 << !IsWindows;
3866 }
3867 return false;
3868 }
3869
3870 if (IsMSVAStart)
Martin Storsjo022e7822017-07-17 20:49:45 +00003871 return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003872 return false;
3873}
3874
3875static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
3876 ParmVarDecl **LastParam = nullptr) {
3877 // Determine whether the current function, block, or obj-c method is variadic
3878 // and get its parameter list.
3879 bool IsVariadic = false;
3880 ArrayRef<ParmVarDecl *> Params;
Reid Klecknerf1deb832017-05-04 19:51:05 +00003881 DeclContext *Caller = S.CurContext;
3882 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
3883 IsVariadic = Block->isVariadic();
3884 Params = Block->parameters();
3885 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003886 IsVariadic = FD->isVariadic();
3887 Params = FD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00003888 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003889 IsVariadic = MD->isVariadic();
3890 // FIXME: This isn't correct for methods (results in bogus warning).
3891 Params = MD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00003892 } else if (isa<CapturedDecl>(Caller)) {
3893 // We don't support va_start in a CapturedDecl.
3894 S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
3895 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003896 } else {
Reid Klecknerf1deb832017-05-04 19:51:05 +00003897 // This must be some other declcontext that parses exprs.
3898 S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
3899 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003900 }
3901
3902 if (!IsVariadic) {
Reid Klecknerf1deb832017-05-04 19:51:05 +00003903 S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003904 return true;
3905 }
3906
3907 if (LastParam)
3908 *LastParam = Params.empty() ? nullptr : Params.back();
3909
3910 return false;
3911}
3912
Charles Davisc7d5c942015-09-17 20:55:33 +00003913/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3914/// for validity. Emit an error and return true on failure; return false
3915/// on success.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003916bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00003917 Expr *Fn = TheCall->getCallee();
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003918
3919 if (checkVAStartABI(*this, BuiltinID, Fn))
3920 return true;
3921
Chris Lattner08464942007-12-28 05:29:59 +00003922 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00003923 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003924 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003925 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3926 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00003927 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003928 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00003929 return true;
3930 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003931
3932 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00003933 return Diag(TheCall->getLocEnd(),
3934 diag::err_typecheck_call_too_few_args_at_least)
3935 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003936 }
3937
John McCall29ad95b2011-08-27 01:09:30 +00003938 // Type-check the first argument normally.
3939 if (checkBuiltinArgument(*this, TheCall, 0))
3940 return true;
3941
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003942 // Check that the current function is variadic, and get its last parameter.
3943 ParmVarDecl *LastParam;
3944 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
Chris Lattner43be2e62007-12-19 23:59:04 +00003945 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003946
Chris Lattner43be2e62007-12-19 23:59:04 +00003947 // Verify that the second argument to the builtin is the last argument of the
3948 // current function or method.
3949 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00003950 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003951
Nico Weber9eea7642013-05-24 23:31:57 +00003952 // These are valid if SecondArgIsLastNamedArgument is false after the next
3953 // block.
3954 QualType Type;
3955 SourceLocation ParamLoc;
Aaron Ballman1de59c52016-04-24 13:30:21 +00003956 bool IsCRegister = false;
Nico Weber9eea7642013-05-24 23:31:57 +00003957
Anders Carlsson6a8350b2008-02-11 04:20:54 +00003958 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3959 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003960 SecondArgIsLastNamedArgument = PV == LastParam;
Nico Weber9eea7642013-05-24 23:31:57 +00003961
3962 Type = PV->getType();
3963 ParamLoc = PV->getLocation();
Aaron Ballman1de59c52016-04-24 13:30:21 +00003964 IsCRegister =
3965 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
Chris Lattner43be2e62007-12-19 23:59:04 +00003966 }
3967 }
Mike Stump11289f42009-09-09 15:08:12 +00003968
Chris Lattner43be2e62007-12-19 23:59:04 +00003969 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00003970 Diag(TheCall->getArg(1)->getLocStart(),
Aaron Ballman05164812016-04-18 18:10:53 +00003971 diag::warn_second_arg_of_va_start_not_last_named_param);
Aaron Ballman1de59c52016-04-24 13:30:21 +00003972 else if (IsCRegister || Type->isReferenceType() ||
Aaron Ballmana4f597f2016-09-15 18:07:51 +00003973 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3974 // Promotable integers are UB, but enumerations need a bit of
3975 // extra checking to see what their promotable type actually is.
3976 if (!Type->isPromotableIntegerType())
3977 return false;
3978 if (!Type->isEnumeralType())
3979 return true;
3980 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3981 return !(ED &&
3982 Context.typesAreCompatible(ED->getPromotionType(), Type));
3983 }()) {
Aaron Ballman1de59c52016-04-24 13:30:21 +00003984 unsigned Reason = 0;
3985 if (Type->isReferenceType()) Reason = 1;
3986 else if (IsCRegister) Reason = 2;
3987 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
Nico Weber9eea7642013-05-24 23:31:57 +00003988 Diag(ParamLoc, diag::note_parameter_type) << Type;
3989 }
3990
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00003991 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00003992 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00003993}
Chris Lattner43be2e62007-12-19 23:59:04 +00003994
Saleem Abdulrasool3450aa72017-09-26 20:12:04 +00003995bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003996 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3997 // const char *named_addr);
3998
3999 Expr *Func = Call->getCallee();
4000
4001 if (Call->getNumArgs() < 3)
4002 return Diag(Call->getLocEnd(),
4003 diag::err_typecheck_call_too_few_args_at_least)
4004 << 0 /*function call*/ << 3 << Call->getNumArgs();
4005
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004006 // Type-check the first argument normally.
4007 if (checkBuiltinArgument(*this, Call, 0))
4008 return true;
4009
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004010 // Check that the current function is variadic.
4011 if (checkVAStartIsInVariadicFunction(*this, Func))
4012 return true;
4013
Saleem Abdulrasool448e8ad2017-09-26 17:44:10 +00004014 // __va_start on Windows does not validate the parameter qualifiers
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004015
Saleem Abdulrasool448e8ad2017-09-26 17:44:10 +00004016 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
4017 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
4018
4019 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
4020 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
4021
4022 const QualType &ConstCharPtrTy =
4023 Context.getPointerType(Context.CharTy.withConst());
4024 if (!Arg1Ty->isPointerType() ||
4025 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
4026 Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible)
4027 << Arg1->getType() << ConstCharPtrTy
4028 << 1 /* different class */
4029 << 0 /* qualifier difference */
4030 << 3 /* parameter mismatch */
4031 << 2 << Arg1->getType() << ConstCharPtrTy;
4032
4033 const QualType SizeTy = Context.getSizeType();
4034 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
4035 Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible)
4036 << Arg2->getType() << SizeTy
4037 << 1 /* different class */
4038 << 0 /* qualifier difference */
4039 << 3 /* parameter mismatch */
4040 << 3 << Arg2->getType() << SizeTy;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004041
4042 return false;
4043}
4044
Chris Lattner2da14fb2007-12-20 00:26:33 +00004045/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
4046/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00004047bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
4048 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00004049 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00004050 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00004051 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00004052 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004053 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004054 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00004055 << SourceRange(TheCall->getArg(2)->getLocStart(),
4056 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00004057
John Wiegley01296292011-04-08 18:41:53 +00004058 ExprResult OrigArg0 = TheCall->getArg(0);
4059 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00004060
Chris Lattner2da14fb2007-12-20 00:26:33 +00004061 // Do standard promotions between the two arguments, returning their common
4062 // type.
Chris Lattner08464942007-12-28 05:29:59 +00004063 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00004064 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
4065 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00004066
4067 // Make sure any conversions are pushed back into the call; this is
4068 // type safe since unordered compare builtins are declared as "_Bool
4069 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00004070 TheCall->setArg(0, OrigArg0.get());
4071 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00004072
John Wiegley01296292011-04-08 18:41:53 +00004073 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00004074 return false;
4075
Chris Lattner2da14fb2007-12-20 00:26:33 +00004076 // If the common type isn't a real floating type, then the arguments were
4077 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00004078 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00004079 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004080 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00004081 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
4082 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00004083
Chris Lattner2da14fb2007-12-20 00:26:33 +00004084 return false;
4085}
4086
Benjamin Kramer634fc102010-02-15 22:42:31 +00004087/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
4088/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00004089/// to check everything. We expect the last argument to be a floating point
4090/// value.
4091bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
4092 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00004093 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00004094 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00004095 if (TheCall->getNumArgs() > NumArgs)
4096 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004097 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004098 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00004099 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004100 (*(TheCall->arg_end()-1))->getLocEnd());
4101
Benjamin Kramer64aae502010-02-16 10:07:31 +00004102 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00004103
Eli Friedman7e4faac2009-08-31 20:06:00 +00004104 if (OrigArg->isTypeDependent())
4105 return false;
4106
Chris Lattner68784ef2010-05-06 05:50:07 +00004107 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00004108 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00004109 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004110 diag::err_typecheck_call_invalid_unary_fp)
4111 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004112
Neil Hickey88c0fac2016-12-13 16:22:50 +00004113 // If this is an implicit conversion from float -> float or double, remove it.
Chris Lattner68784ef2010-05-06 05:50:07 +00004114 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
Neil Hickey7b5ddab2016-12-14 13:18:48 +00004115 // Only remove standard FloatCasts, leaving other casts inplace
4116 if (Cast->getCastKind() == CK_FloatingCast) {
4117 Expr *CastArg = Cast->getSubExpr();
4118 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
4119 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
4120 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
4121 "promotion from float to either float or double is the only expected cast here");
4122 Cast->setSubExpr(nullptr);
4123 TheCall->setArg(NumArgs-1, CastArg);
4124 }
Chris Lattner68784ef2010-05-06 05:50:07 +00004125 }
4126 }
4127
Eli Friedman7e4faac2009-08-31 20:06:00 +00004128 return false;
4129}
4130
Tony Jiangbbc48e92017-05-24 15:13:32 +00004131// Customized Sema Checking for VSX builtins that have the following signature:
4132// vector [...] builtinName(vector [...], vector [...], const int);
4133// Which takes the same type of vectors (any legal vector type) for the first
4134// two arguments and takes compile time constant for the third argument.
4135// Example builtins are :
4136// vector double vec_xxpermdi(vector double, vector double, int);
4137// vector short vec_xxsldwi(vector short, vector short, int);
4138bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
4139 unsigned ExpectedNumArgs = 3;
4140 if (TheCall->getNumArgs() < ExpectedNumArgs)
4141 return Diag(TheCall->getLocEnd(),
4142 diag::err_typecheck_call_too_few_args_at_least)
4143 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4144 << TheCall->getSourceRange();
4145
4146 if (TheCall->getNumArgs() > ExpectedNumArgs)
4147 return Diag(TheCall->getLocEnd(),
4148 diag::err_typecheck_call_too_many_args_at_most)
4149 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4150 << TheCall->getSourceRange();
4151
4152 // Check the third argument is a compile time constant
4153 llvm::APSInt Value;
4154 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
4155 return Diag(TheCall->getLocStart(),
4156 diag::err_vsx_builtin_nonconstant_argument)
4157 << 3 /* argument index */ << TheCall->getDirectCallee()
4158 << SourceRange(TheCall->getArg(2)->getLocStart(),
4159 TheCall->getArg(2)->getLocEnd());
4160
4161 QualType Arg1Ty = TheCall->getArg(0)->getType();
4162 QualType Arg2Ty = TheCall->getArg(1)->getType();
4163
4164 // Check the type of argument 1 and argument 2 are vectors.
4165 SourceLocation BuiltinLoc = TheCall->getLocStart();
4166 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
4167 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
4168 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
4169 << TheCall->getDirectCallee()
4170 << SourceRange(TheCall->getArg(0)->getLocStart(),
4171 TheCall->getArg(1)->getLocEnd());
4172 }
4173
4174 // Check the first two arguments are the same type.
4175 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
4176 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
4177 << TheCall->getDirectCallee()
4178 << SourceRange(TheCall->getArg(0)->getLocStart(),
4179 TheCall->getArg(1)->getLocEnd());
4180 }
4181
4182 // When default clang type checking is turned off and the customized type
4183 // checking is used, the returning type of the function must be explicitly
4184 // set. Otherwise it is _Bool by default.
4185 TheCall->setType(Arg1Ty);
4186
4187 return false;
4188}
4189
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004190/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
4191// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00004192ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00004193 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004194 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00004195 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00004196 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4197 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004198
Nate Begemana0110022010-06-08 00:16:34 +00004199 // Determine which of the following types of shufflevector we're checking:
4200 // 1) unary, vector mask: (lhs, mask)
Craig Topperb3174a82016-05-18 04:11:25 +00004201 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
Nate Begemana0110022010-06-08 00:16:34 +00004202 QualType resType = TheCall->getArg(0)->getType();
4203 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00004204
Douglas Gregorc25f7662009-05-19 22:10:17 +00004205 if (!TheCall->getArg(0)->isTypeDependent() &&
4206 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00004207 QualType LHSType = TheCall->getArg(0)->getType();
4208 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00004209
Craig Topperbaca3892013-07-29 06:47:04 +00004210 if (!LHSType->isVectorType() || !RHSType->isVectorType())
4211 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004212 diag::err_vec_builtin_non_vector)
4213 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004214 << SourceRange(TheCall->getArg(0)->getLocStart(),
4215 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00004216
Nate Begemana0110022010-06-08 00:16:34 +00004217 numElements = LHSType->getAs<VectorType>()->getNumElements();
4218 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00004219
Nate Begemana0110022010-06-08 00:16:34 +00004220 // Check to see if we have a call with 2 vector arguments, the unary shuffle
4221 // with mask. If so, verify that RHS is an integer vector type with the
4222 // same number of elts as lhs.
4223 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00004224 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00004225 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00004226 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004227 diag::err_vec_builtin_incompatible_vector)
4228 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004229 << SourceRange(TheCall->getArg(1)->getLocStart(),
4230 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00004231 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00004232 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004233 diag::err_vec_builtin_incompatible_vector)
4234 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004235 << SourceRange(TheCall->getArg(0)->getLocStart(),
4236 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00004237 } else if (numElements != numResElements) {
4238 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00004239 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00004240 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00004241 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004242 }
4243
4244 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00004245 if (TheCall->getArg(i)->isTypeDependent() ||
4246 TheCall->getArg(i)->isValueDependent())
4247 continue;
4248
Nate Begemana0110022010-06-08 00:16:34 +00004249 llvm::APSInt Result(32);
4250 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
4251 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004252 diag::err_shufflevector_nonconstant_argument)
4253 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004254
Craig Topper50ad5b72013-08-03 17:40:38 +00004255 // Allow -1 which will be translated to undef in the IR.
4256 if (Result.isSigned() && Result.isAllOnesValue())
4257 continue;
4258
Chris Lattner7ab824e2008-08-10 02:05:13 +00004259 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004260 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004261 diag::err_shufflevector_argument_too_large)
4262 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004263 }
4264
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004265 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004266
Chris Lattner7ab824e2008-08-10 02:05:13 +00004267 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004268 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00004269 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004270 }
4271
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004272 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
4273 TheCall->getCallee()->getLocStart(),
4274 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004275}
Chris Lattner43be2e62007-12-19 23:59:04 +00004276
Hal Finkelc4d7c822013-09-18 03:29:45 +00004277/// SemaConvertVectorExpr - Handle __builtin_convertvector
4278ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
4279 SourceLocation BuiltinLoc,
4280 SourceLocation RParenLoc) {
4281 ExprValueKind VK = VK_RValue;
4282 ExprObjectKind OK = OK_Ordinary;
4283 QualType DstTy = TInfo->getType();
4284 QualType SrcTy = E->getType();
4285
4286 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
4287 return ExprError(Diag(BuiltinLoc,
4288 diag::err_convertvector_non_vector)
4289 << E->getSourceRange());
4290 if (!DstTy->isVectorType() && !DstTy->isDependentType())
4291 return ExprError(Diag(BuiltinLoc,
4292 diag::err_convertvector_non_vector_type));
4293
4294 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
4295 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
4296 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
4297 if (SrcElts != DstElts)
4298 return ExprError(Diag(BuiltinLoc,
4299 diag::err_convertvector_incompatible_vector)
4300 << E->getSourceRange());
4301 }
4302
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004303 return new (Context)
4304 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00004305}
4306
Daniel Dunbarb7257262008-07-21 22:59:13 +00004307/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
4308// This is declared to take (const void*, ...) and can take two
4309// optional constant int args.
4310bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00004311 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004312
Chris Lattner3b054132008-11-19 05:08:23 +00004313 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004314 return Diag(TheCall->getLocEnd(),
4315 diag::err_typecheck_call_too_many_args_at_most)
4316 << 0 /*function call*/ << 3 << NumArgs
4317 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004318
4319 // Argument 0 is checked for us and the remaining arguments must be
4320 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00004321 for (unsigned i = 1; i != NumArgs; ++i)
4322 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004323 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004324
Warren Hunt20e4a5d2014-02-21 23:08:53 +00004325 return false;
4326}
4327
Hal Finkelf0417332014-07-17 14:25:55 +00004328/// SemaBuiltinAssume - Handle __assume (MS Extension).
4329// __assume does not evaluate its arguments, and should warn if its argument
4330// has side effects.
4331bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
4332 Expr *Arg = TheCall->getArg(0);
4333 if (Arg->isInstantiationDependent()) return false;
4334
4335 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00004336 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00004337 << Arg->getSourceRange()
4338 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
4339
4340 return false;
4341}
4342
David Majnemer86b1bfa2016-10-31 18:07:57 +00004343/// Handle __builtin_alloca_with_align. This is declared
David Majnemer51169932016-10-31 05:37:48 +00004344/// as (size_t, size_t) where the second size_t must be a power of 2 greater
4345/// than 8.
4346bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
4347 // The alignment must be a constant integer.
4348 Expr *Arg = TheCall->getArg(1);
4349
4350 // We can't check the value of a dependent argument.
4351 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
David Majnemer86b1bfa2016-10-31 18:07:57 +00004352 if (const auto *UE =
4353 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
4354 if (UE->getKind() == UETT_AlignOf)
4355 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
4356 << Arg->getSourceRange();
4357
David Majnemer51169932016-10-31 05:37:48 +00004358 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
4359
4360 if (!Result.isPowerOf2())
4361 return Diag(TheCall->getLocStart(),
4362 diag::err_alignment_not_power_of_two)
4363 << Arg->getSourceRange();
4364
4365 if (Result < Context.getCharWidth())
4366 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
4367 << (unsigned)Context.getCharWidth()
4368 << Arg->getSourceRange();
4369
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004370 if (Result > std::numeric_limits<int32_t>::max())
David Majnemer51169932016-10-31 05:37:48 +00004371 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004372 << std::numeric_limits<int32_t>::max()
David Majnemer51169932016-10-31 05:37:48 +00004373 << Arg->getSourceRange();
4374 }
4375
4376 return false;
4377}
4378
4379/// Handle __builtin_assume_aligned. This is declared
Hal Finkelbcc06082014-09-07 22:58:14 +00004380/// as (const void*, size_t, ...) and can take one optional constant int arg.
4381bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
4382 unsigned NumArgs = TheCall->getNumArgs();
4383
4384 if (NumArgs > 3)
4385 return Diag(TheCall->getLocEnd(),
4386 diag::err_typecheck_call_too_many_args_at_most)
4387 << 0 /*function call*/ << 3 << NumArgs
4388 << TheCall->getSourceRange();
4389
4390 // The alignment must be a constant integer.
4391 Expr *Arg = TheCall->getArg(1);
4392
4393 // We can't check the value of a dependent argument.
4394 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4395 llvm::APSInt Result;
4396 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4397 return true;
4398
4399 if (!Result.isPowerOf2())
4400 return Diag(TheCall->getLocStart(),
4401 diag::err_alignment_not_power_of_two)
4402 << Arg->getSourceRange();
4403 }
4404
4405 if (NumArgs > 2) {
4406 ExprResult Arg(TheCall->getArg(2));
4407 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4408 Context.getSizeType(), false);
4409 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4410 if (Arg.isInvalid()) return true;
4411 TheCall->setArg(2, Arg.get());
4412 }
Hal Finkelf0417332014-07-17 14:25:55 +00004413
4414 return false;
4415}
4416
Mehdi Amini06d367c2016-10-24 20:39:34 +00004417bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4418 unsigned BuiltinID =
4419 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4420 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4421
4422 unsigned NumArgs = TheCall->getNumArgs();
4423 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4424 if (NumArgs < NumRequiredArgs) {
4425 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4426 << 0 /* function call */ << NumRequiredArgs << NumArgs
4427 << TheCall->getSourceRange();
4428 }
4429 if (NumArgs >= NumRequiredArgs + 0x100) {
4430 return Diag(TheCall->getLocEnd(),
4431 diag::err_typecheck_call_too_many_args_at_most)
4432 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4433 << TheCall->getSourceRange();
4434 }
4435 unsigned i = 0;
4436
4437 // For formatting call, check buffer arg.
4438 if (!IsSizeCall) {
4439 ExprResult Arg(TheCall->getArg(i));
4440 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4441 Context, Context.VoidPtrTy, false);
4442 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4443 if (Arg.isInvalid())
4444 return true;
4445 TheCall->setArg(i, Arg.get());
4446 i++;
4447 }
4448
4449 // Check string literal arg.
4450 unsigned FormatIdx = i;
4451 {
4452 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4453 if (Arg.isInvalid())
4454 return true;
4455 TheCall->setArg(i, Arg.get());
4456 i++;
4457 }
4458
4459 // Make sure variadic args are scalar.
4460 unsigned FirstDataArg = i;
4461 while (i < NumArgs) {
4462 ExprResult Arg = DefaultVariadicArgumentPromotion(
4463 TheCall->getArg(i), VariadicFunction, nullptr);
4464 if (Arg.isInvalid())
4465 return true;
4466 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4467 if (ArgSize.getQuantity() >= 0x100) {
4468 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4469 << i << (int)ArgSize.getQuantity() << 0xff
4470 << TheCall->getSourceRange();
4471 }
4472 TheCall->setArg(i, Arg.get());
4473 i++;
4474 }
4475
4476 // Check formatting specifiers. NOTE: We're only doing this for the non-size
4477 // call to avoid duplicate diagnostics.
4478 if (!IsSizeCall) {
4479 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4480 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4481 bool Success = CheckFormatArguments(
4482 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4483 VariadicFunction, TheCall->getLocStart(), SourceRange(),
4484 CheckedVarArgs);
4485 if (!Success)
4486 return true;
4487 }
4488
4489 if (IsSizeCall) {
4490 TheCall->setType(Context.getSizeType());
4491 } else {
4492 TheCall->setType(Context.VoidPtrTy);
4493 }
4494 return false;
4495}
4496
Eric Christopher8d0c6212010-04-17 02:26:23 +00004497/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4498/// TheCall is a constant expression.
4499bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4500 llvm::APSInt &Result) {
4501 Expr *Arg = TheCall->getArg(ArgNum);
4502 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4503 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4504
4505 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4506
4507 if (!Arg->isIntegerConstantExpr(Result, Context))
4508 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00004509 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00004510
Chris Lattnerd545ad12009-09-23 06:06:36 +00004511 return false;
4512}
4513
Richard Sandiford28940af2014-04-16 08:47:51 +00004514/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4515/// TheCall is a constant expression in the range [Low, High].
4516bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4517 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00004518 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004519
4520 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00004521 Expr *Arg = TheCall->getArg(ArgNum);
4522 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004523 return false;
4524
Eric Christopher8d0c6212010-04-17 02:26:23 +00004525 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00004526 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004527 return true;
4528
Richard Sandiford28940af2014-04-16 08:47:51 +00004529 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00004530 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00004531 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00004532
4533 return false;
4534}
4535
Simon Dardis1f90f2d2016-10-19 17:50:52 +00004536/// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4537/// TheCall is a constant expression is a multiple of Num..
4538bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4539 unsigned Num) {
4540 llvm::APSInt Result;
4541
4542 // We can't check the value of a dependent argument.
4543 Expr *Arg = TheCall->getArg(ArgNum);
4544 if (Arg->isTypeDependent() || Arg->isValueDependent())
4545 return false;
4546
4547 // Check constant-ness first.
4548 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4549 return true;
4550
4551 if (Result.getSExtValue() % Num != 0)
4552 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4553 << Num << Arg->getSourceRange();
4554
4555 return false;
4556}
4557
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004558/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4559/// TheCall is an ARM/AArch64 special register string literal.
4560bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4561 int ArgNum, unsigned ExpectedFieldNum,
4562 bool AllowName) {
4563 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4564 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4565 BuiltinID == ARM::BI__builtin_arm_rsr ||
4566 BuiltinID == ARM::BI__builtin_arm_rsrp ||
4567 BuiltinID == ARM::BI__builtin_arm_wsr ||
4568 BuiltinID == ARM::BI__builtin_arm_wsrp;
4569 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4570 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4571 BuiltinID == AArch64::BI__builtin_arm_rsr ||
4572 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4573 BuiltinID == AArch64::BI__builtin_arm_wsr ||
4574 BuiltinID == AArch64::BI__builtin_arm_wsrp;
4575 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4576
4577 // We can't check the value of a dependent argument.
4578 Expr *Arg = TheCall->getArg(ArgNum);
4579 if (Arg->isTypeDependent() || Arg->isValueDependent())
4580 return false;
4581
4582 // Check if the argument is a string literal.
4583 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4584 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4585 << Arg->getSourceRange();
4586
4587 // Check the type of special register given.
4588 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4589 SmallVector<StringRef, 6> Fields;
4590 Reg.split(Fields, ":");
4591
4592 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4593 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4594 << Arg->getSourceRange();
4595
4596 // If the string is the name of a register then we cannot check that it is
4597 // valid here but if the string is of one the forms described in ACLE then we
4598 // can check that the supplied fields are integers and within the valid
4599 // ranges.
4600 if (Fields.size() > 1) {
4601 bool FiveFields = Fields.size() == 5;
4602
4603 bool ValidString = true;
4604 if (IsARMBuiltin) {
4605 ValidString &= Fields[0].startswith_lower("cp") ||
4606 Fields[0].startswith_lower("p");
4607 if (ValidString)
4608 Fields[0] =
4609 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4610
4611 ValidString &= Fields[2].startswith_lower("c");
4612 if (ValidString)
4613 Fields[2] = Fields[2].drop_front(1);
4614
4615 if (FiveFields) {
4616 ValidString &= Fields[3].startswith_lower("c");
4617 if (ValidString)
4618 Fields[3] = Fields[3].drop_front(1);
4619 }
4620 }
4621
4622 SmallVector<int, 5> Ranges;
4623 if (FiveFields)
Oleg Ranevskyy85d93a82016-11-18 21:00:08 +00004624 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004625 else
4626 Ranges.append({15, 7, 15});
4627
4628 for (unsigned i=0; i<Fields.size(); ++i) {
4629 int IntField;
4630 ValidString &= !Fields[i].getAsInteger(10, IntField);
4631 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4632 }
4633
4634 if (!ValidString)
4635 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4636 << Arg->getSourceRange();
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004637 } else if (IsAArch64Builtin && Fields.size() == 1) {
4638 // If the register name is one of those that appear in the condition below
4639 // and the special register builtin being used is one of the write builtins,
4640 // then we require that the argument provided for writing to the register
4641 // is an integer constant expression. This is because it will be lowered to
4642 // an MSR (immediate) instruction, so we need to know the immediate at
4643 // compile time.
4644 if (TheCall->getNumArgs() != 2)
4645 return false;
4646
4647 std::string RegLower = Reg.lower();
4648 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4649 RegLower != "pan" && RegLower != "uao")
4650 return false;
4651
4652 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4653 }
4654
4655 return false;
4656}
4657
Eli Friedmanc97d0142009-05-03 06:04:26 +00004658/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004659/// This checks that the target supports __builtin_longjmp and
4660/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004661bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004662 if (!Context.getTargetInfo().hasSjLjLowering())
4663 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4664 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4665
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004666 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00004667 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00004668
Eric Christopher8d0c6212010-04-17 02:26:23 +00004669 // TODO: This is less than ideal. Overload this to take a value.
4670 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4671 return true;
4672
4673 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004674 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4675 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4676
4677 return false;
4678}
4679
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004680/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4681/// This checks that the target supports __builtin_setjmp.
4682bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4683 if (!Context.getTargetInfo().hasSjLjLowering())
4684 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4685 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4686 return false;
4687}
4688
Richard Smithd7293d72013-08-05 18:49:43 +00004689namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004690
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004691class UncoveredArgHandler {
4692 enum { Unknown = -1, AllCovered = -2 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004693
4694 signed FirstUncoveredArg = Unknown;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004695 SmallVector<const Expr *, 4> DiagnosticExprs;
4696
4697public:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004698 UncoveredArgHandler() = default;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004699
4700 bool hasUncoveredArg() const {
4701 return (FirstUncoveredArg >= 0);
4702 }
4703
4704 unsigned getUncoveredArg() const {
4705 assert(hasUncoveredArg() && "no uncovered argument");
4706 return FirstUncoveredArg;
4707 }
4708
4709 void setAllCovered() {
4710 // A string has been found with all arguments covered, so clear out
4711 // the diagnostics.
4712 DiagnosticExprs.clear();
4713 FirstUncoveredArg = AllCovered;
4714 }
4715
4716 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4717 assert(NewFirstUncoveredArg >= 0 && "Outside range");
4718
4719 // Don't update if a previous string covers all arguments.
4720 if (FirstUncoveredArg == AllCovered)
4721 return;
4722
4723 // UncoveredArgHandler tracks the highest uncovered argument index
4724 // and with it all the strings that match this index.
4725 if (NewFirstUncoveredArg == FirstUncoveredArg)
4726 DiagnosticExprs.push_back(StrExpr);
4727 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4728 DiagnosticExprs.clear();
4729 DiagnosticExprs.push_back(StrExpr);
4730 FirstUncoveredArg = NewFirstUncoveredArg;
4731 }
4732 }
4733
4734 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4735};
4736
Richard Smithd7293d72013-08-05 18:49:43 +00004737enum StringLiteralCheckType {
4738 SLCT_NotALiteral,
4739 SLCT_UncheckedLiteral,
4740 SLCT_CheckedLiteral
4741};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004742
4743} // namespace
Richard Smithd7293d72013-08-05 18:49:43 +00004744
Stephen Hines648c3692016-09-16 01:07:04 +00004745static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4746 BinaryOperatorKind BinOpKind,
4747 bool AddendIsRight) {
4748 unsigned BitWidth = Offset.getBitWidth();
4749 unsigned AddendBitWidth = Addend.getBitWidth();
4750 // There might be negative interim results.
4751 if (Addend.isUnsigned()) {
4752 Addend = Addend.zext(++AddendBitWidth);
4753 Addend.setIsSigned(true);
4754 }
4755 // Adjust the bit width of the APSInts.
4756 if (AddendBitWidth > BitWidth) {
4757 Offset = Offset.sext(AddendBitWidth);
4758 BitWidth = AddendBitWidth;
4759 } else if (BitWidth > AddendBitWidth) {
4760 Addend = Addend.sext(BitWidth);
4761 }
4762
4763 bool Ov = false;
4764 llvm::APSInt ResOffset = Offset;
4765 if (BinOpKind == BO_Add)
4766 ResOffset = Offset.sadd_ov(Addend, Ov);
4767 else {
4768 assert(AddendIsRight && BinOpKind == BO_Sub &&
4769 "operator must be add or sub with addend on the right");
4770 ResOffset = Offset.ssub_ov(Addend, Ov);
4771 }
4772
4773 // We add an offset to a pointer here so we should support an offset as big as
4774 // possible.
4775 if (Ov) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004776 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
4777 "index (intermediate) result too big");
Stephen Hinesfec73ad2016-09-16 07:21:24 +00004778 Offset = Offset.sext(2 * BitWidth);
Stephen Hines648c3692016-09-16 01:07:04 +00004779 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4780 return;
4781 }
4782
4783 Offset = ResOffset;
4784}
4785
4786namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004787
Stephen Hines648c3692016-09-16 01:07:04 +00004788// This is a wrapper class around StringLiteral to support offsetted string
4789// literals as format strings. It takes the offset into account when returning
4790// the string and its length or the source locations to display notes correctly.
4791class FormatStringLiteral {
4792 const StringLiteral *FExpr;
4793 int64_t Offset;
4794
4795 public:
4796 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4797 : FExpr(fexpr), Offset(Offset) {}
4798
4799 StringRef getString() const {
4800 return FExpr->getString().drop_front(Offset);
4801 }
4802
4803 unsigned getByteLength() const {
4804 return FExpr->getByteLength() - getCharByteWidth() * Offset;
4805 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004806
Stephen Hines648c3692016-09-16 01:07:04 +00004807 unsigned getLength() const { return FExpr->getLength() - Offset; }
4808 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4809
4810 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4811
4812 QualType getType() const { return FExpr->getType(); }
4813
4814 bool isAscii() const { return FExpr->isAscii(); }
4815 bool isWide() const { return FExpr->isWide(); }
4816 bool isUTF8() const { return FExpr->isUTF8(); }
4817 bool isUTF16() const { return FExpr->isUTF16(); }
4818 bool isUTF32() const { return FExpr->isUTF32(); }
4819 bool isPascal() const { return FExpr->isPascal(); }
4820
4821 SourceLocation getLocationOfByte(
4822 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4823 const TargetInfo &Target, unsigned *StartToken = nullptr,
4824 unsigned *StartTokenByteOffset = nullptr) const {
4825 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4826 StartToken, StartTokenByteOffset);
4827 }
4828
4829 SourceLocation getLocStart() const LLVM_READONLY {
4830 return FExpr->getLocStart().getLocWithOffset(Offset);
4831 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004832
Stephen Hines648c3692016-09-16 01:07:04 +00004833 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4834};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004835
4836} // namespace
Stephen Hines648c3692016-09-16 01:07:04 +00004837
4838static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004839 const Expr *OrigFormatExpr,
4840 ArrayRef<const Expr *> Args,
4841 bool HasVAListArg, unsigned format_idx,
4842 unsigned firstDataArg,
4843 Sema::FormatStringType Type,
4844 bool inFunctionCall,
4845 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004846 llvm::SmallBitVector &CheckedVarArgs,
4847 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004848
Richard Smith55ce3522012-06-25 20:30:08 +00004849// Determine if an expression is a string literal or constant string.
4850// If this function returns false on the arguments to a function expecting a
4851// format string, we will usually need to emit a warning.
4852// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00004853static StringLiteralCheckType
4854checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4855 bool HasVAListArg, unsigned format_idx,
4856 unsigned firstDataArg, Sema::FormatStringType Type,
4857 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004858 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004859 UncoveredArgHandler &UncoveredArg,
4860 llvm::APSInt Offset) {
Ted Kremenek808829352010-09-09 03:51:39 +00004861 tryAgain:
Stephen Hines648c3692016-09-16 01:07:04 +00004862 assert(Offset.isSigned() && "invalid offset");
4863
Douglas Gregorc25f7662009-05-19 22:10:17 +00004864 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00004865 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004866
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004867 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00004868
Richard Smithd7293d72013-08-05 18:49:43 +00004869 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00004870 // Technically -Wformat-nonliteral does not warn about this case.
4871 // The behavior of printf and friends in this case is implementation
4872 // dependent. Ideally if the format string cannot be null then
4873 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00004874 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00004875
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004876 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00004877 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004878 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00004879 // The expression is a literal if both sub-expressions were, and it was
4880 // completely checked only if both sub-expressions were checked.
4881 const AbstractConditionalOperator *C =
4882 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004883
4884 // Determine whether it is necessary to check both sub-expressions, for
4885 // example, because the condition expression is a constant that can be
4886 // evaluated at compile time.
4887 bool CheckLeft = true, CheckRight = true;
4888
4889 bool Cond;
4890 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4891 if (Cond)
4892 CheckRight = false;
4893 else
4894 CheckLeft = false;
4895 }
4896
Stephen Hines648c3692016-09-16 01:07:04 +00004897 // We need to maintain the offsets for the right and the left hand side
4898 // separately to check if every possible indexed expression is a valid
4899 // string literal. They might have different offsets for different string
4900 // literals in the end.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004901 StringLiteralCheckType Left;
4902 if (!CheckLeft)
4903 Left = SLCT_UncheckedLiteral;
4904 else {
4905 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4906 HasVAListArg, format_idx, firstDataArg,
4907 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004908 CheckedVarArgs, UncoveredArg, Offset);
4909 if (Left == SLCT_NotALiteral || !CheckRight) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004910 return Left;
Stephen Hines648c3692016-09-16 01:07:04 +00004911 }
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004912 }
4913
Richard Smith55ce3522012-06-25 20:30:08 +00004914 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00004915 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004916 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004917 Type, CallType, InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004918 UncoveredArg, Offset);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004919
4920 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004921 }
4922
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004923 case Stmt::ImplicitCastExprClass:
Ted Kremenek808829352010-09-09 03:51:39 +00004924 E = cast<ImplicitCastExpr>(E)->getSubExpr();
4925 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004926
John McCallc07a0c72011-02-17 10:25:35 +00004927 case Stmt::OpaqueValueExprClass:
4928 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4929 E = src;
4930 goto tryAgain;
4931 }
Richard Smith55ce3522012-06-25 20:30:08 +00004932 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00004933
Ted Kremeneka8890832011-02-24 23:03:04 +00004934 case Stmt::PredefinedExprClass:
4935 // While __func__, etc., are technically not string literals, they
4936 // cannot contain format specifiers and thus are not a security
4937 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00004938 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00004939
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004940 case Stmt::DeclRefExprClass: {
4941 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004942
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004943 // As an exception, do not flag errors for variables binding to
4944 // const string literals.
4945 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4946 bool isConstant = false;
4947 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004948
Richard Smithd7293d72013-08-05 18:49:43 +00004949 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4950 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00004951 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00004952 isConstant = T.isConstant(S.Context) &&
4953 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00004954 } else if (T->isObjCObjectPointerType()) {
4955 // In ObjC, there is usually no "const ObjectPointer" type,
4956 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00004957 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004958 }
Mike Stump11289f42009-09-09 15:08:12 +00004959
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004960 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004961 if (const Expr *Init = VD->getAnyInitializer()) {
4962 // Look through initializers like const char c[] = { "foo" }
4963 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4964 if (InitList->isStringLiteralInit())
4965 Init = InitList->getInit(0)->IgnoreParenImpCasts();
4966 }
Richard Smithd7293d72013-08-05 18:49:43 +00004967 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004968 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004969 firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00004970 /*InFunctionCall*/ false, CheckedVarArgs,
4971 UncoveredArg, Offset);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004972 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004973 }
Mike Stump11289f42009-09-09 15:08:12 +00004974
Anders Carlssonb012ca92009-06-28 19:55:58 +00004975 // For vprintf* functions (i.e., HasVAListArg==true), we add a
4976 // special check to see if the format string is a function parameter
4977 // of the function calling the printf function. If the function
4978 // has an attribute indicating it is a printf-like function, then we
4979 // should suppress warnings concerning non-literals being used in a call
4980 // to a vprintf function. For example:
4981 //
4982 // void
4983 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4984 // va_list ap;
4985 // va_start(ap, fmt);
4986 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
4987 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00004988 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004989 if (HasVAListArg) {
4990 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4991 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4992 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00004993 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004994 // adjust for implicit parameter
4995 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4996 if (MD->isInstance())
4997 ++PVIndex;
4998 // We also check if the formats are compatible.
4999 // We can't pass a 'scanf' string to a 'printf' function.
5000 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00005001 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00005002 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00005003 }
5004 }
5005 }
5006 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005007 }
Mike Stump11289f42009-09-09 15:08:12 +00005008
Richard Smith55ce3522012-06-25 20:30:08 +00005009 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005010 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005011
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00005012 case Stmt::CallExprClass:
5013 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005014 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00005015 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
5016 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
5017 unsigned ArgIndex = FA->getFormatIdx();
5018 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5019 if (MD->isInstance())
5020 --ArgIndex;
5021 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00005022
Richard Smithd7293d72013-08-05 18:49:43 +00005023 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005024 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00005025 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00005026 CheckedVarArgs, UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005027 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5028 unsigned BuiltinID = FD->getBuiltinID();
5029 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
5030 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
5031 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00005032 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005033 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005034 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005035 InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00005036 UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005037 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005038 }
5039 }
Mike Stump11289f42009-09-09 15:08:12 +00005040
Richard Smith55ce3522012-06-25 20:30:08 +00005041 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005042 }
Alex Lorenzd9007142016-10-24 09:42:34 +00005043 case Stmt::ObjCMessageExprClass: {
5044 const auto *ME = cast<ObjCMessageExpr>(E);
5045 if (const auto *ND = ME->getMethodDecl()) {
5046 if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
5047 unsigned ArgIndex = FA->getFormatIdx();
5048 const Expr *Arg = ME->getArg(ArgIndex - 1);
5049 return checkFormatStringExpr(
5050 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
5051 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
5052 }
5053 }
5054
5055 return SLCT_NotALiteral;
5056 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005057 case Stmt::ObjCStringLiteralClass:
5058 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00005059 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005060
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005061 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005062 StrE = ObjCFExpr->getString();
5063 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005064 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005065
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005066 if (StrE) {
Stephen Hines648c3692016-09-16 01:07:04 +00005067 if (Offset.isNegative() || Offset > StrE->getLength()) {
5068 // TODO: It would be better to have an explicit warning for out of
5069 // bounds literals.
5070 return SLCT_NotALiteral;
5071 }
5072 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
5073 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005074 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005075 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00005076 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005077 }
Mike Stump11289f42009-09-09 15:08:12 +00005078
Richard Smith55ce3522012-06-25 20:30:08 +00005079 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005080 }
Stephen Hines648c3692016-09-16 01:07:04 +00005081 case Stmt::BinaryOperatorClass: {
5082 llvm::APSInt LResult;
5083 llvm::APSInt RResult;
5084
5085 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
5086
5087 // A string literal + an int offset is still a string literal.
5088 if (BinOp->isAdditiveOp()) {
5089 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
5090 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
5091
5092 if (LIsInt != RIsInt) {
5093 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
5094
5095 if (LIsInt) {
5096 if (BinOpKind == BO_Add) {
5097 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
5098 E = BinOp->getRHS();
5099 goto tryAgain;
5100 }
5101 } else {
5102 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
5103 E = BinOp->getLHS();
5104 goto tryAgain;
5105 }
5106 }
Stephen Hines648c3692016-09-16 01:07:04 +00005107 }
George Burgess IVd273aab2016-09-22 00:00:26 +00005108
5109 return SLCT_NotALiteral;
Stephen Hines648c3692016-09-16 01:07:04 +00005110 }
5111 case Stmt::UnaryOperatorClass: {
5112 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
5113 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005114 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
Stephen Hines648c3692016-09-16 01:07:04 +00005115 llvm::APSInt IndexResult;
5116 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
5117 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
5118 E = ASE->getBase();
5119 goto tryAgain;
5120 }
5121 }
5122
5123 return SLCT_NotALiteral;
5124 }
Mike Stump11289f42009-09-09 15:08:12 +00005125
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005126 default:
Richard Smith55ce3522012-06-25 20:30:08 +00005127 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005128 }
5129}
5130
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005131Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00005132 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Mehdi Amini06d367c2016-10-24 20:39:34 +00005133 .Case("scanf", FST_Scanf)
5134 .Cases("printf", "printf0", FST_Printf)
5135 .Cases("NSString", "CFString", FST_NSString)
5136 .Case("strftime", FST_Strftime)
5137 .Case("strfmon", FST_Strfmon)
5138 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
5139 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
5140 .Case("os_trace", FST_OSLog)
5141 .Case("os_log", FST_OSLog)
5142 .Default(FST_Unknown);
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005143}
5144
Jordan Rose3e0ec582012-07-19 18:10:23 +00005145/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00005146/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00005147/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005148bool Sema::CheckFormatArguments(const FormatAttr *Format,
5149 ArrayRef<const Expr *> Args,
5150 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005151 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00005152 SourceLocation Loc, SourceRange Range,
5153 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00005154 FormatStringInfo FSI;
5155 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005156 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00005157 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00005158 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00005159 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005160}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00005161
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005162bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005163 bool HasVAListArg, unsigned format_idx,
5164 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005165 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00005166 SourceLocation Loc, SourceRange Range,
5167 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00005168 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005169 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005170 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00005171 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005172 }
Mike Stump11289f42009-09-09 15:08:12 +00005173
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005174 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00005175
Chris Lattnerb87b1b32007-08-10 20:18:51 +00005176 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00005177 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005178 // Dynamically generated format strings are difficult to
5179 // automatically vet at compile time. Requiring that format strings
5180 // are string literals: (1) permits the checking of format strings by
5181 // the compiler and thereby (2) can practically remove the source of
5182 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00005183
Mike Stump11289f42009-09-09 15:08:12 +00005184 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00005185 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00005186 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00005187 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005188 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00005189 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00005190 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
5191 format_idx, firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00005192 /*IsFunctionCall*/ true, CheckedVarArgs,
5193 UncoveredArg,
5194 /*no string offset*/ llvm::APSInt(64, false) = 0);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005195
5196 // Generate a diagnostic where an uncovered argument is detected.
5197 if (UncoveredArg.hasUncoveredArg()) {
5198 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
5199 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
5200 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
5201 }
5202
Richard Smith55ce3522012-06-25 20:30:08 +00005203 if (CT != SLCT_NotALiteral)
5204 // Literal format string found, check done!
5205 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00005206
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00005207 // Strftime is particular as it always uses a single 'time' argument,
5208 // so it is safe to pass a non-literal string.
5209 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00005210 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00005211
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00005212 // Do not emit diag when the string param is a macro expansion and the
5213 // format is either NSString or CFString. This is a hack to prevent
5214 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
5215 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005216 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
5217 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00005218 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00005219
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005220 // If there are no arguments specified, warn with -Wformat-security, otherwise
5221 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005222 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00005223 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
5224 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005225 switch (Type) {
5226 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005227 break;
5228 case FST_Kprintf:
5229 case FST_FreeBSDKPrintf:
5230 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00005231 Diag(FormatLoc, diag::note_format_security_fixit)
5232 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005233 break;
5234 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00005235 Diag(FormatLoc, diag::note_format_security_fixit)
5236 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005237 break;
5238 }
5239 } else {
5240 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005241 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005242 }
Richard Smith55ce3522012-06-25 20:30:08 +00005243 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005244}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005245
Ted Kremenekab278de2010-01-28 23:39:18 +00005246namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005247
Ted Kremenek02087932010-07-16 02:11:22 +00005248class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
5249protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00005250 Sema &S;
Stephen Hines648c3692016-09-16 01:07:04 +00005251 const FormatStringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00005252 const Expr *OrigFormatExpr;
Mehdi Amini06d367c2016-10-24 20:39:34 +00005253 const Sema::FormatStringType FSType;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00005254 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00005255 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00005256 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00005257 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005258 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00005259 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00005260 llvm::SmallBitVector CoveredArgs;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005261 bool usesPositionalArgs = false;
5262 bool atFirstArg = true;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005263 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00005264 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00005265 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005266 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005267
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005268public:
Stephen Hines648c3692016-09-16 01:07:04 +00005269 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005270 const Expr *origFormatExpr,
5271 const Sema::FormatStringType type, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005272 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005273 ArrayRef<const Expr *> Args, unsigned formatIdx,
5274 bool inFunctionCall, Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005275 llvm::SmallBitVector &CheckedVarArgs,
5276 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005277 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
5278 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
5279 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
Mehdi Amini06d367c2016-10-24 20:39:34 +00005280 inFunctionCall(inFunctionCall), CallType(callType),
5281 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00005282 CoveredArgs.resize(numDataArgs);
5283 CoveredArgs.reset();
5284 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005285
Ted Kremenek019d2242010-01-29 01:50:07 +00005286 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005287
Ted Kremenek02087932010-07-16 02:11:22 +00005288 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005289 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005290
Jordan Rose92303592012-09-08 04:00:03 +00005291 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005292 const analyze_format_string::FormatSpecifier &FS,
5293 const analyze_format_string::ConversionSpecifier &CS,
5294 const char *startSpecifier, unsigned specifierLen,
5295 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00005296
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005297 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005298 const analyze_format_string::FormatSpecifier &FS,
5299 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005300
5301 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005302 const analyze_format_string::ConversionSpecifier &CS,
5303 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005304
Craig Toppere14c0f82014-03-12 04:55:44 +00005305 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005306
Craig Toppere14c0f82014-03-12 04:55:44 +00005307 void HandleInvalidPosition(const char *startSpecifier,
5308 unsigned specifierLen,
5309 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005310
Craig Toppere14c0f82014-03-12 04:55:44 +00005311 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005312
Craig Toppere14c0f82014-03-12 04:55:44 +00005313 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005314
Richard Trieu03cf7b72011-10-28 00:41:25 +00005315 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00005316 static void
5317 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
5318 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
5319 bool IsStringLocation, Range StringRange,
5320 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005321
Ted Kremenek02087932010-07-16 02:11:22 +00005322protected:
Ted Kremenekce815422010-07-19 21:25:57 +00005323 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
5324 const char *startSpec,
5325 unsigned specifierLen,
5326 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005327
5328 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
5329 const char *startSpec,
5330 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00005331
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005332 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00005333 CharSourceRange getSpecifierRange(const char *startSpecifier,
5334 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00005335 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005336
Ted Kremenek5739de72010-01-29 01:06:55 +00005337 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005338
5339 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
5340 const analyze_format_string::ConversionSpecifier &CS,
5341 const char *startSpecifier, unsigned specifierLen,
5342 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005343
5344 template <typename Range>
5345 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5346 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00005347 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00005348};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005349
5350} // namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00005351
Ted Kremenek02087932010-07-16 02:11:22 +00005352SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00005353 return OrigFormatExpr->getSourceRange();
5354}
5355
Ted Kremenek02087932010-07-16 02:11:22 +00005356CharSourceRange CheckFormatHandler::
5357getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00005358 SourceLocation Start = getLocationOfByte(startSpecifier);
5359 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
5360
5361 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00005362 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00005363
5364 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005365}
5366
Ted Kremenek02087932010-07-16 02:11:22 +00005367SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines648c3692016-09-16 01:07:04 +00005368 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
5369 S.getLangOpts(), S.Context.getTargetInfo());
Ted Kremenekab278de2010-01-28 23:39:18 +00005370}
5371
Ted Kremenek02087932010-07-16 02:11:22 +00005372void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
5373 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00005374 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
5375 getLocationOfByte(startSpecifier),
5376 /*IsStringLocation*/true,
5377 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00005378}
5379
Jordan Rose92303592012-09-08 04:00:03 +00005380void CheckFormatHandler::HandleInvalidLengthModifier(
5381 const analyze_format_string::FormatSpecifier &FS,
5382 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00005383 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00005384 using namespace analyze_format_string;
5385
5386 const LengthModifier &LM = FS.getLengthModifier();
5387 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5388
5389 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005390 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00005391 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005392 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005393 getLocationOfByte(LM.getStart()),
5394 /*IsStringLocation*/true,
5395 getSpecifierRange(startSpecifier, specifierLen));
5396
5397 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5398 << FixedLM->toString()
5399 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5400
5401 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005402 FixItHint Hint;
5403 if (DiagID == diag::warn_format_nonsensical_length)
5404 Hint = FixItHint::CreateRemoval(LMRange);
5405
5406 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005407 getLocationOfByte(LM.getStart()),
5408 /*IsStringLocation*/true,
5409 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00005410 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00005411 }
5412}
5413
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005414void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00005415 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005416 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +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 Rose2f9cc042012-09-08 04:00:12 +00005424 if (FixedLM) {
5425 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5426 << LM.toString() << 0,
5427 getLocationOfByte(LM.getStart()),
5428 /*IsStringLocation*/true,
5429 getSpecifierRange(startSpecifier, specifierLen));
5430
5431 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5432 << FixedLM->toString()
5433 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5434
5435 } else {
5436 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5437 << LM.toString() << 0,
5438 getLocationOfByte(LM.getStart()),
5439 /*IsStringLocation*/true,
5440 getSpecifierRange(startSpecifier, specifierLen));
5441 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005442}
5443
5444void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5445 const analyze_format_string::ConversionSpecifier &CS,
5446 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00005447 using namespace analyze_format_string;
5448
5449 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00005450 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00005451 if (FixedCS) {
5452 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5453 << CS.toString() << /*conversion specifier*/1,
5454 getLocationOfByte(CS.getStart()),
5455 /*IsStringLocation*/true,
5456 getSpecifierRange(startSpecifier, specifierLen));
5457
5458 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5459 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5460 << FixedCS->toString()
5461 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5462 } else {
5463 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5464 << CS.toString() << /*conversion specifier*/1,
5465 getLocationOfByte(CS.getStart()),
5466 /*IsStringLocation*/true,
5467 getSpecifierRange(startSpecifier, specifierLen));
5468 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005469}
5470
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005471void CheckFormatHandler::HandlePosition(const char *startPos,
5472 unsigned posLen) {
5473 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5474 getLocationOfByte(startPos),
5475 /*IsStringLocation*/true,
5476 getSpecifierRange(startPos, posLen));
5477}
5478
Ted Kremenekd1668192010-02-27 01:41:03 +00005479void
Ted Kremenek02087932010-07-16 02:11:22 +00005480CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5481 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005482 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5483 << (unsigned) p,
5484 getLocationOfByte(startPos), /*IsStringLocation*/true,
5485 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005486}
5487
Ted Kremenek02087932010-07-16 02:11:22 +00005488void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00005489 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005490 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5491 getLocationOfByte(startPos),
5492 /*IsStringLocation*/true,
5493 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005494}
5495
Ted Kremenek02087932010-07-16 02:11:22 +00005496void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005497 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005498 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005499 EmitFormatDiagnostic(
5500 S.PDiag(diag::warn_printf_format_string_contains_null_char),
5501 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5502 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005503 }
Ted Kremenek02087932010-07-16 02:11:22 +00005504}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005505
Jordan Rose58bbe422012-07-19 18:10:08 +00005506// Note that this may return NULL if there was an error parsing or building
5507// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00005508const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005509 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00005510}
5511
5512void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005513 // Does the number of data arguments exceed the number of
5514 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00005515 if (!HasVAListArg) {
5516 // Find any arguments that weren't covered.
5517 CoveredArgs.flip();
5518 signed notCoveredArg = CoveredArgs.find_first();
5519 if (notCoveredArg >= 0) {
5520 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005521 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5522 } else {
5523 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00005524 }
5525 }
5526}
5527
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005528void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5529 const Expr *ArgExpr) {
5530 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5531 "Invalid state");
5532
5533 if (!ArgExpr)
5534 return;
5535
5536 SourceLocation Loc = ArgExpr->getLocStart();
5537
5538 if (S.getSourceManager().isInSystemMacro(Loc))
5539 return;
5540
5541 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5542 for (auto E : DiagnosticExprs)
5543 PDiag << E->getSourceRange();
5544
5545 CheckFormatHandler::EmitFormatDiagnostic(
5546 S, IsFunctionCall, DiagnosticExprs[0],
5547 PDiag, Loc, /*IsStringLocation*/false,
5548 DiagnosticExprs[0]->getSourceRange());
5549}
5550
Ted Kremenekce815422010-07-19 21:25:57 +00005551bool
5552CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5553 SourceLocation Loc,
5554 const char *startSpec,
5555 unsigned specifierLen,
5556 const char *csStart,
5557 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00005558 bool keepGoing = true;
5559 if (argIndex < NumDataArgs) {
5560 // Consider the argument coverered, even though the specifier doesn't
5561 // make sense.
5562 CoveredArgs.set(argIndex);
5563 }
5564 else {
5565 // If argIndex exceeds the number of data arguments we
5566 // don't issue a warning because that is just a cascade of warnings (and
5567 // they may have intended '%%' anyway). We don't want to continue processing
5568 // the format string after this point, however, as we will like just get
5569 // gibberish when trying to match arguments.
5570 keepGoing = false;
5571 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005572
5573 StringRef Specifier(csStart, csLen);
5574
5575 // If the specifier in non-printable, it could be the first byte of a UTF-8
5576 // sequence. In that case, print the UTF-8 code point. If not, print the byte
5577 // hex value.
5578 std::string CodePointStr;
5579 if (!llvm::sys::locale::isPrint(*csStart)) {
Justin Lebar90910552016-09-30 00:38:45 +00005580 llvm::UTF32 CodePoint;
5581 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5582 const llvm::UTF8 *E =
5583 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5584 llvm::ConversionResult Result =
5585 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005586
Justin Lebar90910552016-09-30 00:38:45 +00005587 if (Result != llvm::conversionOK) {
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005588 unsigned char FirstChar = *csStart;
Justin Lebar90910552016-09-30 00:38:45 +00005589 CodePoint = (llvm::UTF32)FirstChar;
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005590 }
5591
5592 llvm::raw_string_ostream OS(CodePointStr);
5593 if (CodePoint < 256)
5594 OS << "\\x" << llvm::format("%02x", CodePoint);
5595 else if (CodePoint <= 0xFFFF)
5596 OS << "\\u" << llvm::format("%04x", CodePoint);
5597 else
5598 OS << "\\U" << llvm::format("%08x", CodePoint);
5599 OS.flush();
5600 Specifier = CodePointStr;
5601 }
5602
5603 EmitFormatDiagnostic(
5604 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5605 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5606
Ted Kremenekce815422010-07-19 21:25:57 +00005607 return keepGoing;
5608}
5609
Richard Trieu03cf7b72011-10-28 00:41:25 +00005610void
5611CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5612 const char *startSpec,
5613 unsigned specifierLen) {
5614 EmitFormatDiagnostic(
5615 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5616 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5617}
5618
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005619bool
5620CheckFormatHandler::CheckNumArgs(
5621 const analyze_format_string::FormatSpecifier &FS,
5622 const analyze_format_string::ConversionSpecifier &CS,
5623 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5624
5625 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005626 PartialDiagnostic PDiag = FS.usesPositionalArg()
5627 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5628 << (argIndex+1) << NumDataArgs)
5629 : S.PDiag(diag::warn_printf_insufficient_data_args);
5630 EmitFormatDiagnostic(
5631 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5632 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005633
5634 // Since more arguments than conversion tokens are given, by extension
5635 // all arguments are covered, so mark this as so.
5636 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005637 return false;
5638 }
5639 return true;
5640}
5641
Richard Trieu03cf7b72011-10-28 00:41:25 +00005642template<typename Range>
5643void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5644 SourceLocation Loc,
5645 bool IsStringLocation,
5646 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00005647 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005648 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00005649 Loc, IsStringLocation, StringRange, FixIt);
5650}
5651
5652/// \brief If the format string is not within the funcion call, emit a note
5653/// so that the function call and string are in diagnostic messages.
5654///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005655/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00005656/// call and only one diagnostic message will be produced. Otherwise, an
5657/// extra note will be emitted pointing to location of the format string.
5658///
5659/// \param ArgumentExpr the expression that is passed as the format string
5660/// argument in the function call. Used for getting locations when two
5661/// diagnostics are emitted.
5662///
5663/// \param PDiag the callee should already have provided any strings for the
5664/// diagnostic message. This function only adds locations and fixits
5665/// to diagnostics.
5666///
5667/// \param Loc primary location for diagnostic. If two diagnostics are
5668/// required, one will be at Loc and a new SourceLocation will be created for
5669/// the other one.
5670///
5671/// \param IsStringLocation if true, Loc points to the format string should be
5672/// used for the note. Otherwise, Loc points to the argument list and will
5673/// be used with PDiag.
5674///
5675/// \param StringRange some or all of the string to highlight. This is
5676/// templated so it can accept either a CharSourceRange or a SourceRange.
5677///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005678/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00005679template <typename Range>
5680void CheckFormatHandler::EmitFormatDiagnostic(
5681 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5682 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5683 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00005684 if (InFunctionCall) {
5685 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5686 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005687 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00005688 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005689 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5690 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00005691
5692 const Sema::SemaDiagnosticBuilder &Note =
5693 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5694 diag::note_format_string_defined);
5695
5696 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005697 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005698 }
5699}
5700
Ted Kremenek02087932010-07-16 02:11:22 +00005701//===--- CHECK: Printf format string checking ------------------------------===//
5702
5703namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005704
Ted Kremenek02087932010-07-16 02:11:22 +00005705class CheckPrintfHandler : public CheckFormatHandler {
5706public:
Stephen Hines648c3692016-09-16 01:07:04 +00005707 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005708 const Expr *origFormatExpr,
5709 const Sema::FormatStringType type, unsigned firstDataArg,
5710 unsigned numDataArgs, bool isObjC, const char *beg,
5711 bool hasVAListArg, ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005712 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00005713 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005714 llvm::SmallBitVector &CheckedVarArgs,
5715 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005716 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5717 numDataArgs, beg, hasVAListArg, Args, formatIdx,
5718 inFunctionCall, CallType, CheckedVarArgs,
5719 UncoveredArg) {}
5720
5721 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5722
5723 /// Returns true if '%@' specifiers are allowed in the format string.
5724 bool allowsObjCArg() const {
5725 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5726 FSType == Sema::FST_OSTrace;
5727 }
Jordan Rose3e0ec582012-07-19 18:10:23 +00005728
Ted Kremenek02087932010-07-16 02:11:22 +00005729 bool HandleInvalidPrintfConversionSpecifier(
5730 const analyze_printf::PrintfSpecifier &FS,
5731 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005732 unsigned specifierLen) override;
5733
Ted Kremenek02087932010-07-16 02:11:22 +00005734 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5735 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005736 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005737 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5738 const char *StartSpecifier,
5739 unsigned SpecifierLen,
5740 const Expr *E);
5741
Ted Kremenek02087932010-07-16 02:11:22 +00005742 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5743 const char *startSpecifier, unsigned specifierLen);
5744 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5745 const analyze_printf::OptionalAmount &Amt,
5746 unsigned type,
5747 const char *startSpecifier, unsigned specifierLen);
5748 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5749 const analyze_printf::OptionalFlag &flag,
5750 const char *startSpecifier, unsigned specifierLen);
5751 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5752 const analyze_printf::OptionalFlag &ignoredFlag,
5753 const analyze_printf::OptionalFlag &flag,
5754 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005755 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00005756 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00005757
5758 void HandleEmptyObjCModifierFlag(const char *startFlag,
5759 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005760
Ted Kremenek2b417712015-07-02 05:39:16 +00005761 void HandleInvalidObjCModifierFlag(const char *startFlag,
5762 unsigned flagLen) override;
5763
5764 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5765 const char *flagsEnd,
5766 const char *conversionPosition)
5767 override;
5768};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005769
5770} // namespace
Ted Kremenek02087932010-07-16 02:11:22 +00005771
5772bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5773 const analyze_printf::PrintfSpecifier &FS,
5774 const char *startSpecifier,
5775 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005776 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00005777 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00005778
Ted Kremenekce815422010-07-19 21:25:57 +00005779 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5780 getLocationOfByte(CS.getStart()),
5781 startSpecifier, specifierLen,
5782 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00005783}
5784
Ted Kremenek02087932010-07-16 02:11:22 +00005785bool CheckPrintfHandler::HandleAmount(
5786 const analyze_format_string::OptionalAmount &Amt,
5787 unsigned k, const char *startSpecifier,
5788 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005789 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005790 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00005791 unsigned argIndex = Amt.getArgIndex();
5792 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005793 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5794 << k,
5795 getLocationOfByte(Amt.getStart()),
5796 /*IsStringLocation*/true,
5797 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005798 // Don't do any more checking. We will just emit
5799 // spurious errors.
5800 return false;
5801 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005802
Ted Kremenek5739de72010-01-29 01:06:55 +00005803 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00005804 // Although not in conformance with C99, we also allow the argument to be
5805 // an 'unsigned int' as that is a reasonably safe case. GCC also
5806 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00005807 CoveredArgs.set(argIndex);
5808 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00005809 if (!Arg)
5810 return false;
5811
Ted Kremenek5739de72010-01-29 01:06:55 +00005812 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005813
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005814 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5815 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005816
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005817 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005818 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005819 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00005820 << T << Arg->getSourceRange(),
5821 getLocationOfByte(Amt.getStart()),
5822 /*IsStringLocation*/true,
5823 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005824 // Don't do any more checking. We will just emit
5825 // spurious errors.
5826 return false;
5827 }
5828 }
5829 }
5830 return true;
5831}
Ted Kremenek5739de72010-01-29 01:06:55 +00005832
Tom Careb49ec692010-06-17 19:00:27 +00005833void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00005834 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005835 const analyze_printf::OptionalAmount &Amt,
5836 unsigned type,
5837 const char *startSpecifier,
5838 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005839 const analyze_printf::PrintfConversionSpecifier &CS =
5840 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00005841
Richard Trieu03cf7b72011-10-28 00:41:25 +00005842 FixItHint fixit =
5843 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5844 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5845 Amt.getConstantLength()))
5846 : FixItHint();
5847
5848 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5849 << type << CS.toString(),
5850 getLocationOfByte(Amt.getStart()),
5851 /*IsStringLocation*/true,
5852 getSpecifierRange(startSpecifier, specifierLen),
5853 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00005854}
5855
Ted Kremenek02087932010-07-16 02:11:22 +00005856void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005857 const analyze_printf::OptionalFlag &flag,
5858 const char *startSpecifier,
5859 unsigned specifierLen) {
5860 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005861 const analyze_printf::PrintfConversionSpecifier &CS =
5862 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00005863 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5864 << flag.toString() << CS.toString(),
5865 getLocationOfByte(flag.getPosition()),
5866 /*IsStringLocation*/true,
5867 getSpecifierRange(startSpecifier, specifierLen),
5868 FixItHint::CreateRemoval(
5869 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005870}
5871
5872void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00005873 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005874 const analyze_printf::OptionalFlag &ignoredFlag,
5875 const analyze_printf::OptionalFlag &flag,
5876 const char *startSpecifier,
5877 unsigned specifierLen) {
5878 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005879 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5880 << ignoredFlag.toString() << flag.toString(),
5881 getLocationOfByte(ignoredFlag.getPosition()),
5882 /*IsStringLocation*/true,
5883 getSpecifierRange(startSpecifier, specifierLen),
5884 FixItHint::CreateRemoval(
5885 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005886}
5887
Ted Kremenek2b417712015-07-02 05:39:16 +00005888void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5889 unsigned flagLen) {
5890 // Warn about an empty flag.
5891 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5892 getLocationOfByte(startFlag),
5893 /*IsStringLocation*/true,
5894 getSpecifierRange(startFlag, flagLen));
5895}
5896
5897void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5898 unsigned flagLen) {
5899 // Warn about an invalid flag.
5900 auto Range = getSpecifierRange(startFlag, flagLen);
5901 StringRef flag(startFlag, flagLen);
5902 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5903 getLocationOfByte(startFlag),
5904 /*IsStringLocation*/true,
5905 Range, FixItHint::CreateRemoval(Range));
5906}
5907
5908void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5909 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5910 // Warn about using '[...]' without a '@' conversion.
5911 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5912 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5913 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5914 getLocationOfByte(conversionPosition),
5915 /*IsStringLocation*/true,
5916 Range, FixItHint::CreateRemoval(Range));
5917}
5918
Richard Smith55ce3522012-06-25 20:30:08 +00005919// Determines if the specified is a C++ class or struct containing
5920// a member with the specified name and kind (e.g. a CXXMethodDecl named
5921// "c_str()").
5922template<typename MemberKind>
5923static llvm::SmallPtrSet<MemberKind*, 1>
5924CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5925 const RecordType *RT = Ty->getAs<RecordType>();
5926 llvm::SmallPtrSet<MemberKind*, 1> Results;
5927
5928 if (!RT)
5929 return Results;
5930 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00005931 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00005932 return Results;
5933
Alp Tokerb6cc5922014-05-03 03:45:55 +00005934 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00005935 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00005936 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00005937
5938 // We just need to include all members of the right kind turned up by the
5939 // filter, at this point.
5940 if (S.LookupQualifiedName(R, RT->getDecl()))
5941 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5942 NamedDecl *decl = (*I)->getUnderlyingDecl();
5943 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5944 Results.insert(FK);
5945 }
5946 return Results;
5947}
5948
Richard Smith2868a732014-02-28 01:36:39 +00005949/// Check if we could call '.c_str()' on an object.
5950///
5951/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5952/// allow the call, or if it would be ambiguous).
5953bool Sema::hasCStrMethod(const Expr *E) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005954 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
5955
Richard Smith2868a732014-02-28 01:36:39 +00005956 MethodSet Results =
5957 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5958 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5959 MI != ME; ++MI)
5960 if ((*MI)->getMinRequiredArguments() == 0)
5961 return true;
5962 return false;
5963}
5964
Richard Smith55ce3522012-06-25 20:30:08 +00005965// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005966// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00005967// Returns true when a c_str() conversion method is found.
5968bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00005969 const analyze_printf::ArgType &AT, const Expr *E) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005970 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
Richard Smith55ce3522012-06-25 20:30:08 +00005971
5972 MethodSet Results =
5973 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5974
5975 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5976 MI != ME; ++MI) {
5977 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00005978 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00005979 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00005980 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00005981 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00005982 S.Diag(E->getLocStart(), diag::note_printf_c_str)
5983 << "c_str()"
5984 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5985 return true;
5986 }
5987 }
5988
5989 return false;
5990}
5991
Ted Kremenekab278de2010-01-28 23:39:18 +00005992bool
Ted Kremenek02087932010-07-16 02:11:22 +00005993CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00005994 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00005995 const char *startSpecifier,
5996 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005997 using namespace analyze_format_string;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005998 using namespace analyze_printf;
5999
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006000 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00006001
Ted Kremenek6cd69422010-07-19 22:01:06 +00006002 if (FS.consumesDataArgument()) {
6003 if (atFirstArg) {
6004 atFirstArg = false;
6005 usesPositionalArgs = FS.usesPositionalArg();
6006 }
6007 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006008 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6009 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00006010 return false;
6011 }
Ted Kremenek5739de72010-01-29 01:06:55 +00006012 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006013
Ted Kremenekd1668192010-02-27 01:41:03 +00006014 // First check if the field width, precision, and conversion specifier
6015 // have matching data arguments.
6016 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
6017 startSpecifier, specifierLen)) {
6018 return false;
6019 }
6020
6021 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
6022 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00006023 return false;
6024 }
6025
Ted Kremenek8d9842d2010-01-29 20:55:36 +00006026 if (!CS.consumesDataArgument()) {
6027 // FIXME: Technically specifying a precision or field width here
6028 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00006029 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00006030 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006031
Ted Kremenek4a49d982010-02-26 19:18:41 +00006032 // Consume the argument.
6033 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00006034 if (argIndex < NumDataArgs) {
6035 // The check to see if the argIndex is valid will come later.
6036 // We set the bit here because we may exit early from this
6037 // function if we encounter some other error.
6038 CoveredArgs.set(argIndex);
6039 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00006040
Dimitry Andric6b5ed342015-02-19 22:32:33 +00006041 // FreeBSD kernel extensions.
6042 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
6043 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
6044 // We need at least two arguments.
6045 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
6046 return false;
6047
6048 // Claim the second argument.
6049 CoveredArgs.set(argIndex + 1);
6050
6051 // Type check the first argument (int for %b, pointer for %D)
6052 const Expr *Ex = getDataArg(argIndex);
6053 const analyze_printf::ArgType &AT =
6054 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
6055 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
6056 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
6057 EmitFormatDiagnostic(
6058 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6059 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
6060 << false << Ex->getSourceRange(),
6061 Ex->getLocStart(), /*IsStringLocation*/false,
6062 getSpecifierRange(startSpecifier, specifierLen));
6063
6064 // Type check the second argument (char * for both %b and %D)
6065 Ex = getDataArg(argIndex + 1);
6066 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
6067 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
6068 EmitFormatDiagnostic(
6069 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6070 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
6071 << false << Ex->getSourceRange(),
6072 Ex->getLocStart(), /*IsStringLocation*/false,
6073 getSpecifierRange(startSpecifier, specifierLen));
6074
6075 return true;
6076 }
6077
Ted Kremenek4a49d982010-02-26 19:18:41 +00006078 // Check for using an Objective-C specific conversion specifier
6079 // in a non-ObjC literal.
Mehdi Amini06d367c2016-10-24 20:39:34 +00006080 if (!allowsObjCArg() && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00006081 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6082 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00006083 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006084
Mehdi Amini06d367c2016-10-24 20:39:34 +00006085 // %P can only be used with os_log.
6086 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
6087 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6088 specifierLen);
6089 }
6090
6091 // %n is not allowed with os_log.
6092 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
6093 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
6094 getLocationOfByte(CS.getStart()),
6095 /*IsStringLocation*/ false,
6096 getSpecifierRange(startSpecifier, specifierLen));
6097
6098 return true;
6099 }
6100
6101 // Only scalars are allowed for os_trace.
6102 if (FSType == Sema::FST_OSTrace &&
6103 (CS.getKind() == ConversionSpecifier::PArg ||
6104 CS.getKind() == ConversionSpecifier::sArg ||
6105 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
6106 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6107 specifierLen);
6108 }
6109
6110 // Check for use of public/private annotation outside of os_log().
6111 if (FSType != Sema::FST_OSLog) {
6112 if (FS.isPublic().isSet()) {
6113 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6114 << "public",
6115 getLocationOfByte(FS.isPublic().getPosition()),
6116 /*IsStringLocation*/ false,
6117 getSpecifierRange(startSpecifier, specifierLen));
6118 }
6119 if (FS.isPrivate().isSet()) {
6120 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6121 << "private",
6122 getLocationOfByte(FS.isPrivate().getPosition()),
6123 /*IsStringLocation*/ false,
6124 getSpecifierRange(startSpecifier, specifierLen));
6125 }
6126 }
6127
Tom Careb49ec692010-06-17 19:00:27 +00006128 // Check for invalid use of field width
6129 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00006130 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00006131 startSpecifier, specifierLen);
6132 }
6133
6134 // Check for invalid use of precision
6135 if (!FS.hasValidPrecision()) {
6136 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
6137 startSpecifier, specifierLen);
6138 }
6139
Mehdi Amini06d367c2016-10-24 20:39:34 +00006140 // Precision is mandatory for %P specifier.
6141 if (CS.getKind() == ConversionSpecifier::PArg &&
6142 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
6143 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
6144 getLocationOfByte(startSpecifier),
6145 /*IsStringLocation*/ false,
6146 getSpecifierRange(startSpecifier, specifierLen));
6147 }
6148
Tom Careb49ec692010-06-17 19:00:27 +00006149 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00006150 if (!FS.hasValidThousandsGroupingPrefix())
6151 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006152 if (!FS.hasValidLeadingZeros())
6153 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
6154 if (!FS.hasValidPlusPrefix())
6155 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00006156 if (!FS.hasValidSpacePrefix())
6157 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006158 if (!FS.hasValidAlternativeForm())
6159 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
6160 if (!FS.hasValidLeftJustified())
6161 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
6162
6163 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00006164 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
6165 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
6166 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006167 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
6168 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
6169 startSpecifier, specifierLen);
6170
6171 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006172 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006173 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6174 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006175 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006176 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006177 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006178 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6179 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00006180
Jordan Rose92303592012-09-08 04:00:03 +00006181 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6182 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6183
Ted Kremenek9fcd8302010-01-29 01:43:31 +00006184 // The remaining checks depend on the data arguments.
6185 if (HasVAListArg)
6186 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006187
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006188 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00006189 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006190
Jordan Rose58bbe422012-07-19 18:10:08 +00006191 const Expr *Arg = getDataArg(argIndex);
6192 if (!Arg)
6193 return true;
6194
6195 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00006196}
6197
Jordan Roseaee34382012-09-05 22:56:26 +00006198static bool requiresParensToAddCast(const Expr *E) {
6199 // FIXME: We should have a general way to reason about operator
6200 // precedence and whether parens are actually needed here.
6201 // Take care of a few common cases where they aren't.
6202 const Expr *Inside = E->IgnoreImpCasts();
6203 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
6204 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
6205
6206 switch (Inside->getStmtClass()) {
6207 case Stmt::ArraySubscriptExprClass:
6208 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006209 case Stmt::CharacterLiteralClass:
6210 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006211 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006212 case Stmt::FloatingLiteralClass:
6213 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006214 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006215 case Stmt::ObjCArrayLiteralClass:
6216 case Stmt::ObjCBoolLiteralExprClass:
6217 case Stmt::ObjCBoxedExprClass:
6218 case Stmt::ObjCDictionaryLiteralClass:
6219 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006220 case Stmt::ObjCIvarRefExprClass:
6221 case Stmt::ObjCMessageExprClass:
6222 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006223 case Stmt::ObjCStringLiteralClass:
6224 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006225 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006226 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006227 case Stmt::UnaryOperatorClass:
6228 return false;
6229 default:
6230 return true;
6231 }
6232}
6233
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006234static std::pair<QualType, StringRef>
6235shouldNotPrintDirectly(const ASTContext &Context,
6236 QualType IntendedTy,
6237 const Expr *E) {
6238 // Use a 'while' to peel off layers of typedefs.
6239 QualType TyTy = IntendedTy;
6240 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
6241 StringRef Name = UserTy->getDecl()->getName();
6242 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Saleem Abdulrasoola01ed932017-10-17 17:39:32 +00006243 .Case("CFIndex", Context.getNSIntegerType())
6244 .Case("NSInteger", Context.getNSIntegerType())
6245 .Case("NSUInteger", Context.getNSUIntegerType())
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006246 .Case("SInt32", Context.IntTy)
6247 .Case("UInt32", Context.UnsignedIntTy)
6248 .Default(QualType());
6249
6250 if (!CastTy.isNull())
6251 return std::make_pair(CastTy, Name);
6252
6253 TyTy = UserTy->desugar();
6254 }
6255
6256 // Strip parens if necessary.
6257 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
6258 return shouldNotPrintDirectly(Context,
6259 PE->getSubExpr()->getType(),
6260 PE->getSubExpr());
6261
6262 // If this is a conditional expression, then its result type is constructed
6263 // via usual arithmetic conversions and thus there might be no necessary
6264 // typedef sugar there. Recurse to operands to check for NSInteger &
6265 // Co. usage condition.
6266 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6267 QualType TrueTy, FalseTy;
6268 StringRef TrueName, FalseName;
6269
6270 std::tie(TrueTy, TrueName) =
6271 shouldNotPrintDirectly(Context,
6272 CO->getTrueExpr()->getType(),
6273 CO->getTrueExpr());
6274 std::tie(FalseTy, FalseName) =
6275 shouldNotPrintDirectly(Context,
6276 CO->getFalseExpr()->getType(),
6277 CO->getFalseExpr());
6278
6279 if (TrueTy == FalseTy)
6280 return std::make_pair(TrueTy, TrueName);
6281 else if (TrueTy.isNull())
6282 return std::make_pair(FalseTy, FalseName);
6283 else if (FalseTy.isNull())
6284 return std::make_pair(TrueTy, TrueName);
6285 }
6286
6287 return std::make_pair(QualType(), StringRef());
6288}
6289
Richard Smith55ce3522012-06-25 20:30:08 +00006290bool
6291CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6292 const char *StartSpecifier,
6293 unsigned SpecifierLen,
6294 const Expr *E) {
6295 using namespace analyze_format_string;
6296 using namespace analyze_printf;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006297
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006298 // Now type check the data expression that matches the
6299 // format specifier.
Mehdi Amini06d367c2016-10-24 20:39:34 +00006300 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
Jordan Rose22b74712012-09-05 22:56:19 +00006301 if (!AT.isValid())
6302 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00006303
Jordan Rose598ec092012-12-05 18:44:40 +00006304 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00006305 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
6306 ExprTy = TET->getUnderlyingExpr()->getType();
6307 }
6308
Seth Cantrellb4802962015-03-04 03:12:10 +00006309 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
6310
6311 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00006312 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006313 }
Jordan Rose98709982012-06-04 22:48:57 +00006314
Jordan Rose22b74712012-09-05 22:56:19 +00006315 // Look through argument promotions for our error message's reported type.
6316 // This includes the integral and floating promotions, but excludes array
6317 // and function pointer decay; seeing that an argument intended to be a
6318 // string has type 'char [6]' is probably more confusing than 'char *'.
6319 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6320 if (ICE->getCastKind() == CK_IntegralCast ||
6321 ICE->getCastKind() == CK_FloatingCast) {
6322 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00006323 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00006324
6325 // Check if we didn't match because of an implicit cast from a 'char'
6326 // or 'short' to an 'int'. This is done because printf is a varargs
6327 // function.
6328 if (ICE->getType() == S.Context.IntTy ||
6329 ICE->getType() == S.Context.UnsignedIntTy) {
6330 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00006331 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00006332 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00006333 }
Jordan Rose98709982012-06-04 22:48:57 +00006334 }
Jordan Rose598ec092012-12-05 18:44:40 +00006335 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
6336 // Special case for 'a', which has type 'int' in C.
6337 // Note, however, that we do /not/ want to treat multibyte constants like
6338 // 'MooV' as characters! This form is deprecated but still exists.
6339 if (ExprTy == S.Context.IntTy)
6340 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6341 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00006342 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006343
Jordan Rosebc53ed12014-05-31 04:12:14 +00006344 // Look through enums to their underlying type.
6345 bool IsEnum = false;
6346 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
6347 ExprTy = EnumTy->getDecl()->getIntegerType();
6348 IsEnum = true;
6349 }
6350
Jordan Rose0e5badd2012-12-05 18:44:49 +00006351 // %C in an Objective-C context prints a unichar, not a wchar_t.
6352 // If the argument is an integer of some kind, believe the %C and suggest
6353 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00006354 QualType IntendedTy = ExprTy;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006355 if (isObjCContext() &&
Jordan Rose0e5badd2012-12-05 18:44:49 +00006356 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
6357 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6358 !ExprTy->isCharType()) {
6359 // 'unichar' is defined as a typedef of unsigned short, but we should
6360 // prefer using the typedef if it is visible.
6361 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00006362
6363 // While we are here, check if the value is an IntegerLiteral that happens
6364 // to be within the valid range.
6365 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
6366 const llvm::APInt &V = IL->getValue();
6367 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6368 return true;
6369 }
6370
Jordan Rose0e5badd2012-12-05 18:44:49 +00006371 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
6372 Sema::LookupOrdinaryName);
6373 if (S.LookupName(Result, S.getCurScope())) {
6374 NamedDecl *ND = Result.getFoundDecl();
6375 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
6376 if (TD->getUnderlyingType() == IntendedTy)
6377 IntendedTy = S.Context.getTypedefType(TD);
6378 }
6379 }
6380 }
6381
6382 // Special-case some of Darwin's platform-independence types by suggesting
6383 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006384 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00006385 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006386 QualType CastTy;
6387 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
6388 if (!CastTy.isNull()) {
6389 IntendedTy = CastTy;
6390 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00006391 }
6392 }
6393
Jordan Rose22b74712012-09-05 22:56:19 +00006394 // We may be able to offer a FixItHint if it is a supported type.
6395 PrintfSpecifier fixedFS = FS;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006396 bool success =
6397 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006398
Jordan Rose22b74712012-09-05 22:56:19 +00006399 if (success) {
6400 // Get the fix string from the fixed format specifier
6401 SmallString<16> buf;
6402 llvm::raw_svector_ostream os(buf);
6403 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006404
Jordan Roseaee34382012-09-05 22:56:26 +00006405 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6406
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006407 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00006408 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6409 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6410 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6411 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00006412 // In this case, the specifier is wrong and should be changed to match
6413 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00006414 EmitFormatDiagnostic(S.PDiag(diag)
6415 << AT.getRepresentativeTypeName(S.Context)
6416 << IntendedTy << IsEnum << E->getSourceRange(),
6417 E->getLocStart(),
6418 /*IsStringLocation*/ false, SpecRange,
6419 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00006420 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00006421 // The canonical type for formatting this value is different from the
6422 // actual type of the expression. (This occurs, for example, with Darwin's
6423 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6424 // should be printed as 'long' for 64-bit compatibility.)
6425 // Rather than emitting a normal format/argument mismatch, we want to
6426 // add a cast to the recommended type (and correct the format string
6427 // if necessary).
6428 SmallString<16> CastBuf;
6429 llvm::raw_svector_ostream CastFix(CastBuf);
6430 CastFix << "(";
6431 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6432 CastFix << ")";
6433
6434 SmallVector<FixItHint,4> Hints;
Alexander Shaposhnikov1788a9b2017-09-22 18:36:06 +00006435 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
Jordan Roseaee34382012-09-05 22:56:26 +00006436 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6437
6438 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6439 // If there's already a cast present, just replace it.
6440 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6441 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6442
6443 } else if (!requiresParensToAddCast(E)) {
6444 // If the expression has high enough precedence,
6445 // just write the C-style cast.
6446 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6447 CastFix.str()));
6448 } else {
6449 // Otherwise, add parens around the expression as well as the cast.
6450 CastFix << "(";
6451 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6452 CastFix.str()));
6453
Alp Tokerb6cc5922014-05-03 03:45:55 +00006454 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00006455 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6456 }
6457
Jordan Rose0e5badd2012-12-05 18:44:49 +00006458 if (ShouldNotPrintDirectly) {
6459 // The expression has a type that should not be printed directly.
6460 // We extract the name from the typedef because we don't want to show
6461 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006462 StringRef Name;
6463 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6464 Name = TypedefTy->getDecl()->getName();
6465 else
6466 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00006467 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00006468 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006469 << E->getSourceRange(),
6470 E->getLocStart(), /*IsStringLocation=*/false,
6471 SpecRange, Hints);
6472 } else {
6473 // In this case, the expression could be printed using a different
6474 // specifier, but we've decided that the specifier is probably correct
6475 // and we should cast instead. Just use the normal warning message.
6476 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00006477 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6478 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006479 << E->getSourceRange(),
6480 E->getLocStart(), /*IsStringLocation*/false,
6481 SpecRange, Hints);
6482 }
Jordan Roseaee34382012-09-05 22:56:26 +00006483 }
Jordan Rose22b74712012-09-05 22:56:19 +00006484 } else {
6485 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6486 SpecifierLen);
6487 // Since the warning for passing non-POD types to variadic functions
6488 // was deferred until now, we emit a warning for non-POD
6489 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00006490 switch (S.isValidVarArgType(ExprTy)) {
6491 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00006492 case Sema::VAK_ValidInCXX11: {
6493 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6494 if (match == analyze_printf::ArgType::NoMatchPedantic) {
6495 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6496 }
Richard Smithd7293d72013-08-05 18:49:43 +00006497
Seth Cantrellb4802962015-03-04 03:12:10 +00006498 EmitFormatDiagnostic(
6499 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6500 << IsEnum << CSR << E->getSourceRange(),
6501 E->getLocStart(), /*IsStringLocation*/ false, CSR);
6502 break;
6503 }
Richard Smithd7293d72013-08-05 18:49:43 +00006504 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00006505 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00006506 EmitFormatDiagnostic(
6507 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006508 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00006509 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00006510 << CallType
6511 << AT.getRepresentativeTypeName(S.Context)
6512 << CSR
6513 << E->getSourceRange(),
6514 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00006515 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00006516 break;
6517
6518 case Sema::VAK_Invalid:
6519 if (ExprTy->isObjCObjectType())
6520 EmitFormatDiagnostic(
6521 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6522 << S.getLangOpts().CPlusPlus11
6523 << ExprTy
6524 << CallType
6525 << AT.getRepresentativeTypeName(S.Context)
6526 << CSR
6527 << E->getSourceRange(),
6528 E->getLocStart(), /*IsStringLocation*/false, CSR);
6529 else
6530 // FIXME: If this is an initializer list, suggest removing the braces
6531 // or inserting a cast to the target type.
6532 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6533 << isa<InitListExpr>(E) << ExprTy << CallType
6534 << AT.getRepresentativeTypeName(S.Context)
6535 << E->getSourceRange();
6536 break;
6537 }
6538
6539 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6540 "format string specifier index out of range");
6541 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006542 }
6543
Ted Kremenekab278de2010-01-28 23:39:18 +00006544 return true;
6545}
6546
Ted Kremenek02087932010-07-16 02:11:22 +00006547//===--- CHECK: Scanf format string checking ------------------------------===//
6548
6549namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006550
Ted Kremenek02087932010-07-16 02:11:22 +00006551class CheckScanfHandler : public CheckFormatHandler {
6552public:
Stephen Hines648c3692016-09-16 01:07:04 +00006553 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006554 const Expr *origFormatExpr, Sema::FormatStringType type,
6555 unsigned firstDataArg, unsigned numDataArgs,
6556 const char *beg, bool hasVAListArg,
6557 ArrayRef<const Expr *> Args, unsigned formatIdx,
6558 bool inFunctionCall, Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006559 llvm::SmallBitVector &CheckedVarArgs,
6560 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006561 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6562 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6563 inFunctionCall, CallType, CheckedVarArgs,
6564 UncoveredArg) {}
6565
Ted Kremenek02087932010-07-16 02:11:22 +00006566 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6567 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006568 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00006569
6570 bool HandleInvalidScanfConversionSpecifier(
6571 const analyze_scanf::ScanfSpecifier &FS,
6572 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006573 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006574
Craig Toppere14c0f82014-03-12 04:55:44 +00006575 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00006576};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006577
6578} // namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00006579
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006580void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6581 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006582 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6583 getLocationOfByte(end), /*IsStringLocation*/true,
6584 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006585}
6586
Ted Kremenekce815422010-07-19 21:25:57 +00006587bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6588 const analyze_scanf::ScanfSpecifier &FS,
6589 const char *startSpecifier,
6590 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006591 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00006592 FS.getConversionSpecifier();
6593
6594 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6595 getLocationOfByte(CS.getStart()),
6596 startSpecifier, specifierLen,
6597 CS.getStart(), CS.getLength());
6598}
6599
Ted Kremenek02087932010-07-16 02:11:22 +00006600bool CheckScanfHandler::HandleScanfSpecifier(
6601 const analyze_scanf::ScanfSpecifier &FS,
6602 const char *startSpecifier,
6603 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00006604 using namespace analyze_scanf;
6605 using namespace analyze_format_string;
6606
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006607 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00006608
Ted Kremenek6cd69422010-07-19 22:01:06 +00006609 // Handle case where '%' and '*' don't consume an argument. These shouldn't
6610 // be used to decide if we are using positional arguments consistently.
6611 if (FS.consumesDataArgument()) {
6612 if (atFirstArg) {
6613 atFirstArg = false;
6614 usesPositionalArgs = FS.usesPositionalArg();
6615 }
6616 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006617 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6618 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00006619 return false;
6620 }
Ted Kremenek02087932010-07-16 02:11:22 +00006621 }
6622
6623 // Check if the field with is non-zero.
6624 const OptionalAmount &Amt = FS.getFieldWidth();
6625 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6626 if (Amt.getConstantAmount() == 0) {
6627 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6628 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00006629 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6630 getLocationOfByte(Amt.getStart()),
6631 /*IsStringLocation*/true, R,
6632 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00006633 }
6634 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006635
Ted Kremenek02087932010-07-16 02:11:22 +00006636 if (!FS.consumesDataArgument()) {
6637 // FIXME: Technically specifying a precision or field width here
6638 // makes no sense. Worth issuing a warning at some point.
6639 return true;
6640 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006641
Ted Kremenek02087932010-07-16 02:11:22 +00006642 // Consume the argument.
6643 unsigned argIndex = FS.getArgIndex();
6644 if (argIndex < NumDataArgs) {
6645 // The check to see if the argIndex is valid will come later.
6646 // We set the bit here because we may exit early from this
6647 // function if we encounter some other error.
6648 CoveredArgs.set(argIndex);
6649 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006650
Ted Kremenek4407ea42010-07-20 20:04:47 +00006651 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006652 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006653 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6654 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006655 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006656 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006657 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006658 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6659 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006660
Jordan Rose92303592012-09-08 04:00:03 +00006661 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6662 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6663
Ted Kremenek02087932010-07-16 02:11:22 +00006664 // The remaining checks depend on the data arguments.
6665 if (HasVAListArg)
6666 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006667
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006668 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00006669 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00006670
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006671 // Check that the argument type matches the format specifier.
6672 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00006673 if (!Ex)
6674 return true;
6675
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00006676 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00006677
6678 if (!AT.isValid()) {
6679 return true;
6680 }
6681
Seth Cantrellb4802962015-03-04 03:12:10 +00006682 analyze_format_string::ArgType::MatchKind match =
6683 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00006684 if (match == analyze_format_string::ArgType::Match) {
6685 return true;
6686 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006687
Seth Cantrell79340072015-03-04 05:58:08 +00006688 ScanfSpecifier fixedFS = FS;
6689 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6690 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006691
Seth Cantrell79340072015-03-04 05:58:08 +00006692 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6693 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6694 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6695 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006696
Seth Cantrell79340072015-03-04 05:58:08 +00006697 if (success) {
6698 // Get the fix string from the fixed format specifier.
6699 SmallString<128> buf;
6700 llvm::raw_svector_ostream os(buf);
6701 fixedFS.toString(os);
6702
6703 EmitFormatDiagnostic(
6704 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6705 << Ex->getType() << false << Ex->getSourceRange(),
6706 Ex->getLocStart(),
6707 /*IsStringLocation*/ false,
6708 getSpecifierRange(startSpecifier, specifierLen),
6709 FixItHint::CreateReplacement(
6710 getSpecifierRange(startSpecifier, specifierLen), os.str()));
6711 } else {
6712 EmitFormatDiagnostic(S.PDiag(diag)
6713 << AT.getRepresentativeTypeName(S.Context)
6714 << Ex->getType() << false << Ex->getSourceRange(),
6715 Ex->getLocStart(),
6716 /*IsStringLocation*/ false,
6717 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006718 }
6719
Ted Kremenek02087932010-07-16 02:11:22 +00006720 return true;
6721}
6722
Stephen Hines648c3692016-09-16 01:07:04 +00006723static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006724 const Expr *OrigFormatExpr,
6725 ArrayRef<const Expr *> Args,
6726 bool HasVAListArg, unsigned format_idx,
6727 unsigned firstDataArg,
6728 Sema::FormatStringType Type,
6729 bool inFunctionCall,
6730 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006731 llvm::SmallBitVector &CheckedVarArgs,
6732 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00006733 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00006734 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006735 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006736 S, inFunctionCall, Args[format_idx],
6737 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006738 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006739 return;
6740 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006741
Ted Kremenekab278de2010-01-28 23:39:18 +00006742 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006743 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00006744 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006745 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006746 const ConstantArrayType *T =
6747 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006748 assert(T && "String literal not of constant array type!");
6749 size_t TypeSize = T->getSize().getZExtValue();
6750 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006751 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006752
6753 // Emit a warning if the string literal is truncated and does not contain an
6754 // embedded null character.
6755 if (TypeSize <= StrRef.size() &&
6756 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6757 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006758 S, inFunctionCall, Args[format_idx],
6759 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006760 FExpr->getLocStart(),
6761 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6762 return;
6763 }
6764
Ted Kremenekab278de2010-01-28 23:39:18 +00006765 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00006766 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006767 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006768 S, inFunctionCall, Args[format_idx],
6769 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006770 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006771 return;
6772 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006773
6774 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
Mehdi Amini06d367c2016-10-24 20:39:34 +00006775 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6776 Type == Sema::FST_OSTrace) {
6777 CheckPrintfHandler H(
6778 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6779 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6780 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6781 CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006782
Hans Wennborg23926bd2011-12-15 10:25:47 +00006783 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006784 S.getLangOpts(),
6785 S.Context.getTargetInfo(),
6786 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00006787 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006788 } else if (Type == Sema::FST_Scanf) {
Mehdi Amini06d367c2016-10-24 20:39:34 +00006789 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6790 numDataArgs, Str, HasVAListArg, Args, format_idx,
6791 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006792
Hans Wennborg23926bd2011-12-15 10:25:47 +00006793 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006794 S.getLangOpts(),
6795 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00006796 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006797 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00006798}
6799
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00006800bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6801 // Str - The format string. NOTE: this is NOT null-terminated!
6802 StringRef StrRef = FExpr->getString();
6803 const char *Str = StrRef.data();
6804 // Account for cases where the string literal is truncated in a declaration.
6805 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6806 assert(T && "String literal not of constant array type!");
6807 size_t TypeSize = T->getSize().getZExtValue();
6808 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6809 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6810 getLangOpts(),
6811 Context.getTargetInfo());
6812}
6813
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006814//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6815
6816// Returns the related absolute value function that is larger, of 0 if one
6817// does not exist.
6818static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6819 switch (AbsFunction) {
6820 default:
6821 return 0;
6822
6823 case Builtin::BI__builtin_abs:
6824 return Builtin::BI__builtin_labs;
6825 case Builtin::BI__builtin_labs:
6826 return Builtin::BI__builtin_llabs;
6827 case Builtin::BI__builtin_llabs:
6828 return 0;
6829
6830 case Builtin::BI__builtin_fabsf:
6831 return Builtin::BI__builtin_fabs;
6832 case Builtin::BI__builtin_fabs:
6833 return Builtin::BI__builtin_fabsl;
6834 case Builtin::BI__builtin_fabsl:
6835 return 0;
6836
6837 case Builtin::BI__builtin_cabsf:
6838 return Builtin::BI__builtin_cabs;
6839 case Builtin::BI__builtin_cabs:
6840 return Builtin::BI__builtin_cabsl;
6841 case Builtin::BI__builtin_cabsl:
6842 return 0;
6843
6844 case Builtin::BIabs:
6845 return Builtin::BIlabs;
6846 case Builtin::BIlabs:
6847 return Builtin::BIllabs;
6848 case Builtin::BIllabs:
6849 return 0;
6850
6851 case Builtin::BIfabsf:
6852 return Builtin::BIfabs;
6853 case Builtin::BIfabs:
6854 return Builtin::BIfabsl;
6855 case Builtin::BIfabsl:
6856 return 0;
6857
6858 case Builtin::BIcabsf:
6859 return Builtin::BIcabs;
6860 case Builtin::BIcabs:
6861 return Builtin::BIcabsl;
6862 case Builtin::BIcabsl:
6863 return 0;
6864 }
6865}
6866
6867// Returns the argument type of the absolute value function.
6868static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6869 unsigned AbsType) {
6870 if (AbsType == 0)
6871 return QualType();
6872
6873 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6874 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6875 if (Error != ASTContext::GE_None)
6876 return QualType();
6877
6878 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6879 if (!FT)
6880 return QualType();
6881
6882 if (FT->getNumParams() != 1)
6883 return QualType();
6884
6885 return FT->getParamType(0);
6886}
6887
6888// Returns the best absolute value function, or zero, based on type and
6889// current absolute value function.
6890static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6891 unsigned AbsFunctionKind) {
6892 unsigned BestKind = 0;
6893 uint64_t ArgSize = Context.getTypeSize(ArgType);
6894 for (unsigned Kind = AbsFunctionKind; Kind != 0;
6895 Kind = getLargerAbsoluteValueFunction(Kind)) {
6896 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6897 if (Context.getTypeSize(ParamType) >= ArgSize) {
6898 if (BestKind == 0)
6899 BestKind = Kind;
6900 else if (Context.hasSameType(ParamType, ArgType)) {
6901 BestKind = Kind;
6902 break;
6903 }
6904 }
6905 }
6906 return BestKind;
6907}
6908
6909enum AbsoluteValueKind {
6910 AVK_Integer,
6911 AVK_Floating,
6912 AVK_Complex
6913};
6914
6915static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6916 if (T->isIntegralOrEnumerationType())
6917 return AVK_Integer;
6918 if (T->isRealFloatingType())
6919 return AVK_Floating;
6920 if (T->isAnyComplexType())
6921 return AVK_Complex;
6922
6923 llvm_unreachable("Type not integer, floating, or complex");
6924}
6925
6926// Changes the absolute value function to a different type. Preserves whether
6927// the function is a builtin.
6928static unsigned changeAbsFunction(unsigned AbsKind,
6929 AbsoluteValueKind ValueKind) {
6930 switch (ValueKind) {
6931 case AVK_Integer:
6932 switch (AbsKind) {
6933 default:
6934 return 0;
6935 case Builtin::BI__builtin_fabsf:
6936 case Builtin::BI__builtin_fabs:
6937 case Builtin::BI__builtin_fabsl:
6938 case Builtin::BI__builtin_cabsf:
6939 case Builtin::BI__builtin_cabs:
6940 case Builtin::BI__builtin_cabsl:
6941 return Builtin::BI__builtin_abs;
6942 case Builtin::BIfabsf:
6943 case Builtin::BIfabs:
6944 case Builtin::BIfabsl:
6945 case Builtin::BIcabsf:
6946 case Builtin::BIcabs:
6947 case Builtin::BIcabsl:
6948 return Builtin::BIabs;
6949 }
6950 case AVK_Floating:
6951 switch (AbsKind) {
6952 default:
6953 return 0;
6954 case Builtin::BI__builtin_abs:
6955 case Builtin::BI__builtin_labs:
6956 case Builtin::BI__builtin_llabs:
6957 case Builtin::BI__builtin_cabsf:
6958 case Builtin::BI__builtin_cabs:
6959 case Builtin::BI__builtin_cabsl:
6960 return Builtin::BI__builtin_fabsf;
6961 case Builtin::BIabs:
6962 case Builtin::BIlabs:
6963 case Builtin::BIllabs:
6964 case Builtin::BIcabsf:
6965 case Builtin::BIcabs:
6966 case Builtin::BIcabsl:
6967 return Builtin::BIfabsf;
6968 }
6969 case AVK_Complex:
6970 switch (AbsKind) {
6971 default:
6972 return 0;
6973 case Builtin::BI__builtin_abs:
6974 case Builtin::BI__builtin_labs:
6975 case Builtin::BI__builtin_llabs:
6976 case Builtin::BI__builtin_fabsf:
6977 case Builtin::BI__builtin_fabs:
6978 case Builtin::BI__builtin_fabsl:
6979 return Builtin::BI__builtin_cabsf;
6980 case Builtin::BIabs:
6981 case Builtin::BIlabs:
6982 case Builtin::BIllabs:
6983 case Builtin::BIfabsf:
6984 case Builtin::BIfabs:
6985 case Builtin::BIfabsl:
6986 return Builtin::BIcabsf;
6987 }
6988 }
6989 llvm_unreachable("Unable to convert function");
6990}
6991
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00006992static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006993 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6994 if (!FnInfo)
6995 return 0;
6996
6997 switch (FDecl->getBuiltinID()) {
6998 default:
6999 return 0;
7000 case Builtin::BI__builtin_abs:
7001 case Builtin::BI__builtin_fabs:
7002 case Builtin::BI__builtin_fabsf:
7003 case Builtin::BI__builtin_fabsl:
7004 case Builtin::BI__builtin_labs:
7005 case Builtin::BI__builtin_llabs:
7006 case Builtin::BI__builtin_cabs:
7007 case Builtin::BI__builtin_cabsf:
7008 case Builtin::BI__builtin_cabsl:
7009 case Builtin::BIabs:
7010 case Builtin::BIlabs:
7011 case Builtin::BIllabs:
7012 case Builtin::BIfabs:
7013 case Builtin::BIfabsf:
7014 case Builtin::BIfabsl:
7015 case Builtin::BIcabs:
7016 case Builtin::BIcabsf:
7017 case Builtin::BIcabsl:
7018 return FDecl->getBuiltinID();
7019 }
7020 llvm_unreachable("Unknown Builtin type");
7021}
7022
7023// If the replacement is valid, emit a note with replacement function.
7024// Additionally, suggest including the proper header if not already included.
7025static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00007026 unsigned AbsKind, QualType ArgType) {
7027 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00007028 const char *HeaderName = nullptr;
Mehdi Amini7186a432016-10-11 19:04:24 +00007029 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00007030 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
7031 FunctionName = "std::abs";
7032 if (ArgType->isIntegralOrEnumerationType()) {
7033 HeaderName = "cstdlib";
7034 } else if (ArgType->isRealFloatingType()) {
7035 HeaderName = "cmath";
7036 } else {
7037 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007038 }
Richard Trieubeffb832014-04-15 23:47:53 +00007039
7040 // Lookup all std::abs
7041 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00007042 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00007043 R.suppressDiagnostics();
7044 S.LookupQualifiedName(R, Std);
7045
7046 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007047 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00007048 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
7049 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
7050 } else {
7051 FDecl = dyn_cast<FunctionDecl>(I);
7052 }
7053 if (!FDecl)
7054 continue;
7055
7056 // Found std::abs(), check that they are the right ones.
7057 if (FDecl->getNumParams() != 1)
7058 continue;
7059
7060 // Check that the parameter type can handle the argument.
7061 QualType ParamType = FDecl->getParamDecl(0)->getType();
7062 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
7063 S.Context.getTypeSize(ArgType) <=
7064 S.Context.getTypeSize(ParamType)) {
7065 // Found a function, don't need the header hint.
7066 EmitHeaderHint = false;
7067 break;
7068 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007069 }
Richard Trieubeffb832014-04-15 23:47:53 +00007070 }
7071 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00007072 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00007073 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
7074
7075 if (HeaderName) {
7076 DeclarationName DN(&S.Context.Idents.get(FunctionName));
7077 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
7078 R.suppressDiagnostics();
7079 S.LookupName(R, S.getCurScope());
7080
7081 if (R.isSingleResult()) {
7082 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
7083 if (FD && FD->getBuiltinID() == AbsKind) {
7084 EmitHeaderHint = false;
7085 } else {
7086 return;
7087 }
7088 } else if (!R.empty()) {
7089 return;
7090 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007091 }
7092 }
7093
7094 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00007095 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007096
Richard Trieubeffb832014-04-15 23:47:53 +00007097 if (!HeaderName)
7098 return;
7099
7100 if (!EmitHeaderHint)
7101 return;
7102
Alp Toker5d96e0a2014-07-11 20:53:51 +00007103 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
7104 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00007105}
7106
Richard Trieua7f30b12016-12-06 01:42:28 +00007107template <std::size_t StrLen>
7108static bool IsStdFunction(const FunctionDecl *FDecl,
7109 const char (&Str)[StrLen]) {
Richard Trieubeffb832014-04-15 23:47:53 +00007110 if (!FDecl)
7111 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00007112 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
Richard Trieubeffb832014-04-15 23:47:53 +00007113 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00007114 if (!FDecl->isInStdNamespace())
Richard Trieubeffb832014-04-15 23:47:53 +00007115 return false;
7116
7117 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007118}
7119
7120// Warn when using the wrong abs() function.
7121void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
Richard Trieua7f30b12016-12-06 01:42:28 +00007122 const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007123 if (Call->getNumArgs() != 1)
7124 return;
7125
7126 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieua7f30b12016-12-06 01:42:28 +00007127 bool IsStdAbs = IsStdFunction(FDecl, "abs");
Richard Trieubeffb832014-04-15 23:47:53 +00007128 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007129 return;
7130
7131 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7132 QualType ParamType = Call->getArg(0)->getType();
7133
Alp Toker5d96e0a2014-07-11 20:53:51 +00007134 // Unsigned types cannot be negative. Suggest removing the absolute value
7135 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007136 if (ArgType->isUnsignedIntegerType()) {
Mehdi Amini7186a432016-10-11 19:04:24 +00007137 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00007138 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007139 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
7140 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00007141 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007142 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
7143 return;
7144 }
7145
David Majnemer7f77eb92015-11-15 03:04:34 +00007146 // Taking the absolute value of a pointer is very suspicious, they probably
7147 // wanted to index into an array, dereference a pointer, call a function, etc.
7148 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
7149 unsigned DiagType = 0;
7150 if (ArgType->isFunctionType())
7151 DiagType = 1;
7152 else if (ArgType->isArrayType())
7153 DiagType = 2;
7154
7155 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
7156 return;
7157 }
7158
Richard Trieubeffb832014-04-15 23:47:53 +00007159 // std::abs has overloads which prevent most of the absolute value problems
7160 // from occurring.
7161 if (IsStdAbs)
7162 return;
7163
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007164 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
7165 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
7166
7167 // The argument and parameter are the same kind. Check if they are the right
7168 // size.
7169 if (ArgValueKind == ParamValueKind) {
7170 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
7171 return;
7172
7173 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
7174 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
7175 << FDecl << ArgType << ParamType;
7176
7177 if (NewAbsKind == 0)
7178 return;
7179
7180 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00007181 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007182 return;
7183 }
7184
7185 // ArgValueKind != ParamValueKind
7186 // The wrong type of absolute value function was used. Attempt to find the
7187 // proper one.
7188 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
7189 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
7190 if (NewAbsKind == 0)
7191 return;
7192
7193 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
7194 << FDecl << ParamValueKind << ArgValueKind;
7195
7196 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00007197 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007198}
7199
Richard Trieu67c00712016-12-05 23:41:46 +00007200//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
Richard Trieua7f30b12016-12-06 01:42:28 +00007201void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
7202 const FunctionDecl *FDecl) {
Richard Trieu67c00712016-12-05 23:41:46 +00007203 if (!Call || !FDecl) return;
7204
7205 // Ignore template specializations and macros.
Richard Smith51ec0cf2017-02-21 01:17:38 +00007206 if (inTemplateInstantiation()) return;
Richard Trieu67c00712016-12-05 23:41:46 +00007207 if (Call->getExprLoc().isMacroID()) return;
7208
7209 // Only care about the one template argument, two function parameter std::max
7210 if (Call->getNumArgs() != 2) return;
Richard Trieua7f30b12016-12-06 01:42:28 +00007211 if (!IsStdFunction(FDecl, "max")) return;
Richard Trieu67c00712016-12-05 23:41:46 +00007212 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
7213 if (!ArgList) return;
7214 if (ArgList->size() != 1) return;
7215
7216 // Check that template type argument is unsigned integer.
7217 const auto& TA = ArgList->get(0);
7218 if (TA.getKind() != TemplateArgument::Type) return;
7219 QualType ArgType = TA.getAsType();
7220 if (!ArgType->isUnsignedIntegerType()) return;
7221
7222 // See if either argument is a literal zero.
7223 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
7224 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
7225 if (!MTE) return false;
7226 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
7227 if (!Num) return false;
7228 if (Num->getValue() != 0) return false;
7229 return true;
7230 };
7231
7232 const Expr *FirstArg = Call->getArg(0);
7233 const Expr *SecondArg = Call->getArg(1);
7234 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
7235 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
7236
7237 // Only warn when exactly one argument is zero.
7238 if (IsFirstArgZero == IsSecondArgZero) return;
7239
7240 SourceRange FirstRange = FirstArg->getSourceRange();
7241 SourceRange SecondRange = SecondArg->getSourceRange();
7242
7243 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
7244
7245 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
7246 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
7247
7248 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
7249 SourceRange RemovalRange;
7250 if (IsFirstArgZero) {
7251 RemovalRange = SourceRange(FirstRange.getBegin(),
7252 SecondRange.getBegin().getLocWithOffset(-1));
7253 } else {
7254 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
7255 SecondRange.getEnd());
7256 }
7257
7258 Diag(Call->getExprLoc(), diag::note_remove_max_call)
7259 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
7260 << FixItHint::CreateRemoval(RemovalRange);
7261}
7262
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007263//===--- CHECK: Standard memory functions ---------------------------------===//
7264
Nico Weber0e6daef2013-12-26 23:38:39 +00007265/// \brief Takes the expression passed to the size_t parameter of functions
7266/// such as memcmp, strncat, etc and warns if it's a comparison.
7267///
7268/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
7269static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
7270 IdentifierInfo *FnName,
7271 SourceLocation FnLoc,
7272 SourceLocation RParenLoc) {
7273 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
7274 if (!Size)
7275 return false;
7276
7277 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
7278 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
7279 return false;
7280
Nico Weber0e6daef2013-12-26 23:38:39 +00007281 SourceRange SizeRange = Size->getSourceRange();
7282 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
7283 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00007284 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007285 << FnName << FixItHint::CreateInsertion(
7286 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00007287 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00007288 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00007289 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00007290 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
7291 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00007292
7293 return true;
7294}
7295
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007296/// \brief Determine whether the given type is or contains a dynamic class type
7297/// (e.g., whether it has a vtable).
7298static const CXXRecordDecl *getContainedDynamicClass(QualType T,
7299 bool &IsContained) {
7300 // Look through array types while ignoring qualifiers.
7301 const Type *Ty = T->getBaseElementTypeUnsafe();
7302 IsContained = false;
7303
7304 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
7305 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00007306 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007307 return nullptr;
7308
7309 if (RD->isDynamicClass())
7310 return RD;
7311
7312 // Check all the fields. If any bases were dynamic, the class is dynamic.
7313 // It's impossible for a class to transitively contain itself by value, so
7314 // infinite recursion is impossible.
7315 for (auto *FD : RD->fields()) {
7316 bool SubContained;
7317 if (const CXXRecordDecl *ContainedRD =
7318 getContainedDynamicClass(FD->getType(), SubContained)) {
7319 IsContained = true;
7320 return ContainedRD;
7321 }
7322 }
7323
7324 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00007325}
7326
Chandler Carruth889ed862011-06-21 23:04:20 +00007327/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007328/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00007329static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00007330 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007331 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007332 if (SizeOf->getKind() == UETT_SizeOf && !SizeOf->isArgumentType())
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007333 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007334
Craig Topperc3ec1492014-05-26 06:22:03 +00007335 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007336}
7337
Chandler Carruth889ed862011-06-21 23:04:20 +00007338/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00007339static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007340 if (const UnaryExprOrTypeTraitExpr *SizeOf =
7341 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007342 if (SizeOf->getKind() == UETT_SizeOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007343 return SizeOf->getTypeOfArgument();
7344
7345 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00007346}
7347
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007348/// \brief Check for dangerous or invalid arguments to memset().
7349///
Chandler Carruthac687262011-06-03 06:23:57 +00007350/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007351/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
7352/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007353///
7354/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007355void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00007356 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007357 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00007358 assert(BId != 0);
7359
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007360 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00007361 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007362 unsigned ExpectedNumArgs =
7363 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00007364 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007365 return;
7366
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007367 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00007368 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007369 unsigned LenArg =
7370 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00007371 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007372
Nico Weber0e6daef2013-12-26 23:38:39 +00007373 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
7374 Call->getLocStart(), Call->getRParenLoc()))
7375 return;
7376
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007377 // We have special checking when the length is a sizeof expression.
7378 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
7379 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
7380 llvm::FoldingSetNodeID SizeOfArgID;
7381
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00007382 // Although widely used, 'bzero' is not a standard function. Be more strict
7383 // with the argument types before allowing diagnostics and only allow the
7384 // form bzero(ptr, sizeof(...)).
7385 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7386 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
7387 return;
7388
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007389 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7390 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007391 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007392
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007393 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00007394 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007395 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00007396 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00007397
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007398 // Never warn about void type pointers. This can be used to suppress
7399 // false positives.
7400 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007401 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007402
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007403 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
7404 // actually comparing the expressions for equality. Because computing the
7405 // expression IDs can be expensive, we only do this if the diagnostic is
7406 // enabled.
7407 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007408 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
7409 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007410 // We only compute IDs for expressions if the warning is enabled, and
7411 // cache the sizeof arg's ID.
7412 if (SizeOfArgID == llvm::FoldingSetNodeID())
7413 SizeOfArg->Profile(SizeOfArgID, Context, true);
7414 llvm::FoldingSetNodeID DestID;
7415 Dest->Profile(DestID, Context, true);
7416 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00007417 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
7418 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007419 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00007420 StringRef ReadableName = FnName->getName();
7421
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007422 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00007423 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007424 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00007425 if (!PointeeTy->isIncompleteType() &&
7426 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007427 ActionIdx = 2; // If the pointee's size is sizeof(char),
7428 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00007429
7430 // If the function is defined as a builtin macro, do not show macro
7431 // expansion.
7432 SourceLocation SL = SizeOfArg->getExprLoc();
7433 SourceRange DSR = Dest->getSourceRange();
7434 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007435 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00007436
7437 if (SM.isMacroArgExpansion(SL)) {
7438 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7439 SL = SM.getSpellingLoc(SL);
7440 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7441 SM.getSpellingLoc(DSR.getEnd()));
7442 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7443 SM.getSpellingLoc(SSR.getEnd()));
7444 }
7445
Anna Zaksd08d9152012-05-30 23:14:52 +00007446 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007447 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00007448 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00007449 << PointeeTy
7450 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00007451 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00007452 << SSR);
7453 DiagRuntimeBehavior(SL, SizeOfArg,
7454 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7455 << ActionIdx
7456 << SSR);
7457
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007458 break;
7459 }
7460 }
7461
7462 // Also check for cases where the sizeof argument is the exact same
7463 // type as the memory argument, and where it points to a user-defined
7464 // record type.
7465 if (SizeOfArgTy != QualType()) {
7466 if (PointeeTy->isRecordType() &&
7467 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7468 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7469 PDiag(diag::warn_sizeof_pointer_type_memaccess)
7470 << FnName << SizeOfArgTy << ArgIdx
7471 << PointeeTy << Dest->getSourceRange()
7472 << LenExpr->getSourceRange());
7473 break;
7474 }
Nico Weberc5e73862011-06-14 16:14:58 +00007475 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00007476 } else if (DestTy->isArrayType()) {
7477 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00007478 }
Nico Weberc5e73862011-06-14 16:14:58 +00007479
Nico Weberc44b35e2015-03-21 17:37:46 +00007480 if (PointeeTy == QualType())
7481 continue;
Anna Zaks22122702012-01-17 00:37:07 +00007482
Nico Weberc44b35e2015-03-21 17:37:46 +00007483 // Always complain about dynamic classes.
7484 bool IsContained;
7485 if (const CXXRecordDecl *ContainedRD =
7486 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00007487
Nico Weberc44b35e2015-03-21 17:37:46 +00007488 unsigned OperationType = 0;
7489 // "overwritten" if we're warning about the destination for any call
7490 // but memcmp; otherwise a verb appropriate to the call.
7491 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7492 if (BId == Builtin::BImemcpy)
7493 OperationType = 1;
7494 else if(BId == Builtin::BImemmove)
7495 OperationType = 2;
7496 else if (BId == Builtin::BImemcmp)
7497 OperationType = 3;
7498 }
7499
John McCall31168b02011-06-15 23:02:42 +00007500 DiagRuntimeBehavior(
7501 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00007502 PDiag(diag::warn_dyn_class_memaccess)
7503 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7504 << FnName << IsContained << ContainedRD << OperationType
7505 << Call->getCallee()->getSourceRange());
7506 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7507 BId != Builtin::BImemset)
7508 DiagRuntimeBehavior(
7509 Dest->getExprLoc(), Dest,
7510 PDiag(diag::warn_arc_object_memaccess)
7511 << ArgIdx << FnName << PointeeTy
7512 << Call->getCallee()->getSourceRange());
7513 else
7514 continue;
7515
7516 DiagRuntimeBehavior(
7517 Dest->getExprLoc(), Dest,
7518 PDiag(diag::note_bad_memaccess_silence)
7519 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7520 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007521 }
7522}
7523
Ted Kremenek6865f772011-08-18 20:55:45 +00007524// A little helper routine: ignore addition and subtraction of integer literals.
7525// This intentionally does not ignore all integer constant expressions because
7526// we don't want to remove sizeof().
7527static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7528 Ex = Ex->IgnoreParenCasts();
7529
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007530 while (true) {
Ted Kremenek6865f772011-08-18 20:55:45 +00007531 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7532 if (!BO || !BO->isAdditiveOp())
7533 break;
7534
7535 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7536 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7537
7538 if (isa<IntegerLiteral>(RHS))
7539 Ex = LHS;
7540 else if (isa<IntegerLiteral>(LHS))
7541 Ex = RHS;
7542 else
7543 break;
7544 }
7545
7546 return Ex;
7547}
7548
Anna Zaks13b08572012-08-08 21:42:23 +00007549static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7550 ASTContext &Context) {
7551 // Only handle constant-sized or VLAs, but not flexible members.
7552 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7553 // Only issue the FIXIT for arrays of size > 1.
7554 if (CAT->getSize().getSExtValue() <= 1)
7555 return false;
7556 } else if (!Ty->isVariableArrayType()) {
7557 return false;
7558 }
7559 return true;
7560}
7561
Ted Kremenek6865f772011-08-18 20:55:45 +00007562// Warn if the user has made the 'size' argument to strlcpy or strlcat
7563// be the size of the source, instead of the destination.
7564void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7565 IdentifierInfo *FnName) {
7566
7567 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00007568 unsigned NumArgs = Call->getNumArgs();
7569 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00007570 return;
7571
7572 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7573 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00007574 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00007575
7576 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7577 Call->getLocStart(), Call->getRParenLoc()))
7578 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00007579
7580 // Look for 'strlcpy(dst, x, sizeof(x))'
7581 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7582 CompareWithSrc = Ex;
7583 else {
7584 // Look for 'strlcpy(dst, x, strlen(x))'
7585 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00007586 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7587 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00007588 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7589 }
7590 }
7591
7592 if (!CompareWithSrc)
7593 return;
7594
7595 // Determine if the argument to sizeof/strlen is equal to the source
7596 // argument. In principle there's all kinds of things you could do
7597 // here, for instance creating an == expression and evaluating it with
7598 // EvaluateAsBooleanCondition, but this uses a more direct technique:
7599 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7600 if (!SrcArgDRE)
7601 return;
7602
7603 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7604 if (!CompareWithSrcDRE ||
7605 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7606 return;
7607
7608 const Expr *OriginalSizeArg = Call->getArg(2);
7609 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7610 << OriginalSizeArg->getSourceRange() << FnName;
7611
7612 // Output a FIXIT hint if the destination is an array (rather than a
7613 // pointer to an array). This could be enhanced to handle some
7614 // pointers if we know the actual size, like if DstArg is 'array+2'
7615 // we could say 'sizeof(array)-2'.
7616 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00007617 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00007618 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007619
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007620 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007621 llvm::raw_svector_ostream OS(sizeString);
7622 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007623 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00007624 OS << ")";
7625
7626 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7627 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7628 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00007629}
7630
Anna Zaks314cd092012-02-01 19:08:57 +00007631/// Check if two expressions refer to the same declaration.
7632static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7633 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7634 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7635 return D1->getDecl() == D2->getDecl();
7636 return false;
7637}
7638
7639static const Expr *getStrlenExprArg(const Expr *E) {
7640 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7641 const FunctionDecl *FD = CE->getDirectCallee();
7642 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00007643 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007644 return CE->getArg(0)->IgnoreParenCasts();
7645 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007646 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007647}
7648
7649// Warn on anti-patterns as the 'size' argument to strncat.
7650// The correct size argument should look like following:
7651// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7652void Sema::CheckStrncatArguments(const CallExpr *CE,
7653 IdentifierInfo *FnName) {
7654 // Don't crash if the user has the wrong number of arguments.
7655 if (CE->getNumArgs() < 3)
7656 return;
7657 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7658 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7659 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7660
Nico Weber0e6daef2013-12-26 23:38:39 +00007661 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7662 CE->getRParenLoc()))
7663 return;
7664
Anna Zaks314cd092012-02-01 19:08:57 +00007665 // Identify common expressions, which are wrongly used as the size argument
7666 // to strncat and may lead to buffer overflows.
7667 unsigned PatternType = 0;
7668 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7669 // - sizeof(dst)
7670 if (referToTheSameDecl(SizeOfArg, DstArg))
7671 PatternType = 1;
7672 // - sizeof(src)
7673 else if (referToTheSameDecl(SizeOfArg, SrcArg))
7674 PatternType = 2;
7675 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7676 if (BE->getOpcode() == BO_Sub) {
7677 const Expr *L = BE->getLHS()->IgnoreParenCasts();
7678 const Expr *R = BE->getRHS()->IgnoreParenCasts();
7679 // - sizeof(dst) - strlen(dst)
7680 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7681 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7682 PatternType = 1;
7683 // - sizeof(src) - (anything)
7684 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7685 PatternType = 2;
7686 }
7687 }
7688
7689 if (PatternType == 0)
7690 return;
7691
Anna Zaks5069aa32012-02-03 01:27:37 +00007692 // Generate the diagnostic.
7693 SourceLocation SL = LenArg->getLocStart();
7694 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007695 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00007696
7697 // If the function is defined as a builtin macro, do not show macro expansion.
7698 if (SM.isMacroArgExpansion(SL)) {
7699 SL = SM.getSpellingLoc(SL);
7700 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7701 SM.getSpellingLoc(SR.getEnd()));
7702 }
7703
Anna Zaks13b08572012-08-08 21:42:23 +00007704 // Check if the destination is an array (rather than a pointer to an array).
7705 QualType DstTy = DstArg->getType();
7706 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7707 Context);
7708 if (!isKnownSizeArray) {
7709 if (PatternType == 1)
7710 Diag(SL, diag::warn_strncat_wrong_size) << SR;
7711 else
7712 Diag(SL, diag::warn_strncat_src_size) << SR;
7713 return;
7714 }
7715
Anna Zaks314cd092012-02-01 19:08:57 +00007716 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00007717 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007718 else
Anna Zaks5069aa32012-02-03 01:27:37 +00007719 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007720
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007721 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00007722 llvm::raw_svector_ostream OS(sizeString);
7723 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007724 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007725 OS << ") - ";
7726 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007727 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007728 OS << ") - 1";
7729
Anna Zaks5069aa32012-02-03 01:27:37 +00007730 Diag(SL, diag::note_strncat_wrong_size)
7731 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00007732}
7733
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007734//===--- CHECK: Return Address of Stack Variable --------------------------===//
7735
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007736static const Expr *EvalVal(const Expr *E,
7737 SmallVectorImpl<const DeclRefExpr *> &refVars,
7738 const Decl *ParentDecl);
7739static const Expr *EvalAddr(const Expr *E,
7740 SmallVectorImpl<const DeclRefExpr *> &refVars,
7741 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007742
7743/// CheckReturnStackAddr - Check if a return statement returns the address
7744/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007745static void
7746CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7747 SourceLocation ReturnLoc) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007748 const Expr *stackE = nullptr;
7749 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007750
7751 // Perform checking for returned stack addresses, local blocks,
7752 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00007753 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007754 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007755 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00007756 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007757 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007758 }
7759
Craig Topperc3ec1492014-05-26 06:22:03 +00007760 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007761 return; // Nothing suspicious was found.
7762
Simon Pilgrim750bde62017-03-31 11:00:53 +00007763 // Parameters are initialized in the calling scope, so taking the address
Richard Trieu81b6c562016-08-05 23:24:47 +00007764 // of a parameter reference doesn't need a warning.
7765 for (auto *DRE : refVars)
7766 if (isa<ParmVarDecl>(DRE->getDecl()))
7767 return;
7768
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007769 SourceLocation diagLoc;
7770 SourceRange diagRange;
7771 if (refVars.empty()) {
7772 diagLoc = stackE->getLocStart();
7773 diagRange = stackE->getSourceRange();
7774 } else {
7775 // We followed through a reference variable. 'stackE' contains the
7776 // problematic expression but we will warn at the return statement pointing
7777 // at the reference variable. We will later display the "trail" of
7778 // reference variables using notes.
7779 diagLoc = refVars[0]->getLocStart();
7780 diagRange = refVars[0]->getSourceRange();
7781 }
7782
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007783 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7784 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00007785 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007786 << DR->getDecl()->getDeclName() << diagRange;
7787 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007788 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007789 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007790 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007791 } else { // local temporary.
Richard Trieu81b6c562016-08-05 23:24:47 +00007792 // If there is an LValue->RValue conversion, then the value of the
7793 // reference type is used, not the reference.
7794 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7795 if (ICE->getCastKind() == CK_LValueToRValue) {
7796 return;
7797 }
7798 }
Craig Topperda7b27f2015-11-17 05:40:09 +00007799 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7800 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007801 }
7802
7803 // Display the "trail" of reference variables that we followed until we
7804 // found the problematic expression using notes.
7805 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007806 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007807 // If this var binds to another reference var, show the range of the next
7808 // var, otherwise the var binds to the problematic expression, in which case
7809 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007810 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7811 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007812 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7813 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007814 }
7815}
7816
7817/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7818/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007819/// to a location on the stack, a local block, an address of a label, or a
7820/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007821/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007822/// encounter a subexpression that (1) clearly does not lead to one of the
7823/// above problematic expressions (2) is something we cannot determine leads to
7824/// a problematic expression based on such local checking.
7825///
7826/// Both EvalAddr and EvalVal follow through reference variables to evaluate
7827/// the expression that they point to. Such variables are added to the
7828/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007829///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00007830/// EvalAddr processes expressions that are pointers that are used as
7831/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007832/// At the base case of the recursion is a check for the above problematic
7833/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007834///
7835/// This implementation handles:
7836///
7837/// * pointer-to-pointer casts
7838/// * implicit conversions from array references to pointers
7839/// * taking the address of fields
7840/// * arbitrary interplay between "&" and "*" operators
7841/// * pointer arithmetic from an address of a stack variable
7842/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007843static const Expr *EvalAddr(const Expr *E,
7844 SmallVectorImpl<const DeclRefExpr *> &refVars,
7845 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007846 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00007847 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007848
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007849 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00007850 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00007851 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007852 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00007853 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00007854
Peter Collingbourne91147592011-04-15 00:35:48 +00007855 E = E->IgnoreParens();
7856
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007857 // Our "symbolic interpreter" is just a dispatch off the currently
7858 // viewed AST node. We then recursively traverse the AST by calling
7859 // EvalAddr and EvalVal appropriately.
7860 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007861 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007862 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007863
Richard Smith40f08eb2014-01-30 22:05:38 +00007864 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00007865 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00007866 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00007867
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007868 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007869 // If this is a reference variable, follow through to the expression that
7870 // it points to.
7871 if (V->hasLocalStorage() &&
7872 V->getType()->isReferenceType() && V->hasInit()) {
7873 // Add the reference variable to the "trail".
7874 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007875 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007876 }
7877
Craig Topperc3ec1492014-05-26 06:22:03 +00007878 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007879 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007880
Chris Lattner934edb22007-12-28 05:31:15 +00007881 case Stmt::UnaryOperatorClass: {
7882 // The only unary operator that make sense to handle here
7883 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007884 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007885
John McCalle3027922010-08-25 11:45:40 +00007886 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007887 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007888 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007889 }
Mike Stump11289f42009-09-09 15:08:12 +00007890
Chris Lattner934edb22007-12-28 05:31:15 +00007891 case Stmt::BinaryOperatorClass: {
7892 // Handle pointer arithmetic. All other binary operators are not valid
7893 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007894 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00007895 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00007896
John McCalle3027922010-08-25 11:45:40 +00007897 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00007898 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007899
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007900 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00007901
7902 // Determine which argument is the real pointer base. It could be
7903 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007904 if (!Base->getType()->isPointerType())
7905 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00007906
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007907 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007908 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007909 }
Steve Naroff2752a172008-09-10 19:17:48 +00007910
Chris Lattner934edb22007-12-28 05:31:15 +00007911 // For conditional operators we need to see if either the LHS or RHS are
7912 // valid DeclRefExpr*s. If one of them is valid, we return it.
7913 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007914 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007915
Chris Lattner934edb22007-12-28 05:31:15 +00007916 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007917 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007918 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007919 // In C++, we can have a throw-expression, which has 'void' type.
7920 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007921 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007922 return LHS;
7923 }
Chris Lattner934edb22007-12-28 05:31:15 +00007924
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007925 // In C++, we can have a throw-expression, which has 'void' type.
7926 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00007927 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007928
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007929 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007930 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007931
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007932 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00007933 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007934 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00007935 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007936
7937 case Stmt::AddrLabelExprClass:
7938 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00007939
John McCall28fc7092011-11-10 05:35:25 +00007940 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007941 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7942 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00007943
Ted Kremenekc3b4c522008-08-07 00:49:01 +00007944 // For casts, we need to handle conversions from arrays to
7945 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00007946 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00007947 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00007948 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00007949 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00007950 case Stmt::CXXStaticCastExprClass:
7951 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00007952 case Stmt::CXXConstCastExprClass:
7953 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007954 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00007955 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00007956 case CK_LValueToRValue:
7957 case CK_NoOp:
7958 case CK_BaseToDerived:
7959 case CK_DerivedToBase:
7960 case CK_UncheckedDerivedToBase:
7961 case CK_Dynamic:
7962 case CK_CPointerToObjCPointerCast:
7963 case CK_BlockPointerToObjCPointerCast:
7964 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007965 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007966
7967 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007968 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007969
Richard Trieudadefde2014-07-02 04:39:38 +00007970 case CK_BitCast:
7971 if (SubExpr->getType()->isAnyPointerType() ||
7972 SubExpr->getType()->isBlockPointerType() ||
7973 SubExpr->getType()->isObjCQualifiedIdType())
7974 return EvalAddr(SubExpr, refVars, ParentDecl);
7975 else
7976 return nullptr;
7977
Eli Friedman8195ad72012-02-23 23:04:32 +00007978 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007979 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00007980 }
Chris Lattner934edb22007-12-28 05:31:15 +00007981 }
Mike Stump11289f42009-09-09 15:08:12 +00007982
Douglas Gregorfe314812011-06-21 17:03:29 +00007983 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007984 if (const Expr *Result =
7985 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7986 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00007987 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00007988 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007989
Chris Lattner934edb22007-12-28 05:31:15 +00007990 // Everything else: we simply don't reason about them.
7991 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007992 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00007993 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007994}
Mike Stump11289f42009-09-09 15:08:12 +00007995
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007996/// EvalVal - This function is complements EvalAddr in the mutual recursion.
7997/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007998static const Expr *EvalVal(const Expr *E,
7999 SmallVectorImpl<const DeclRefExpr *> &refVars,
8000 const Decl *ParentDecl) {
8001 do {
8002 // We should only be called for evaluating non-pointer expressions, or
8003 // expressions with a pointer type that are not used as references but
8004 // instead
8005 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00008006
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008007 // Our "symbolic interpreter" is just a dispatch off the currently
8008 // viewed AST node. We then recursively traverse the AST by calling
8009 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00008010
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008011 E = E->IgnoreParens();
8012 switch (E->getStmtClass()) {
8013 case Stmt::ImplicitCastExprClass: {
8014 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
8015 if (IE->getValueKind() == VK_LValue) {
8016 E = IE->getSubExpr();
8017 continue;
8018 }
Craig Topperc3ec1492014-05-26 06:22:03 +00008019 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008020 }
Richard Smith40f08eb2014-01-30 22:05:38 +00008021
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008022 case Stmt::ExprWithCleanupsClass:
8023 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
8024 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008025
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008026 case Stmt::DeclRefExprClass: {
8027 // When we hit a DeclRefExpr we are looking at code that refers to a
8028 // variable's name. If it's not a reference variable we check if it has
8029 // local storage within the function, and if so, return the expression.
8030 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
8031
8032 // If we leave the immediate function, the lifetime isn't about to end.
8033 if (DR->refersToEnclosingVariableOrCapture())
8034 return nullptr;
8035
8036 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
8037 // Check if it refers to itself, e.g. "int& i = i;".
8038 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008039 return DR;
8040
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008041 if (V->hasLocalStorage()) {
8042 if (!V->getType()->isReferenceType())
8043 return DR;
8044
8045 // Reference variable, follow through to the expression that
8046 // it points to.
8047 if (V->hasInit()) {
8048 // Add the reference variable to the "trail".
8049 refVars.push_back(DR);
8050 return EvalVal(V->getInit(), refVars, V);
8051 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008052 }
8053 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008054
8055 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008056 }
Mike Stump11289f42009-09-09 15:08:12 +00008057
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008058 case Stmt::UnaryOperatorClass: {
8059 // The only unary operator that make sense to handle here
8060 // is Deref. All others don't resolve to a "name." This includes
8061 // handling all sorts of rvalues passed to a unary operator.
8062 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00008063
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008064 if (U->getOpcode() == UO_Deref)
8065 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00008066
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008067 return nullptr;
8068 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008069
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008070 case Stmt::ArraySubscriptExprClass: {
8071 // Array subscripts are potential references to data on the stack. We
8072 // retrieve the DeclRefExpr* for the array variable if it indeed
8073 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00008074 const auto *ASE = cast<ArraySubscriptExpr>(E);
8075 if (ASE->isTypeDependent())
8076 return nullptr;
8077 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008078 }
Mike Stump11289f42009-09-09 15:08:12 +00008079
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008080 case Stmt::OMPArraySectionExprClass: {
8081 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
8082 ParentDecl);
8083 }
Mike Stump11289f42009-09-09 15:08:12 +00008084
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008085 case Stmt::ConditionalOperatorClass: {
8086 // For conditional operators we need to see if either the LHS or RHS are
8087 // non-NULL Expr's. If one is non-NULL, we return it.
8088 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00008089
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008090 // Handle the GNU extension for missing LHS.
8091 if (const Expr *LHSExpr = C->getLHS()) {
8092 // In C++, we can have a throw-expression, which has 'void' type.
8093 if (!LHSExpr->getType()->isVoidType())
8094 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
8095 return LHS;
8096 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008097
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008098 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008099 if (C->getRHS()->getType()->isVoidType())
8100 return nullptr;
8101
8102 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008103 }
8104
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008105 // Accesses to members are potential references to data on the stack.
8106 case Stmt::MemberExprClass: {
8107 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00008108
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008109 // Check for indirect access. We only want direct field accesses.
8110 if (M->isArrow())
8111 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008112
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008113 // Check whether the member type is itself a reference, in which case
8114 // we're not going to refer to the member, but to what the member refers
8115 // to.
8116 if (M->getMemberDecl()->getType()->isReferenceType())
8117 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008118
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008119 return EvalVal(M->getBase(), refVars, ParentDecl);
8120 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00008121
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008122 case Stmt::MaterializeTemporaryExprClass:
8123 if (const Expr *Result =
8124 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8125 refVars, ParentDecl))
8126 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008127 return E;
8128
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008129 default:
8130 // Check that we don't return or take the address of a reference to a
8131 // temporary. This is only useful in C++.
8132 if (!E->isTypeDependent() && E->isRValue())
8133 return E;
8134
8135 // Everything else: we simply don't reason about them.
8136 return nullptr;
8137 }
8138 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008139}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008140
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008141void
8142Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
8143 SourceLocation ReturnLoc,
8144 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00008145 const AttrVec *Attrs,
8146 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008147 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
8148
8149 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00008150 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
8151 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00008152 CheckNonNullExpr(*this, RetValExp))
8153 Diag(ReturnLoc, diag::warn_null_ret)
8154 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00008155
8156 // C++11 [basic.stc.dynamic.allocation]p4:
8157 // If an allocation function declared with a non-throwing
8158 // exception-specification fails to allocate storage, it shall return
8159 // a null pointer. Any other allocation function that fails to allocate
8160 // storage shall indicate failure only by throwing an exception [...]
8161 if (FD) {
8162 OverloadedOperatorKind Op = FD->getOverloadedOperator();
8163 if (Op == OO_New || Op == OO_Array_New) {
8164 const FunctionProtoType *Proto
8165 = FD->getType()->castAs<FunctionProtoType>();
8166 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
8167 CheckNonNullExpr(*this, RetValExp))
8168 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
8169 << FD << getLangOpts().CPlusPlus11;
8170 }
8171 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008172}
8173
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008174//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
8175
8176/// Check for comparisons of floating point operands using != and ==.
8177/// Issue a warning if these are no self-comparisons, as they are not likely
8178/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00008179void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00008180 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
8181 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008182
8183 // Special case: check for x == x (which is OK).
8184 // Do not emit warnings for such cases.
8185 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
8186 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
8187 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00008188 return;
Mike Stump11289f42009-09-09 15:08:12 +00008189
Ted Kremenekeda40e22007-11-29 00:59:04 +00008190 // Special case: check for comparisons against literals that can be exactly
8191 // represented by APFloat. In such cases, do not emit a warning. This
8192 // is a heuristic: often comparison against such literals are used to
8193 // detect if a value in a variable has not changed. This clearly can
8194 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00008195 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
8196 if (FLL->isExact())
8197 return;
8198 } else
8199 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
8200 if (FLR->isExact())
8201 return;
Mike Stump11289f42009-09-09 15:08:12 +00008202
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008203 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00008204 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00008205 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00008206 return;
Mike Stump11289f42009-09-09 15:08:12 +00008207
David Blaikie1f4ff152012-07-16 20:47:22 +00008208 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00008209 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00008210 return;
Mike Stump11289f42009-09-09 15:08:12 +00008211
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008212 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00008213 Diag(Loc, diag::warn_floatingpoint_eq)
8214 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008215}
John McCallca01b222010-01-04 23:21:16 +00008216
John McCall70aa5392010-01-06 05:24:50 +00008217//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
8218//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00008219
John McCall70aa5392010-01-06 05:24:50 +00008220namespace {
John McCallca01b222010-01-04 23:21:16 +00008221
John McCall70aa5392010-01-06 05:24:50 +00008222/// Structure recording the 'active' range of an integer-valued
8223/// expression.
8224struct IntRange {
8225 /// The number of bits active in the int.
8226 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00008227
John McCall70aa5392010-01-06 05:24:50 +00008228 /// True if the int is known not to have negative values.
8229 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00008230
John McCall70aa5392010-01-06 05:24:50 +00008231 IntRange(unsigned Width, bool NonNegative)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008232 : Width(Width), NonNegative(NonNegative) {}
John McCallca01b222010-01-04 23:21:16 +00008233
John McCall817d4af2010-11-10 23:38:19 +00008234 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00008235 static IntRange forBoolType() {
8236 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00008237 }
8238
John McCall817d4af2010-11-10 23:38:19 +00008239 /// Returns the range of an opaque value of the given integral type.
8240 static IntRange forValueOfType(ASTContext &C, QualType T) {
8241 return forValueOfCanonicalType(C,
8242 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00008243 }
8244
John McCall817d4af2010-11-10 23:38:19 +00008245 /// Returns the range of an opaque value of a canonical integral type.
8246 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00008247 assert(T->isCanonicalUnqualified());
8248
8249 if (const VectorType *VT = dyn_cast<VectorType>(T))
8250 T = VT->getElementType().getTypePtr();
8251 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8252 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008253 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8254 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00008255
Roman Lebedevca1aaac2017-10-21 16:44:03 +00008256 if (!C.getLangOpts().CPlusPlus) {
8257 // For enum types in C code, use the underlying datatype.
8258 if (const EnumType *ET = dyn_cast<EnumType>(T))
8259 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
8260 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
8261 // For enum types in C++, use the known bit width of the enumerators.
David Majnemer6a426652013-06-07 22:07:20 +00008262 EnumDecl *Enum = ET->getDecl();
Erich Keane69dbbb02017-09-21 19:58:55 +00008263 // In C++11, enums without definitions can have an explicitly specified
8264 // underlying type. Use this type to compute the range.
David Majnemer6a426652013-06-07 22:07:20 +00008265 if (!Enum->isCompleteDefinition())
Erich Keane69dbbb02017-09-21 19:58:55 +00008266 return IntRange(C.getIntWidth(QualType(T, 0)),
8267 !ET->isSignedIntegerOrEnumerationType());
John McCall18a2c2c2010-11-09 22:22:12 +00008268
David Majnemer6a426652013-06-07 22:07:20 +00008269 unsigned NumPositive = Enum->getNumPositiveBits();
8270 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00008271
David Majnemer6a426652013-06-07 22:07:20 +00008272 if (NumNegative == 0)
8273 return IntRange(NumPositive, true/*NonNegative*/);
8274 else
8275 return IntRange(std::max(NumPositive + 1, NumNegative),
8276 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00008277 }
John McCall70aa5392010-01-06 05:24:50 +00008278
8279 const BuiltinType *BT = cast<BuiltinType>(T);
8280 assert(BT->isInteger());
8281
8282 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8283 }
8284
John McCall817d4af2010-11-10 23:38:19 +00008285 /// Returns the "target" range of a canonical integral type, i.e.
8286 /// the range of values expressible in the type.
8287 ///
8288 /// This matches forValueOfCanonicalType except that enums have the
8289 /// full range of their type, not the range of their enumerators.
8290 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
8291 assert(T->isCanonicalUnqualified());
8292
8293 if (const VectorType *VT = dyn_cast<VectorType>(T))
8294 T = VT->getElementType().getTypePtr();
8295 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8296 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008297 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8298 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008299 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00008300 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008301
8302 const BuiltinType *BT = cast<BuiltinType>(T);
8303 assert(BT->isInteger());
8304
8305 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8306 }
8307
8308 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00008309 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00008310 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00008311 L.NonNegative && R.NonNegative);
8312 }
8313
John McCall817d4af2010-11-10 23:38:19 +00008314 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00008315 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00008316 return IntRange(std::min(L.Width, R.Width),
8317 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00008318 }
8319};
8320
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008321} // namespace
8322
8323static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
8324 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008325 if (value.isSigned() && value.isNegative())
8326 return IntRange(value.getMinSignedBits(), false);
8327
8328 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00008329 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008330
8331 // isNonNegative() just checks the sign bit without considering
8332 // signedness.
8333 return IntRange(value.getActiveBits(), true);
8334}
8335
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008336static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
8337 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008338 if (result.isInt())
8339 return GetValueRange(C, result.getInt(), MaxWidth);
8340
8341 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00008342 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
8343 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
8344 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
8345 R = IntRange::join(R, El);
8346 }
John McCall70aa5392010-01-06 05:24:50 +00008347 return R;
8348 }
8349
8350 if (result.isComplexInt()) {
8351 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
8352 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
8353 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00008354 }
8355
8356 // This can happen with lossless casts to intptr_t of "based" lvalues.
8357 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00008358 // FIXME: The only reason we need to pass the type in here is to get
8359 // the sign right on this one case. It would be nice if APValue
8360 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008361 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00008362 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00008363}
John McCall70aa5392010-01-06 05:24:50 +00008364
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008365static QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008366 QualType Ty = E->getType();
8367 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
8368 Ty = AtomicRHS->getValueType();
8369 return Ty;
8370}
8371
John McCall70aa5392010-01-06 05:24:50 +00008372/// Pseudo-evaluate the given integer expression, estimating the
8373/// range of values it might take.
8374///
8375/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008376static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008377 E = E->IgnoreParens();
8378
8379 // Try a full evaluation first.
8380 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00008381 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00008382 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008383
8384 // I think we only want to look through implicit casts here; if the
8385 // user has an explicit widening cast, we should treat the value as
8386 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008387 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00008388 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00008389 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
8390
Eli Friedmane6d33952013-07-08 20:20:06 +00008391 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00008392
George Burgess IVdf1ed002016-01-13 01:52:39 +00008393 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
8394 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00008395
John McCall70aa5392010-01-06 05:24:50 +00008396 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00008397 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00008398 return OutputTypeRange;
8399
8400 IntRange SubRange
8401 = GetExprRange(C, CE->getSubExpr(),
8402 std::min(MaxWidth, OutputTypeRange.Width));
8403
8404 // Bail out if the subexpr's range is as wide as the cast type.
8405 if (SubRange.Width >= OutputTypeRange.Width)
8406 return OutputTypeRange;
8407
8408 // Otherwise, we take the smaller width, and we're non-negative if
8409 // either the output type or the subexpr is.
8410 return IntRange(SubRange.Width,
8411 SubRange.NonNegative || OutputTypeRange.NonNegative);
8412 }
8413
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008414 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008415 // If we can fold the condition, just take that operand.
8416 bool CondResult;
8417 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
8418 return GetExprRange(C, CondResult ? CO->getTrueExpr()
8419 : CO->getFalseExpr(),
8420 MaxWidth);
8421
8422 // Otherwise, conservatively merge.
8423 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
8424 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
8425 return IntRange::join(L, R);
8426 }
8427
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008428 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008429 switch (BO->getOpcode()) {
8430
8431 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00008432 case BO_LAnd:
8433 case BO_LOr:
8434 case BO_LT:
8435 case BO_GT:
8436 case BO_LE:
8437 case BO_GE:
8438 case BO_EQ:
8439 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00008440 return IntRange::forBoolType();
8441
John McCallc3688382011-07-13 06:35:24 +00008442 // The type of the assignments is the type of the LHS, so the RHS
8443 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00008444 case BO_MulAssign:
8445 case BO_DivAssign:
8446 case BO_RemAssign:
8447 case BO_AddAssign:
8448 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00008449 case BO_XorAssign:
8450 case BO_OrAssign:
8451 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00008452 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00008453
John McCallc3688382011-07-13 06:35:24 +00008454 // Simple assignments just pass through the RHS, which will have
8455 // been coerced to the LHS type.
8456 case BO_Assign:
8457 // TODO: bitfields?
8458 return GetExprRange(C, BO->getRHS(), MaxWidth);
8459
John McCall70aa5392010-01-06 05:24:50 +00008460 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008461 case BO_PtrMemD:
8462 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00008463 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008464
John McCall2ce81ad2010-01-06 22:07:33 +00008465 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00008466 case BO_And:
8467 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00008468 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8469 GetExprRange(C, BO->getRHS(), MaxWidth));
8470
John McCall70aa5392010-01-06 05:24:50 +00008471 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00008472 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00008473 // ...except that we want to treat '1 << (blah)' as logically
8474 // positive. It's an important idiom.
8475 if (IntegerLiteral *I
8476 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8477 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008478 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00008479 return IntRange(R.Width, /*NonNegative*/ true);
8480 }
8481 }
8482 // fallthrough
8483
John McCalle3027922010-08-25 11:45:40 +00008484 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00008485 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008486
John McCall2ce81ad2010-01-06 22:07:33 +00008487 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00008488 case BO_Shr:
8489 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00008490 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8491
8492 // If the shift amount is a positive constant, drop the width by
8493 // that much.
8494 llvm::APSInt shift;
8495 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8496 shift.isNonNegative()) {
8497 unsigned zext = shift.getZExtValue();
8498 if (zext >= L.Width)
8499 L.Width = (L.NonNegative ? 0 : 1);
8500 else
8501 L.Width -= zext;
8502 }
8503
8504 return L;
8505 }
8506
8507 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00008508 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00008509 return GetExprRange(C, BO->getRHS(), MaxWidth);
8510
John McCall2ce81ad2010-01-06 22:07:33 +00008511 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00008512 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00008513 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00008514 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008515 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00008516
John McCall51431812011-07-14 22:39:48 +00008517 // The width of a division result is mostly determined by the size
8518 // of the LHS.
8519 case BO_Div: {
8520 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008521 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008522 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8523
8524 // If the divisor is constant, use that.
8525 llvm::APSInt divisor;
8526 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8527 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8528 if (log2 >= L.Width)
8529 L.Width = (L.NonNegative ? 0 : 1);
8530 else
8531 L.Width = std::min(L.Width - log2, MaxWidth);
8532 return L;
8533 }
8534
8535 // Otherwise, just use the LHS's width.
8536 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8537 return IntRange(L.Width, L.NonNegative && R.NonNegative);
8538 }
8539
8540 // The result of a remainder can't be larger than the result of
8541 // either side.
8542 case BO_Rem: {
8543 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008544 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008545 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8546 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8547
8548 IntRange meet = IntRange::meet(L, R);
8549 meet.Width = std::min(meet.Width, MaxWidth);
8550 return meet;
8551 }
8552
8553 // The default behavior is okay for these.
8554 case BO_Mul:
8555 case BO_Add:
8556 case BO_Xor:
8557 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00008558 break;
8559 }
8560
John McCall51431812011-07-14 22:39:48 +00008561 // The default case is to treat the operation as if it were closed
8562 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00008563 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8564 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8565 return IntRange::join(L, R);
8566 }
8567
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008568 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008569 switch (UO->getOpcode()) {
8570 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00008571 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00008572 return IntRange::forBoolType();
8573
8574 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008575 case UO_Deref:
8576 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00008577 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008578
8579 default:
8580 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8581 }
8582 }
8583
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008584 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00008585 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8586
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008587 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00008588 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00008589 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00008590
Eli Friedmane6d33952013-07-08 20:20:06 +00008591 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008592}
John McCall263a48b2010-01-04 23:31:57 +00008593
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008594static IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008595 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00008596}
8597
John McCall263a48b2010-01-04 23:31:57 +00008598/// Checks whether the given value, which currently has the given
8599/// source semantics, has the same value when coerced through the
8600/// target semantics.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008601static bool IsSameFloatAfterCast(const llvm::APFloat &value,
8602 const llvm::fltSemantics &Src,
8603 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008604 llvm::APFloat truncated = value;
8605
8606 bool ignored;
8607 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8608 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8609
8610 return truncated.bitwiseIsEqual(value);
8611}
8612
8613/// Checks whether the given value, which currently has the given
8614/// source semantics, has the same value when coerced through the
8615/// target semantics.
8616///
8617/// The value might be a vector of floats (or a complex number).
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008618static bool IsSameFloatAfterCast(const APValue &value,
8619 const llvm::fltSemantics &Src,
8620 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008621 if (value.isFloat())
8622 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8623
8624 if (value.isVector()) {
8625 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8626 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8627 return false;
8628 return true;
8629 }
8630
8631 assert(value.isComplexFloat());
8632 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8633 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8634}
8635
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008636static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008637
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008638static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00008639 // Suppress cases where we are comparing against an enum constant.
8640 if (const DeclRefExpr *DR =
8641 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8642 if (isa<EnumConstantDecl>(DR->getDecl()))
Roman Lebedev6de129e2017-10-15 20:13:17 +00008643 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +00008644
8645 // Suppress cases where the '0' value is expanded from a macro.
8646 if (E->getLocStart().isMacroID())
Roman Lebedev6de129e2017-10-15 20:13:17 +00008647 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +00008648
Roman Lebedev6de129e2017-10-15 20:13:17 +00008649 return false;
8650}
8651
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008652static bool isNonBooleanIntegerValue(Expr *E) {
Roman Lebedev6de129e2017-10-15 20:13:17 +00008653 return !E->isKnownToHaveBooleanValue() && E->getType()->isIntegerType();
8654}
8655
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008656static bool isNonBooleanUnsignedValue(Expr *E) {
Roman Lebedev6de129e2017-10-15 20:13:17 +00008657 // We are checking that the expression is not known to have boolean value,
8658 // is an integer type; and is either unsigned after implicit casts,
8659 // or was unsigned before implicit casts.
8660 return isNonBooleanIntegerValue(E) &&
8661 (!E->getType()->isSignedIntegerType() ||
8662 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
8663}
8664
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008665namespace {
8666
Roman Lebedev6de129e2017-10-15 20:13:17 +00008667enum class LimitType {
Roman Lebedevca1aaac2017-10-21 16:44:03 +00008668 Max = 1U << 0U, // e.g. 32767 for short
8669 Min = 1U << 1U, // e.g. -32768 for short
8670 Both = Max | Min // When the value is both the Min and the Max limit at the
8671 // same time; e.g. in C++, A::a in enum A { a = 0 };
Roman Lebedev6de129e2017-10-15 20:13:17 +00008672};
8673
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008674} // namespace
8675
Roman Lebedev6de129e2017-10-15 20:13:17 +00008676/// Checks whether Expr 'Constant' may be the
8677/// std::numeric_limits<>::max() or std::numeric_limits<>::min()
8678/// of the Expr 'Other'. If true, then returns the limit type (min or max).
8679/// The Value is the evaluation of Constant
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008680static llvm::Optional<LimitType> IsTypeLimit(Sema &S, Expr *Constant,
8681 Expr *Other,
8682 const llvm::APSInt &Value) {
Roman Lebedev6de129e2017-10-15 20:13:17 +00008683 if (IsEnumConstOrFromMacro(S, Constant))
8684 return llvm::Optional<LimitType>();
8685
8686 if (isNonBooleanUnsignedValue(Other) && Value == 0)
8687 return LimitType::Min;
8688
8689 // TODO: Investigate using GetExprRange() to get tighter bounds
8690 // on the bit ranges.
8691 QualType OtherT = Other->IgnoreParenImpCasts()->getType();
8692 if (const auto *AT = OtherT->getAs<AtomicType>())
8693 OtherT = AT->getValueType();
8694
8695 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8696
Roman Lebedevca1aaac2017-10-21 16:44:03 +00008697 // Special-case for C++ for enum with one enumerator with value of 0.
8698 if (OtherRange.Width == 0)
8699 return Value == 0 ? LimitType::Both : llvm::Optional<LimitType>();
8700
Roman Lebedev6de129e2017-10-15 20:13:17 +00008701 if (llvm::APSInt::isSameValue(
8702 llvm::APSInt::getMaxValue(OtherRange.Width,
8703 OtherT->isUnsignedIntegerType()),
8704 Value))
8705 return LimitType::Max;
8706
8707 if (llvm::APSInt::isSameValue(
8708 llvm::APSInt::getMinValue(OtherRange.Width,
8709 OtherT->isUnsignedIntegerType()),
8710 Value))
8711 return LimitType::Min;
8712
Roman Lebedevca1aaac2017-10-21 16:44:03 +00008713 return llvm::None;
John McCallcc7e5bf2010-05-06 08:58:33 +00008714}
8715
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008716static bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00008717 // Strip off implicit integral promotions.
8718 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008719 if (ICE->getCastKind() != CK_IntegralCast &&
8720 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00008721 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008722 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00008723 }
8724
8725 return E->getType()->isEnumeralType();
8726}
8727
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008728static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
8729 Expr *Constant, Expr *Other,
8730 const llvm::APSInt &Value,
8731 bool RhsConstant) {
Roman Lebedev6de129e2017-10-15 20:13:17 +00008732 // Disable warning in template instantiations
8733 // and only analyze <, >, <= and >= operations.
8734 if (S.inTemplateInstantiation() || !E->isRelationalOp())
Roman Lebedevbd1fc222017-10-12 20:16:51 +00008735 return false;
8736
Roman Lebedev6f405db2017-10-12 22:03:20 +00008737 BinaryOperatorKind Op = E->getOpcode();
Roman Lebedev6de129e2017-10-15 20:13:17 +00008738
8739 QualType OType = Other->IgnoreParenImpCasts()->getType();
8740
8741 llvm::Optional<LimitType> ValueType; // Which limit (min/max) is the constant?
8742
8743 if (!(isNonBooleanIntegerValue(Other) &&
8744 (ValueType = IsTypeLimit(S, Constant, Other, Value))))
Roman Lebedev6f405db2017-10-12 22:03:20 +00008745 return false;
8746
Roman Lebedev6de129e2017-10-15 20:13:17 +00008747 bool ConstIsLowerBound = (Op == BO_LT || Op == BO_LE) ^ RhsConstant;
8748 bool ResultWhenConstEqualsOther = (Op == BO_LE || Op == BO_GE);
Roman Lebedevca1aaac2017-10-21 16:44:03 +00008749 if (ValueType != LimitType::Both) {
8750 bool ResultWhenConstNeOther =
8751 ConstIsLowerBound ^ (ValueType == LimitType::Max);
8752 if (ResultWhenConstEqualsOther != ResultWhenConstNeOther)
8753 return false; // The comparison is not tautological.
8754 } else if (ResultWhenConstEqualsOther == ConstIsLowerBound)
Roman Lebedev6de129e2017-10-15 20:13:17 +00008755 return false; // The comparison is not tautological.
Roman Lebedev6f405db2017-10-12 22:03:20 +00008756
Roman Lebedev6de129e2017-10-15 20:13:17 +00008757 const bool Result = ResultWhenConstEqualsOther;
Roman Lebedev6f405db2017-10-12 22:03:20 +00008758
Roman Lebedev6de129e2017-10-15 20:13:17 +00008759 unsigned Diag = (isNonBooleanUnsignedValue(Other) && Value == 0)
8760 ? (HasEnumType(Other)
8761 ? diag::warn_unsigned_enum_always_true_comparison
8762 : diag::warn_unsigned_always_true_comparison)
8763 : diag::warn_tautological_constant_compare;
Roman Lebedev6f405db2017-10-12 22:03:20 +00008764
Roman Lebedev6de129e2017-10-15 20:13:17 +00008765 // Should be enough for uint128 (39 decimal digits)
8766 SmallString<64> PrettySourceValue;
8767 llvm::raw_svector_ostream OS(PrettySourceValue);
8768 OS << Value;
8769
8770 S.Diag(E->getOperatorLoc(), Diag)
8771 << RhsConstant << OType << E->getOpcodeStr() << OS.str() << Result
8772 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8773
8774 return true;
Roman Lebedev6f405db2017-10-12 22:03:20 +00008775}
8776
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008777static bool DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
8778 Expr *Constant, Expr *Other,
8779 const llvm::APSInt &Value,
8780 bool RhsConstant) {
Roman Lebedev6f405db2017-10-12 22:03:20 +00008781 // Disable warning in template instantiations.
8782 if (S.inTemplateInstantiation())
Roman Lebedev6de129e2017-10-15 20:13:17 +00008783 return false;
8784
8785 Constant = Constant->IgnoreParenImpCasts();
8786 Other = Other->IgnoreParenImpCasts();
Richard Trieudd51d742013-11-01 21:19:43 +00008787
Richard Trieu0f097742014-04-04 04:13:47 +00008788 // TODO: Investigate using GetExprRange() to get tighter bounds
8789 // on the bit ranges.
8790 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00008791 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00008792 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00008793 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8794 unsigned OtherWidth = OtherRange.Width;
8795
8796 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
8797
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008798 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00008799 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00008800
Richard Trieu0f097742014-04-04 04:13:47 +00008801 // Used for diagnostic printout.
8802 enum {
8803 LiteralConstant = 0,
8804 CXXBoolLiteralTrue,
8805 CXXBoolLiteralFalse
8806 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00008807
Richard Trieu0f097742014-04-04 04:13:47 +00008808 if (!OtherIsBooleanType) {
8809 QualType ConstantT = Constant->getType();
8810 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00008811
Richard Trieu0f097742014-04-04 04:13:47 +00008812 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
Roman Lebedev6de129e2017-10-15 20:13:17 +00008813 return false;
Richard Trieu0f097742014-04-04 04:13:47 +00008814 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
8815 "comparison with non-integer type");
8816
8817 bool ConstantSigned = ConstantT->isSignedIntegerType();
8818 bool CommonSigned = CommonT->isSignedIntegerType();
8819
8820 bool EqualityOnly = false;
8821
8822 if (CommonSigned) {
8823 // The common type is signed, therefore no signed to unsigned conversion.
8824 if (!OtherRange.NonNegative) {
8825 // Check that the constant is representable in type OtherT.
8826 if (ConstantSigned) {
8827 if (OtherWidth >= Value.getMinSignedBits())
Roman Lebedev6de129e2017-10-15 20:13:17 +00008828 return false;
Richard Trieu0f097742014-04-04 04:13:47 +00008829 } else { // !ConstantSigned
8830 if (OtherWidth >= Value.getActiveBits() + 1)
Roman Lebedev6de129e2017-10-15 20:13:17 +00008831 return false;
Richard Trieu0f097742014-04-04 04:13:47 +00008832 }
8833 } else { // !OtherSigned
8834 // Check that the constant is representable in type OtherT.
8835 // Negative values are out of range.
8836 if (ConstantSigned) {
8837 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
Roman Lebedev6de129e2017-10-15 20:13:17 +00008838 return false;
Richard Trieu0f097742014-04-04 04:13:47 +00008839 } else { // !ConstantSigned
8840 if (OtherWidth >= Value.getActiveBits())
Roman Lebedev6de129e2017-10-15 20:13:17 +00008841 return false;
Richard Trieu0f097742014-04-04 04:13:47 +00008842 }
Richard Trieu560910c2012-11-14 22:50:24 +00008843 }
Richard Trieu0f097742014-04-04 04:13:47 +00008844 } else { // !CommonSigned
8845 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00008846 if (OtherWidth >= Value.getActiveBits())
Roman Lebedev6de129e2017-10-15 20:13:17 +00008847 return false;
Craig Toppercf360162014-06-18 05:13:11 +00008848 } else { // OtherSigned
8849 assert(!ConstantSigned &&
8850 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00008851 // Check to see if the constant is representable in OtherT.
8852 if (OtherWidth > Value.getActiveBits())
Roman Lebedev6de129e2017-10-15 20:13:17 +00008853 return false;
Richard Trieu0f097742014-04-04 04:13:47 +00008854 // Check to see if the constant is equivalent to a negative value
8855 // cast to CommonT.
8856 if (S.Context.getIntWidth(ConstantT) ==
8857 S.Context.getIntWidth(CommonT) &&
8858 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
Roman Lebedev6de129e2017-10-15 20:13:17 +00008859 return false;
Richard Trieu0f097742014-04-04 04:13:47 +00008860 // The constant value rests between values that OtherT can represent
8861 // after conversion. Relational comparison still works, but equality
8862 // comparisons will be tautological.
8863 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00008864 }
8865 }
Richard Trieu0f097742014-04-04 04:13:47 +00008866
8867 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
8868
8869 if (op == BO_EQ || op == BO_NE) {
8870 IsTrue = op == BO_NE;
8871 } else if (EqualityOnly) {
Roman Lebedev6de129e2017-10-15 20:13:17 +00008872 return false;
Richard Trieu0f097742014-04-04 04:13:47 +00008873 } else if (RhsConstant) {
8874 if (op == BO_GT || op == BO_GE)
8875 IsTrue = !PositiveConstant;
8876 else // op == BO_LT || op == BO_LE
8877 IsTrue = PositiveConstant;
8878 } else {
8879 if (op == BO_LT || op == BO_LE)
8880 IsTrue = !PositiveConstant;
8881 else // op == BO_GT || op == BO_GE
8882 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00008883 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008884 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00008885 // Other isKnownToHaveBooleanValue
8886 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
8887 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
8888 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
8889
8890 static const struct LinkedConditions {
8891 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
8892 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
8893 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
8894 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
8895 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
8896 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
8897
8898 } TruthTable = {
8899 // Constant on LHS. | Constant on RHS. |
8900 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
8901 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
8902 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
8903 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
8904 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
8905 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
8906 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
8907 };
8908
8909 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
8910
8911 enum ConstantValue ConstVal = Zero;
8912 if (Value.isUnsigned() || Value.isNonNegative()) {
8913 if (Value == 0) {
8914 LiteralOrBoolConstant =
8915 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
8916 ConstVal = Zero;
8917 } else if (Value == 1) {
8918 LiteralOrBoolConstant =
8919 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
8920 ConstVal = One;
8921 } else {
8922 LiteralOrBoolConstant = LiteralConstant;
8923 ConstVal = GT_One;
8924 }
8925 } else {
8926 ConstVal = LT_Zero;
8927 }
8928
8929 CompareBoolWithConstantResult CmpRes;
8930
8931 switch (op) {
8932 case BO_LT:
8933 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
8934 break;
8935 case BO_GT:
8936 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
8937 break;
8938 case BO_LE:
8939 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
8940 break;
8941 case BO_GE:
8942 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
8943 break;
8944 case BO_EQ:
8945 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
8946 break;
8947 case BO_NE:
8948 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
8949 break;
8950 default:
8951 CmpRes = Unkwn;
8952 break;
8953 }
8954
8955 if (CmpRes == AFals) {
8956 IsTrue = false;
8957 } else if (CmpRes == ATrue) {
8958 IsTrue = true;
8959 } else {
Roman Lebedev6de129e2017-10-15 20:13:17 +00008960 return false;
Richard Trieu0f097742014-04-04 04:13:47 +00008961 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008962 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008963
8964 // If this is a comparison to an enum constant, include that
8965 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00008966 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008967 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8968 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8969
8970 SmallString<64> PrettySourceValue;
8971 llvm::raw_svector_ostream OS(PrettySourceValue);
8972 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00008973 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008974 else
8975 OS << Value;
8976
Richard Trieu0f097742014-04-04 04:13:47 +00008977 S.DiagRuntimeBehavior(
8978 E->getOperatorLoc(), E,
8979 S.PDiag(diag::warn_out_of_range_compare)
8980 << OS.str() << LiteralOrBoolConstant
8981 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
8982 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Roman Lebedev6de129e2017-10-15 20:13:17 +00008983
8984 return true;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008985}
8986
John McCallcc7e5bf2010-05-06 08:58:33 +00008987/// Analyze the operands of the given comparison. Implements the
8988/// fallback case from AnalyzeComparison.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008989static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00008990 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8991 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00008992}
John McCall263a48b2010-01-04 23:31:57 +00008993
John McCallca01b222010-01-04 23:21:16 +00008994/// \brief Implements -Wsign-compare.
8995///
Richard Trieu82402a02011-09-15 21:56:47 +00008996/// \param E the binary operator to check for warnings
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008997static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008998 // The type the comparison is being performed in.
8999 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00009000
9001 // Only analyze comparison operators where both sides have been converted to
9002 // the same type.
9003 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
9004 return AnalyzeImpConvsInComparison(S, E);
9005
9006 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00009007 if (E->isValueDependent())
9008 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00009009
Roman Lebedev6de129e2017-10-15 20:13:17 +00009010 Expr *LHS = E->getLHS();
9011 Expr *RHS = E->getRHS();
9012
Fariborz Jahanianb1885422012-09-18 17:37:21 +00009013 if (T->isIntegralType(S.Context)) {
9014 llvm::APSInt RHSValue;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00009015 llvm::APSInt LHSValue;
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009016
Roman Lebedev6de129e2017-10-15 20:13:17 +00009017 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
9018 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
Roman Lebedevbd1fc222017-10-12 20:16:51 +00009019
Roman Lebedev6de129e2017-10-15 20:13:17 +00009020 // We don't care about expressions whose result is a constant.
9021 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
9022 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6f405db2017-10-12 22:03:20 +00009023
Roman Lebedev6de129e2017-10-15 20:13:17 +00009024 // We only care about expressions where just one side is literal
9025 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
9026 // Is the constant on the RHS or LHS?
9027 const bool RhsConstant = IsRHSIntegralLiteral;
9028 Expr *Const = RhsConstant ? RHS : LHS;
9029 Expr *Other = RhsConstant ? LHS : RHS;
9030 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
9031
9032 // Check whether an integer constant comparison results in a value
9033 // of 'true' or 'false'.
9034
9035 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
9036 return AnalyzeImpConvsInComparison(S, E);
9037
9038 if (DiagnoseOutOfRangeComparison(S, E, Const, Other, Value, RhsConstant))
9039 return AnalyzeImpConvsInComparison(S, E);
9040 }
9041 }
9042
9043 if (!T->hasUnsignedIntegerRepresentation()) {
9044 // We don't do anything special if this isn't an unsigned integral
9045 // comparison: we're only interested in integral comparisons, and
9046 // signed comparisons only happen in cases we don't care to warn about.
Roman Lebedev6f405db2017-10-12 22:03:20 +00009047 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6de129e2017-10-15 20:13:17 +00009048 }
9049
9050 LHS = LHS->IgnoreParenImpCasts();
9051 RHS = RHS->IgnoreParenImpCasts();
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009052
John McCallcc7e5bf2010-05-06 08:58:33 +00009053 // Check to see if one of the (unmodified) operands is of different
9054 // signedness.
9055 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00009056 if (LHS->getType()->hasSignedIntegerRepresentation()) {
9057 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00009058 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00009059 signedOperand = LHS;
9060 unsignedOperand = RHS;
9061 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
9062 signedOperand = RHS;
9063 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00009064 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00009065 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00009066 }
9067
John McCallcc7e5bf2010-05-06 08:58:33 +00009068 // Otherwise, calculate the effective range of the signed operand.
9069 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00009070
John McCallcc7e5bf2010-05-06 08:58:33 +00009071 // Go ahead and analyze implicit conversions in the operands. Note
9072 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00009073 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
9074 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00009075
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009076 // If the signed range is non-negative, -Wsign-compare won't fire.
John McCallcc7e5bf2010-05-06 08:58:33 +00009077 if (signedRange.NonNegative)
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009078 return;
John McCallca01b222010-01-04 23:21:16 +00009079
9080 // For (in)equality comparisons, if the unsigned operand is a
9081 // constant which cannot collide with a overflowed signed operand,
9082 // then reinterpreting the signed operand as unsigned will not
9083 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00009084 if (E->isEqualityOp()) {
9085 unsigned comparisonWidth = S.Context.getIntWidth(T);
9086 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00009087
John McCallcc7e5bf2010-05-06 08:58:33 +00009088 // We should never be unable to prove that the unsigned operand is
9089 // non-negative.
9090 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
9091
9092 if (unsignedRange.Width < comparisonWidth)
9093 return;
9094 }
9095
Douglas Gregorbfb4a212012-05-01 01:53:49 +00009096 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
9097 S.PDiag(diag::warn_mixed_sign_comparison)
9098 << LHS->getType() << RHS->getType()
9099 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00009100}
9101
John McCall1f425642010-11-11 03:21:53 +00009102/// Analyzes an attempt to assign the given value to a bitfield.
9103///
9104/// Returns true if there was something fishy about the attempt.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009105static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
9106 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00009107 assert(Bitfield->isBitField());
9108 if (Bitfield->isInvalidDecl())
9109 return false;
9110
John McCalldeebbcf2010-11-11 05:33:51 +00009111 // White-list bool bitfields.
Reid Klecknerad425622016-11-16 23:40:00 +00009112 QualType BitfieldType = Bitfield->getType();
9113 if (BitfieldType->isBooleanType())
9114 return false;
9115
9116 if (BitfieldType->isEnumeralType()) {
9117 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
9118 // If the underlying enum type was not explicitly specified as an unsigned
9119 // type and the enum contain only positive values, MSVC++ will cause an
9120 // inconsistency by storing this as a signed type.
9121 if (S.getLangOpts().CPlusPlus11 &&
9122 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
9123 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
9124 BitfieldEnumDecl->getNumNegativeBits() == 0) {
9125 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
9126 << BitfieldEnumDecl->getNameAsString();
9127 }
9128 }
9129
John McCalldeebbcf2010-11-11 05:33:51 +00009130 if (Bitfield->getType()->isBooleanType())
9131 return false;
9132
Douglas Gregor789adec2011-02-04 13:09:01 +00009133 // Ignore value- or type-dependent expressions.
9134 if (Bitfield->getBitWidth()->isValueDependent() ||
9135 Bitfield->getBitWidth()->isTypeDependent() ||
9136 Init->isValueDependent() ||
9137 Init->isTypeDependent())
9138 return false;
9139
John McCall1f425642010-11-11 03:21:53 +00009140 Expr *OriginalInit = Init->IgnoreParenImpCasts();
Reid Kleckner329f24d2017-03-14 18:01:02 +00009141 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00009142
Richard Smith5fab0c92011-12-28 19:48:30 +00009143 llvm::APSInt Value;
Reid Kleckner329f24d2017-03-14 18:01:02 +00009144 if (!OriginalInit->EvaluateAsInt(Value, S.Context,
9145 Expr::SE_AllowSideEffects)) {
9146 // The RHS is not constant. If the RHS has an enum type, make sure the
9147 // bitfield is wide enough to hold all the values of the enum without
9148 // truncation.
9149 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
9150 EnumDecl *ED = EnumTy->getDecl();
9151 bool SignedBitfield = BitfieldType->isSignedIntegerType();
9152
9153 // Enum types are implicitly signed on Windows, so check if there are any
9154 // negative enumerators to see if the enum was intended to be signed or
9155 // not.
9156 bool SignedEnum = ED->getNumNegativeBits() > 0;
9157
9158 // Check for surprising sign changes when assigning enum values to a
9159 // bitfield of different signedness. If the bitfield is signed and we
9160 // have exactly the right number of bits to store this unsigned enum,
9161 // suggest changing the enum to an unsigned type. This typically happens
9162 // on Windows where unfixed enums always use an underlying type of 'int'.
9163 unsigned DiagID = 0;
9164 if (SignedEnum && !SignedBitfield) {
9165 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
9166 } else if (SignedBitfield && !SignedEnum &&
9167 ED->getNumPositiveBits() == FieldWidth) {
9168 DiagID = diag::warn_signed_bitfield_enum_conversion;
9169 }
9170
9171 if (DiagID) {
9172 S.Diag(InitLoc, DiagID) << Bitfield << ED;
9173 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
9174 SourceRange TypeRange =
9175 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
9176 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
9177 << SignedEnum << TypeRange;
9178 }
9179
9180 // Compute the required bitwidth. If the enum has negative values, we need
9181 // one more bit than the normal number of positive bits to represent the
9182 // sign bit.
9183 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
9184 ED->getNumNegativeBits())
9185 : ED->getNumPositiveBits();
9186
9187 // Check the bitwidth.
9188 if (BitsNeeded > FieldWidth) {
9189 Expr *WidthExpr = Bitfield->getBitWidth();
9190 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
9191 << Bitfield << ED;
9192 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
9193 << BitsNeeded << ED << WidthExpr->getSourceRange();
9194 }
9195 }
9196
John McCall1f425642010-11-11 03:21:53 +00009197 return false;
Reid Kleckner329f24d2017-03-14 18:01:02 +00009198 }
John McCall1f425642010-11-11 03:21:53 +00009199
John McCall1f425642010-11-11 03:21:53 +00009200 unsigned OriginalWidth = Value.getBitWidth();
John McCall1f425642010-11-11 03:21:53 +00009201
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00009202 if (!Value.isSigned() || Value.isNegative())
Richard Trieu7561ed02016-08-05 02:39:30 +00009203 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00009204 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
9205 OriginalWidth = Value.getMinSignedBits();
Richard Trieu7561ed02016-08-05 02:39:30 +00009206
John McCall1f425642010-11-11 03:21:53 +00009207 if (OriginalWidth <= FieldWidth)
9208 return false;
9209
Eli Friedmanc267a322012-01-26 23:11:39 +00009210 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00009211 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Reid Klecknerad425622016-11-16 23:40:00 +00009212 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00009213
Eli Friedmanc267a322012-01-26 23:11:39 +00009214 // Check whether the stored value is equal to the original value.
9215 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00009216 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00009217 return false;
9218
Eli Friedmanc267a322012-01-26 23:11:39 +00009219 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00009220 // therefore don't strictly fit into a signed bitfield of width 1.
9221 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00009222 return false;
9223
John McCall1f425642010-11-11 03:21:53 +00009224 std::string PrettyValue = Value.toString(10);
9225 std::string PrettyTrunc = TruncatedValue.toString(10);
9226
9227 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
9228 << PrettyValue << PrettyTrunc << OriginalInit->getType()
9229 << Init->getSourceRange();
9230
9231 return true;
9232}
9233
John McCalld2a53122010-11-09 23:24:47 +00009234/// Analyze the given simple or compound assignment for warning-worthy
9235/// operations.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009236static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00009237 // Just recurse on the LHS.
9238 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9239
9240 // We want to recurse on the RHS as normal unless we're assigning to
9241 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00009242 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009243 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00009244 E->getOperatorLoc())) {
9245 // Recurse, ignoring any implicit conversions on the RHS.
9246 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
9247 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00009248 }
9249 }
9250
9251 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9252}
9253
John McCall263a48b2010-01-04 23:31:57 +00009254/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009255static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
9256 SourceLocation CContext, unsigned diag,
9257 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00009258 if (pruneControlFlow) {
9259 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9260 S.PDiag(diag)
9261 << SourceType << T << E->getSourceRange()
9262 << SourceRange(CContext));
9263 return;
9264 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00009265 S.Diag(E->getExprLoc(), diag)
9266 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
9267}
9268
Chandler Carruth7f3654f2011-04-05 06:47:57 +00009269/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009270static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
9271 SourceLocation CContext,
9272 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00009273 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00009274}
9275
Richard Trieube234c32016-04-21 21:04:55 +00009276
9277/// Diagnose an implicit cast from a floating point value to an integer value.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009278static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
9279 SourceLocation CContext) {
Richard Trieube234c32016-04-21 21:04:55 +00009280 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
Richard Smith51ec0cf2017-02-21 01:17:38 +00009281 const bool PruneWarnings = S.inTemplateInstantiation();
Richard Trieube234c32016-04-21 21:04:55 +00009282
9283 Expr *InnerE = E->IgnoreParenImpCasts();
9284 // We also want to warn on, e.g., "int i = -1.234"
9285 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
9286 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
9287 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
9288
9289 const bool IsLiteral =
9290 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
9291
9292 llvm::APFloat Value(0.0);
9293 bool IsConstant =
9294 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
9295 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00009296 return DiagnoseImpCast(S, E, T, CContext,
9297 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00009298 }
9299
Chandler Carruth016ef402011-04-10 08:36:24 +00009300 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00009301
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00009302 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
9303 T->hasUnsignedIntegerRepresentation());
Richard Trieube234c32016-04-21 21:04:55 +00009304 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
9305 &isExact) == llvm::APFloat::opOK &&
Richard Trieu891f0f12016-04-22 22:14:32 +00009306 isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00009307 if (IsLiteral) return;
9308 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
9309 PruneWarnings);
9310 }
9311
9312 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00009313 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00009314 // Warn on floating point literal to integer.
9315 DiagID = diag::warn_impcast_literal_float_to_integer;
9316 } else if (IntegerValue == 0) {
9317 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
9318 return DiagnoseImpCast(S, E, T, CContext,
9319 diag::warn_impcast_float_integer, PruneWarnings);
9320 }
9321 // Warn on non-zero to zero conversion.
9322 DiagID = diag::warn_impcast_float_to_integer_zero;
9323 } else {
9324 if (IntegerValue.isUnsigned()) {
9325 if (!IntegerValue.isMaxValue()) {
9326 return DiagnoseImpCast(S, E, T, CContext,
9327 diag::warn_impcast_float_integer, PruneWarnings);
9328 }
9329 } else { // IntegerValue.isSigned()
9330 if (!IntegerValue.isMaxSignedValue() &&
9331 !IntegerValue.isMinSignedValue()) {
9332 return DiagnoseImpCast(S, E, T, CContext,
9333 diag::warn_impcast_float_integer, PruneWarnings);
9334 }
9335 }
9336 // Warn on evaluatable floating point expression to integer conversion.
9337 DiagID = diag::warn_impcast_float_to_integer;
9338 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009339
Eli Friedman07185912013-08-29 23:44:43 +00009340 // FIXME: Force the precision of the source value down so we don't print
9341 // digits which are usually useless (we don't really care here if we
9342 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
9343 // would automatically print the shortest representation, but it's a bit
9344 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00009345 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00009346 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
9347 precision = (precision * 59 + 195) / 196;
9348 Value.toString(PrettySourceValue, precision);
9349
David Blaikie9b88cc02012-05-15 17:18:27 +00009350 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00009351 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00009352 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00009353 else
David Blaikie9b88cc02012-05-15 17:18:27 +00009354 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00009355
Richard Trieube234c32016-04-21 21:04:55 +00009356 if (PruneWarnings) {
9357 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9358 S.PDiag(DiagID)
9359 << E->getType() << T.getUnqualifiedType()
9360 << PrettySourceValue << PrettyTargetValue
9361 << E->getSourceRange() << SourceRange(CContext));
9362 } else {
9363 S.Diag(E->getExprLoc(), DiagID)
9364 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
9365 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
9366 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009367}
9368
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009369static std::string PrettyPrintInRange(const llvm::APSInt &Value,
9370 IntRange Range) {
John McCall18a2c2c2010-11-09 22:22:12 +00009371 if (!Range.Width) return "0";
9372
9373 llvm::APSInt ValueInRange = Value;
9374 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00009375 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00009376 return ValueInRange.toString(10);
9377}
9378
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009379static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009380 if (!isa<ImplicitCastExpr>(Ex))
9381 return false;
9382
9383 Expr *InnerE = Ex->IgnoreParenImpCasts();
9384 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
9385 const Type *Source =
9386 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
9387 if (Target->isDependentType())
9388 return false;
9389
9390 const BuiltinType *FloatCandidateBT =
9391 dyn_cast<BuiltinType>(ToBool ? Source : Target);
9392 const Type *BoolCandidateType = ToBool ? Target : Source;
9393
9394 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
9395 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
9396}
9397
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009398static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
9399 SourceLocation CC) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009400 unsigned NumArgs = TheCall->getNumArgs();
9401 for (unsigned i = 0; i < NumArgs; ++i) {
9402 Expr *CurrA = TheCall->getArg(i);
9403 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
9404 continue;
9405
9406 bool IsSwapped = ((i > 0) &&
9407 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
9408 IsSwapped |= ((i < (NumArgs - 1)) &&
9409 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
9410 if (IsSwapped) {
9411 // Warn on this floating-point to bool conversion.
9412 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
9413 CurrA->getType(), CC,
9414 diag::warn_impcast_floating_point_to_bool);
9415 }
9416 }
9417}
9418
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009419static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
9420 SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00009421 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
9422 E->getExprLoc()))
9423 return;
9424
Richard Trieu09d6b802016-01-08 23:35:06 +00009425 // Don't warn on functions which have return type nullptr_t.
9426 if (isa<CallExpr>(E))
9427 return;
9428
Richard Trieu5b993502014-10-15 03:42:06 +00009429 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
9430 const Expr::NullPointerConstantKind NullKind =
9431 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
9432 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
9433 return;
9434
9435 // Return if target type is a safe conversion.
9436 if (T->isAnyPointerType() || T->isBlockPointerType() ||
9437 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
9438 return;
9439
9440 SourceLocation Loc = E->getSourceRange().getBegin();
9441
Richard Trieu0a5e1662016-02-13 00:58:53 +00009442 // Venture through the macro stacks to get to the source of macro arguments.
9443 // The new location is a better location than the complete location that was
9444 // passed in.
9445 while (S.SourceMgr.isMacroArgExpansion(Loc))
9446 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
9447
9448 while (S.SourceMgr.isMacroArgExpansion(CC))
9449 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
9450
Richard Trieu5b993502014-10-15 03:42:06 +00009451 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00009452 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
9453 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
9454 Loc, S.SourceMgr, S.getLangOpts());
9455 if (MacroName == "NULL")
9456 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00009457 }
9458
9459 // Only warn if the null and context location are in the same macro expansion.
9460 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
9461 return;
9462
9463 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009464 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
Richard Trieu5b993502014-10-15 03:42:06 +00009465 << FixItHint::CreateReplacement(Loc,
9466 S.getFixItZeroLiteralForType(T, Loc));
9467}
9468
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009469static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9470 ObjCArrayLiteral *ArrayLiteral);
9471
9472static void
9473checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9474 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00009475
9476/// Check a single element within a collection literal against the
9477/// target element type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009478static void checkObjCCollectionLiteralElement(Sema &S,
9479 QualType TargetElementType,
9480 Expr *Element,
9481 unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009482 // Skip a bitcast to 'id' or qualified 'id'.
9483 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
9484 if (ICE->getCastKind() == CK_BitCast &&
9485 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
9486 Element = ICE->getSubExpr();
9487 }
9488
9489 QualType ElementType = Element->getType();
9490 ExprResult ElementResult(Element);
9491 if (ElementType->getAs<ObjCObjectPointerType>() &&
9492 S.CheckSingleAssignmentConstraints(TargetElementType,
9493 ElementResult,
9494 false, false)
9495 != Sema::Compatible) {
9496 S.Diag(Element->getLocStart(),
9497 diag::warn_objc_collection_literal_element)
9498 << ElementType << ElementKind << TargetElementType
9499 << Element->getSourceRange();
9500 }
9501
9502 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
9503 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
9504 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
9505 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
9506}
9507
9508/// Check an Objective-C array literal being converted to the given
9509/// target type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009510static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9511 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009512 if (!S.NSArrayDecl)
9513 return;
9514
9515 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9516 if (!TargetObjCPtr)
9517 return;
9518
9519 if (TargetObjCPtr->isUnspecialized() ||
9520 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9521 != S.NSArrayDecl->getCanonicalDecl())
9522 return;
9523
9524 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9525 if (TypeArgs.size() != 1)
9526 return;
9527
9528 QualType TargetElementType = TypeArgs[0];
9529 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
9530 checkObjCCollectionLiteralElement(S, TargetElementType,
9531 ArrayLiteral->getElement(I),
9532 0);
9533 }
9534}
9535
9536/// Check an Objective-C dictionary literal being converted to the given
9537/// target type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009538static void
9539checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9540 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009541 if (!S.NSDictionaryDecl)
9542 return;
9543
9544 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9545 if (!TargetObjCPtr)
9546 return;
9547
9548 if (TargetObjCPtr->isUnspecialized() ||
9549 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9550 != S.NSDictionaryDecl->getCanonicalDecl())
9551 return;
9552
9553 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9554 if (TypeArgs.size() != 2)
9555 return;
9556
9557 QualType TargetKeyType = TypeArgs[0];
9558 QualType TargetObjectType = TypeArgs[1];
9559 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
9560 auto Element = DictionaryLiteral->getKeyValueElement(I);
9561 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
9562 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
9563 }
9564}
9565
Richard Trieufc404c72016-02-05 23:02:38 +00009566// Helper function to filter out cases for constant width constant conversion.
9567// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009568static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
9569 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00009570 // If initializing from a constant, and the constant starts with '0',
9571 // then it is a binary, octal, or hexadecimal. Allow these constants
9572 // to fill all the bits, even if there is a sign change.
9573 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
9574 const char FirstLiteralCharacter =
9575 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
9576 if (FirstLiteralCharacter == '0')
9577 return false;
9578 }
9579
9580 // If the CC location points to a '{', and the type is char, then assume
9581 // assume it is an array initialization.
9582 if (CC.isValid() && T->isCharType()) {
9583 const char FirstContextCharacter =
9584 S.getSourceManager().getCharacterData(CC)[0];
9585 if (FirstContextCharacter == '{')
9586 return false;
9587 }
9588
9589 return true;
9590}
9591
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009592static void
9593CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
9594 bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009595 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00009596
John McCallcc7e5bf2010-05-06 08:58:33 +00009597 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
9598 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
9599 if (Source == Target) return;
9600 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00009601
Chandler Carruthc22845a2011-07-26 05:40:03 +00009602 // If the conversion context location is invalid don't complain. We also
9603 // don't want to emit a warning if the issue occurs from the expansion of
9604 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
9605 // delay this check as long as possible. Once we detect we are in that
9606 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009607 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00009608 return;
9609
Richard Trieu021baa32011-09-23 20:10:00 +00009610 // Diagnose implicit casts to bool.
9611 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
9612 if (isa<StringLiteral>(E))
9613 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00009614 // and expressions, for instance, assert(0 && "error here"), are
9615 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00009616 return DiagnoseImpCast(S, E, T, CC,
9617 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00009618 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
9619 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
9620 // This covers the literal expressions that evaluate to Objective-C
9621 // objects.
9622 return DiagnoseImpCast(S, E, T, CC,
9623 diag::warn_impcast_objective_c_literal_to_bool);
9624 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00009625 if (Source->isPointerType() || Source->canDecayToPointerType()) {
9626 // Warn on pointer to bool conversion that is always true.
9627 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
9628 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00009629 }
Richard Trieu021baa32011-09-23 20:10:00 +00009630 }
John McCall263a48b2010-01-04 23:31:57 +00009631
Douglas Gregor5054cb02015-07-07 03:58:22 +00009632 // Check implicit casts from Objective-C collection literals to specialized
9633 // collection types, e.g., NSArray<NSString *> *.
9634 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
9635 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
9636 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
9637 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
9638
John McCall263a48b2010-01-04 23:31:57 +00009639 // Strip vector types.
9640 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009641 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009642 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009643 return;
John McCallacf0ee52010-10-08 02:01:28 +00009644 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009645 }
Chris Lattneree7286f2011-06-14 04:51:15 +00009646
9647 // If the vector cast is cast between two vectors of the same size, it is
9648 // a bitcast, not a conversion.
9649 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
9650 return;
John McCall263a48b2010-01-04 23:31:57 +00009651
9652 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
9653 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
9654 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00009655 if (auto VecTy = dyn_cast<VectorType>(Target))
9656 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00009657
9658 // Strip complex types.
9659 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009660 if (!isa<ComplexType>(Target)) {
Tim Northover02416372017-08-08 23:18:05 +00009661 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009662 return;
9663
Tim Northover02416372017-08-08 23:18:05 +00009664 return DiagnoseImpCast(S, E, T, CC,
9665 S.getLangOpts().CPlusPlus
9666 ? diag::err_impcast_complex_scalar
9667 : diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009668 }
John McCall263a48b2010-01-04 23:31:57 +00009669
9670 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
9671 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
9672 }
9673
9674 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
9675 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
9676
9677 // If the source is floating point...
9678 if (SourceBT && SourceBT->isFloatingPoint()) {
9679 // ...and the target is floating point...
9680 if (TargetBT && TargetBT->isFloatingPoint()) {
9681 // ...then warn if we're dropping FP rank.
9682
9683 // Builtin FP kinds are ordered by increasing FP rank.
9684 if (SourceBT->getKind() > TargetBT->getKind()) {
9685 // Don't warn about float constants that are precisely
9686 // representable in the target type.
9687 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00009688 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00009689 // Value might be a float, a float vector, or a float complex.
9690 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00009691 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9692 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00009693 return;
9694 }
9695
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009696 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009697 return;
9698
John McCallacf0ee52010-10-08 02:01:28 +00009699 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00009700 }
9701 // ... or possibly if we're increasing rank, too
9702 else if (TargetBT->getKind() > SourceBT->getKind()) {
9703 if (S.SourceMgr.isInSystemMacro(CC))
9704 return;
9705
9706 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00009707 }
9708 return;
9709 }
9710
Richard Trieube234c32016-04-21 21:04:55 +00009711 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00009712 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009713 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009714 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00009715
Richard Trieube234c32016-04-21 21:04:55 +00009716 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00009717 }
John McCall263a48b2010-01-04 23:31:57 +00009718
Richard Smith54894fd2015-12-30 01:06:52 +00009719 // Detect the case where a call result is converted from floating-point to
9720 // to bool, and the final argument to the call is converted from bool, to
9721 // discover this typo:
9722 //
9723 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
9724 //
9725 // FIXME: This is an incredibly special case; is there some more general
9726 // way to detect this class of misplaced-parentheses bug?
9727 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009728 // Check last argument of function call to see if it is an
9729 // implicit cast from a type matching the type the result
9730 // is being cast to.
9731 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00009732 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009733 Expr *LastA = CEx->getArg(NumArgs - 1);
9734 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00009735 if (isa<ImplicitCastExpr>(LastA) &&
9736 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009737 // Warn on this floating-point to bool conversion
9738 DiagnoseImpCast(S, E, T, CC,
9739 diag::warn_impcast_floating_point_to_bool);
9740 }
9741 }
9742 }
John McCall263a48b2010-01-04 23:31:57 +00009743 return;
9744 }
9745
Richard Trieu5b993502014-10-15 03:42:06 +00009746 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00009747
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00009748 S.DiscardMisalignedMemberAddress(Target, E);
9749
David Blaikie9366d2b2012-06-19 21:19:06 +00009750 if (!Source->isIntegerType() || !Target->isIntegerType())
9751 return;
9752
David Blaikie7555b6a2012-05-15 16:56:36 +00009753 // TODO: remove this early return once the false positives for constant->bool
9754 // in templates, macros, etc, are reduced or removed.
9755 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9756 return;
9757
John McCallcc7e5bf2010-05-06 08:58:33 +00009758 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00009759 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00009760
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009761 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00009762 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009763 // TODO: this should happen for bitfield stores, too.
9764 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00009765 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009766 if (S.SourceMgr.isInSystemMacro(CC))
9767 return;
9768
John McCall18a2c2c2010-11-09 22:22:12 +00009769 std::string PrettySourceValue = Value.toString(10);
9770 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009771
Ted Kremenek33ba9952011-10-22 02:37:33 +00009772 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9773 S.PDiag(diag::warn_impcast_integer_precision_constant)
9774 << PrettySourceValue << PrettyTargetValue
9775 << E->getType() << T << E->getSourceRange()
9776 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00009777 return;
9778 }
9779
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009780 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9781 if (S.SourceMgr.isInSystemMacro(CC))
9782 return;
9783
David Blaikie9455da02012-04-12 22:40:54 +00009784 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00009785 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9786 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00009787 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00009788 }
9789
Richard Trieudcb55572016-01-29 23:51:16 +00009790 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9791 SourceRange.NonNegative && Source->isSignedIntegerType()) {
9792 // Warn when doing a signed to signed conversion, warn if the positive
9793 // source value is exactly the width of the target type, which will
9794 // cause a negative value to be stored.
9795
9796 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00009797 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9798 !S.SourceMgr.isInSystemMacro(CC)) {
9799 if (isSameWidthConstantConversion(S, E, T, CC)) {
9800 std::string PrettySourceValue = Value.toString(10);
9801 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00009802
Richard Trieufc404c72016-02-05 23:02:38 +00009803 S.DiagRuntimeBehavior(
9804 E->getExprLoc(), E,
9805 S.PDiag(diag::warn_impcast_integer_precision_constant)
9806 << PrettySourceValue << PrettyTargetValue << E->getType() << T
9807 << E->getSourceRange() << clang::SourceRange(CC));
9808 return;
Richard Trieudcb55572016-01-29 23:51:16 +00009809 }
9810 }
Richard Trieufc404c72016-02-05 23:02:38 +00009811
Richard Trieudcb55572016-01-29 23:51:16 +00009812 // Fall through for non-constants to give a sign conversion warning.
9813 }
9814
John McCallcc7e5bf2010-05-06 08:58:33 +00009815 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9816 (!TargetRange.NonNegative && SourceRange.NonNegative &&
9817 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009818 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009819 return;
9820
John McCallcc7e5bf2010-05-06 08:58:33 +00009821 unsigned DiagID = diag::warn_impcast_integer_sign;
9822
9823 // Traditionally, gcc has warned about this under -Wsign-compare.
9824 // We also want to warn about it in -Wconversion.
9825 // So if -Wconversion is off, use a completely identical diagnostic
9826 // in the sign-compare group.
9827 // The conditional-checking code will
9828 if (ICContext) {
9829 DiagID = diag::warn_impcast_integer_sign_conditional;
9830 *ICContext = true;
9831 }
9832
John McCallacf0ee52010-10-08 02:01:28 +00009833 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00009834 }
9835
Douglas Gregora78f1932011-02-22 02:45:07 +00009836 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00009837 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9838 // type, to give us better diagnostics.
9839 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00009840 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00009841 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9842 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9843 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9844 SourceType = S.Context.getTypeDeclType(Enum);
9845 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9846 }
9847 }
9848
Douglas Gregora78f1932011-02-22 02:45:07 +00009849 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9850 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00009851 if (SourceEnum->getDecl()->hasNameForLinkage() &&
9852 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009853 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009854 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009855 return;
9856
Douglas Gregor364f7db2011-03-12 00:14:31 +00009857 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00009858 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009859 }
John McCall263a48b2010-01-04 23:31:57 +00009860}
9861
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009862static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9863 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009864
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009865static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
9866 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009867 E = E->IgnoreParenImpCasts();
9868
9869 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00009870 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009871
John McCallacf0ee52010-10-08 02:01:28 +00009872 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009873 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009874 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00009875}
9876
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009877static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9878 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00009879 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00009880
9881 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00009882 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9883 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009884
9885 // If -Wconversion would have warned about either of the candidates
9886 // for a signedness conversion to the context type...
9887 if (!Suspicious) return;
9888
9889 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009890 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00009891 return;
9892
John McCallcc7e5bf2010-05-06 08:58:33 +00009893 // ...then check whether it would have warned about either of the
9894 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00009895 if (E->getType() == T) return;
9896
9897 Suspicious = false;
9898 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
9899 E->getType(), CC, &Suspicious);
9900 if (!Suspicious)
9901 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00009902 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009903}
9904
Richard Trieu65724892014-11-15 06:37:39 +00009905/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9906/// Input argument E is a logical expression.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009907static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00009908 if (S.getLangOpts().Bool)
9909 return;
9910 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
9911}
9912
John McCallcc7e5bf2010-05-06 08:58:33 +00009913/// AnalyzeImplicitConversions - Find and report any interesting
9914/// implicit conversions in the given expression. There are a couple
9915/// of competing diagnostics here, -Wconversion and -Wsign-compare.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009916static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
9917 SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00009918 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00009919 Expr *E = OrigE->IgnoreParenImpCasts();
9920
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00009921 if (E->isTypeDependent() || E->isValueDependent())
9922 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00009923
John McCallcc7e5bf2010-05-06 08:58:33 +00009924 // For conditional operators, we analyze the arguments as if they
9925 // were being fed directly into the output.
9926 if (isa<ConditionalOperator>(E)) {
9927 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00009928 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009929 return;
9930 }
9931
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009932 // Check implicit argument conversions for function calls.
9933 if (CallExpr *Call = dyn_cast<CallExpr>(E))
9934 CheckImplicitArgumentConversions(S, Call, CC);
9935
John McCallcc7e5bf2010-05-06 08:58:33 +00009936 // Go ahead and check any implicit conversions we might have skipped.
9937 // The non-canonical typecheck is just an optimization;
9938 // CheckImplicitConversion will filter out dead implicit conversions.
9939 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009940 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009941
9942 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00009943
9944 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
9945 // The bound subexpressions in a PseudoObjectExpr are not reachable
9946 // as transitive children.
9947 // FIXME: Use a more uniform representation for this.
9948 for (auto *SE : POE->semantics())
9949 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9950 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00009951 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00009952
John McCallcc7e5bf2010-05-06 08:58:33 +00009953 // Skip past explicit casts.
9954 if (isa<ExplicitCastExpr>(E)) {
9955 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00009956 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009957 }
9958
John McCalld2a53122010-11-09 23:24:47 +00009959 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9960 // Do a somewhat different check with comparison operators.
9961 if (BO->isComparisonOp())
9962 return AnalyzeComparison(S, BO);
9963
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009964 // And with simple assignments.
9965 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00009966 return AnalyzeAssignment(S, BO);
9967 }
John McCallcc7e5bf2010-05-06 08:58:33 +00009968
9969 // These break the otherwise-useful invariant below. Fortunately,
9970 // we don't really need to recurse into them, because any internal
9971 // expressions should have been analyzed already when they were
9972 // built into statements.
9973 if (isa<StmtExpr>(E)) return;
9974
9975 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00009976 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00009977
9978 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00009979 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00009980 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00009981 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00009982 for (Stmt *SubStmt : E->children()) {
9983 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00009984 if (!ChildExpr)
9985 continue;
9986
Richard Trieu955231d2014-01-25 01:10:35 +00009987 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00009988 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00009989 // Ignore checking string literals that are in logical and operators.
9990 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00009991 continue;
9992 AnalyzeImplicitConversions(S, ChildExpr, CC);
9993 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009994
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009995 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00009996 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
9997 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009998 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00009999
10000 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
10001 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +000010002 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000010003 }
Richard Trieu791b86e2014-11-19 06:08:18 +000010004
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000010005 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
10006 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +000010007 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010008}
10009
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000010010/// Diagnose integer type and any valid implicit convertion to it.
10011static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
10012 // Taking into account implicit conversions,
10013 // allow any integer.
10014 if (!E->getType()->isIntegerType()) {
10015 S.Diag(E->getLocStart(),
10016 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
10017 return true;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010018 }
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000010019 // Potentially emit standard warnings for implicit conversions if enabled
10020 // using -Wconversion.
10021 CheckImplicitConversion(S, E, IntT, E->getLocStart());
10022 return false;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010023}
10024
Richard Trieuc1888e02014-06-28 23:25:37 +000010025// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
10026// Returns true when emitting a warning about taking the address of a reference.
10027static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +000010028 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +000010029 E = E->IgnoreParenImpCasts();
10030
10031 const FunctionDecl *FD = nullptr;
10032
10033 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10034 if (!DRE->getDecl()->getType()->isReferenceType())
10035 return false;
10036 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10037 if (!M->getMemberDecl()->getType()->isReferenceType())
10038 return false;
10039 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +000010040 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +000010041 return false;
10042 FD = Call->getDirectCallee();
10043 } else {
10044 return false;
10045 }
10046
10047 SemaRef.Diag(E->getExprLoc(), PD);
10048
10049 // If possible, point to location of function.
10050 if (FD) {
10051 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
10052 }
10053
10054 return true;
10055}
10056
Richard Trieu4cbff5c2014-08-08 22:41:43 +000010057// Returns true if the SourceLocation is expanded from any macro body.
10058// Returns false if the SourceLocation is invalid, is from not in a macro
10059// expansion, or is from expanded from a top-level macro argument.
10060static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
10061 if (Loc.isInvalid())
10062 return false;
10063
10064 while (Loc.isMacroID()) {
10065 if (SM.isMacroBodyExpansion(Loc))
10066 return true;
10067 Loc = SM.getImmediateMacroCallerLoc(Loc);
10068 }
10069
10070 return false;
10071}
10072
Richard Trieu3bb8b562014-02-26 02:36:06 +000010073/// \brief Diagnose pointers that are always non-null.
10074/// \param E the expression containing the pointer
10075/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
10076/// compared to a null pointer
10077/// \param IsEqual True when the comparison is equal to a null pointer
10078/// \param Range Extra SourceRange to highlight in the diagnostic
10079void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
10080 Expr::NullPointerConstantKind NullKind,
10081 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +000010082 if (!E)
10083 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010084
10085 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +000010086 if (E->getExprLoc().isMacroID()) {
10087 const SourceManager &SM = getSourceManager();
10088 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
10089 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +000010090 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +000010091 }
Richard Trieu3bb8b562014-02-26 02:36:06 +000010092 E = E->IgnoreImpCasts();
10093
10094 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
10095
Richard Trieuf7432752014-06-06 21:39:26 +000010096 if (isa<CXXThisExpr>(E)) {
10097 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
10098 : diag::warn_this_bool_conversion;
10099 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
10100 return;
10101 }
10102
Richard Trieu3bb8b562014-02-26 02:36:06 +000010103 bool IsAddressOf = false;
10104
10105 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10106 if (UO->getOpcode() != UO_AddrOf)
10107 return;
10108 IsAddressOf = true;
10109 E = UO->getSubExpr();
10110 }
10111
Richard Trieuc1888e02014-06-28 23:25:37 +000010112 if (IsAddressOf) {
10113 unsigned DiagID = IsCompare
10114 ? diag::warn_address_of_reference_null_compare
10115 : diag::warn_address_of_reference_bool_conversion;
10116 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
10117 << IsEqual;
10118 if (CheckForReference(*this, E, PD)) {
10119 return;
10120 }
10121 }
10122
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010123 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
10124 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +000010125 std::string Str;
10126 llvm::raw_string_ostream S(Str);
10127 E->printPretty(S, nullptr, getPrintingPolicy());
10128 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
10129 : diag::warn_cast_nonnull_to_bool;
10130 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
10131 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010132 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +000010133 };
10134
10135 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
10136 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
10137 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010138 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
10139 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000010140 return;
10141 }
10142 }
10143 }
10144
Richard Trieu3bb8b562014-02-26 02:36:06 +000010145 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +000010146 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010147 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
10148 D = R->getDecl();
10149 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10150 D = M->getMemberDecl();
10151 }
10152
10153 // Weak Decls can be null.
10154 if (!D || D->isWeak())
10155 return;
George Burgess IV850269a2015-12-08 22:02:00 +000010156
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010157 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +000010158 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
10159 if (getCurFunction() &&
10160 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010161 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
10162 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000010163 return;
10164 }
10165
10166 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +000010167 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +000010168 assert(ParamIter != FD->param_end());
10169 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
10170
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010171 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
10172 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010173 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +000010174 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010175 }
George Burgess IV850269a2015-12-08 22:02:00 +000010176
10177 for (unsigned ArgNo : NonNull->args()) {
10178 if (ArgNo == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010179 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010180 return;
10181 }
George Burgess IV850269a2015-12-08 22:02:00 +000010182 }
10183 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010184 }
10185 }
George Burgess IV850269a2015-12-08 22:02:00 +000010186 }
10187
Richard Trieu3bb8b562014-02-26 02:36:06 +000010188 QualType T = D->getType();
10189 const bool IsArray = T->isArrayType();
10190 const bool IsFunction = T->isFunctionType();
10191
Richard Trieuc1888e02014-06-28 23:25:37 +000010192 // Address of function is used to silence the function warning.
10193 if (IsAddressOf && IsFunction) {
10194 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010195 }
10196
10197 // Found nothing.
10198 if (!IsAddressOf && !IsFunction && !IsArray)
10199 return;
10200
10201 // Pretty print the expression for the diagnostic.
10202 std::string Str;
10203 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +000010204 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +000010205
10206 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
10207 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +000010208 enum {
10209 AddressOf,
10210 FunctionPointer,
10211 ArrayPointer
10212 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010213 if (IsAddressOf)
10214 DiagType = AddressOf;
10215 else if (IsFunction)
10216 DiagType = FunctionPointer;
10217 else if (IsArray)
10218 DiagType = ArrayPointer;
10219 else
10220 llvm_unreachable("Could not determine diagnostic.");
10221 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
10222 << Range << IsEqual;
10223
10224 if (!IsFunction)
10225 return;
10226
10227 // Suggest '&' to silence the function warning.
10228 Diag(E->getExprLoc(), diag::note_function_warning_silence)
10229 << FixItHint::CreateInsertion(E->getLocStart(), "&");
10230
10231 // Check to see if '()' fixit should be emitted.
10232 QualType ReturnType;
10233 UnresolvedSet<4> NonTemplateOverloads;
10234 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
10235 if (ReturnType.isNull())
10236 return;
10237
10238 if (IsCompare) {
10239 // There are two cases here. If there is null constant, the only suggest
10240 // for a pointer return type. If the null is 0, then suggest if the return
10241 // type is a pointer or an integer type.
10242 if (!ReturnType->isPointerType()) {
10243 if (NullKind == Expr::NPCK_ZeroExpression ||
10244 NullKind == Expr::NPCK_ZeroLiteral) {
10245 if (!ReturnType->isIntegerType())
10246 return;
10247 } else {
10248 return;
10249 }
10250 }
10251 } else { // !IsCompare
10252 // For function to bool, only suggest if the function pointer has bool
10253 // return type.
10254 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
10255 return;
10256 }
10257 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +000010258 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +000010259}
10260
John McCallcc7e5bf2010-05-06 08:58:33 +000010261/// Diagnoses "dangerous" implicit conversions within the given
10262/// expression (which is a full expression). Implements -Wconversion
10263/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +000010264///
10265/// \param CC the "context" location of the implicit conversion, i.e.
10266/// the most location of the syntactic entity requiring the implicit
10267/// conversion
10268void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010269 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +000010270 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +000010271 return;
10272
10273 // Don't diagnose for value- or type-dependent expressions.
10274 if (E->isTypeDependent() || E->isValueDependent())
10275 return;
10276
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010277 // Check for array bounds violations in cases where the check isn't triggered
10278 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
10279 // ArraySubscriptExpr is on the RHS of a variable initialization.
10280 CheckArrayAccess(E);
10281
John McCallacf0ee52010-10-08 02:01:28 +000010282 // This is not the right CC for (e.g.) a variable initialization.
10283 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010284}
10285
Richard Trieu65724892014-11-15 06:37:39 +000010286/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10287/// Input argument E is a logical expression.
10288void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
10289 ::CheckBoolLikeConversion(*this, E, CC);
10290}
10291
Richard Smith9f7df0c2017-06-26 23:19:32 +000010292/// Diagnose when expression is an integer constant expression and its evaluation
10293/// results in integer overflow
10294void Sema::CheckForIntOverflow (Expr *E) {
10295 // Use a work list to deal with nested struct initializers.
10296 SmallVector<Expr *, 2> Exprs(1, E);
10297
10298 do {
10299 Expr *E = Exprs.pop_back_val();
10300
10301 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
10302 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
10303 continue;
10304 }
10305
10306 if (auto InitList = dyn_cast<InitListExpr>(E))
10307 Exprs.append(InitList->inits().begin(), InitList->inits().end());
10308
10309 if (isa<ObjCBoxedExpr>(E))
10310 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
10311 } while (!Exprs.empty());
10312}
10313
Richard Smithc406cb72013-01-17 01:17:56 +000010314namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010315
Richard Smithc406cb72013-01-17 01:17:56 +000010316/// \brief Visitor for expressions which looks for unsequenced operations on the
10317/// same object.
10318class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010319 using Base = EvaluatedExprVisitor<SequenceChecker>;
Richard Smithe3dbfe02013-06-30 10:40:20 +000010320
Richard Smithc406cb72013-01-17 01:17:56 +000010321 /// \brief A tree of sequenced regions within an expression. Two regions are
10322 /// unsequenced if one is an ancestor or a descendent of the other. When we
10323 /// finish processing an expression with sequencing, such as a comma
10324 /// expression, we fold its tree nodes into its parent, since they are
10325 /// unsequenced with respect to nodes we will visit later.
10326 class SequenceTree {
10327 struct Value {
10328 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
10329 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +000010330 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +000010331 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010332 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +000010333
10334 public:
10335 /// \brief A region within an expression which may be sequenced with respect
10336 /// to some other region.
10337 class Seq {
Richard Smithc406cb72013-01-17 01:17:56 +000010338 friend class SequenceTree;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010339
10340 unsigned Index = 0;
10341
10342 explicit Seq(unsigned N) : Index(N) {}
10343
Richard Smithc406cb72013-01-17 01:17:56 +000010344 public:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010345 Seq() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010346 };
10347
10348 SequenceTree() { Values.push_back(Value(0)); }
10349 Seq root() const { return Seq(0); }
10350
10351 /// \brief Create a new sequence of operations, which is an unsequenced
10352 /// subset of \p Parent. This sequence of operations is sequenced with
10353 /// respect to other children of \p Parent.
10354 Seq allocate(Seq Parent) {
10355 Values.push_back(Value(Parent.Index));
10356 return Seq(Values.size() - 1);
10357 }
10358
10359 /// \brief Merge a sequence of operations into its parent.
10360 void merge(Seq S) {
10361 Values[S.Index].Merged = true;
10362 }
10363
10364 /// \brief Determine whether two operations are unsequenced. This operation
10365 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
10366 /// should have been merged into its parent as appropriate.
10367 bool isUnsequenced(Seq Cur, Seq Old) {
10368 unsigned C = representative(Cur.Index);
10369 unsigned Target = representative(Old.Index);
10370 while (C >= Target) {
10371 if (C == Target)
10372 return true;
10373 C = Values[C].Parent;
10374 }
10375 return false;
10376 }
10377
10378 private:
10379 /// \brief Pick a representative for a sequence.
10380 unsigned representative(unsigned K) {
10381 if (Values[K].Merged)
10382 // Perform path compression as we go.
10383 return Values[K].Parent = representative(Values[K].Parent);
10384 return K;
10385 }
10386 };
10387
10388 /// An object for which we can track unsequenced uses.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010389 using Object = NamedDecl *;
Richard Smithc406cb72013-01-17 01:17:56 +000010390
10391 /// Different flavors of object usage which we track. We only track the
10392 /// least-sequenced usage of each kind.
10393 enum UsageKind {
10394 /// A read of an object. Multiple unsequenced reads are OK.
10395 UK_Use,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010396
Richard Smithc406cb72013-01-17 01:17:56 +000010397 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +000010398 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +000010399 UK_ModAsValue,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010400
Richard Smithc406cb72013-01-17 01:17:56 +000010401 /// A modification of an object which is not sequenced before the value
10402 /// computation of the expression, such as n++.
10403 UK_ModAsSideEffect,
10404
10405 UK_Count = UK_ModAsSideEffect + 1
10406 };
10407
10408 struct Usage {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010409 Expr *Use = nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000010410 SequenceTree::Seq Seq;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010411
10412 Usage() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010413 };
10414
10415 struct UsageInfo {
Richard Smithc406cb72013-01-17 01:17:56 +000010416 Usage Uses[UK_Count];
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010417
Richard Smithc406cb72013-01-17 01:17:56 +000010418 /// Have we issued a diagnostic for this variable already?
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010419 bool Diagnosed = false;
10420
10421 UsageInfo() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010422 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010423 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
Richard Smithc406cb72013-01-17 01:17:56 +000010424
10425 Sema &SemaRef;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010426
Richard Smithc406cb72013-01-17 01:17:56 +000010427 /// Sequenced regions within the expression.
10428 SequenceTree Tree;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010429
Richard Smithc406cb72013-01-17 01:17:56 +000010430 /// Declaration modifications and references which we have seen.
10431 UsageInfoMap UsageMap;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010432
Richard Smithc406cb72013-01-17 01:17:56 +000010433 /// The region we are currently within.
10434 SequenceTree::Seq Region;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010435
Richard Smithc406cb72013-01-17 01:17:56 +000010436 /// Filled in with declarations which were modified as a side-effect
10437 /// (that is, post-increment operations).
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010438 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
10439
Richard Smithd33f5202013-01-17 23:18:09 +000010440 /// Expressions to check later. We defer checking these to reduce
10441 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010442 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +000010443
10444 /// RAII object wrapping the visitation of a sequenced subexpression of an
10445 /// expression. At the end of this process, the side-effects of the evaluation
10446 /// become sequenced with respect to the value computation of the result, so
10447 /// we downgrade any UK_ModAsSideEffect within the evaluation to
10448 /// UK_ModAsValue.
10449 struct SequencedSubexpression {
10450 SequencedSubexpression(SequenceChecker &Self)
10451 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
10452 Self.ModAsSideEffect = &ModAsSideEffect;
10453 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010454
Richard Smithc406cb72013-01-17 01:17:56 +000010455 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +000010456 for (auto &M : llvm::reverse(ModAsSideEffect)) {
10457 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +000010458 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +000010459 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
10460 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +000010461 }
10462 Self.ModAsSideEffect = OldModAsSideEffect;
10463 }
10464
10465 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010466 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010467 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +000010468 };
10469
Richard Smith40238f02013-06-20 22:21:56 +000010470 /// RAII object wrapping the visitation of a subexpression which we might
10471 /// choose to evaluate as a constant. If any subexpression is evaluated and
10472 /// found to be non-constant, this allows us to suppress the evaluation of
10473 /// the outer expression.
10474 class EvaluationTracker {
10475 public:
10476 EvaluationTracker(SequenceChecker &Self)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010477 : Self(Self), Prev(Self.EvalTracker) {
Richard Smith40238f02013-06-20 22:21:56 +000010478 Self.EvalTracker = this;
10479 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010480
Richard Smith40238f02013-06-20 22:21:56 +000010481 ~EvaluationTracker() {
10482 Self.EvalTracker = Prev;
10483 if (Prev)
10484 Prev->EvalOK &= EvalOK;
10485 }
10486
10487 bool evaluate(const Expr *E, bool &Result) {
10488 if (!EvalOK || E->isValueDependent())
10489 return false;
10490 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
10491 return EvalOK;
10492 }
10493
10494 private:
10495 SequenceChecker &Self;
10496 EvaluationTracker *Prev;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010497 bool EvalOK = true;
10498 } *EvalTracker = nullptr;
Richard Smith40238f02013-06-20 22:21:56 +000010499
Richard Smithc406cb72013-01-17 01:17:56 +000010500 /// \brief Find the object which is produced by the specified expression,
10501 /// if any.
10502 Object getObject(Expr *E, bool Mod) const {
10503 E = E->IgnoreParenCasts();
10504 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10505 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
10506 return getObject(UO->getSubExpr(), Mod);
10507 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10508 if (BO->getOpcode() == BO_Comma)
10509 return getObject(BO->getRHS(), Mod);
10510 if (Mod && BO->isAssignmentOp())
10511 return getObject(BO->getLHS(), Mod);
10512 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10513 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
10514 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
10515 return ME->getMemberDecl();
10516 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10517 // FIXME: If this is a reference, map through to its value.
10518 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +000010519 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000010520 }
10521
10522 /// \brief Note that an object was modified or used by an expression.
10523 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
10524 Usage &U = UI.Uses[UK];
10525 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
10526 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
10527 ModAsSideEffect->push_back(std::make_pair(O, U));
10528 U.Use = Ref;
10529 U.Seq = Region;
10530 }
10531 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010532
Richard Smithc406cb72013-01-17 01:17:56 +000010533 /// \brief Check whether a modification or use conflicts with a prior usage.
10534 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
10535 bool IsModMod) {
10536 if (UI.Diagnosed)
10537 return;
10538
10539 const Usage &U = UI.Uses[OtherKind];
10540 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
10541 return;
10542
10543 Expr *Mod = U.Use;
10544 Expr *ModOrUse = Ref;
10545 if (OtherKind == UK_Use)
10546 std::swap(Mod, ModOrUse);
10547
10548 SemaRef.Diag(Mod->getExprLoc(),
10549 IsModMod ? diag::warn_unsequenced_mod_mod
10550 : diag::warn_unsequenced_mod_use)
10551 << O << SourceRange(ModOrUse->getExprLoc());
10552 UI.Diagnosed = true;
10553 }
10554
10555 void notePreUse(Object O, Expr *Use) {
10556 UsageInfo &U = UsageMap[O];
10557 // Uses conflict with other modifications.
10558 checkUsage(O, U, Use, UK_ModAsValue, false);
10559 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010560
Richard Smithc406cb72013-01-17 01:17:56 +000010561 void notePostUse(Object O, Expr *Use) {
10562 UsageInfo &U = UsageMap[O];
10563 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
10564 addUsage(U, O, Use, UK_Use);
10565 }
10566
10567 void notePreMod(Object O, Expr *Mod) {
10568 UsageInfo &U = UsageMap[O];
10569 // Modifications conflict with other modifications and with uses.
10570 checkUsage(O, U, Mod, UK_ModAsValue, true);
10571 checkUsage(O, U, Mod, UK_Use, false);
10572 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010573
Richard Smithc406cb72013-01-17 01:17:56 +000010574 void notePostMod(Object O, Expr *Use, UsageKind UK) {
10575 UsageInfo &U = UsageMap[O];
10576 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
10577 addUsage(U, O, Use, UK);
10578 }
10579
10580public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010581 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010582 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
Richard Smithc406cb72013-01-17 01:17:56 +000010583 Visit(E);
10584 }
10585
10586 void VisitStmt(Stmt *S) {
10587 // Skip all statements which aren't expressions for now.
10588 }
10589
10590 void VisitExpr(Expr *E) {
10591 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +000010592 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +000010593 }
10594
10595 void VisitCastExpr(CastExpr *E) {
10596 Object O = Object();
10597 if (E->getCastKind() == CK_LValueToRValue)
10598 O = getObject(E->getSubExpr(), false);
10599
10600 if (O)
10601 notePreUse(O, E);
10602 VisitExpr(E);
10603 if (O)
10604 notePostUse(O, E);
10605 }
10606
10607 void VisitBinComma(BinaryOperator *BO) {
10608 // C++11 [expr.comma]p1:
10609 // Every value computation and side effect associated with the left
10610 // expression is sequenced before every value computation and side
10611 // effect associated with the right expression.
10612 SequenceTree::Seq LHS = Tree.allocate(Region);
10613 SequenceTree::Seq RHS = Tree.allocate(Region);
10614 SequenceTree::Seq OldRegion = Region;
10615
10616 {
10617 SequencedSubexpression SeqLHS(*this);
10618 Region = LHS;
10619 Visit(BO->getLHS());
10620 }
10621
10622 Region = RHS;
10623 Visit(BO->getRHS());
10624
10625 Region = OldRegion;
10626
10627 // Forget that LHS and RHS are sequenced. They are both unsequenced
10628 // with respect to other stuff.
10629 Tree.merge(LHS);
10630 Tree.merge(RHS);
10631 }
10632
10633 void VisitBinAssign(BinaryOperator *BO) {
10634 // The modification is sequenced after the value computation of the LHS
10635 // and RHS, so check it before inspecting the operands and update the
10636 // map afterwards.
10637 Object O = getObject(BO->getLHS(), true);
10638 if (!O)
10639 return VisitExpr(BO);
10640
10641 notePreMod(O, BO);
10642
10643 // C++11 [expr.ass]p7:
10644 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
10645 // only once.
10646 //
10647 // Therefore, for a compound assignment operator, O is considered used
10648 // everywhere except within the evaluation of E1 itself.
10649 if (isa<CompoundAssignOperator>(BO))
10650 notePreUse(O, BO);
10651
10652 Visit(BO->getLHS());
10653
10654 if (isa<CompoundAssignOperator>(BO))
10655 notePostUse(O, BO);
10656
10657 Visit(BO->getRHS());
10658
Richard Smith83e37bee2013-06-26 23:16:51 +000010659 // C++11 [expr.ass]p1:
10660 // the assignment is sequenced [...] before the value computation of the
10661 // assignment expression.
10662 // C11 6.5.16/3 has no such rule.
10663 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10664 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010665 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010666
Richard Smithc406cb72013-01-17 01:17:56 +000010667 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
10668 VisitBinAssign(CAO);
10669 }
10670
10671 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10672 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10673 void VisitUnaryPreIncDec(UnaryOperator *UO) {
10674 Object O = getObject(UO->getSubExpr(), true);
10675 if (!O)
10676 return VisitExpr(UO);
10677
10678 notePreMod(O, UO);
10679 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +000010680 // C++11 [expr.pre.incr]p1:
10681 // the expression ++x is equivalent to x+=1
10682 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10683 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010684 }
10685
10686 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10687 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10688 void VisitUnaryPostIncDec(UnaryOperator *UO) {
10689 Object O = getObject(UO->getSubExpr(), true);
10690 if (!O)
10691 return VisitExpr(UO);
10692
10693 notePreMod(O, UO);
10694 Visit(UO->getSubExpr());
10695 notePostMod(O, UO, UK_ModAsSideEffect);
10696 }
10697
10698 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
10699 void VisitBinLOr(BinaryOperator *BO) {
10700 // The side-effects of the LHS of an '&&' are sequenced before the
10701 // value computation of the RHS, and hence before the value computation
10702 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10703 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +000010704 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010705 {
10706 SequencedSubexpression Sequenced(*this);
10707 Visit(BO->getLHS());
10708 }
10709
10710 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010711 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010712 if (!Result)
10713 Visit(BO->getRHS());
10714 } else {
10715 // Check for unsequenced operations in the RHS, treating it as an
10716 // entirely separate evaluation.
10717 //
10718 // FIXME: If there are operations in the RHS which are unsequenced
10719 // with respect to operations outside the RHS, and those operations
10720 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +000010721 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010722 }
Richard Smithc406cb72013-01-17 01:17:56 +000010723 }
10724 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +000010725 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010726 {
10727 SequencedSubexpression Sequenced(*this);
10728 Visit(BO->getLHS());
10729 }
10730
10731 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010732 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010733 if (Result)
10734 Visit(BO->getRHS());
10735 } else {
Richard Smithd33f5202013-01-17 23:18:09 +000010736 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010737 }
Richard Smithc406cb72013-01-17 01:17:56 +000010738 }
10739
10740 // Only visit the condition, unless we can be sure which subexpression will
10741 // be chosen.
10742 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +000010743 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +000010744 {
10745 SequencedSubexpression Sequenced(*this);
10746 Visit(CO->getCond());
10747 }
Richard Smithc406cb72013-01-17 01:17:56 +000010748
10749 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010750 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +000010751 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010752 else {
Richard Smithd33f5202013-01-17 23:18:09 +000010753 WorkList.push_back(CO->getTrueExpr());
10754 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010755 }
Richard Smithc406cb72013-01-17 01:17:56 +000010756 }
10757
Richard Smithe3dbfe02013-06-30 10:40:20 +000010758 void VisitCallExpr(CallExpr *CE) {
10759 // C++11 [intro.execution]p15:
10760 // When calling a function [...], every value computation and side effect
10761 // associated with any argument expression, or with the postfix expression
10762 // designating the called function, is sequenced before execution of every
10763 // expression or statement in the body of the function [and thus before
10764 // the value computation of its result].
10765 SequencedSubexpression Sequenced(*this);
10766 Base::VisitCallExpr(CE);
10767
10768 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10769 }
10770
Richard Smithc406cb72013-01-17 01:17:56 +000010771 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +000010772 // This is a call, so all subexpressions are sequenced before the result.
10773 SequencedSubexpression Sequenced(*this);
10774
Richard Smithc406cb72013-01-17 01:17:56 +000010775 if (!CCE->isListInitialization())
10776 return VisitExpr(CCE);
10777
10778 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010779 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010780 SequenceTree::Seq Parent = Region;
10781 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10782 E = CCE->arg_end();
10783 I != E; ++I) {
10784 Region = Tree.allocate(Parent);
10785 Elts.push_back(Region);
10786 Visit(*I);
10787 }
10788
10789 // Forget that the initializers are sequenced.
10790 Region = Parent;
10791 for (unsigned I = 0; I < Elts.size(); ++I)
10792 Tree.merge(Elts[I]);
10793 }
10794
10795 void VisitInitListExpr(InitListExpr *ILE) {
10796 if (!SemaRef.getLangOpts().CPlusPlus11)
10797 return VisitExpr(ILE);
10798
10799 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010800 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010801 SequenceTree::Seq Parent = Region;
10802 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10803 Expr *E = ILE->getInit(I);
10804 if (!E) continue;
10805 Region = Tree.allocate(Parent);
10806 Elts.push_back(Region);
10807 Visit(E);
10808 }
10809
10810 // Forget that the initializers are sequenced.
10811 Region = Parent;
10812 for (unsigned I = 0; I < Elts.size(); ++I)
10813 Tree.merge(Elts[I]);
10814 }
10815};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010816
10817} // namespace
Richard Smithc406cb72013-01-17 01:17:56 +000010818
10819void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010820 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +000010821 WorkList.push_back(E);
10822 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +000010823 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +000010824 SequenceChecker(*this, Item, WorkList);
10825 }
Richard Smithc406cb72013-01-17 01:17:56 +000010826}
10827
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010828void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10829 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +000010830 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +000010831 if (!E->isInstantiationDependent())
10832 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010833 if (!IsConstexpr && !E->isValueDependent())
Richard Smith9f7df0c2017-06-26 23:19:32 +000010834 CheckForIntOverflow(E);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000010835 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +000010836}
10837
John McCall1f425642010-11-11 03:21:53 +000010838void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10839 FieldDecl *BitField,
10840 Expr *Init) {
10841 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10842}
10843
David Majnemer61a5bbf2015-04-07 22:08:51 +000010844static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
10845 SourceLocation Loc) {
10846 if (!PType->isVariablyModifiedType())
10847 return;
10848 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10849 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10850 return;
10851 }
David Majnemerdf8f73f2015-04-09 19:53:25 +000010852 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10853 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10854 return;
10855 }
David Majnemer61a5bbf2015-04-07 22:08:51 +000010856 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10857 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10858 return;
10859 }
10860
10861 const ArrayType *AT = S.Context.getAsArrayType(PType);
10862 if (!AT)
10863 return;
10864
10865 if (AT->getSizeModifier() != ArrayType::Star) {
10866 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
10867 return;
10868 }
10869
10870 S.Diag(Loc, diag::err_array_star_in_function_definition);
10871}
10872
Mike Stump0c2ec772010-01-21 03:59:47 +000010873/// CheckParmsForFunctionDef - Check that the parameters of the given
10874/// function are appropriate for the definition of a function. This
10875/// takes care of any checks that cannot be performed on the
10876/// declaration itself, e.g., that the types of each of the function
10877/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +000010878bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +000010879 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010880 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +000010881 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010882 // C99 6.7.5.3p4: the parameters in a parameter type list in a
10883 // function declarator that is part of a function definition of
10884 // that function shall not have incomplete type.
10885 //
10886 // This is also C++ [dcl.fct]p6.
10887 if (!Param->isInvalidDecl() &&
10888 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000010889 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010890 Param->setInvalidDecl();
10891 HasInvalidParm = true;
10892 }
10893
10894 // C99 6.9.1p5: If the declarator includes a parameter type list, the
10895 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +000010896 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +000010897 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +000010898 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000010899 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +000010900 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +000010901
10902 // C99 6.7.5.3p12:
10903 // If the function declarator is not part of a definition of that
10904 // function, parameters may have incomplete type and may use the [*]
10905 // notation in their sequences of declarator specifiers to specify
10906 // variable length array types.
10907 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +000010908 // FIXME: This diagnostic should point the '[*]' if source-location
10909 // information is added for it.
10910 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010911
10912 // MSVC destroys objects passed by value in the callee. Therefore a
10913 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010914 // object's destructor. However, we don't perform any direct access check
10915 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +000010916 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
10917 .getCXXABI()
10918 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +000010919 if (!Param->isInvalidDecl()) {
10920 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
10921 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
10922 if (!ClassDecl->isInvalidDecl() &&
10923 !ClassDecl->hasIrrelevantDestructor() &&
10924 !ClassDecl->isDependentContext()) {
10925 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10926 MarkFunctionReferenced(Param->getLocation(), Destructor);
10927 DiagnoseUseOfDecl(Destructor, Param->getLocation());
10928 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010929 }
10930 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010931 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010932
10933 // Parameters with the pass_object_size attribute only need to be marked
10934 // constant at function definitions. Because we lack information about
10935 // whether we're on a declaration or definition when we're instantiating the
10936 // attribute, we need to check for constness here.
10937 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
10938 if (!Param->getType().isConstQualified())
10939 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10940 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +000010941 }
10942
10943 return HasInvalidParm;
10944}
John McCall2b5c1b22010-08-12 21:44:57 +000010945
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000010946/// A helper function to get the alignment of a Decl referred to by DeclRefExpr
10947/// or MemberExpr.
10948static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
10949 ASTContext &Context) {
10950 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
10951 return Context.getDeclAlign(DRE->getDecl());
10952
10953 if (const auto *ME = dyn_cast<MemberExpr>(E))
10954 return Context.getDeclAlign(ME->getMemberDecl());
10955
10956 return TypeAlign;
10957}
10958
John McCall2b5c1b22010-08-12 21:44:57 +000010959/// CheckCastAlign - Implements -Wcast-align, which warns when a
10960/// pointer cast increases the alignment requirements.
10961void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
10962 // This is actually a lot of work to potentially be doing on every
10963 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010964 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +000010965 return;
10966
10967 // Ignore dependent types.
10968 if (T->isDependentType() || Op->getType()->isDependentType())
10969 return;
10970
10971 // Require that the destination be a pointer type.
10972 const PointerType *DestPtr = T->getAs<PointerType>();
10973 if (!DestPtr) return;
10974
10975 // If the destination has alignment 1, we're done.
10976 QualType DestPointee = DestPtr->getPointeeType();
10977 if (DestPointee->isIncompleteType()) return;
10978 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
10979 if (DestAlign.isOne()) return;
10980
10981 // Require that the source be a pointer type.
10982 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
10983 if (!SrcPtr) return;
10984 QualType SrcPointee = SrcPtr->getPointeeType();
10985
10986 // Whitelist casts from cv void*. We already implicitly
10987 // whitelisted casts to cv void*, since they have alignment 1.
10988 // Also whitelist casts involving incomplete types, which implicitly
10989 // includes 'void'.
10990 if (SrcPointee->isIncompleteType()) return;
10991
10992 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000010993
10994 if (auto *CE = dyn_cast<CastExpr>(Op)) {
10995 if (CE->getCastKind() == CK_ArrayToPointerDecay)
10996 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
10997 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
10998 if (UO->getOpcode() == UO_AddrOf)
10999 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
11000 }
11001
John McCall2b5c1b22010-08-12 21:44:57 +000011002 if (SrcAlign >= DestAlign) return;
11003
11004 Diag(TRange.getBegin(), diag::warn_cast_align)
11005 << Op->getType() << T
11006 << static_cast<unsigned>(SrcAlign.getQuantity())
11007 << static_cast<unsigned>(DestAlign.getQuantity())
11008 << TRange << Op->getSourceRange();
11009}
11010
Chandler Carruth28389f02011-08-05 09:10:50 +000011011/// \brief Check whether this array fits the idiom of a size-one tail padded
11012/// array member of a struct.
11013///
11014/// We avoid emitting out-of-bounds access warnings for such arrays as they are
11015/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +000011016static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +000011017 const NamedDecl *ND) {
11018 if (Size != 1 || !ND) return false;
11019
11020 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
11021 if (!FD) return false;
11022
11023 // Don't consider sizes resulting from macro expansions or template argument
11024 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +000011025
11026 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000011027 while (TInfo) {
11028 TypeLoc TL = TInfo->getTypeLoc();
11029 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +000011030 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
11031 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000011032 TInfo = TDL->getTypeSourceInfo();
11033 continue;
11034 }
David Blaikie6adc78e2013-02-18 22:06:02 +000011035 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
11036 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +000011037 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
11038 return false;
11039 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +000011040 break;
Sean Callanan06a48a62012-05-04 18:22:53 +000011041 }
Chandler Carruth28389f02011-08-05 09:10:50 +000011042
11043 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +000011044 if (!RD) return false;
11045 if (RD->isUnion()) return false;
11046 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
11047 if (!CRD->isStandardLayout()) return false;
11048 }
Chandler Carruth28389f02011-08-05 09:10:50 +000011049
Benjamin Kramer8c543672011-08-06 03:04:42 +000011050 // See if this is the last field decl in the record.
11051 const Decl *D = FD;
11052 while ((D = D->getNextDeclInContext()))
11053 if (isa<FieldDecl>(D))
11054 return false;
11055 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +000011056}
11057
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011058void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011059 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +000011060 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011061 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011062 if (IndexExpr->isValueDependent())
11063 return;
11064
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000011065 const Type *EffectiveType =
11066 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011067 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011068 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011069 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011070 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +000011071 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +000011072
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011073 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +000011074 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +000011075 return;
Richard Smith13f67182011-12-16 19:31:14 +000011076 if (IndexNegated)
11077 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +000011078
Craig Topperc3ec1492014-05-26 06:22:03 +000011079 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +000011080 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
11081 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +000011082 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +000011083 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +000011084
Ted Kremeneke4b316c2011-02-23 23:06:04 +000011085 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011086 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +000011087 if (!size.isStrictlyPositive())
11088 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011089
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000011090 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +000011091 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011092 // Make sure we're comparing apples to apples when comparing index to size
11093 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
11094 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +000011095 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +000011096 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011097 if (ptrarith_typesize != array_typesize) {
11098 // There's a cast to a different size type involved
11099 uint64_t ratio = array_typesize / ptrarith_typesize;
11100 // TODO: Be smarter about handling cases where array_typesize is not a
11101 // multiple of ptrarith_typesize
11102 if (ptrarith_typesize * ratio == array_typesize)
11103 size *= llvm::APInt(size.getBitWidth(), ratio);
11104 }
11105 }
11106
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011107 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011108 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011109 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011110 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011111
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011112 // For array subscripting the index must be less than size, but for pointer
11113 // arithmetic also allow the index (offset) to be equal to size since
11114 // computing the next address after the end of the array is legal and
11115 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011116 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +000011117 return;
11118
11119 // Also don't warn for arrays of size 1 which are members of some
11120 // structure. These are often used to approximate flexible arrays in C89
11121 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011122 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +000011123 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011124
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011125 // Suppress the warning if the subscript expression (as identified by the
11126 // ']' location) and the index expression are both from macro expansions
11127 // within a system header.
11128 if (ASE) {
11129 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
11130 ASE->getRBracketLoc());
11131 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
11132 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
11133 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +000011134 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011135 return;
11136 }
11137 }
11138
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011139 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011140 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011141 DiagID = diag::warn_array_index_exceeds_bounds;
11142
11143 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11144 PDiag(DiagID) << index.toString(10, true)
11145 << size.toString(10, true)
11146 << (unsigned)size.getLimitedValue(~0U)
11147 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011148 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011149 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011150 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011151 DiagID = diag::warn_ptr_arith_precedes_bounds;
11152 if (index.isNegative()) index = -index;
11153 }
11154
11155 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11156 PDiag(DiagID) << index.toString(10, true)
11157 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +000011158 }
Chandler Carruth1af88f12011-02-17 21:10:52 +000011159
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000011160 if (!ND) {
11161 // Try harder to find a NamedDecl to point at in the note.
11162 while (const ArraySubscriptExpr *ASE =
11163 dyn_cast<ArraySubscriptExpr>(BaseExpr))
11164 BaseExpr = ASE->getBase()->IgnoreParenCasts();
11165 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
11166 ND = dyn_cast<NamedDecl>(DRE->getDecl());
11167 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
11168 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
11169 }
11170
Chandler Carruth1af88f12011-02-17 21:10:52 +000011171 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011172 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
11173 PDiag(diag::note_array_index_out_of_bounds)
11174 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +000011175}
11176
Ted Kremenekdf26df72011-03-01 18:41:00 +000011177void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011178 int AllowOnePastEnd = 0;
11179 while (expr) {
11180 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +000011181 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011182 case Stmt::ArraySubscriptExprClass: {
11183 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011184 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011185 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +000011186 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011187 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +000011188 case Stmt::OMPArraySectionExprClass: {
11189 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
11190 if (ASE->getLowerBound())
11191 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
11192 /*ASE=*/nullptr, AllowOnePastEnd > 0);
11193 return;
11194 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011195 case Stmt::UnaryOperatorClass: {
11196 // Only unwrap the * and & unary operators
11197 const UnaryOperator *UO = cast<UnaryOperator>(expr);
11198 expr = UO->getSubExpr();
11199 switch (UO->getOpcode()) {
11200 case UO_AddrOf:
11201 AllowOnePastEnd++;
11202 break;
11203 case UO_Deref:
11204 AllowOnePastEnd--;
11205 break;
11206 default:
11207 return;
11208 }
11209 break;
11210 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011211 case Stmt::ConditionalOperatorClass: {
11212 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
11213 if (const Expr *lhs = cond->getLHS())
11214 CheckArrayAccess(lhs);
11215 if (const Expr *rhs = cond->getRHS())
11216 CheckArrayAccess(rhs);
11217 return;
11218 }
Daniel Marjamaki20a209e2017-02-28 14:53:50 +000011219 case Stmt::CXXOperatorCallExprClass: {
11220 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
11221 for (const auto *Arg : OCE->arguments())
11222 CheckArrayAccess(Arg);
11223 return;
11224 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011225 default:
11226 return;
11227 }
Peter Collingbourne91147592011-04-15 00:35:48 +000011228 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011229}
John McCall31168b02011-06-15 23:02:42 +000011230
11231//===--- CHECK: Objective-C retain cycles ----------------------------------//
11232
11233namespace {
John McCall31168b02011-06-15 23:02:42 +000011234
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011235struct RetainCycleOwner {
11236 VarDecl *Variable = nullptr;
11237 SourceRange Range;
11238 SourceLocation Loc;
11239 bool Indirect = false;
11240
11241 RetainCycleOwner() = default;
11242
11243 void setLocsFrom(Expr *e) {
11244 Loc = e->getExprLoc();
11245 Range = e->getSourceRange();
11246 }
11247};
11248
11249} // namespace
John McCall31168b02011-06-15 23:02:42 +000011250
11251/// Consider whether capturing the given variable can possibly lead to
11252/// a retain cycle.
11253static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000011254 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +000011255 // lifetime. In MRR, it's captured strongly if the variable is
11256 // __block and has an appropriate type.
11257 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11258 return false;
11259
11260 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011261 if (ref)
11262 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +000011263 return true;
11264}
11265
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011266static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +000011267 while (true) {
11268 e = e->IgnoreParens();
11269 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
11270 switch (cast->getCastKind()) {
11271 case CK_BitCast:
11272 case CK_LValueBitCast:
11273 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +000011274 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +000011275 e = cast->getSubExpr();
11276 continue;
11277
John McCall31168b02011-06-15 23:02:42 +000011278 default:
11279 return false;
11280 }
11281 }
11282
11283 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
11284 ObjCIvarDecl *ivar = ref->getDecl();
11285 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11286 return false;
11287
11288 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011289 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +000011290 return false;
11291
11292 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
11293 owner.Indirect = true;
11294 return true;
11295 }
11296
11297 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
11298 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
11299 if (!var) return false;
11300 return considerVariable(var, ref, owner);
11301 }
11302
John McCall31168b02011-06-15 23:02:42 +000011303 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
11304 if (member->isArrow()) return false;
11305
11306 // Don't count this as an indirect ownership.
11307 e = member->getBase();
11308 continue;
11309 }
11310
John McCallfe96e0b2011-11-06 09:01:30 +000011311 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
11312 // Only pay attention to pseudo-objects on property references.
11313 ObjCPropertyRefExpr *pre
11314 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
11315 ->IgnoreParens());
11316 if (!pre) return false;
11317 if (pre->isImplicitProperty()) return false;
11318 ObjCPropertyDecl *property = pre->getExplicitProperty();
11319 if (!property->isRetaining() &&
11320 !(property->getPropertyIvarDecl() &&
11321 property->getPropertyIvarDecl()->getType()
11322 .getObjCLifetime() == Qualifiers::OCL_Strong))
11323 return false;
11324
11325 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011326 if (pre->isSuperReceiver()) {
11327 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
11328 if (!owner.Variable)
11329 return false;
11330 owner.Loc = pre->getLocation();
11331 owner.Range = pre->getSourceRange();
11332 return true;
11333 }
John McCallfe96e0b2011-11-06 09:01:30 +000011334 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
11335 ->getSourceExpr());
11336 continue;
11337 }
11338
John McCall31168b02011-06-15 23:02:42 +000011339 // Array ivars?
11340
11341 return false;
11342 }
11343}
11344
11345namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011346
John McCall31168b02011-06-15 23:02:42 +000011347 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011348 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +000011349 VarDecl *Variable;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011350 Expr *Capturer = nullptr;
11351 bool VarWillBeReased = false;
11352
11353 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
11354 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
11355 Context(Context), Variable(variable) {}
John McCall31168b02011-06-15 23:02:42 +000011356
11357 void VisitDeclRefExpr(DeclRefExpr *ref) {
11358 if (ref->getDecl() == Variable && !Capturer)
11359 Capturer = ref;
11360 }
11361
John McCall31168b02011-06-15 23:02:42 +000011362 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
11363 if (Capturer) return;
11364 Visit(ref->getBase());
11365 if (Capturer && ref->isFreeIvar())
11366 Capturer = ref;
11367 }
11368
11369 void VisitBlockExpr(BlockExpr *block) {
11370 // Look inside nested blocks
11371 if (block->getBlockDecl()->capturesVariable(Variable))
11372 Visit(block->getBlockDecl()->getBody());
11373 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +000011374
11375 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
11376 if (Capturer) return;
11377 if (OVE->getSourceExpr())
11378 Visit(OVE->getSourceExpr());
11379 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011380
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011381 void VisitBinaryOperator(BinaryOperator *BinOp) {
11382 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
11383 return;
11384 Expr *LHS = BinOp->getLHS();
11385 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
11386 if (DRE->getDecl() != Variable)
11387 return;
11388 if (Expr *RHS = BinOp->getRHS()) {
11389 RHS = RHS->IgnoreParenCasts();
11390 llvm::APSInt Value;
11391 VarWillBeReased =
11392 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
11393 }
11394 }
11395 }
John McCall31168b02011-06-15 23:02:42 +000011396 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011397
11398} // namespace
John McCall31168b02011-06-15 23:02:42 +000011399
11400/// Check whether the given argument is a block which captures a
11401/// variable.
11402static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
11403 assert(owner.Variable && owner.Loc.isValid());
11404
11405 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000011406
11407 // Look through [^{...} copy] and Block_copy(^{...}).
11408 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
11409 Selector Cmd = ME->getSelector();
11410 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
11411 e = ME->getInstanceReceiver();
11412 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000011413 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000011414 e = e->IgnoreParenCasts();
11415 }
11416 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
11417 if (CE->getNumArgs() == 1) {
11418 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000011419 if (Fn) {
11420 const IdentifierInfo *FnI = Fn->getIdentifier();
11421 if (FnI && FnI->isStr("_Block_copy")) {
11422 e = CE->getArg(0)->IgnoreParenCasts();
11423 }
11424 }
Jordan Rose67e887c2012-09-17 17:54:30 +000011425 }
11426 }
11427
John McCall31168b02011-06-15 23:02:42 +000011428 BlockExpr *block = dyn_cast<BlockExpr>(e);
11429 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000011430 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000011431
11432 FindCaptureVisitor visitor(S.Context, owner.Variable);
11433 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011434 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000011435}
11436
11437static void diagnoseRetainCycle(Sema &S, Expr *capturer,
11438 RetainCycleOwner &owner) {
11439 assert(capturer);
11440 assert(owner.Variable && owner.Loc.isValid());
11441
11442 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
11443 << owner.Variable << capturer->getSourceRange();
11444 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
11445 << owner.Indirect << owner.Range;
11446}
11447
11448/// Check for a keyword selector that starts with the word 'add' or
11449/// 'set'.
11450static bool isSetterLikeSelector(Selector sel) {
11451 if (sel.isUnarySelector()) return false;
11452
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011453 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000011454 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011455 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000011456 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011457 else if (str.startswith("add")) {
11458 // Specially whitelist 'addOperationWithBlock:'.
11459 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
11460 return false;
11461 str = str.substr(3);
11462 }
John McCall31168b02011-06-15 23:02:42 +000011463 else
11464 return false;
11465
11466 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000011467 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000011468}
11469
Benjamin Kramer3a743452015-03-09 15:03:32 +000011470static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
11471 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011472 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
11473 Message->getReceiverInterface(),
11474 NSAPI::ClassId_NSMutableArray);
11475 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011476 return None;
11477 }
11478
11479 Selector Sel = Message->getSelector();
11480
11481 Optional<NSAPI::NSArrayMethodKind> MKOpt =
11482 S.NSAPIObj->getNSArrayMethodKind(Sel);
11483 if (!MKOpt) {
11484 return None;
11485 }
11486
11487 NSAPI::NSArrayMethodKind MK = *MKOpt;
11488
11489 switch (MK) {
11490 case NSAPI::NSMutableArr_addObject:
11491 case NSAPI::NSMutableArr_insertObjectAtIndex:
11492 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
11493 return 0;
11494 case NSAPI::NSMutableArr_replaceObjectAtIndex:
11495 return 1;
11496
11497 default:
11498 return None;
11499 }
11500
11501 return None;
11502}
11503
11504static
11505Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
11506 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011507 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
11508 Message->getReceiverInterface(),
11509 NSAPI::ClassId_NSMutableDictionary);
11510 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011511 return None;
11512 }
11513
11514 Selector Sel = Message->getSelector();
11515
11516 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
11517 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
11518 if (!MKOpt) {
11519 return None;
11520 }
11521
11522 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
11523
11524 switch (MK) {
11525 case NSAPI::NSMutableDict_setObjectForKey:
11526 case NSAPI::NSMutableDict_setValueForKey:
11527 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
11528 return 0;
11529
11530 default:
11531 return None;
11532 }
11533
11534 return None;
11535}
11536
11537static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011538 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
11539 Message->getReceiverInterface(),
11540 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000011541
Alex Denisov5dfac812015-08-06 04:51:14 +000011542 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
11543 Message->getReceiverInterface(),
11544 NSAPI::ClassId_NSMutableOrderedSet);
11545 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011546 return None;
11547 }
11548
11549 Selector Sel = Message->getSelector();
11550
11551 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
11552 if (!MKOpt) {
11553 return None;
11554 }
11555
11556 NSAPI::NSSetMethodKind MK = *MKOpt;
11557
11558 switch (MK) {
11559 case NSAPI::NSMutableSet_addObject:
11560 case NSAPI::NSOrderedSet_setObjectAtIndex:
11561 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
11562 case NSAPI::NSOrderedSet_insertObjectAtIndex:
11563 return 0;
11564 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
11565 return 1;
11566 }
11567
11568 return None;
11569}
11570
11571void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
11572 if (!Message->isInstanceMessage()) {
11573 return;
11574 }
11575
11576 Optional<int> ArgOpt;
11577
11578 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
11579 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
11580 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
11581 return;
11582 }
11583
11584 int ArgIndex = *ArgOpt;
11585
Alex Denisove1d882c2015-03-04 17:55:52 +000011586 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
11587 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
11588 Arg = OE->getSourceExpr()->IgnoreImpCasts();
11589 }
11590
Alex Denisov5dfac812015-08-06 04:51:14 +000011591 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011592 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011593 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011594 Diag(Message->getSourceRange().getBegin(),
11595 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +000011596 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +000011597 }
11598 }
Alex Denisov5dfac812015-08-06 04:51:14 +000011599 } else {
11600 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
11601
11602 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
11603 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
11604 }
11605
11606 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
11607 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11608 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
11609 ValueDecl *Decl = ReceiverRE->getDecl();
11610 Diag(Message->getSourceRange().getBegin(),
11611 diag::warn_objc_circular_container)
11612 << Decl->getName() << Decl->getName();
11613 if (!ArgRE->isObjCSelfExpr()) {
11614 Diag(Decl->getLocation(),
11615 diag::note_objc_circular_container_declared_here)
11616 << Decl->getName();
11617 }
11618 }
11619 }
11620 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
11621 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
11622 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
11623 ObjCIvarDecl *Decl = IvarRE->getDecl();
11624 Diag(Message->getSourceRange().getBegin(),
11625 diag::warn_objc_circular_container)
11626 << Decl->getName() << Decl->getName();
11627 Diag(Decl->getLocation(),
11628 diag::note_objc_circular_container_declared_here)
11629 << Decl->getName();
11630 }
Alex Denisove1d882c2015-03-04 17:55:52 +000011631 }
11632 }
11633 }
Alex Denisove1d882c2015-03-04 17:55:52 +000011634}
11635
John McCall31168b02011-06-15 23:02:42 +000011636/// Check a message send to see if it's likely to cause a retain cycle.
11637void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
11638 // Only check instance methods whose selector looks like a setter.
11639 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
11640 return;
11641
11642 // Try to find a variable that the receiver is strongly owned by.
11643 RetainCycleOwner owner;
11644 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011645 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000011646 return;
11647 } else {
11648 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
11649 owner.Variable = getCurMethodDecl()->getSelfDecl();
11650 owner.Loc = msg->getSuperLoc();
11651 owner.Range = msg->getSuperLoc();
11652 }
11653
11654 // Check whether the receiver is captured by any of the arguments.
Alex Lorenz42a97a92017-11-17 20:44:25 +000011655 const ObjCMethodDecl *MD = msg->getMethodDecl();
11656 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
11657 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
11658 // noescape blocks should not be retained by the method.
11659 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
11660 continue;
John McCall31168b02011-06-15 23:02:42 +000011661 return diagnoseRetainCycle(*this, capturer, owner);
Alex Lorenz42a97a92017-11-17 20:44:25 +000011662 }
11663 }
John McCall31168b02011-06-15 23:02:42 +000011664}
11665
11666/// Check a property assign to see if it's likely to cause a retain cycle.
11667void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
11668 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011669 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000011670 return;
11671
11672 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
11673 diagnoseRetainCycle(*this, capturer, owner);
11674}
11675
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011676void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
11677 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000011678 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011679 return;
11680
11681 // Because we don't have an expression for the variable, we have to set the
11682 // location explicitly here.
11683 Owner.Loc = Var->getLocation();
11684 Owner.Range = Var->getSourceRange();
11685
11686 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
11687 diagnoseRetainCycle(*this, Capturer, Owner);
11688}
11689
Ted Kremenek9304da92012-12-21 08:04:28 +000011690static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
11691 Expr *RHS, bool isProperty) {
11692 // Check if RHS is an Objective-C object literal, which also can get
11693 // immediately zapped in a weak reference. Note that we explicitly
11694 // allow ObjCStringLiterals, since those are designed to never really die.
11695 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011696
Ted Kremenek64873352012-12-21 22:46:35 +000011697 // This enum needs to match with the 'select' in
11698 // warn_objc_arc_literal_assign (off-by-1).
11699 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
11700 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
11701 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011702
11703 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000011704 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000011705 << (isProperty ? 0 : 1)
11706 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011707
11708 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000011709}
11710
Ted Kremenekc1f014a2012-12-21 19:45:30 +000011711static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
11712 Qualifiers::ObjCLifetime LT,
11713 Expr *RHS, bool isProperty) {
11714 // Strip off any implicit cast added to get to the one ARC-specific.
11715 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11716 if (cast->getCastKind() == CK_ARCConsumeObject) {
11717 S.Diag(Loc, diag::warn_arc_retained_assign)
11718 << (LT == Qualifiers::OCL_ExplicitNone)
11719 << (isProperty ? 0 : 1)
11720 << RHS->getSourceRange();
11721 return true;
11722 }
11723 RHS = cast->getSubExpr();
11724 }
11725
11726 if (LT == Qualifiers::OCL_Weak &&
11727 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
11728 return true;
11729
11730 return false;
11731}
11732
Ted Kremenekb36234d2012-12-21 08:04:20 +000011733bool Sema::checkUnsafeAssigns(SourceLocation Loc,
11734 QualType LHS, Expr *RHS) {
11735 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
11736
11737 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
11738 return false;
11739
11740 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
11741 return true;
11742
11743 return false;
11744}
11745
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011746void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
11747 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011748 QualType LHSType;
11749 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000011750 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011751 ObjCPropertyRefExpr *PRE
11752 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11753 if (PRE && !PRE->isImplicitProperty()) {
11754 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11755 if (PD)
11756 LHSType = PD->getType();
11757 }
11758
11759 if (LHSType.isNull())
11760 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000011761
11762 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
11763
11764 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011765 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000011766 getCurFunction()->markSafeWeakUse(LHS);
11767 }
11768
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011769 if (checkUnsafeAssigns(Loc, LHSType, RHS))
11770 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000011771
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011772 // FIXME. Check for other life times.
11773 if (LT != Qualifiers::OCL_None)
11774 return;
11775
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011776 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011777 if (PRE->isImplicitProperty())
11778 return;
11779 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11780 if (!PD)
11781 return;
11782
Bill Wendling44426052012-12-20 19:22:21 +000011783 unsigned Attributes = PD->getPropertyAttributes();
11784 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011785 // when 'assign' attribute was not explicitly specified
11786 // by user, ignore it and rely on property type itself
11787 // for lifetime info.
11788 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11789 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11790 LHSType->isObjCRetainableType())
11791 return;
11792
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011793 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000011794 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011795 Diag(Loc, diag::warn_arc_retained_property_assign)
11796 << RHS->getSourceRange();
11797 return;
11798 }
11799 RHS = cast->getSubExpr();
11800 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011801 }
Bill Wendling44426052012-12-20 19:22:21 +000011802 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000011803 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11804 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000011805 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011806 }
11807}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011808
11809//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11810
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011811static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11812 SourceLocation StmtLoc,
11813 const NullStmt *Body) {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011814 // Do not warn if the body is a macro that expands to nothing, e.g:
11815 //
11816 // #define CALL(x)
11817 // if (condition)
11818 // CALL(0);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011819 if (Body->hasLeadingEmptyMacro())
11820 return false;
11821
11822 // Get line numbers of statement and body.
11823 bool StmtLineInvalid;
Hans Wennborg95419752017-11-20 17:38:16 +000011824 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011825 &StmtLineInvalid);
11826 if (StmtLineInvalid)
11827 return false;
11828
11829 bool BodyLineInvalid;
11830 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11831 &BodyLineInvalid);
11832 if (BodyLineInvalid)
11833 return false;
11834
11835 // Warn if null statement and body are on the same line.
11836 if (StmtLine != BodyLine)
11837 return false;
11838
11839 return true;
11840}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011841
11842void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
11843 const Stmt *Body,
11844 unsigned DiagID) {
11845 // Since this is a syntactic check, don't emit diagnostic for template
11846 // instantiations, this just adds noise.
11847 if (CurrentInstantiationScope)
11848 return;
11849
11850 // The body should be a null statement.
11851 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11852 if (!NBody)
11853 return;
11854
11855 // Do the usual checks.
11856 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11857 return;
11858
11859 Diag(NBody->getSemiLoc(), DiagID);
11860 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11861}
11862
11863void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
11864 const Stmt *PossibleBody) {
11865 assert(!CurrentInstantiationScope); // Ensured by caller
11866
11867 SourceLocation StmtLoc;
11868 const Stmt *Body;
11869 unsigned DiagID;
11870 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11871 StmtLoc = FS->getRParenLoc();
11872 Body = FS->getBody();
11873 DiagID = diag::warn_empty_for_body;
11874 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11875 StmtLoc = WS->getCond()->getSourceRange().getEnd();
11876 Body = WS->getBody();
11877 DiagID = diag::warn_empty_while_body;
11878 } else
11879 return; // Neither `for' nor `while'.
11880
11881 // The body should be a null statement.
11882 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11883 if (!NBody)
11884 return;
11885
11886 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011887 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011888 return;
11889
11890 // Do the usual checks.
11891 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11892 return;
11893
11894 // `for(...);' and `while(...);' are popular idioms, so in order to keep
11895 // noise level low, emit diagnostics only if for/while is followed by a
11896 // CompoundStmt, e.g.:
11897 // for (int i = 0; i < n; i++);
11898 // {
11899 // a(i);
11900 // }
11901 // or if for/while is followed by a statement with more indentation
11902 // than for/while itself:
11903 // for (int i = 0; i < n; i++);
11904 // a(i);
11905 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
11906 if (!ProbableTypo) {
11907 bool BodyColInvalid;
11908 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
11909 PossibleBody->getLocStart(),
11910 &BodyColInvalid);
11911 if (BodyColInvalid)
11912 return;
11913
11914 bool StmtColInvalid;
11915 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
11916 S->getLocStart(),
11917 &StmtColInvalid);
11918 if (StmtColInvalid)
11919 return;
11920
11921 if (BodyCol > StmtCol)
11922 ProbableTypo = true;
11923 }
11924
11925 if (ProbableTypo) {
11926 Diag(NBody->getSemiLoc(), DiagID);
11927 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11928 }
11929}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011930
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011931//===--- CHECK: Warn on self move with std::move. -------------------------===//
11932
11933/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
11934void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
11935 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011936 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11937 return;
11938
Richard Smith51ec0cf2017-02-21 01:17:38 +000011939 if (inTemplateInstantiation())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011940 return;
11941
11942 // Strip parens and casts away.
11943 LHSExpr = LHSExpr->IgnoreParenImpCasts();
11944 RHSExpr = RHSExpr->IgnoreParenImpCasts();
11945
11946 // Check for a call expression
11947 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
11948 if (!CE || CE->getNumArgs() != 1)
11949 return;
11950
11951 // Check for a call to std::move
Nico Weberb688d132017-09-28 16:16:39 +000011952 if (!CE->isCallToStdMove())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011953 return;
11954
11955 // Get argument from std::move
11956 RHSExpr = CE->getArg(0);
11957
11958 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11959 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11960
11961 // Two DeclRefExpr's, check that the decls are the same.
11962 if (LHSDeclRef && RHSDeclRef) {
11963 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11964 return;
11965 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11966 RHSDeclRef->getDecl()->getCanonicalDecl())
11967 return;
11968
11969 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11970 << LHSExpr->getSourceRange()
11971 << RHSExpr->getSourceRange();
11972 return;
11973 }
11974
11975 // Member variables require a different approach to check for self moves.
11976 // MemberExpr's are the same if every nested MemberExpr refers to the same
11977 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
11978 // the base Expr's are CXXThisExpr's.
11979 const Expr *LHSBase = LHSExpr;
11980 const Expr *RHSBase = RHSExpr;
11981 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
11982 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
11983 if (!LHSME || !RHSME)
11984 return;
11985
11986 while (LHSME && RHSME) {
11987 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
11988 RHSME->getMemberDecl()->getCanonicalDecl())
11989 return;
11990
11991 LHSBase = LHSME->getBase();
11992 RHSBase = RHSME->getBase();
11993 LHSME = dyn_cast<MemberExpr>(LHSBase);
11994 RHSME = dyn_cast<MemberExpr>(RHSBase);
11995 }
11996
11997 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
11998 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
11999 if (LHSDeclRef && RHSDeclRef) {
12000 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
12001 return;
12002 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
12003 RHSDeclRef->getDecl()->getCanonicalDecl())
12004 return;
12005
12006 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12007 << LHSExpr->getSourceRange()
12008 << RHSExpr->getSourceRange();
12009 return;
12010 }
12011
12012 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
12013 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12014 << LHSExpr->getSourceRange()
12015 << RHSExpr->getSourceRange();
12016}
12017
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012018//===--- Layout compatibility ----------------------------------------------//
12019
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012020static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012021
12022/// \brief Check if two enumeration types are layout-compatible.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012023static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012024 // C++11 [dcl.enum] p8:
12025 // Two enumeration types are layout-compatible if they have the same
12026 // underlying type.
12027 return ED1->isComplete() && ED2->isComplete() &&
12028 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
12029}
12030
12031/// \brief Check if two fields are layout-compatible.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012032static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
12033 FieldDecl *Field2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012034 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
12035 return false;
12036
12037 if (Field1->isBitField() != Field2->isBitField())
12038 return false;
12039
12040 if (Field1->isBitField()) {
12041 // Make sure that the bit-fields are the same length.
12042 unsigned Bits1 = Field1->getBitWidthValue(C);
12043 unsigned Bits2 = Field2->getBitWidthValue(C);
12044
12045 if (Bits1 != Bits2)
12046 return false;
12047 }
12048
12049 return true;
12050}
12051
12052/// \brief Check if two standard-layout structs are layout-compatible.
12053/// (C++11 [class.mem] p17)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012054static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
12055 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012056 // If both records are C++ classes, check that base classes match.
12057 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
12058 // If one of records is a CXXRecordDecl we are in C++ mode,
12059 // thus the other one is a CXXRecordDecl, too.
12060 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
12061 // Check number of base classes.
12062 if (D1CXX->getNumBases() != D2CXX->getNumBases())
12063 return false;
12064
12065 // Check the base classes.
12066 for (CXXRecordDecl::base_class_const_iterator
12067 Base1 = D1CXX->bases_begin(),
12068 BaseEnd1 = D1CXX->bases_end(),
12069 Base2 = D2CXX->bases_begin();
12070 Base1 != BaseEnd1;
12071 ++Base1, ++Base2) {
12072 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
12073 return false;
12074 }
12075 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
12076 // If only RD2 is a C++ class, it should have zero base classes.
12077 if (D2CXX->getNumBases() > 0)
12078 return false;
12079 }
12080
12081 // Check the fields.
12082 RecordDecl::field_iterator Field2 = RD2->field_begin(),
12083 Field2End = RD2->field_end(),
12084 Field1 = RD1->field_begin(),
12085 Field1End = RD1->field_end();
12086 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
12087 if (!isLayoutCompatible(C, *Field1, *Field2))
12088 return false;
12089 }
12090 if (Field1 != Field1End || Field2 != Field2End)
12091 return false;
12092
12093 return true;
12094}
12095
12096/// \brief Check if two standard-layout unions are layout-compatible.
12097/// (C++11 [class.mem] p18)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012098static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
12099 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012100 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012101 for (auto *Field2 : RD2->fields())
12102 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012103
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012104 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012105 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
12106 I = UnmatchedFields.begin(),
12107 E = UnmatchedFields.end();
12108
12109 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012110 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012111 bool Result = UnmatchedFields.erase(*I);
12112 (void) Result;
12113 assert(Result);
12114 break;
12115 }
12116 }
12117 if (I == E)
12118 return false;
12119 }
12120
12121 return UnmatchedFields.empty();
12122}
12123
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012124static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
12125 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012126 if (RD1->isUnion() != RD2->isUnion())
12127 return false;
12128
12129 if (RD1->isUnion())
12130 return isLayoutCompatibleUnion(C, RD1, RD2);
12131 else
12132 return isLayoutCompatibleStruct(C, RD1, RD2);
12133}
12134
12135/// \brief Check if two types are layout-compatible in C++11 sense.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012136static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012137 if (T1.isNull() || T2.isNull())
12138 return false;
12139
12140 // C++11 [basic.types] p11:
12141 // If two types T1 and T2 are the same type, then T1 and T2 are
12142 // layout-compatible types.
12143 if (C.hasSameType(T1, T2))
12144 return true;
12145
12146 T1 = T1.getCanonicalType().getUnqualifiedType();
12147 T2 = T2.getCanonicalType().getUnqualifiedType();
12148
12149 const Type::TypeClass TC1 = T1->getTypeClass();
12150 const Type::TypeClass TC2 = T2->getTypeClass();
12151
12152 if (TC1 != TC2)
12153 return false;
12154
12155 if (TC1 == Type::Enum) {
12156 return isLayoutCompatible(C,
12157 cast<EnumType>(T1)->getDecl(),
12158 cast<EnumType>(T2)->getDecl());
12159 } else if (TC1 == Type::Record) {
12160 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
12161 return false;
12162
12163 return isLayoutCompatible(C,
12164 cast<RecordType>(T1)->getDecl(),
12165 cast<RecordType>(T2)->getDecl());
12166 }
12167
12168 return false;
12169}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012170
12171//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
12172
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012173/// \brief Given a type tag expression find the type tag itself.
12174///
12175/// \param TypeExpr Type tag expression, as it appears in user's code.
12176///
12177/// \param VD Declaration of an identifier that appears in a type tag.
12178///
12179/// \param MagicValue Type tag magic value.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012180static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
12181 const ValueDecl **VD, uint64_t *MagicValue) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012182 while(true) {
12183 if (!TypeExpr)
12184 return false;
12185
12186 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
12187
12188 switch (TypeExpr->getStmtClass()) {
12189 case Stmt::UnaryOperatorClass: {
12190 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
12191 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
12192 TypeExpr = UO->getSubExpr();
12193 continue;
12194 }
12195 return false;
12196 }
12197
12198 case Stmt::DeclRefExprClass: {
12199 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
12200 *VD = DRE->getDecl();
12201 return true;
12202 }
12203
12204 case Stmt::IntegerLiteralClass: {
12205 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
12206 llvm::APInt MagicValueAPInt = IL->getValue();
12207 if (MagicValueAPInt.getActiveBits() <= 64) {
12208 *MagicValue = MagicValueAPInt.getZExtValue();
12209 return true;
12210 } else
12211 return false;
12212 }
12213
12214 case Stmt::BinaryConditionalOperatorClass:
12215 case Stmt::ConditionalOperatorClass: {
12216 const AbstractConditionalOperator *ACO =
12217 cast<AbstractConditionalOperator>(TypeExpr);
12218 bool Result;
12219 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
12220 if (Result)
12221 TypeExpr = ACO->getTrueExpr();
12222 else
12223 TypeExpr = ACO->getFalseExpr();
12224 continue;
12225 }
12226 return false;
12227 }
12228
12229 case Stmt::BinaryOperatorClass: {
12230 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
12231 if (BO->getOpcode() == BO_Comma) {
12232 TypeExpr = BO->getRHS();
12233 continue;
12234 }
12235 return false;
12236 }
12237
12238 default:
12239 return false;
12240 }
12241 }
12242}
12243
12244/// \brief Retrieve the C type corresponding to type tag TypeExpr.
12245///
12246/// \param TypeExpr Expression that specifies a type tag.
12247///
12248/// \param MagicValues Registered magic values.
12249///
12250/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
12251/// kind.
12252///
12253/// \param TypeInfo Information about the corresponding C type.
12254///
12255/// \returns true if the corresponding C type was found.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012256static bool GetMatchingCType(
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012257 const IdentifierInfo *ArgumentKind,
12258 const Expr *TypeExpr, const ASTContext &Ctx,
12259 const llvm::DenseMap<Sema::TypeTagMagicValue,
12260 Sema::TypeTagData> *MagicValues,
12261 bool &FoundWrongKind,
12262 Sema::TypeTagData &TypeInfo) {
12263 FoundWrongKind = false;
12264
12265 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000012266 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012267
12268 uint64_t MagicValue;
12269
12270 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
12271 return false;
12272
12273 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000012274 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012275 if (I->getArgumentKind() != ArgumentKind) {
12276 FoundWrongKind = true;
12277 return false;
12278 }
12279 TypeInfo.Type = I->getMatchingCType();
12280 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
12281 TypeInfo.MustBeNull = I->getMustBeNull();
12282 return true;
12283 }
12284 return false;
12285 }
12286
12287 if (!MagicValues)
12288 return false;
12289
12290 llvm::DenseMap<Sema::TypeTagMagicValue,
12291 Sema::TypeTagData>::const_iterator I =
12292 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
12293 if (I == MagicValues->end())
12294 return false;
12295
12296 TypeInfo = I->second;
12297 return true;
12298}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012299
12300void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
12301 uint64_t MagicValue, QualType Type,
12302 bool LayoutCompatible,
12303 bool MustBeNull) {
12304 if (!TypeTagForDatatypeMagicValues)
12305 TypeTagForDatatypeMagicValues.reset(
12306 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
12307
12308 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
12309 (*TypeTagForDatatypeMagicValues)[Magic] =
12310 TypeTagData(Type, LayoutCompatible, MustBeNull);
12311}
12312
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012313static bool IsSameCharType(QualType T1, QualType T2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012314 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
12315 if (!BT1)
12316 return false;
12317
12318 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
12319 if (!BT2)
12320 return false;
12321
12322 BuiltinType::Kind T1Kind = BT1->getKind();
12323 BuiltinType::Kind T2Kind = BT2->getKind();
12324
12325 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
12326 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
12327 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
12328 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
12329}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012330
12331void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
12332 const Expr * const *ExprArgs) {
12333 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
12334 bool IsPointerAttr = Attr->getIsPointer();
12335
12336 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
12337 bool FoundWrongKind;
12338 TypeTagData TypeInfo;
12339 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
12340 TypeTagForDatatypeMagicValues.get(),
12341 FoundWrongKind, TypeInfo)) {
12342 if (FoundWrongKind)
12343 Diag(TypeTagExpr->getExprLoc(),
12344 diag::warn_type_tag_for_datatype_wrong_kind)
12345 << TypeTagExpr->getSourceRange();
12346 return;
12347 }
12348
12349 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
12350 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() ||
12440 (T->isPointerType() &&
12441 Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment)))
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012442 MisalignedMembers.erase(MA);
12443 }
12444 }
12445}
12446
12447void Sema::RefersToMemberWithReducedAlignment(
12448 Expr *E,
Benjamin Kramera8c3e672016-12-12 14:41:19 +000012449 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
12450 Action) {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012451 const auto *ME = dyn_cast<MemberExpr>(E);
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012452 if (!ME)
12453 return;
12454
Roger Ferrer Ibanez9f963472017-03-13 13:18:21 +000012455 // No need to check expressions with an __unaligned-qualified type.
12456 if (E->getType().getQualifiers().hasUnaligned())
12457 return;
12458
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012459 // For a chain of MemberExpr like "a.b.c.d" this list
12460 // will keep FieldDecl's like [d, c, b].
12461 SmallVector<FieldDecl *, 4> ReverseMemberChain;
12462 const MemberExpr *TopME = nullptr;
12463 bool AnyIsPacked = false;
12464 do {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012465 QualType BaseType = ME->getBase()->getType();
12466 if (ME->isArrow())
12467 BaseType = BaseType->getPointeeType();
12468 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
Olivier Goffart67049f02017-07-07 09:38:59 +000012469 if (RD->isInvalidDecl())
12470 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012471
12472 ValueDecl *MD = ME->getMemberDecl();
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012473 auto *FD = dyn_cast<FieldDecl>(MD);
12474 // We do not care about non-data members.
12475 if (!FD || FD->isInvalidDecl())
12476 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012477
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012478 AnyIsPacked =
12479 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
12480 ReverseMemberChain.push_back(FD);
12481
12482 TopME = ME;
12483 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
12484 } while (ME);
12485 assert(TopME && "We did not compute a topmost MemberExpr!");
12486
12487 // Not the scope of this diagnostic.
12488 if (!AnyIsPacked)
12489 return;
12490
12491 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
12492 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
12493 // TODO: The innermost base of the member expression may be too complicated.
12494 // For now, just disregard these cases. This is left for future
12495 // improvement.
12496 if (!DRE && !isa<CXXThisExpr>(TopBase))
12497 return;
12498
12499 // Alignment expected by the whole expression.
12500 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
12501
12502 // No need to do anything else with this case.
12503 if (ExpectedAlignment.isOne())
12504 return;
12505
12506 // Synthesize offset of the whole access.
12507 CharUnits Offset;
12508 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
12509 I++) {
12510 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
12511 }
12512
12513 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
12514 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
12515 ReverseMemberChain.back()->getParent()->getTypeForDecl());
12516
12517 // The base expression of the innermost MemberExpr may give
12518 // stronger guarantees than the class containing the member.
12519 if (DRE && !TopME->isArrow()) {
12520 const ValueDecl *VD = DRE->getDecl();
12521 if (!VD->getType()->isReferenceType())
12522 CompleteObjectAlignment =
12523 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
12524 }
12525
12526 // Check if the synthesized offset fulfills the alignment.
12527 if (Offset % ExpectedAlignment != 0 ||
12528 // It may fulfill the offset it but the effective alignment may still be
12529 // lower than the expected expression alignment.
12530 CompleteObjectAlignment < ExpectedAlignment) {
12531 // If this happens, we want to determine a sensible culprit of this.
12532 // Intuitively, watching the chain of member expressions from right to
12533 // left, we start with the required alignment (as required by the field
12534 // type) but some packed attribute in that chain has reduced the alignment.
12535 // It may happen that another packed structure increases it again. But if
12536 // we are here such increase has not been enough. So pointing the first
12537 // FieldDecl that either is packed or else its RecordDecl is,
12538 // seems reasonable.
12539 FieldDecl *FD = nullptr;
12540 CharUnits Alignment;
12541 for (FieldDecl *FDI : ReverseMemberChain) {
12542 if (FDI->hasAttr<PackedAttr>() ||
12543 FDI->getParent()->hasAttr<PackedAttr>()) {
12544 FD = FDI;
12545 Alignment = std::min(
12546 Context.getTypeAlignInChars(FD->getType()),
12547 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
12548 break;
12549 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012550 }
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012551 assert(FD && "We did not find a packed FieldDecl!");
12552 Action(E, FD->getParent(), FD, Alignment);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012553 }
12554}
12555
12556void Sema::CheckAddressOfPackedMember(Expr *rhs) {
12557 using namespace std::placeholders;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012558
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012559 RefersToMemberWithReducedAlignment(
12560 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
12561 _2, _3, _4));
12562}