blob: 803f87b3c56869e13a1885d034bd2bdfaf3d3654 [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.
Sjoerd Meijer293da702017-12-07 09:54:39 +00001557 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begemand773fe62010-06-13 04:47:52 +00001558 switch (BuiltinID) {
1559 default: return false;
Sjoerd Meijer293da702017-12-07 09:54:39 +00001560 case ARM::BI__builtin_arm_ssat:
1561 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
1562 case ARM::BI__builtin_arm_usat:
1563 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
1564 case ARM::BI__builtin_arm_ssat16:
1565 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
1566 case ARM::BI__builtin_arm_usat16:
1567 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
Nate Begemanf568b072010-08-03 21:32:34 +00001568 case ARM::BI__builtin_arm_vcvtr_f:
Sjoerd Meijer293da702017-12-07 09:54:39 +00001569 case ARM::BI__builtin_arm_vcvtr_d:
1570 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
Weiming Zhao87bb4922013-11-12 21:42:50 +00001571 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001572 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001573 case ARM::BI__builtin_arm_isb:
Sjoerd Meijer293da702017-12-07 09:54:39 +00001574 case ARM::BI__builtin_arm_dbg:
1575 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
Richard Sandiford28940af2014-04-16 08:47:51 +00001576 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001577}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001578
Tim Northover573cbee2014-05-24 12:52:07 +00001579bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001580 CallExpr *TheCall) {
Tim Northover573cbee2014-05-24 12:52:07 +00001581 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001582 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1583 BuiltinID == AArch64::BI__builtin_arm_strex ||
1584 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001585 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1586 }
1587
Yi Konga5548432014-08-13 19:18:20 +00001588 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1589 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1590 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1591 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1592 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1593 }
1594
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001595 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1596 BuiltinID == AArch64::BI__builtin_arm_wsr64)
Tim Northover54e50002016-04-13 17:08:55 +00001597 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001598
1599 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1600 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1601 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1602 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1603 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1604
Tim Northovera2ee4332014-03-29 15:09:45 +00001605 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1606 return true;
1607
Yi Kong19a29ac2014-07-17 10:52:06 +00001608 // For intrinsics which take an immediate value as part of the instruction,
1609 // range check them here.
1610 unsigned i = 0, l = 0, u = 0;
1611 switch (BuiltinID) {
1612 default: return false;
1613 case AArch64::BI__builtin_arm_dmb:
1614 case AArch64::BI__builtin_arm_dsb:
1615 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1616 }
1617
Yi Kong19a29ac2014-07-17 10:52:06 +00001618 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001619}
1620
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001621// CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1622// intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1623// ordering for DSP is unspecified. MSA is ordered by the data format used
1624// by the underlying instruction i.e., df/m, df/n and then by size.
1625//
1626// FIXME: The size tests here should instead be tablegen'd along with the
1627// definitions from include/clang/Basic/BuiltinsMips.def.
1628// FIXME: GCC is strict on signedness for some of these intrinsics, we should
1629// be too.
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001630bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001631 unsigned i = 0, l = 0, u = 0, m = 0;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001632 switch (BuiltinID) {
1633 default: return false;
1634 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1635 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00001636 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1637 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1638 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1639 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1640 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001641 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1642 // df/m field.
1643 // These intrinsics take an unsigned 3 bit immediate.
1644 case Mips::BI__builtin_msa_bclri_b:
1645 case Mips::BI__builtin_msa_bnegi_b:
1646 case Mips::BI__builtin_msa_bseti_b:
1647 case Mips::BI__builtin_msa_sat_s_b:
1648 case Mips::BI__builtin_msa_sat_u_b:
1649 case Mips::BI__builtin_msa_slli_b:
1650 case Mips::BI__builtin_msa_srai_b:
1651 case Mips::BI__builtin_msa_srari_b:
1652 case Mips::BI__builtin_msa_srli_b:
1653 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1654 case Mips::BI__builtin_msa_binsli_b:
1655 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1656 // These intrinsics take an unsigned 4 bit immediate.
1657 case Mips::BI__builtin_msa_bclri_h:
1658 case Mips::BI__builtin_msa_bnegi_h:
1659 case Mips::BI__builtin_msa_bseti_h:
1660 case Mips::BI__builtin_msa_sat_s_h:
1661 case Mips::BI__builtin_msa_sat_u_h:
1662 case Mips::BI__builtin_msa_slli_h:
1663 case Mips::BI__builtin_msa_srai_h:
1664 case Mips::BI__builtin_msa_srari_h:
1665 case Mips::BI__builtin_msa_srli_h:
1666 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1667 case Mips::BI__builtin_msa_binsli_h:
1668 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
1669 // These intrinsics take an unsigned 5 bit immedate.
1670 // The first block of intrinsics actually have an unsigned 5 bit field,
1671 // not a df/n field.
1672 case Mips::BI__builtin_msa_clei_u_b:
1673 case Mips::BI__builtin_msa_clei_u_h:
1674 case Mips::BI__builtin_msa_clei_u_w:
1675 case Mips::BI__builtin_msa_clei_u_d:
1676 case Mips::BI__builtin_msa_clti_u_b:
1677 case Mips::BI__builtin_msa_clti_u_h:
1678 case Mips::BI__builtin_msa_clti_u_w:
1679 case Mips::BI__builtin_msa_clti_u_d:
1680 case Mips::BI__builtin_msa_maxi_u_b:
1681 case Mips::BI__builtin_msa_maxi_u_h:
1682 case Mips::BI__builtin_msa_maxi_u_w:
1683 case Mips::BI__builtin_msa_maxi_u_d:
1684 case Mips::BI__builtin_msa_mini_u_b:
1685 case Mips::BI__builtin_msa_mini_u_h:
1686 case Mips::BI__builtin_msa_mini_u_w:
1687 case Mips::BI__builtin_msa_mini_u_d:
1688 case Mips::BI__builtin_msa_addvi_b:
1689 case Mips::BI__builtin_msa_addvi_h:
1690 case Mips::BI__builtin_msa_addvi_w:
1691 case Mips::BI__builtin_msa_addvi_d:
1692 case Mips::BI__builtin_msa_bclri_w:
1693 case Mips::BI__builtin_msa_bnegi_w:
1694 case Mips::BI__builtin_msa_bseti_w:
1695 case Mips::BI__builtin_msa_sat_s_w:
1696 case Mips::BI__builtin_msa_sat_u_w:
1697 case Mips::BI__builtin_msa_slli_w:
1698 case Mips::BI__builtin_msa_srai_w:
1699 case Mips::BI__builtin_msa_srari_w:
1700 case Mips::BI__builtin_msa_srli_w:
1701 case Mips::BI__builtin_msa_srlri_w:
1702 case Mips::BI__builtin_msa_subvi_b:
1703 case Mips::BI__builtin_msa_subvi_h:
1704 case Mips::BI__builtin_msa_subvi_w:
1705 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1706 case Mips::BI__builtin_msa_binsli_w:
1707 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1708 // These intrinsics take an unsigned 6 bit immediate.
1709 case Mips::BI__builtin_msa_bclri_d:
1710 case Mips::BI__builtin_msa_bnegi_d:
1711 case Mips::BI__builtin_msa_bseti_d:
1712 case Mips::BI__builtin_msa_sat_s_d:
1713 case Mips::BI__builtin_msa_sat_u_d:
1714 case Mips::BI__builtin_msa_slli_d:
1715 case Mips::BI__builtin_msa_srai_d:
1716 case Mips::BI__builtin_msa_srari_d:
1717 case Mips::BI__builtin_msa_srli_d:
1718 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1719 case Mips::BI__builtin_msa_binsli_d:
1720 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1721 // These intrinsics take a signed 5 bit immediate.
1722 case Mips::BI__builtin_msa_ceqi_b:
1723 case Mips::BI__builtin_msa_ceqi_h:
1724 case Mips::BI__builtin_msa_ceqi_w:
1725 case Mips::BI__builtin_msa_ceqi_d:
1726 case Mips::BI__builtin_msa_clti_s_b:
1727 case Mips::BI__builtin_msa_clti_s_h:
1728 case Mips::BI__builtin_msa_clti_s_w:
1729 case Mips::BI__builtin_msa_clti_s_d:
1730 case Mips::BI__builtin_msa_clei_s_b:
1731 case Mips::BI__builtin_msa_clei_s_h:
1732 case Mips::BI__builtin_msa_clei_s_w:
1733 case Mips::BI__builtin_msa_clei_s_d:
1734 case Mips::BI__builtin_msa_maxi_s_b:
1735 case Mips::BI__builtin_msa_maxi_s_h:
1736 case Mips::BI__builtin_msa_maxi_s_w:
1737 case Mips::BI__builtin_msa_maxi_s_d:
1738 case Mips::BI__builtin_msa_mini_s_b:
1739 case Mips::BI__builtin_msa_mini_s_h:
1740 case Mips::BI__builtin_msa_mini_s_w:
1741 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
1742 // These intrinsics take an unsigned 8 bit immediate.
1743 case Mips::BI__builtin_msa_andi_b:
1744 case Mips::BI__builtin_msa_nori_b:
1745 case Mips::BI__builtin_msa_ori_b:
1746 case Mips::BI__builtin_msa_shf_b:
1747 case Mips::BI__builtin_msa_shf_h:
1748 case Mips::BI__builtin_msa_shf_w:
1749 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
1750 case Mips::BI__builtin_msa_bseli_b:
1751 case Mips::BI__builtin_msa_bmnzi_b:
1752 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
1753 // df/n format
1754 // These intrinsics take an unsigned 4 bit immediate.
1755 case Mips::BI__builtin_msa_copy_s_b:
1756 case Mips::BI__builtin_msa_copy_u_b:
1757 case Mips::BI__builtin_msa_insve_b:
1758 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001759 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
1760 // These intrinsics take an unsigned 3 bit immediate.
1761 case Mips::BI__builtin_msa_copy_s_h:
1762 case Mips::BI__builtin_msa_copy_u_h:
1763 case Mips::BI__builtin_msa_insve_h:
1764 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001765 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1766 // These intrinsics take an unsigned 2 bit immediate.
1767 case Mips::BI__builtin_msa_copy_s_w:
1768 case Mips::BI__builtin_msa_copy_u_w:
1769 case Mips::BI__builtin_msa_insve_w:
1770 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001771 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1772 // These intrinsics take an unsigned 1 bit immediate.
1773 case Mips::BI__builtin_msa_copy_s_d:
1774 case Mips::BI__builtin_msa_copy_u_d:
1775 case Mips::BI__builtin_msa_insve_d:
1776 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001777 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1778 // Memory offsets and immediate loads.
1779 // These intrinsics take a signed 10 bit immediate.
Petar Jovanovic9b8b9e82017-03-31 16:16:43 +00001780 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001781 case Mips::BI__builtin_msa_ldi_h:
1782 case Mips::BI__builtin_msa_ldi_w:
1783 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1784 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1785 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1786 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1787 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1788 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1789 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1790 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1791 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001792 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001793
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001794 if (!m)
1795 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1796
1797 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1798 SemaBuiltinConstantArgMultiple(TheCall, i, m);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001799}
1800
Kit Bartone50adcb2015-03-30 19:40:59 +00001801bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1802 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00001803 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1804 BuiltinID == PPC::BI__builtin_divdeu ||
1805 BuiltinID == PPC::BI__builtin_bpermd;
1806 bool IsTarget64Bit = Context.getTargetInfo()
1807 .getTypeWidth(Context
1808 .getTargetInfo()
1809 .getIntPtrType()) == 64;
1810 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1811 BuiltinID == PPC::BI__builtin_divweu ||
1812 BuiltinID == PPC::BI__builtin_divde ||
1813 BuiltinID == PPC::BI__builtin_divdeu;
1814
1815 if (Is64BitBltin && !IsTarget64Bit)
1816 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1817 << TheCall->getSourceRange();
1818
1819 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1820 (BuiltinID == PPC::BI__builtin_bpermd &&
1821 !Context.getTargetInfo().hasFeature("bpermd")))
1822 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1823 << TheCall->getSourceRange();
1824
Kit Bartone50adcb2015-03-30 19:40:59 +00001825 switch (BuiltinID) {
1826 default: return false;
1827 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1828 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1829 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1830 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1831 case PPC::BI__builtin_tbegin:
1832 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1833 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1834 case PPC::BI__builtin_tabortwc:
1835 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1836 case PPC::BI__builtin_tabortwci:
1837 case PPC::BI__builtin_tabortdci:
1838 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1839 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
Tony Jiangbbc48e92017-05-24 15:13:32 +00001840 case PPC::BI__builtin_vsx_xxpermdi:
Tony Jiang9aa2c032017-05-24 15:54:13 +00001841 case PPC::BI__builtin_vsx_xxsldwi:
Tony Jiangbbc48e92017-05-24 15:13:32 +00001842 return SemaBuiltinVSX(TheCall);
Kit Bartone50adcb2015-03-30 19:40:59 +00001843 }
1844 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1845}
1846
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001847bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1848 CallExpr *TheCall) {
1849 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1850 Expr *Arg = TheCall->getArg(0);
1851 llvm::APSInt AbortCode(32);
1852 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1853 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1854 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1855 << Arg->getSourceRange();
1856 }
1857
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001858 // For intrinsics which take an immediate value as part of the instruction,
1859 // range check them here.
1860 unsigned i = 0, l = 0, u = 0;
1861 switch (BuiltinID) {
1862 default: return false;
1863 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1864 case SystemZ::BI__builtin_s390_verimb:
1865 case SystemZ::BI__builtin_s390_verimh:
1866 case SystemZ::BI__builtin_s390_verimf:
1867 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1868 case SystemZ::BI__builtin_s390_vfaeb:
1869 case SystemZ::BI__builtin_s390_vfaeh:
1870 case SystemZ::BI__builtin_s390_vfaef:
1871 case SystemZ::BI__builtin_s390_vfaebs:
1872 case SystemZ::BI__builtin_s390_vfaehs:
1873 case SystemZ::BI__builtin_s390_vfaefs:
1874 case SystemZ::BI__builtin_s390_vfaezb:
1875 case SystemZ::BI__builtin_s390_vfaezh:
1876 case SystemZ::BI__builtin_s390_vfaezf:
1877 case SystemZ::BI__builtin_s390_vfaezbs:
1878 case SystemZ::BI__builtin_s390_vfaezhs:
1879 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00001880 case SystemZ::BI__builtin_s390_vfisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001881 case SystemZ::BI__builtin_s390_vfidb:
1882 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1883 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00001884 case SystemZ::BI__builtin_s390_vftcisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001885 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1886 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1887 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1888 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1889 case SystemZ::BI__builtin_s390_vstrcb:
1890 case SystemZ::BI__builtin_s390_vstrch:
1891 case SystemZ::BI__builtin_s390_vstrcf:
1892 case SystemZ::BI__builtin_s390_vstrczb:
1893 case SystemZ::BI__builtin_s390_vstrczh:
1894 case SystemZ::BI__builtin_s390_vstrczf:
1895 case SystemZ::BI__builtin_s390_vstrcbs:
1896 case SystemZ::BI__builtin_s390_vstrchs:
1897 case SystemZ::BI__builtin_s390_vstrcfs:
1898 case SystemZ::BI__builtin_s390_vstrczbs:
1899 case SystemZ::BI__builtin_s390_vstrczhs:
1900 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00001901 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
1902 case SystemZ::BI__builtin_s390_vfminsb:
1903 case SystemZ::BI__builtin_s390_vfmaxsb:
1904 case SystemZ::BI__builtin_s390_vfmindb:
1905 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001906 }
1907 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001908}
1909
Craig Topper5ba2c502015-11-07 08:08:31 +00001910/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1911/// This checks that the target supports __builtin_cpu_supports and
1912/// that the string argument is constant and valid.
1913static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1914 Expr *Arg = TheCall->getArg(0);
1915
1916 // Check if the argument is a string literal.
1917 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1918 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1919 << Arg->getSourceRange();
1920
1921 // Check the contents of the string.
1922 StringRef Feature =
1923 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1924 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1925 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1926 << Arg->getSourceRange();
1927 return false;
1928}
1929
Craig Topper699ae0c2017-08-10 20:28:30 +00001930/// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
1931/// This checks that the target supports __builtin_cpu_is and
1932/// that the string argument is constant and valid.
1933static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
1934 Expr *Arg = TheCall->getArg(0);
1935
1936 // Check if the argument is a string literal.
1937 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1938 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1939 << Arg->getSourceRange();
1940
1941 // Check the contents of the string.
1942 StringRef Feature =
1943 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1944 if (!S.Context.getTargetInfo().validateCpuIs(Feature))
1945 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is)
1946 << Arg->getSourceRange();
1947 return false;
1948}
1949
Craig Toppera7e253e2016-09-23 04:48:31 +00001950// Check if the rounding mode is legal.
1951bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
1952 // Indicates if this instruction has rounding control or just SAE.
1953 bool HasRC = false;
1954
1955 unsigned ArgNum = 0;
1956 switch (BuiltinID) {
1957 default:
1958 return false;
1959 case X86::BI__builtin_ia32_vcvttsd2si32:
1960 case X86::BI__builtin_ia32_vcvttsd2si64:
1961 case X86::BI__builtin_ia32_vcvttsd2usi32:
1962 case X86::BI__builtin_ia32_vcvttsd2usi64:
1963 case X86::BI__builtin_ia32_vcvttss2si32:
1964 case X86::BI__builtin_ia32_vcvttss2si64:
1965 case X86::BI__builtin_ia32_vcvttss2usi32:
1966 case X86::BI__builtin_ia32_vcvttss2usi64:
1967 ArgNum = 1;
1968 break;
1969 case X86::BI__builtin_ia32_cvtps2pd512_mask:
1970 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1971 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1972 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1973 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1974 case X86::BI__builtin_ia32_cvttps2dq512_mask:
1975 case X86::BI__builtin_ia32_cvttps2qq512_mask:
1976 case X86::BI__builtin_ia32_cvttps2udq512_mask:
1977 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1978 case X86::BI__builtin_ia32_exp2pd_mask:
1979 case X86::BI__builtin_ia32_exp2ps_mask:
1980 case X86::BI__builtin_ia32_getexppd512_mask:
1981 case X86::BI__builtin_ia32_getexpps512_mask:
1982 case X86::BI__builtin_ia32_rcp28pd_mask:
1983 case X86::BI__builtin_ia32_rcp28ps_mask:
1984 case X86::BI__builtin_ia32_rsqrt28pd_mask:
1985 case X86::BI__builtin_ia32_rsqrt28ps_mask:
1986 case X86::BI__builtin_ia32_vcomisd:
1987 case X86::BI__builtin_ia32_vcomiss:
1988 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1989 ArgNum = 3;
1990 break;
1991 case X86::BI__builtin_ia32_cmppd512_mask:
1992 case X86::BI__builtin_ia32_cmpps512_mask:
1993 case X86::BI__builtin_ia32_cmpsd_mask:
1994 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001995 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00001996 case X86::BI__builtin_ia32_getexpsd128_round_mask:
1997 case X86::BI__builtin_ia32_getexpss128_round_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001998 case X86::BI__builtin_ia32_maxpd512_mask:
1999 case X86::BI__builtin_ia32_maxps512_mask:
2000 case X86::BI__builtin_ia32_maxsd_round_mask:
2001 case X86::BI__builtin_ia32_maxss_round_mask:
2002 case X86::BI__builtin_ia32_minpd512_mask:
2003 case X86::BI__builtin_ia32_minps512_mask:
2004 case X86::BI__builtin_ia32_minsd_round_mask:
2005 case X86::BI__builtin_ia32_minss_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00002006 case X86::BI__builtin_ia32_rcp28sd_round_mask:
2007 case X86::BI__builtin_ia32_rcp28ss_round_mask:
2008 case X86::BI__builtin_ia32_reducepd512_mask:
2009 case X86::BI__builtin_ia32_reduceps512_mask:
2010 case X86::BI__builtin_ia32_rndscalepd_mask:
2011 case X86::BI__builtin_ia32_rndscaleps_mask:
2012 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
2013 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
2014 ArgNum = 4;
2015 break;
2016 case X86::BI__builtin_ia32_fixupimmpd512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002017 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002018 case X86::BI__builtin_ia32_fixupimmps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002019 case X86::BI__builtin_ia32_fixupimmps512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002020 case X86::BI__builtin_ia32_fixupimmsd_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002021 case X86::BI__builtin_ia32_fixupimmsd_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002022 case X86::BI__builtin_ia32_fixupimmss_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002023 case X86::BI__builtin_ia32_fixupimmss_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002024 case X86::BI__builtin_ia32_rangepd512_mask:
2025 case X86::BI__builtin_ia32_rangeps512_mask:
2026 case X86::BI__builtin_ia32_rangesd128_round_mask:
2027 case X86::BI__builtin_ia32_rangess128_round_mask:
2028 case X86::BI__builtin_ia32_reducesd_mask:
2029 case X86::BI__builtin_ia32_reducess_mask:
2030 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2031 case X86::BI__builtin_ia32_rndscaless_round_mask:
2032 ArgNum = 5;
2033 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00002034 case X86::BI__builtin_ia32_vcvtsd2si64:
2035 case X86::BI__builtin_ia32_vcvtsd2si32:
2036 case X86::BI__builtin_ia32_vcvtsd2usi32:
2037 case X86::BI__builtin_ia32_vcvtsd2usi64:
2038 case X86::BI__builtin_ia32_vcvtss2si32:
2039 case X86::BI__builtin_ia32_vcvtss2si64:
2040 case X86::BI__builtin_ia32_vcvtss2usi32:
2041 case X86::BI__builtin_ia32_vcvtss2usi64:
2042 ArgNum = 1;
2043 HasRC = true;
2044 break;
Craig Topper8e066312016-11-07 07:01:09 +00002045 case X86::BI__builtin_ia32_cvtsi2sd64:
2046 case X86::BI__builtin_ia32_cvtsi2ss32:
2047 case X86::BI__builtin_ia32_cvtsi2ss64:
Craig Topper7609f1c2016-10-01 21:03:50 +00002048 case X86::BI__builtin_ia32_cvtusi2sd64:
2049 case X86::BI__builtin_ia32_cvtusi2ss32:
2050 case X86::BI__builtin_ia32_cvtusi2ss64:
2051 ArgNum = 2;
2052 HasRC = true;
2053 break;
2054 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
2055 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
2056 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
2057 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
2058 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
2059 case X86::BI__builtin_ia32_cvtps2qq512_mask:
2060 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
2061 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
2062 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
2063 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
2064 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002065 case X86::BI__builtin_ia32_sqrtpd512_mask:
2066 case X86::BI__builtin_ia32_sqrtps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002067 ArgNum = 3;
2068 HasRC = true;
2069 break;
2070 case X86::BI__builtin_ia32_addpd512_mask:
2071 case X86::BI__builtin_ia32_addps512_mask:
2072 case X86::BI__builtin_ia32_divpd512_mask:
2073 case X86::BI__builtin_ia32_divps512_mask:
2074 case X86::BI__builtin_ia32_mulpd512_mask:
2075 case X86::BI__builtin_ia32_mulps512_mask:
2076 case X86::BI__builtin_ia32_subpd512_mask:
2077 case X86::BI__builtin_ia32_subps512_mask:
2078 case X86::BI__builtin_ia32_addss_round_mask:
2079 case X86::BI__builtin_ia32_addsd_round_mask:
2080 case X86::BI__builtin_ia32_divss_round_mask:
2081 case X86::BI__builtin_ia32_divsd_round_mask:
2082 case X86::BI__builtin_ia32_mulss_round_mask:
2083 case X86::BI__builtin_ia32_mulsd_round_mask:
2084 case X86::BI__builtin_ia32_subss_round_mask:
2085 case X86::BI__builtin_ia32_subsd_round_mask:
2086 case X86::BI__builtin_ia32_scalefpd512_mask:
2087 case X86::BI__builtin_ia32_scalefps512_mask:
2088 case X86::BI__builtin_ia32_scalefsd_round_mask:
2089 case X86::BI__builtin_ia32_scalefss_round_mask:
2090 case X86::BI__builtin_ia32_getmantpd512_mask:
2091 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002092 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
2093 case X86::BI__builtin_ia32_sqrtsd_round_mask:
2094 case X86::BI__builtin_ia32_sqrtss_round_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002095 case X86::BI__builtin_ia32_vfmaddpd512_mask:
2096 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
2097 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
2098 case X86::BI__builtin_ia32_vfmaddps512_mask:
2099 case X86::BI__builtin_ia32_vfmaddps512_mask3:
2100 case X86::BI__builtin_ia32_vfmaddps512_maskz:
2101 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
2102 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
2103 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
2104 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
2105 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
2106 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
2107 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
2108 case X86::BI__builtin_ia32_vfmsubps512_mask3:
2109 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
2110 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
2111 case X86::BI__builtin_ia32_vfnmaddpd512_mask:
2112 case X86::BI__builtin_ia32_vfnmaddps512_mask:
2113 case X86::BI__builtin_ia32_vfnmsubpd512_mask:
2114 case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
2115 case X86::BI__builtin_ia32_vfnmsubps512_mask:
2116 case X86::BI__builtin_ia32_vfnmsubps512_mask3:
2117 case X86::BI__builtin_ia32_vfmaddsd3_mask:
2118 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
2119 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
2120 case X86::BI__builtin_ia32_vfmaddss3_mask:
2121 case X86::BI__builtin_ia32_vfmaddss3_maskz:
2122 case X86::BI__builtin_ia32_vfmaddss3_mask3:
2123 ArgNum = 4;
2124 HasRC = true;
2125 break;
2126 case X86::BI__builtin_ia32_getmantsd_round_mask:
2127 case X86::BI__builtin_ia32_getmantss_round_mask:
2128 ArgNum = 5;
2129 HasRC = true;
2130 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00002131 }
2132
2133 llvm::APSInt Result;
2134
2135 // We can't check the value of a dependent argument.
2136 Expr *Arg = TheCall->getArg(ArgNum);
2137 if (Arg->isTypeDependent() || Arg->isValueDependent())
2138 return false;
2139
2140 // Check constant-ness first.
2141 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2142 return true;
2143
2144 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
2145 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
2146 // combined with ROUND_NO_EXC.
2147 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
2148 Result == 8/*ROUND_NO_EXC*/ ||
2149 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
2150 return false;
2151
2152 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
2153 << Arg->getSourceRange();
2154}
2155
Craig Topperdf5beb22017-03-13 17:16:50 +00002156// Check if the gather/scatter scale is legal.
2157bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
2158 CallExpr *TheCall) {
2159 unsigned ArgNum = 0;
2160 switch (BuiltinID) {
2161 default:
2162 return false;
2163 case X86::BI__builtin_ia32_gatherpfdpd:
2164 case X86::BI__builtin_ia32_gatherpfdps:
2165 case X86::BI__builtin_ia32_gatherpfqpd:
2166 case X86::BI__builtin_ia32_gatherpfqps:
2167 case X86::BI__builtin_ia32_scatterpfdpd:
2168 case X86::BI__builtin_ia32_scatterpfdps:
2169 case X86::BI__builtin_ia32_scatterpfqpd:
2170 case X86::BI__builtin_ia32_scatterpfqps:
2171 ArgNum = 3;
2172 break;
2173 case X86::BI__builtin_ia32_gatherd_pd:
2174 case X86::BI__builtin_ia32_gatherd_pd256:
2175 case X86::BI__builtin_ia32_gatherq_pd:
2176 case X86::BI__builtin_ia32_gatherq_pd256:
2177 case X86::BI__builtin_ia32_gatherd_ps:
2178 case X86::BI__builtin_ia32_gatherd_ps256:
2179 case X86::BI__builtin_ia32_gatherq_ps:
2180 case X86::BI__builtin_ia32_gatherq_ps256:
2181 case X86::BI__builtin_ia32_gatherd_q:
2182 case X86::BI__builtin_ia32_gatherd_q256:
2183 case X86::BI__builtin_ia32_gatherq_q:
2184 case X86::BI__builtin_ia32_gatherq_q256:
2185 case X86::BI__builtin_ia32_gatherd_d:
2186 case X86::BI__builtin_ia32_gatherd_d256:
2187 case X86::BI__builtin_ia32_gatherq_d:
2188 case X86::BI__builtin_ia32_gatherq_d256:
2189 case X86::BI__builtin_ia32_gather3div2df:
2190 case X86::BI__builtin_ia32_gather3div2di:
2191 case X86::BI__builtin_ia32_gather3div4df:
2192 case X86::BI__builtin_ia32_gather3div4di:
2193 case X86::BI__builtin_ia32_gather3div4sf:
2194 case X86::BI__builtin_ia32_gather3div4si:
2195 case X86::BI__builtin_ia32_gather3div8sf:
2196 case X86::BI__builtin_ia32_gather3div8si:
2197 case X86::BI__builtin_ia32_gather3siv2df:
2198 case X86::BI__builtin_ia32_gather3siv2di:
2199 case X86::BI__builtin_ia32_gather3siv4df:
2200 case X86::BI__builtin_ia32_gather3siv4di:
2201 case X86::BI__builtin_ia32_gather3siv4sf:
2202 case X86::BI__builtin_ia32_gather3siv4si:
2203 case X86::BI__builtin_ia32_gather3siv8sf:
2204 case X86::BI__builtin_ia32_gather3siv8si:
2205 case X86::BI__builtin_ia32_gathersiv8df:
2206 case X86::BI__builtin_ia32_gathersiv16sf:
2207 case X86::BI__builtin_ia32_gatherdiv8df:
2208 case X86::BI__builtin_ia32_gatherdiv16sf:
2209 case X86::BI__builtin_ia32_gathersiv8di:
2210 case X86::BI__builtin_ia32_gathersiv16si:
2211 case X86::BI__builtin_ia32_gatherdiv8di:
2212 case X86::BI__builtin_ia32_gatherdiv16si:
2213 case X86::BI__builtin_ia32_scatterdiv2df:
2214 case X86::BI__builtin_ia32_scatterdiv2di:
2215 case X86::BI__builtin_ia32_scatterdiv4df:
2216 case X86::BI__builtin_ia32_scatterdiv4di:
2217 case X86::BI__builtin_ia32_scatterdiv4sf:
2218 case X86::BI__builtin_ia32_scatterdiv4si:
2219 case X86::BI__builtin_ia32_scatterdiv8sf:
2220 case X86::BI__builtin_ia32_scatterdiv8si:
2221 case X86::BI__builtin_ia32_scattersiv2df:
2222 case X86::BI__builtin_ia32_scattersiv2di:
2223 case X86::BI__builtin_ia32_scattersiv4df:
2224 case X86::BI__builtin_ia32_scattersiv4di:
2225 case X86::BI__builtin_ia32_scattersiv4sf:
2226 case X86::BI__builtin_ia32_scattersiv4si:
2227 case X86::BI__builtin_ia32_scattersiv8sf:
2228 case X86::BI__builtin_ia32_scattersiv8si:
2229 case X86::BI__builtin_ia32_scattersiv8df:
2230 case X86::BI__builtin_ia32_scattersiv16sf:
2231 case X86::BI__builtin_ia32_scatterdiv8df:
2232 case X86::BI__builtin_ia32_scatterdiv16sf:
2233 case X86::BI__builtin_ia32_scattersiv8di:
2234 case X86::BI__builtin_ia32_scattersiv16si:
2235 case X86::BI__builtin_ia32_scatterdiv8di:
2236 case X86::BI__builtin_ia32_scatterdiv16si:
2237 ArgNum = 4;
2238 break;
2239 }
2240
2241 llvm::APSInt Result;
2242
2243 // We can't check the value of a dependent argument.
2244 Expr *Arg = TheCall->getArg(ArgNum);
2245 if (Arg->isTypeDependent() || Arg->isValueDependent())
2246 return false;
2247
2248 // Check constant-ness first.
2249 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2250 return true;
2251
2252 if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
2253 return false;
2254
2255 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
2256 << Arg->getSourceRange();
2257}
2258
Craig Topperf0ddc892016-09-23 04:48:27 +00002259bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2260 if (BuiltinID == X86::BI__builtin_cpu_supports)
2261 return SemaBuiltinCpuSupports(*this, TheCall);
2262
Craig Topper699ae0c2017-08-10 20:28:30 +00002263 if (BuiltinID == X86::BI__builtin_cpu_is)
2264 return SemaBuiltinCpuIs(*this, TheCall);
2265
Craig Toppera7e253e2016-09-23 04:48:31 +00002266 // If the intrinsic has rounding or SAE make sure its valid.
2267 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2268 return true;
2269
Craig Topperdf5beb22017-03-13 17:16:50 +00002270 // If the intrinsic has a gather/scatter scale immediate make sure its valid.
2271 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
2272 return true;
2273
Craig Topperf0ddc892016-09-23 04:48:27 +00002274 // For intrinsics which take an immediate value as part of the instruction,
2275 // range check them here.
2276 int i = 0, l = 0, u = 0;
2277 switch (BuiltinID) {
2278 default:
2279 return false;
Richard Trieucc3949d2016-02-18 22:34:54 +00002280 case X86::BI_mm_prefetch:
Craig Topper170de4b2017-12-21 23:50:22 +00002281 i = 1; l = 0; u = 7;
Craig Topper39c87102016-05-18 03:18:12 +00002282 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00002283 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper39c87102016-05-18 03:18:12 +00002284 case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2285 case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2286 case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2287 case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002288 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002289 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00002290 case X86::BI__builtin_ia32_vpermil2pd:
2291 case X86::BI__builtin_ia32_vpermil2pd256:
2292 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00002293 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00002294 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002295 break;
Craig Topper95b0d732015-01-25 23:30:05 +00002296 case X86::BI__builtin_ia32_cmpb128_mask:
2297 case X86::BI__builtin_ia32_cmpw128_mask:
2298 case X86::BI__builtin_ia32_cmpd128_mask:
2299 case X86::BI__builtin_ia32_cmpq128_mask:
2300 case X86::BI__builtin_ia32_cmpb256_mask:
2301 case X86::BI__builtin_ia32_cmpw256_mask:
2302 case X86::BI__builtin_ia32_cmpd256_mask:
2303 case X86::BI__builtin_ia32_cmpq256_mask:
2304 case X86::BI__builtin_ia32_cmpb512_mask:
2305 case X86::BI__builtin_ia32_cmpw512_mask:
2306 case X86::BI__builtin_ia32_cmpd512_mask:
2307 case X86::BI__builtin_ia32_cmpq512_mask:
2308 case X86::BI__builtin_ia32_ucmpb128_mask:
2309 case X86::BI__builtin_ia32_ucmpw128_mask:
2310 case X86::BI__builtin_ia32_ucmpd128_mask:
2311 case X86::BI__builtin_ia32_ucmpq128_mask:
2312 case X86::BI__builtin_ia32_ucmpb256_mask:
2313 case X86::BI__builtin_ia32_ucmpw256_mask:
2314 case X86::BI__builtin_ia32_ucmpd256_mask:
2315 case X86::BI__builtin_ia32_ucmpq256_mask:
2316 case X86::BI__builtin_ia32_ucmpb512_mask:
2317 case X86::BI__builtin_ia32_ucmpw512_mask:
2318 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00002319 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00002320 case X86::BI__builtin_ia32_vpcomub:
2321 case X86::BI__builtin_ia32_vpcomuw:
2322 case X86::BI__builtin_ia32_vpcomud:
2323 case X86::BI__builtin_ia32_vpcomuq:
2324 case X86::BI__builtin_ia32_vpcomb:
2325 case X86::BI__builtin_ia32_vpcomw:
2326 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00002327 case X86::BI__builtin_ia32_vpcomq:
Craig Topper39c87102016-05-18 03:18:12 +00002328 i = 2; l = 0; u = 7;
2329 break;
2330 case X86::BI__builtin_ia32_roundps:
2331 case X86::BI__builtin_ia32_roundpd:
2332 case X86::BI__builtin_ia32_roundps256:
2333 case X86::BI__builtin_ia32_roundpd256:
Craig Topper39c87102016-05-18 03:18:12 +00002334 i = 1; l = 0; u = 15;
2335 break;
2336 case X86::BI__builtin_ia32_roundss:
2337 case X86::BI__builtin_ia32_roundsd:
2338 case X86::BI__builtin_ia32_rangepd128_mask:
2339 case X86::BI__builtin_ia32_rangepd256_mask:
2340 case X86::BI__builtin_ia32_rangepd512_mask:
2341 case X86::BI__builtin_ia32_rangeps128_mask:
2342 case X86::BI__builtin_ia32_rangeps256_mask:
2343 case X86::BI__builtin_ia32_rangeps512_mask:
2344 case X86::BI__builtin_ia32_getmantsd_round_mask:
2345 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002346 i = 2; l = 0; u = 15;
2347 break;
2348 case X86::BI__builtin_ia32_cmpps:
2349 case X86::BI__builtin_ia32_cmpss:
2350 case X86::BI__builtin_ia32_cmppd:
2351 case X86::BI__builtin_ia32_cmpsd:
2352 case X86::BI__builtin_ia32_cmpps256:
2353 case X86::BI__builtin_ia32_cmppd256:
2354 case X86::BI__builtin_ia32_cmpps128_mask:
2355 case X86::BI__builtin_ia32_cmppd128_mask:
2356 case X86::BI__builtin_ia32_cmpps256_mask:
2357 case X86::BI__builtin_ia32_cmppd256_mask:
2358 case X86::BI__builtin_ia32_cmpps512_mask:
2359 case X86::BI__builtin_ia32_cmppd512_mask:
2360 case X86::BI__builtin_ia32_cmpsd_mask:
2361 case X86::BI__builtin_ia32_cmpss_mask:
2362 i = 2; l = 0; u = 31;
2363 break;
2364 case X86::BI__builtin_ia32_xabort:
2365 i = 0; l = -128; u = 255;
2366 break;
2367 case X86::BI__builtin_ia32_pshufw:
2368 case X86::BI__builtin_ia32_aeskeygenassist128:
2369 i = 1; l = -128; u = 255;
2370 break;
2371 case X86::BI__builtin_ia32_vcvtps2ph:
Craig Topper23a30222017-11-08 04:54:26 +00002372 case X86::BI__builtin_ia32_vcvtps2ph_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002373 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper23a30222017-11-08 04:54:26 +00002374 case X86::BI__builtin_ia32_vcvtps2ph256_mask:
2375 case X86::BI__builtin_ia32_vcvtps2ph512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002376 case X86::BI__builtin_ia32_rndscaleps_128_mask:
2377 case X86::BI__builtin_ia32_rndscalepd_128_mask:
2378 case X86::BI__builtin_ia32_rndscaleps_256_mask:
2379 case X86::BI__builtin_ia32_rndscalepd_256_mask:
2380 case X86::BI__builtin_ia32_rndscaleps_mask:
2381 case X86::BI__builtin_ia32_rndscalepd_mask:
2382 case X86::BI__builtin_ia32_reducepd128_mask:
2383 case X86::BI__builtin_ia32_reducepd256_mask:
2384 case X86::BI__builtin_ia32_reducepd512_mask:
2385 case X86::BI__builtin_ia32_reduceps128_mask:
2386 case X86::BI__builtin_ia32_reduceps256_mask:
2387 case X86::BI__builtin_ia32_reduceps512_mask:
2388 case X86::BI__builtin_ia32_prold512_mask:
2389 case X86::BI__builtin_ia32_prolq512_mask:
2390 case X86::BI__builtin_ia32_prold128_mask:
2391 case X86::BI__builtin_ia32_prold256_mask:
2392 case X86::BI__builtin_ia32_prolq128_mask:
2393 case X86::BI__builtin_ia32_prolq256_mask:
2394 case X86::BI__builtin_ia32_prord128_mask:
2395 case X86::BI__builtin_ia32_prord256_mask:
2396 case X86::BI__builtin_ia32_prorq128_mask:
2397 case X86::BI__builtin_ia32_prorq256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002398 case X86::BI__builtin_ia32_fpclasspd128_mask:
2399 case X86::BI__builtin_ia32_fpclasspd256_mask:
2400 case X86::BI__builtin_ia32_fpclassps128_mask:
2401 case X86::BI__builtin_ia32_fpclassps256_mask:
2402 case X86::BI__builtin_ia32_fpclassps512_mask:
2403 case X86::BI__builtin_ia32_fpclasspd512_mask:
2404 case X86::BI__builtin_ia32_fpclasssd_mask:
2405 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002406 i = 1; l = 0; u = 255;
2407 break;
2408 case X86::BI__builtin_ia32_palignr:
2409 case X86::BI__builtin_ia32_insertps128:
2410 case X86::BI__builtin_ia32_dpps:
2411 case X86::BI__builtin_ia32_dppd:
2412 case X86::BI__builtin_ia32_dpps256:
2413 case X86::BI__builtin_ia32_mpsadbw128:
2414 case X86::BI__builtin_ia32_mpsadbw256:
2415 case X86::BI__builtin_ia32_pcmpistrm128:
2416 case X86::BI__builtin_ia32_pcmpistri128:
2417 case X86::BI__builtin_ia32_pcmpistria128:
2418 case X86::BI__builtin_ia32_pcmpistric128:
2419 case X86::BI__builtin_ia32_pcmpistrio128:
2420 case X86::BI__builtin_ia32_pcmpistris128:
2421 case X86::BI__builtin_ia32_pcmpistriz128:
2422 case X86::BI__builtin_ia32_pclmulqdq128:
2423 case X86::BI__builtin_ia32_vperm2f128_pd256:
2424 case X86::BI__builtin_ia32_vperm2f128_ps256:
2425 case X86::BI__builtin_ia32_vperm2f128_si256:
2426 case X86::BI__builtin_ia32_permti256:
2427 i = 2; l = -128; u = 255;
2428 break;
2429 case X86::BI__builtin_ia32_palignr128:
2430 case X86::BI__builtin_ia32_palignr256:
Craig Topper39c87102016-05-18 03:18:12 +00002431 case X86::BI__builtin_ia32_palignr512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002432 case X86::BI__builtin_ia32_vcomisd:
2433 case X86::BI__builtin_ia32_vcomiss:
2434 case X86::BI__builtin_ia32_shuf_f32x4_mask:
2435 case X86::BI__builtin_ia32_shuf_f64x2_mask:
2436 case X86::BI__builtin_ia32_shuf_i32x4_mask:
2437 case X86::BI__builtin_ia32_shuf_i64x2_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002438 case X86::BI__builtin_ia32_dbpsadbw128_mask:
2439 case X86::BI__builtin_ia32_dbpsadbw256_mask:
2440 case X86::BI__builtin_ia32_dbpsadbw512_mask:
2441 i = 2; l = 0; u = 255;
2442 break;
2443 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2444 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2445 case X86::BI__builtin_ia32_fixupimmps512_mask:
2446 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2447 case X86::BI__builtin_ia32_fixupimmsd_mask:
2448 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2449 case X86::BI__builtin_ia32_fixupimmss_mask:
2450 case X86::BI__builtin_ia32_fixupimmss_maskz:
2451 case X86::BI__builtin_ia32_fixupimmpd128_mask:
2452 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2453 case X86::BI__builtin_ia32_fixupimmpd256_mask:
2454 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2455 case X86::BI__builtin_ia32_fixupimmps128_mask:
2456 case X86::BI__builtin_ia32_fixupimmps128_maskz:
2457 case X86::BI__builtin_ia32_fixupimmps256_mask:
2458 case X86::BI__builtin_ia32_fixupimmps256_maskz:
2459 case X86::BI__builtin_ia32_pternlogd512_mask:
2460 case X86::BI__builtin_ia32_pternlogd512_maskz:
2461 case X86::BI__builtin_ia32_pternlogq512_mask:
2462 case X86::BI__builtin_ia32_pternlogq512_maskz:
2463 case X86::BI__builtin_ia32_pternlogd128_mask:
2464 case X86::BI__builtin_ia32_pternlogd128_maskz:
2465 case X86::BI__builtin_ia32_pternlogd256_mask:
2466 case X86::BI__builtin_ia32_pternlogd256_maskz:
2467 case X86::BI__builtin_ia32_pternlogq128_mask:
2468 case X86::BI__builtin_ia32_pternlogq128_maskz:
2469 case X86::BI__builtin_ia32_pternlogq256_mask:
2470 case X86::BI__builtin_ia32_pternlogq256_maskz:
2471 i = 3; l = 0; u = 255;
2472 break;
Craig Topper9625db02017-03-12 22:19:10 +00002473 case X86::BI__builtin_ia32_gatherpfdpd:
2474 case X86::BI__builtin_ia32_gatherpfdps:
2475 case X86::BI__builtin_ia32_gatherpfqpd:
2476 case X86::BI__builtin_ia32_gatherpfqps:
2477 case X86::BI__builtin_ia32_scatterpfdpd:
2478 case X86::BI__builtin_ia32_scatterpfdps:
2479 case X86::BI__builtin_ia32_scatterpfqpd:
2480 case X86::BI__builtin_ia32_scatterpfqps:
Craig Topperf771f79b2017-03-31 17:22:30 +00002481 i = 4; l = 2; u = 3;
Craig Topper9625db02017-03-12 22:19:10 +00002482 break;
Craig Topper39c87102016-05-18 03:18:12 +00002483 case X86::BI__builtin_ia32_pcmpestrm128:
2484 case X86::BI__builtin_ia32_pcmpestri128:
2485 case X86::BI__builtin_ia32_pcmpestria128:
2486 case X86::BI__builtin_ia32_pcmpestric128:
2487 case X86::BI__builtin_ia32_pcmpestrio128:
2488 case X86::BI__builtin_ia32_pcmpestris128:
2489 case X86::BI__builtin_ia32_pcmpestriz128:
2490 i = 4; l = -128; u = 255;
2491 break;
2492 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2493 case X86::BI__builtin_ia32_rndscaless_round_mask:
2494 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00002495 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002496 }
Craig Topperdd84ec52014-12-27 07:00:08 +00002497 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002498}
2499
Richard Smith55ce3522012-06-25 20:30:08 +00002500/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2501/// parameter with the FormatAttr's correct format_idx and firstDataArg.
2502/// Returns true when the format fits the function and the FormatStringInfo has
2503/// been populated.
2504bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2505 FormatStringInfo *FSI) {
2506 FSI->HasVAListArg = Format->getFirstArg() == 0;
2507 FSI->FormatIdx = Format->getFormatIdx() - 1;
2508 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002509
Richard Smith55ce3522012-06-25 20:30:08 +00002510 // The way the format attribute works in GCC, the implicit this argument
2511 // of member functions is counted. However, it doesn't appear in our own
2512 // lists, so decrement format_idx in that case.
2513 if (IsCXXMember) {
2514 if(FSI->FormatIdx == 0)
2515 return false;
2516 --FSI->FormatIdx;
2517 if (FSI->FirstDataArg != 0)
2518 --FSI->FirstDataArg;
2519 }
2520 return true;
2521}
Mike Stump11289f42009-09-09 15:08:12 +00002522
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002523/// Checks if a the given expression evaluates to null.
2524///
2525/// \brief Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00002526static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002527 // If the expression has non-null type, it doesn't evaluate to null.
2528 if (auto nullability
2529 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2530 if (*nullability == NullabilityKind::NonNull)
2531 return false;
2532 }
2533
Ted Kremeneka146db32014-01-17 06:24:47 +00002534 // As a special case, transparent unions initialized with zero are
2535 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002536 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00002537 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2538 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002539 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00002540 if (const InitListExpr *ILE =
2541 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002542 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00002543 }
2544
2545 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00002546 return (!Expr->isValueDependent() &&
2547 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2548 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002549}
2550
2551static void CheckNonNullArgument(Sema &S,
2552 const Expr *ArgExpr,
2553 SourceLocation CallSiteLoc) {
2554 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00002555 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2556 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00002557}
2558
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002559bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2560 FormatStringInfo FSI;
2561 if ((GetFormatStringType(Format) == FST_NSString) &&
2562 getFormatStringInfo(Format, false, &FSI)) {
2563 Idx = FSI.FormatIdx;
2564 return true;
2565 }
2566 return false;
2567}
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002568
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002569/// \brief Diagnose use of %s directive in an NSString which is being passed
2570/// as formatting string to formatting method.
2571static void
2572DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2573 const NamedDecl *FDecl,
2574 Expr **Args,
2575 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002576 unsigned Idx = 0;
2577 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002578 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2579 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002580 Idx = 2;
2581 Format = true;
2582 }
2583 else
2584 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2585 if (S.GetFormatNSStringIdx(I, Idx)) {
2586 Format = true;
2587 break;
2588 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002589 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002590 if (!Format || NumArgs <= Idx)
2591 return;
2592 const Expr *FormatExpr = Args[Idx];
2593 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2594 FormatExpr = CSCE->getSubExpr();
2595 const StringLiteral *FormatString;
2596 if (const ObjCStringLiteral *OSL =
2597 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2598 FormatString = OSL->getString();
2599 else
2600 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2601 if (!FormatString)
2602 return;
2603 if (S.FormatStringHasSArg(FormatString)) {
2604 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2605 << "%s" << 1 << 1;
2606 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2607 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002608 }
2609}
2610
Douglas Gregorb4866e82015-06-19 18:13:19 +00002611/// Determine whether the given type has a non-null nullability annotation.
2612static bool isNonNullType(ASTContext &ctx, QualType type) {
2613 if (auto nullability = type->getNullability(ctx))
2614 return *nullability == NullabilityKind::NonNull;
2615
2616 return false;
2617}
2618
Ted Kremenek2bc73332014-01-17 06:24:43 +00002619static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00002620 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002621 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00002622 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00002623 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002624 assert((FDecl || Proto) && "Need a function declaration or prototype");
2625
Ted Kremenek9aedc152014-01-17 06:24:56 +00002626 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00002627 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00002628 if (FDecl) {
2629 // Handle the nonnull attribute on the function/method declaration itself.
2630 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2631 if (!NonNull->args_size()) {
2632 // Easy case: all pointer arguments are nonnull.
2633 for (const auto *Arg : Args)
2634 if (S.isValidPointerAttrType(Arg->getType()))
2635 CheckNonNullArgument(S, Arg, CallSiteLoc);
2636 return;
2637 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002638
Douglas Gregorb4866e82015-06-19 18:13:19 +00002639 for (unsigned Val : NonNull->args()) {
2640 if (Val >= Args.size())
2641 continue;
2642 if (NonNullArgs.empty())
2643 NonNullArgs.resize(Args.size());
2644 NonNullArgs.set(Val);
2645 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002646 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002647 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002648
Douglas Gregorb4866e82015-06-19 18:13:19 +00002649 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2650 // Handle the nonnull attribute on the parameters of the
2651 // function/method.
2652 ArrayRef<ParmVarDecl*> parms;
2653 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2654 parms = FD->parameters();
2655 else
2656 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2657
2658 unsigned ParamIndex = 0;
2659 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2660 I != E; ++I, ++ParamIndex) {
2661 const ParmVarDecl *PVD = *I;
2662 if (PVD->hasAttr<NonNullAttr>() ||
2663 isNonNullType(S.Context, PVD->getType())) {
2664 if (NonNullArgs.empty())
2665 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00002666
Douglas Gregorb4866e82015-06-19 18:13:19 +00002667 NonNullArgs.set(ParamIndex);
2668 }
2669 }
2670 } else {
2671 // If we have a non-function, non-method declaration but no
2672 // function prototype, try to dig out the function prototype.
2673 if (!Proto) {
2674 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2675 QualType type = VD->getType().getNonReferenceType();
2676 if (auto pointerType = type->getAs<PointerType>())
2677 type = pointerType->getPointeeType();
2678 else if (auto blockType = type->getAs<BlockPointerType>())
2679 type = blockType->getPointeeType();
2680 // FIXME: data member pointers?
2681
2682 // Dig out the function prototype, if there is one.
2683 Proto = type->getAs<FunctionProtoType>();
2684 }
2685 }
2686
2687 // Fill in non-null argument information from the nullability
2688 // information on the parameter types (if we have them).
2689 if (Proto) {
2690 unsigned Index = 0;
2691 for (auto paramType : Proto->getParamTypes()) {
2692 if (isNonNullType(S.Context, paramType)) {
2693 if (NonNullArgs.empty())
2694 NonNullArgs.resize(Args.size());
2695
2696 NonNullArgs.set(Index);
2697 }
2698
2699 ++Index;
2700 }
2701 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002702 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002703
Douglas Gregorb4866e82015-06-19 18:13:19 +00002704 // Check for non-null arguments.
2705 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2706 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00002707 if (NonNullArgs[ArgIndex])
2708 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00002709 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002710}
2711
Richard Smith55ce3522012-06-25 20:30:08 +00002712/// Handles the checks for format strings, non-POD arguments to vararg
George Burgess IVce6284b2017-01-28 02:19:40 +00002713/// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
2714/// attributes.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002715void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
George Burgess IVce6284b2017-01-28 02:19:40 +00002716 const Expr *ThisArg, ArrayRef<const Expr *> Args,
2717 bool IsMemberFunction, SourceLocation Loc,
2718 SourceRange Range, VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00002719 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00002720 if (CurContext->isDependentContext())
2721 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00002722
Ted Kremenekb8176da2010-09-09 04:33:05 +00002723 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00002724 llvm::SmallBitVector CheckedVarArgs;
2725 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002726 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002727 // Only create vector if there are format attributes.
2728 CheckedVarArgs.resize(Args.size());
2729
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002730 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00002731 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002732 }
Richard Smithd7293d72013-08-05 18:49:43 +00002733 }
Richard Smith55ce3522012-06-25 20:30:08 +00002734
2735 // Refuse POD arguments that weren't caught by the format string
2736 // checks above.
Richard Smith836de6b2016-12-19 23:59:34 +00002737 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
2738 if (CallType != VariadicDoesNotApply &&
2739 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002740 unsigned NumParams = Proto ? Proto->getNumParams()
2741 : FDecl && isa<FunctionDecl>(FDecl)
2742 ? cast<FunctionDecl>(FDecl)->getNumParams()
2743 : FDecl && isa<ObjCMethodDecl>(FDecl)
2744 ? cast<ObjCMethodDecl>(FDecl)->param_size()
2745 : 0;
2746
Alp Toker9cacbab2014-01-20 20:26:09 +00002747 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002748 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00002749 if (const Expr *Arg = Args[ArgIdx]) {
2750 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2751 checkVariadicArgument(Arg, CallType);
2752 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002753 }
Richard Smithd7293d72013-08-05 18:49:43 +00002754 }
Mike Stump11289f42009-09-09 15:08:12 +00002755
Douglas Gregorb4866e82015-06-19 18:13:19 +00002756 if (FDecl || Proto) {
2757 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002758
Richard Trieu41bc0992013-06-22 00:20:41 +00002759 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002760 if (FDecl) {
2761 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +00002762 CheckArgumentWithTypeTag(I, Args, Loc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00002763 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002764 }
George Burgess IVce6284b2017-01-28 02:19:40 +00002765
2766 if (FD)
2767 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
Richard Smith55ce3522012-06-25 20:30:08 +00002768}
2769
2770/// CheckConstructorCall - Check a constructor call for correctness and safety
2771/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002772void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2773 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002774 const FunctionProtoType *Proto,
2775 SourceLocation Loc) {
2776 VariadicCallType CallType =
2777 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
George Burgess IVce6284b2017-01-28 02:19:40 +00002778 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
2779 Loc, SourceRange(), CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00002780}
2781
2782/// CheckFunctionCall - Check a direct function call for various correctness
2783/// and safety properties not strictly enforced by the C type system.
2784bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2785 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002786 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2787 isa<CXXMethodDecl>(FDecl);
2788 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2789 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00002790 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2791 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00002792 Expr** Args = TheCall->getArgs();
2793 unsigned NumArgs = TheCall->getNumArgs();
George Burgess IVce6284b2017-01-28 02:19:40 +00002794
2795 Expr *ImplicitThis = nullptr;
Eli Friedmanadf42182012-10-11 00:34:15 +00002796 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002797 // If this is a call to a member operator, hide the first argument
2798 // from checkCall.
2799 // FIXME: Our choice of AST representation here is less than ideal.
George Burgess IVce6284b2017-01-28 02:19:40 +00002800 ImplicitThis = Args[0];
Eli Friedman726d11c2012-10-11 00:30:58 +00002801 ++Args;
2802 --NumArgs;
George Burgess IVce6284b2017-01-28 02:19:40 +00002803 } else if (IsMemberFunction)
2804 ImplicitThis =
2805 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
2806
2807 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00002808 IsMemberFunction, TheCall->getRParenLoc(),
2809 TheCall->getCallee()->getSourceRange(), CallType);
2810
2811 IdentifierInfo *FnInfo = FDecl->getIdentifier();
2812 // None of the checks below are needed for functions that don't have
2813 // simple names (e.g., C++ conversion functions).
2814 if (!FnInfo)
2815 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002816
Richard Trieua7f30b12016-12-06 01:42:28 +00002817 CheckAbsoluteValueFunction(TheCall, FDecl);
2818 CheckMaxUnsignedZero(TheCall, FDecl);
Richard Trieu67c00712016-12-05 23:41:46 +00002819
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002820 if (getLangOpts().ObjC1)
2821 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00002822
Anna Zaks22122702012-01-17 00:37:07 +00002823 unsigned CMId = FDecl->getMemoryFunctionKind();
2824 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00002825 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00002826
Anna Zaks201d4892012-01-13 21:52:01 +00002827 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00002828 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00002829 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00002830 else if (CMId == Builtin::BIstrncat)
2831 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00002832 else
Anna Zaks22122702012-01-17 00:37:07 +00002833 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002834
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002835 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00002836}
2837
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002838bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00002839 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00002840 VariadicCallType CallType =
2841 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002842
George Burgess IVce6284b2017-01-28 02:19:40 +00002843 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
2844 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002845 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002846
2847 return false;
2848}
2849
Richard Trieu664c4c62013-06-20 21:03:13 +00002850bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2851 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00002852 QualType Ty;
2853 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002854 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002855 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002856 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002857 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002858 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002859
Douglas Gregorb4866e82015-06-19 18:13:19 +00002860 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2861 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002862 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002863
Richard Trieu664c4c62013-06-20 21:03:13 +00002864 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00002865 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00002866 CallType = VariadicDoesNotApply;
2867 } else if (Ty->isBlockPointerType()) {
2868 CallType = VariadicBlock;
2869 } else { // Ty->isFunctionPointerType()
2870 CallType = VariadicFunction;
2871 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002872
George Burgess IVce6284b2017-01-28 02:19:40 +00002873 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002874 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2875 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00002876 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00002877
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002878 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00002879}
2880
Richard Trieu41bc0992013-06-22 00:20:41 +00002881/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2882/// such as function pointers returned from functions.
2883bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002884 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00002885 TheCall->getCallee());
George Burgess IVce6284b2017-01-28 02:19:40 +00002886 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00002887 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002888 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00002889 TheCall->getCallee()->getSourceRange(), CallType);
2890
2891 return false;
2892}
2893
Tim Northovere94a34c2014-03-11 10:49:14 +00002894static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00002895 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00002896 return false;
2897
JF Bastiendda2cb12016-04-18 18:01:49 +00002898 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00002899 switch (Op) {
2900 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00002901 case AtomicExpr::AO__opencl_atomic_init:
Tim Northovere94a34c2014-03-11 10:49:14 +00002902 llvm_unreachable("There is no ordering argument for an init");
2903
2904 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00002905 case AtomicExpr::AO__opencl_atomic_load:
Tim Northovere94a34c2014-03-11 10:49:14 +00002906 case AtomicExpr::AO__atomic_load_n:
2907 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00002908 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2909 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002910
2911 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00002912 case AtomicExpr::AO__opencl_atomic_store:
Tim Northovere94a34c2014-03-11 10:49:14 +00002913 case AtomicExpr::AO__atomic_store:
2914 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00002915 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2916 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2917 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002918
2919 default:
2920 return true;
2921 }
2922}
2923
Richard Smithfeea8832012-04-12 05:08:17 +00002924ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2925 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002926 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2927 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002928
Yaxun Liu39195062017-08-04 18:16:31 +00002929 // All the non-OpenCL operations take one of the following forms.
2930 // The OpenCL operations take the __c11 forms with one extra argument for
2931 // synchronization scope.
Richard Smithfeea8832012-04-12 05:08:17 +00002932 enum {
2933 // C __c11_atomic_init(A *, C)
2934 Init,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002935
Richard Smithfeea8832012-04-12 05:08:17 +00002936 // C __c11_atomic_load(A *, int)
2937 Load,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002938
Richard Smithfeea8832012-04-12 05:08:17 +00002939 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00002940 LoadCopy,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002941
Eric Fiselier8d662442016-03-30 23:39:56 +00002942 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00002943 Copy,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002944
Richard Smithfeea8832012-04-12 05:08:17 +00002945 // C __c11_atomic_add(A *, M, int)
2946 Arithmetic,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002947
Richard Smithfeea8832012-04-12 05:08:17 +00002948 // C __atomic_exchange_n(A *, CP, int)
2949 Xchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002950
Richard Smithfeea8832012-04-12 05:08:17 +00002951 // void __atomic_exchange(A *, C *, CP, int)
2952 GNUXchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002953
Richard Smithfeea8832012-04-12 05:08:17 +00002954 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2955 C11CmpXchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002956
Richard Smithfeea8832012-04-12 05:08:17 +00002957 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2958 GNUCmpXchg
2959 } Form = Init;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002960
Yaxun Liu39195062017-08-04 18:16:31 +00002961 const unsigned NumForm = GNUCmpXchg + 1;
Eric Fiselier8d662442016-03-30 23:39:56 +00002962 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2963 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00002964 // where:
2965 // C is an appropriate type,
2966 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2967 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2968 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2969 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002970
Yaxun Liu39195062017-08-04 18:16:31 +00002971 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
2972 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
2973 "need to update code for modified forms");
Gabor Horvath98bd0982015-03-16 09:59:54 +00002974 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2975 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2976 AtomicExpr::AO__atomic_load,
2977 "need to update code for modified C11 atomics");
Yaxun Liu39195062017-08-04 18:16:31 +00002978 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
2979 Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
2980 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
2981 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
2982 IsOpenCL;
Richard Smithfeea8832012-04-12 05:08:17 +00002983 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2984 Op == AtomicExpr::AO__atomic_store_n ||
2985 Op == AtomicExpr::AO__atomic_exchange_n ||
2986 Op == AtomicExpr::AO__atomic_compare_exchange_n;
2987 bool IsAddSub = false;
2988
2989 switch (Op) {
2990 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00002991 case AtomicExpr::AO__opencl_atomic_init:
Richard Smithfeea8832012-04-12 05:08:17 +00002992 Form = Init;
2993 break;
2994
2995 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00002996 case AtomicExpr::AO__opencl_atomic_load:
Richard Smithfeea8832012-04-12 05:08:17 +00002997 case AtomicExpr::AO__atomic_load_n:
2998 Form = Load;
2999 break;
3000
Richard Smithfeea8832012-04-12 05:08:17 +00003001 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00003002 Form = LoadCopy;
3003 break;
3004
3005 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00003006 case AtomicExpr::AO__opencl_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00003007 case AtomicExpr::AO__atomic_store:
3008 case AtomicExpr::AO__atomic_store_n:
3009 Form = Copy;
3010 break;
3011
3012 case AtomicExpr::AO__c11_atomic_fetch_add:
3013 case AtomicExpr::AO__c11_atomic_fetch_sub:
Yaxun Liu39195062017-08-04 18:16:31 +00003014 case AtomicExpr::AO__opencl_atomic_fetch_add:
3015 case AtomicExpr::AO__opencl_atomic_fetch_sub:
3016 case AtomicExpr::AO__opencl_atomic_fetch_min:
3017 case AtomicExpr::AO__opencl_atomic_fetch_max:
Richard Smithfeea8832012-04-12 05:08:17 +00003018 case AtomicExpr::AO__atomic_fetch_add:
3019 case AtomicExpr::AO__atomic_fetch_sub:
3020 case AtomicExpr::AO__atomic_add_fetch:
3021 case AtomicExpr::AO__atomic_sub_fetch:
3022 IsAddSub = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00003023 LLVM_FALLTHROUGH;
Richard Smithfeea8832012-04-12 05:08:17 +00003024 case AtomicExpr::AO__c11_atomic_fetch_and:
3025 case AtomicExpr::AO__c11_atomic_fetch_or:
3026 case AtomicExpr::AO__c11_atomic_fetch_xor:
Yaxun Liu39195062017-08-04 18:16:31 +00003027 case AtomicExpr::AO__opencl_atomic_fetch_and:
3028 case AtomicExpr::AO__opencl_atomic_fetch_or:
3029 case AtomicExpr::AO__opencl_atomic_fetch_xor:
Richard Smithfeea8832012-04-12 05:08:17 +00003030 case AtomicExpr::AO__atomic_fetch_and:
3031 case AtomicExpr::AO__atomic_fetch_or:
3032 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00003033 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00003034 case AtomicExpr::AO__atomic_and_fetch:
3035 case AtomicExpr::AO__atomic_or_fetch:
3036 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00003037 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00003038 Form = Arithmetic;
3039 break;
3040
3041 case AtomicExpr::AO__c11_atomic_exchange:
Yaxun Liu39195062017-08-04 18:16:31 +00003042 case AtomicExpr::AO__opencl_atomic_exchange:
Richard Smithfeea8832012-04-12 05:08:17 +00003043 case AtomicExpr::AO__atomic_exchange_n:
3044 Form = Xchg;
3045 break;
3046
3047 case AtomicExpr::AO__atomic_exchange:
3048 Form = GNUXchg;
3049 break;
3050
3051 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3052 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
Yaxun Liu39195062017-08-04 18:16:31 +00003053 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
3054 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
Richard Smithfeea8832012-04-12 05:08:17 +00003055 Form = C11CmpXchg;
3056 break;
3057
3058 case AtomicExpr::AO__atomic_compare_exchange:
3059 case AtomicExpr::AO__atomic_compare_exchange_n:
3060 Form = GNUCmpXchg;
3061 break;
3062 }
3063
Yaxun Liu39195062017-08-04 18:16:31 +00003064 unsigned AdjustedNumArgs = NumArgs[Form];
3065 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
3066 ++AdjustedNumArgs;
Richard Smithfeea8832012-04-12 05:08:17 +00003067 // Check we have the right number of arguments.
Yaxun Liu39195062017-08-04 18:16:31 +00003068 if (TheCall->getNumArgs() < AdjustedNumArgs) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003069 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Yaxun Liu39195062017-08-04 18:16:31 +00003070 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003071 << TheCall->getCallee()->getSourceRange();
3072 return ExprError();
Yaxun Liu39195062017-08-04 18:16:31 +00003073 } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
3074 Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003075 diag::err_typecheck_call_too_many_args)
Yaxun Liu39195062017-08-04 18:16:31 +00003076 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003077 << TheCall->getCallee()->getSourceRange();
3078 return ExprError();
3079 }
3080
Richard Smithfeea8832012-04-12 05:08:17 +00003081 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003082 Expr *Ptr = TheCall->getArg(0);
George Burgess IV92b43a42016-07-21 03:28:13 +00003083 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
3084 if (ConvertedPtr.isInvalid())
3085 return ExprError();
3086
3087 Ptr = ConvertedPtr.get();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003088 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
3089 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00003090 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003091 << Ptr->getType() << Ptr->getSourceRange();
3092 return ExprError();
3093 }
3094
Richard Smithfeea8832012-04-12 05:08:17 +00003095 // For a __c11 builtin, this should be a pointer to an _Atomic type.
3096 QualType AtomTy = pointerType->getPointeeType(); // 'A'
3097 QualType ValType = AtomTy; // 'C'
3098 if (IsC11) {
3099 if (!AtomTy->isAtomicType()) {
3100 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
3101 << Ptr->getType() << Ptr->getSourceRange();
3102 return ExprError();
3103 }
Yaxun Liu39195062017-08-04 18:16:31 +00003104 if (AtomTy.isConstQualified() ||
3105 AtomTy.getAddressSpace() == LangAS::opencl_constant) {
Richard Smithe00921a2012-09-15 06:09:58 +00003106 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
Yaxun Liu39195062017-08-04 18:16:31 +00003107 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
3108 << Ptr->getSourceRange();
Richard Smithe00921a2012-09-15 06:09:58 +00003109 return ExprError();
3110 }
Richard Smithfeea8832012-04-12 05:08:17 +00003111 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00003112 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00003113 if (ValType.isConstQualified()) {
3114 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
3115 << Ptr->getType() << Ptr->getSourceRange();
3116 return ExprError();
3117 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003118 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003119
Richard Smithfeea8832012-04-12 05:08:17 +00003120 // For an arithmetic operation, the implied arithmetic must be well-formed.
3121 if (Form == Arithmetic) {
3122 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
3123 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
3124 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3125 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3126 return ExprError();
3127 }
3128 if (!IsAddSub && !ValType->isIntegerType()) {
3129 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
3130 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3131 return ExprError();
3132 }
David Majnemere85cff82015-01-28 05:48:06 +00003133 if (IsC11 && ValType->isPointerType() &&
3134 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
3135 diag::err_incomplete_type)) {
3136 return ExprError();
3137 }
Richard Smithfeea8832012-04-12 05:08:17 +00003138 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
3139 // For __atomic_*_n operations, the value type must be a scalar integral or
3140 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003141 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00003142 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3143 return ExprError();
3144 }
3145
Eli Friedmanaa769812013-09-11 03:49:34 +00003146 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
3147 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00003148 // For GNU atomics, require a trivially-copyable type. This is not part of
3149 // the GNU atomics specification, but we enforce it for sanity.
3150 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003151 << Ptr->getType() << Ptr->getSourceRange();
3152 return ExprError();
3153 }
3154
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003155 switch (ValType.getObjCLifetime()) {
3156 case Qualifiers::OCL_None:
3157 case Qualifiers::OCL_ExplicitNone:
3158 // okay
3159 break;
3160
3161 case Qualifiers::OCL_Weak:
3162 case Qualifiers::OCL_Strong:
3163 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00003164 // FIXME: Can this happen? By this point, ValType should be known
3165 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003166 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3167 << ValType << Ptr->getSourceRange();
3168 return ExprError();
3169 }
3170
David Majnemerc6eb6502015-06-03 00:26:35 +00003171 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
3172 // volatile-ness of the pointee-type inject itself into the result or the
Eric Fiselier8d662442016-03-30 23:39:56 +00003173 // other operands. Similarly atomic_load can take a pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00003174 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00003175 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003176 QualType ResultType = ValType;
Yaxun Liu39195062017-08-04 18:16:31 +00003177 if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
3178 Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003179 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00003180 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003181 ResultType = Context.BoolTy;
3182
Richard Smithfeea8832012-04-12 05:08:17 +00003183 // The type of a parameter passed 'by value'. In the GNU atomics, such
3184 // arguments are actually passed as pointers.
3185 QualType ByValType = ValType; // 'CP'
3186 if (!IsC11 && !IsN)
3187 ByValType = Ptr->getType();
3188
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003189 // The first argument --- the pointer --- has a fixed type; we
3190 // deduce the types of the rest of the arguments accordingly. Walk
3191 // the remaining arguments, converting them to the deduced value type.
Yaxun Liu39195062017-08-04 18:16:31 +00003192 for (unsigned i = 1; i != TheCall->getNumArgs(); ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003193 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00003194 if (i < NumVals[Form] + 1) {
3195 switch (i) {
3196 case 1:
3197 // The second argument is the non-atomic operand. For arithmetic, this
3198 // is always passed by value, and for a compare_exchange it is always
3199 // passed by address. For the rest, GNU uses by-address and C11 uses
3200 // by-value.
3201 assert(Form != Load);
3202 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
3203 Ty = ValType;
3204 else if (Form == Copy || Form == Xchg)
3205 Ty = ByValType;
3206 else if (Form == Arithmetic)
3207 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003208 else {
3209 Expr *ValArg = TheCall->getArg(i);
Alex Lorenz67522152016-11-23 16:57:03 +00003210 // Treat this argument as _Nonnull as we want to show a warning if
3211 // NULL is passed into it.
3212 CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
Alexander Richardson6d989432017-10-15 18:48:14 +00003213 LangAS AS = LangAS::Default;
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003214 // Keep address space of non-atomic pointer type.
3215 if (const PointerType *PtrTy =
3216 ValArg->getType()->getAs<PointerType>()) {
3217 AS = PtrTy->getPointeeType().getAddressSpace();
3218 }
3219 Ty = Context.getPointerType(
3220 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
3221 }
Richard Smithfeea8832012-04-12 05:08:17 +00003222 break;
3223 case 2:
3224 // The third argument to compare_exchange / GNU exchange is a
3225 // (pointer to a) desired value.
3226 Ty = ByValType;
3227 break;
3228 case 3:
3229 // The fourth argument to GNU compare_exchange is a 'weak' flag.
3230 Ty = Context.BoolTy;
3231 break;
3232 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003233 } else {
Yaxun Liu39195062017-08-04 18:16:31 +00003234 // The order(s) and scope are always converted to int.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003235 Ty = Context.IntTy;
3236 }
Richard Smithfeea8832012-04-12 05:08:17 +00003237
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003238 InitializedEntity Entity =
3239 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00003240 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003241 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3242 if (Arg.isInvalid())
3243 return true;
3244 TheCall->setArg(i, Arg.get());
3245 }
3246
Richard Smithfeea8832012-04-12 05:08:17 +00003247 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003248 SmallVector<Expr*, 5> SubExprs;
3249 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00003250 switch (Form) {
3251 case Init:
3252 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00003253 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003254 break;
3255 case Load:
3256 SubExprs.push_back(TheCall->getArg(1)); // Order
3257 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00003258 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00003259 case Copy:
3260 case Arithmetic:
3261 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003262 SubExprs.push_back(TheCall->getArg(2)); // Order
3263 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003264 break;
3265 case GNUXchg:
3266 // Note, AtomicExpr::getVal2() has a special case for this atomic.
3267 SubExprs.push_back(TheCall->getArg(3)); // Order
3268 SubExprs.push_back(TheCall->getArg(1)); // Val1
3269 SubExprs.push_back(TheCall->getArg(2)); // Val2
3270 break;
3271 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003272 SubExprs.push_back(TheCall->getArg(3)); // Order
3273 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003274 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00003275 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00003276 break;
3277 case GNUCmpXchg:
3278 SubExprs.push_back(TheCall->getArg(4)); // Order
3279 SubExprs.push_back(TheCall->getArg(1)); // Val1
3280 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
3281 SubExprs.push_back(TheCall->getArg(2)); // Val2
3282 SubExprs.push_back(TheCall->getArg(3)); // Weak
3283 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003284 }
Tim Northovere94a34c2014-03-11 10:49:14 +00003285
3286 if (SubExprs.size() >= 2 && Form != Init) {
3287 llvm::APSInt Result(32);
3288 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
3289 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00003290 Diag(SubExprs[1]->getLocStart(),
3291 diag::warn_atomic_op_has_invalid_memory_order)
3292 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00003293 }
3294
Yaxun Liu30d652a2017-08-15 16:02:49 +00003295 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
3296 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
3297 llvm::APSInt Result(32);
3298 if (Scope->isIntegerConstantExpr(Result, Context) &&
3299 !ScopeModel->isValid(Result.getZExtValue())) {
3300 Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope)
3301 << Scope->getSourceRange();
3302 }
3303 SubExprs.push_back(Scope);
3304 }
3305
Fariborz Jahanian615de762013-05-28 17:37:39 +00003306 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
3307 SubExprs, ResultType, Op,
3308 TheCall->getRParenLoc());
3309
3310 if ((Op == AtomicExpr::AO__c11_atomic_load ||
Yaxun Liu39195062017-08-04 18:16:31 +00003311 Op == AtomicExpr::AO__c11_atomic_store ||
3312 Op == AtomicExpr::AO__opencl_atomic_load ||
3313 Op == AtomicExpr::AO__opencl_atomic_store ) &&
Fariborz Jahanian615de762013-05-28 17:37:39 +00003314 Context.AtomicUsesUnsupportedLibcall(AE))
Yaxun Liu39195062017-08-04 18:16:31 +00003315 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib)
3316 << ((Op == AtomicExpr::AO__c11_atomic_load ||
3317 Op == AtomicExpr::AO__opencl_atomic_load)
3318 ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003319
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003320 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003321}
3322
John McCall29ad95b2011-08-27 01:09:30 +00003323/// checkBuiltinArgument - Given a call to a builtin function, perform
3324/// normal type-checking on the given argument, updating the call in
3325/// place. This is useful when a builtin function requires custom
3326/// type-checking for some of its arguments but not necessarily all of
3327/// them.
3328///
3329/// Returns true on error.
3330static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
3331 FunctionDecl *Fn = E->getDirectCallee();
3332 assert(Fn && "builtin call without direct callee!");
3333
3334 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
3335 InitializedEntity Entity =
3336 InitializedEntity::InitializeParameter(S.Context, Param);
3337
3338 ExprResult Arg = E->getArg(0);
3339 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3340 if (Arg.isInvalid())
3341 return true;
3342
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003343 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00003344 return false;
3345}
3346
Chris Lattnerdc046542009-05-08 06:58:22 +00003347/// SemaBuiltinAtomicOverloaded - We have a call to a function like
3348/// __sync_fetch_and_add, which is an overloaded function based on the pointer
3349/// type of its first argument. The main ActOnCallExpr routines have already
3350/// promoted the types of arguments because all of these calls are prototyped as
3351/// void(...).
3352///
3353/// This function goes through and does final semantic checking for these
3354/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00003355ExprResult
3356Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003357 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00003358 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3359 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3360
3361 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003362 if (TheCall->getNumArgs() < 1) {
3363 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3364 << 0 << 1 << TheCall->getNumArgs()
3365 << TheCall->getCallee()->getSourceRange();
3366 return ExprError();
3367 }
Mike Stump11289f42009-09-09 15:08:12 +00003368
Chris Lattnerdc046542009-05-08 06:58:22 +00003369 // Inspect the first argument of the atomic builtin. This should always be
3370 // a pointer type, whose element is an integral scalar or pointer type.
3371 // Because it is a pointer type, we don't have to worry about any implicit
3372 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003373 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00003374 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00003375 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3376 if (FirstArgResult.isInvalid())
3377 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003378 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00003379 TheCall->setArg(0, FirstArg);
3380
John McCall31168b02011-06-15 23:02:42 +00003381 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3382 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003383 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3384 << FirstArg->getType() << FirstArg->getSourceRange();
3385 return ExprError();
3386 }
Mike Stump11289f42009-09-09 15:08:12 +00003387
John McCall31168b02011-06-15 23:02:42 +00003388 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00003389 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003390 !ValType->isBlockPointerType()) {
3391 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3392 << FirstArg->getType() << FirstArg->getSourceRange();
3393 return ExprError();
3394 }
Chris Lattnerdc046542009-05-08 06:58:22 +00003395
John McCall31168b02011-06-15 23:02:42 +00003396 switch (ValType.getObjCLifetime()) {
3397 case Qualifiers::OCL_None:
3398 case Qualifiers::OCL_ExplicitNone:
3399 // okay
3400 break;
3401
3402 case Qualifiers::OCL_Weak:
3403 case Qualifiers::OCL_Strong:
3404 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00003405 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00003406 << ValType << FirstArg->getSourceRange();
3407 return ExprError();
3408 }
3409
John McCallb50451a2011-10-05 07:41:44 +00003410 // Strip any qualifiers off ValType.
3411 ValType = ValType.getUnqualifiedType();
3412
Chandler Carruth3973af72010-07-18 20:54:12 +00003413 // The majority of builtins return a value, but a few have special return
3414 // types, so allow them to override appropriately below.
3415 QualType ResultType = ValType;
3416
Chris Lattnerdc046542009-05-08 06:58:22 +00003417 // We need to figure out which concrete builtin this maps onto. For example,
3418 // __sync_fetch_and_add with a 2 byte object turns into
3419 // __sync_fetch_and_add_2.
3420#define BUILTIN_ROW(x) \
3421 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3422 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00003423
Chris Lattnerdc046542009-05-08 06:58:22 +00003424 static const unsigned BuiltinIndices[][5] = {
3425 BUILTIN_ROW(__sync_fetch_and_add),
3426 BUILTIN_ROW(__sync_fetch_and_sub),
3427 BUILTIN_ROW(__sync_fetch_and_or),
3428 BUILTIN_ROW(__sync_fetch_and_and),
3429 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00003430 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00003431
Chris Lattnerdc046542009-05-08 06:58:22 +00003432 BUILTIN_ROW(__sync_add_and_fetch),
3433 BUILTIN_ROW(__sync_sub_and_fetch),
3434 BUILTIN_ROW(__sync_and_and_fetch),
3435 BUILTIN_ROW(__sync_or_and_fetch),
3436 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00003437 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00003438
Chris Lattnerdc046542009-05-08 06:58:22 +00003439 BUILTIN_ROW(__sync_val_compare_and_swap),
3440 BUILTIN_ROW(__sync_bool_compare_and_swap),
3441 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00003442 BUILTIN_ROW(__sync_lock_release),
3443 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00003444 };
Mike Stump11289f42009-09-09 15:08:12 +00003445#undef BUILTIN_ROW
3446
Chris Lattnerdc046542009-05-08 06:58:22 +00003447 // Determine the index of the size.
3448 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00003449 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00003450 case 1: SizeIndex = 0; break;
3451 case 2: SizeIndex = 1; break;
3452 case 4: SizeIndex = 2; break;
3453 case 8: SizeIndex = 3; break;
3454 case 16: SizeIndex = 4; break;
3455 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003456 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3457 << FirstArg->getType() << FirstArg->getSourceRange();
3458 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00003459 }
Mike Stump11289f42009-09-09 15:08:12 +00003460
Chris Lattnerdc046542009-05-08 06:58:22 +00003461 // Each of these builtins has one pointer argument, followed by some number of
3462 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3463 // that we ignore. Find out which row of BuiltinIndices to read from as well
3464 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00003465 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00003466 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00003467 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00003468 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00003469 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00003470 case Builtin::BI__sync_fetch_and_add:
3471 case Builtin::BI__sync_fetch_and_add_1:
3472 case Builtin::BI__sync_fetch_and_add_2:
3473 case Builtin::BI__sync_fetch_and_add_4:
3474 case Builtin::BI__sync_fetch_and_add_8:
3475 case Builtin::BI__sync_fetch_and_add_16:
3476 BuiltinIndex = 0;
3477 break;
3478
3479 case Builtin::BI__sync_fetch_and_sub:
3480 case Builtin::BI__sync_fetch_and_sub_1:
3481 case Builtin::BI__sync_fetch_and_sub_2:
3482 case Builtin::BI__sync_fetch_and_sub_4:
3483 case Builtin::BI__sync_fetch_and_sub_8:
3484 case Builtin::BI__sync_fetch_and_sub_16:
3485 BuiltinIndex = 1;
3486 break;
3487
3488 case Builtin::BI__sync_fetch_and_or:
3489 case Builtin::BI__sync_fetch_and_or_1:
3490 case Builtin::BI__sync_fetch_and_or_2:
3491 case Builtin::BI__sync_fetch_and_or_4:
3492 case Builtin::BI__sync_fetch_and_or_8:
3493 case Builtin::BI__sync_fetch_and_or_16:
3494 BuiltinIndex = 2;
3495 break;
3496
3497 case Builtin::BI__sync_fetch_and_and:
3498 case Builtin::BI__sync_fetch_and_and_1:
3499 case Builtin::BI__sync_fetch_and_and_2:
3500 case Builtin::BI__sync_fetch_and_and_4:
3501 case Builtin::BI__sync_fetch_and_and_8:
3502 case Builtin::BI__sync_fetch_and_and_16:
3503 BuiltinIndex = 3;
3504 break;
Mike Stump11289f42009-09-09 15:08:12 +00003505
Douglas Gregor73722482011-11-28 16:30:08 +00003506 case Builtin::BI__sync_fetch_and_xor:
3507 case Builtin::BI__sync_fetch_and_xor_1:
3508 case Builtin::BI__sync_fetch_and_xor_2:
3509 case Builtin::BI__sync_fetch_and_xor_4:
3510 case Builtin::BI__sync_fetch_and_xor_8:
3511 case Builtin::BI__sync_fetch_and_xor_16:
3512 BuiltinIndex = 4;
3513 break;
3514
Hal Finkeld2208b52014-10-02 20:53:50 +00003515 case Builtin::BI__sync_fetch_and_nand:
3516 case Builtin::BI__sync_fetch_and_nand_1:
3517 case Builtin::BI__sync_fetch_and_nand_2:
3518 case Builtin::BI__sync_fetch_and_nand_4:
3519 case Builtin::BI__sync_fetch_and_nand_8:
3520 case Builtin::BI__sync_fetch_and_nand_16:
3521 BuiltinIndex = 5;
3522 WarnAboutSemanticsChange = true;
3523 break;
3524
Douglas Gregor73722482011-11-28 16:30:08 +00003525 case Builtin::BI__sync_add_and_fetch:
3526 case Builtin::BI__sync_add_and_fetch_1:
3527 case Builtin::BI__sync_add_and_fetch_2:
3528 case Builtin::BI__sync_add_and_fetch_4:
3529 case Builtin::BI__sync_add_and_fetch_8:
3530 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003531 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00003532 break;
3533
3534 case Builtin::BI__sync_sub_and_fetch:
3535 case Builtin::BI__sync_sub_and_fetch_1:
3536 case Builtin::BI__sync_sub_and_fetch_2:
3537 case Builtin::BI__sync_sub_and_fetch_4:
3538 case Builtin::BI__sync_sub_and_fetch_8:
3539 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003540 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00003541 break;
3542
3543 case Builtin::BI__sync_and_and_fetch:
3544 case Builtin::BI__sync_and_and_fetch_1:
3545 case Builtin::BI__sync_and_and_fetch_2:
3546 case Builtin::BI__sync_and_and_fetch_4:
3547 case Builtin::BI__sync_and_and_fetch_8:
3548 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003549 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00003550 break;
3551
3552 case Builtin::BI__sync_or_and_fetch:
3553 case Builtin::BI__sync_or_and_fetch_1:
3554 case Builtin::BI__sync_or_and_fetch_2:
3555 case Builtin::BI__sync_or_and_fetch_4:
3556 case Builtin::BI__sync_or_and_fetch_8:
3557 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003558 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00003559 break;
3560
3561 case Builtin::BI__sync_xor_and_fetch:
3562 case Builtin::BI__sync_xor_and_fetch_1:
3563 case Builtin::BI__sync_xor_and_fetch_2:
3564 case Builtin::BI__sync_xor_and_fetch_4:
3565 case Builtin::BI__sync_xor_and_fetch_8:
3566 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003567 BuiltinIndex = 10;
3568 break;
3569
3570 case Builtin::BI__sync_nand_and_fetch:
3571 case Builtin::BI__sync_nand_and_fetch_1:
3572 case Builtin::BI__sync_nand_and_fetch_2:
3573 case Builtin::BI__sync_nand_and_fetch_4:
3574 case Builtin::BI__sync_nand_and_fetch_8:
3575 case Builtin::BI__sync_nand_and_fetch_16:
3576 BuiltinIndex = 11;
3577 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00003578 break;
Mike Stump11289f42009-09-09 15:08:12 +00003579
Chris Lattnerdc046542009-05-08 06:58:22 +00003580 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003581 case Builtin::BI__sync_val_compare_and_swap_1:
3582 case Builtin::BI__sync_val_compare_and_swap_2:
3583 case Builtin::BI__sync_val_compare_and_swap_4:
3584 case Builtin::BI__sync_val_compare_and_swap_8:
3585 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003586 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00003587 NumFixed = 2;
3588 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003589
Chris Lattnerdc046542009-05-08 06:58:22 +00003590 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003591 case Builtin::BI__sync_bool_compare_and_swap_1:
3592 case Builtin::BI__sync_bool_compare_and_swap_2:
3593 case Builtin::BI__sync_bool_compare_and_swap_4:
3594 case Builtin::BI__sync_bool_compare_and_swap_8:
3595 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003596 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00003597 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00003598 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003599 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003600
3601 case Builtin::BI__sync_lock_test_and_set:
3602 case Builtin::BI__sync_lock_test_and_set_1:
3603 case Builtin::BI__sync_lock_test_and_set_2:
3604 case Builtin::BI__sync_lock_test_and_set_4:
3605 case Builtin::BI__sync_lock_test_and_set_8:
3606 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003607 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00003608 break;
3609
Chris Lattnerdc046542009-05-08 06:58:22 +00003610 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00003611 case Builtin::BI__sync_lock_release_1:
3612 case Builtin::BI__sync_lock_release_2:
3613 case Builtin::BI__sync_lock_release_4:
3614 case Builtin::BI__sync_lock_release_8:
3615 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003616 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00003617 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00003618 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003619 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003620
3621 case Builtin::BI__sync_swap:
3622 case Builtin::BI__sync_swap_1:
3623 case Builtin::BI__sync_swap_2:
3624 case Builtin::BI__sync_swap_4:
3625 case Builtin::BI__sync_swap_8:
3626 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003627 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00003628 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00003629 }
Mike Stump11289f42009-09-09 15:08:12 +00003630
Chris Lattnerdc046542009-05-08 06:58:22 +00003631 // Now that we know how many fixed arguments we expect, first check that we
3632 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003633 if (TheCall->getNumArgs() < 1+NumFixed) {
3634 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3635 << 0 << 1+NumFixed << TheCall->getNumArgs()
3636 << TheCall->getCallee()->getSourceRange();
3637 return ExprError();
3638 }
Mike Stump11289f42009-09-09 15:08:12 +00003639
Hal Finkeld2208b52014-10-02 20:53:50 +00003640 if (WarnAboutSemanticsChange) {
3641 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3642 << TheCall->getCallee()->getSourceRange();
3643 }
3644
Chris Lattner5b9241b2009-05-08 15:36:58 +00003645 // Get the decl for the concrete builtin from this, we can tell what the
3646 // concrete integer type we should convert to is.
3647 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Mehdi Amini7186a432016-10-11 19:04:24 +00003648 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003649 FunctionDecl *NewBuiltinDecl;
3650 if (NewBuiltinID == BuiltinID)
3651 NewBuiltinDecl = FDecl;
3652 else {
3653 // Perform builtin lookup to avoid redeclaring it.
3654 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3655 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3656 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3657 assert(Res.getFoundDecl());
3658 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00003659 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003660 return ExprError();
3661 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003662
John McCallcf142162010-08-07 06:22:56 +00003663 // The first argument --- the pointer --- has a fixed type; we
3664 // deduce the types of the rest of the arguments accordingly. Walk
3665 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00003666 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00003667 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00003668
Chris Lattnerdc046542009-05-08 06:58:22 +00003669 // GCC does an implicit conversion to the pointer or integer ValType. This
3670 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00003671 // Initialize the argument.
3672 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3673 ValType, /*consume*/ false);
3674 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00003675 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003676 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003677
Chris Lattnerdc046542009-05-08 06:58:22 +00003678 // Okay, we have something that *can* be converted to the right type. Check
3679 // to see if there is a potentially weird extension going on here. This can
3680 // happen when you do an atomic operation on something like an char* and
3681 // pass in 42. The 42 gets converted to char. This is even more strange
3682 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00003683 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003684 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00003685 }
Mike Stump11289f42009-09-09 15:08:12 +00003686
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003687 ASTContext& Context = this->getASTContext();
3688
3689 // Create a new DeclRefExpr to refer to the new decl.
3690 DeclRefExpr* NewDRE = DeclRefExpr::Create(
3691 Context,
3692 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00003693 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003694 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00003695 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003696 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00003697 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003698 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00003699
Chris Lattnerdc046542009-05-08 06:58:22 +00003700 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00003701 // FIXME: This loses syntactic information.
3702 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3703 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3704 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003705 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00003706
Chandler Carruthbc8cab12010-07-18 07:23:17 +00003707 // Change the result type of the call to match the original value type. This
3708 // is arbitrary, but the codegen for these builtins ins design to handle it
3709 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00003710 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003711
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003712 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00003713}
3714
Michael Zolotukhin84df1232015-09-08 23:52:33 +00003715/// SemaBuiltinNontemporalOverloaded - We have a call to
3716/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3717/// overloaded function based on the pointer type of its last argument.
3718///
3719/// This function goes through and does final semantic checking for these
3720/// builtins.
3721ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3722 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3723 DeclRefExpr *DRE =
3724 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3725 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3726 unsigned BuiltinID = FDecl->getBuiltinID();
3727 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3728 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3729 "Unexpected nontemporal load/store builtin!");
3730 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3731 unsigned numArgs = isStore ? 2 : 1;
3732
3733 // Ensure that we have the proper number of arguments.
3734 if (checkArgCount(*this, TheCall, numArgs))
3735 return ExprError();
3736
3737 // Inspect the last argument of the nontemporal builtin. This should always
3738 // be a pointer type, from which we imply the type of the memory access.
3739 // Because it is a pointer type, we don't have to worry about any implicit
3740 // casts here.
3741 Expr *PointerArg = TheCall->getArg(numArgs - 1);
3742 ExprResult PointerArgResult =
3743 DefaultFunctionArrayLvalueConversion(PointerArg);
3744
3745 if (PointerArgResult.isInvalid())
3746 return ExprError();
3747 PointerArg = PointerArgResult.get();
3748 TheCall->setArg(numArgs - 1, PointerArg);
3749
3750 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3751 if (!pointerType) {
3752 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3753 << PointerArg->getType() << PointerArg->getSourceRange();
3754 return ExprError();
3755 }
3756
3757 QualType ValType = pointerType->getPointeeType();
3758
3759 // Strip any qualifiers off ValType.
3760 ValType = ValType.getUnqualifiedType();
3761 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3762 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3763 !ValType->isVectorType()) {
3764 Diag(DRE->getLocStart(),
3765 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3766 << PointerArg->getType() << PointerArg->getSourceRange();
3767 return ExprError();
3768 }
3769
3770 if (!isStore) {
3771 TheCall->setType(ValType);
3772 return TheCallResult;
3773 }
3774
3775 ExprResult ValArg = TheCall->getArg(0);
3776 InitializedEntity Entity = InitializedEntity::InitializeParameter(
3777 Context, ValType, /*consume*/ false);
3778 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3779 if (ValArg.isInvalid())
3780 return ExprError();
3781
3782 TheCall->setArg(0, ValArg.get());
3783 TheCall->setType(Context.VoidTy);
3784 return TheCallResult;
3785}
3786
Chris Lattner6436fb62009-02-18 06:01:06 +00003787/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00003788/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00003789/// Note: It might also make sense to do the UTF-16 conversion here (would
3790/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00003791bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00003792 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00003793 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3794
Douglas Gregorfb65e592011-07-27 05:40:30 +00003795 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003796 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3797 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00003798 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00003799 }
Mike Stump11289f42009-09-09 15:08:12 +00003800
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003801 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003802 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003803 unsigned NumBytes = String.size();
Justin Lebar90910552016-09-30 00:38:45 +00003804 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3805 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3806 llvm::UTF16 *ToPtr = &ToBuf[0];
3807
3808 llvm::ConversionResult Result =
3809 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3810 ToPtr + NumBytes, llvm::strictConversion);
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003811 // Check for conversion failure.
Justin Lebar90910552016-09-30 00:38:45 +00003812 if (Result != llvm::conversionOK)
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003813 Diag(Arg->getLocStart(),
3814 diag::warn_cfstring_truncated) << Arg->getSourceRange();
3815 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00003816 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003817}
3818
Mehdi Amini06d367c2016-10-24 20:39:34 +00003819/// CheckObjCString - Checks that the format string argument to the os_log()
3820/// and os_trace() functions is correct, and converts it to const char *.
3821ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3822 Arg = Arg->IgnoreParenCasts();
3823 auto *Literal = dyn_cast<StringLiteral>(Arg);
3824 if (!Literal) {
3825 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3826 Literal = ObjcLiteral->getString();
3827 }
3828 }
3829
3830 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3831 return ExprError(
3832 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3833 << Arg->getSourceRange());
3834 }
3835
3836 ExprResult Result(Literal);
3837 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3838 InitializedEntity Entity =
3839 InitializedEntity::InitializeParameter(Context, ResultTy, false);
3840 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3841 return Result;
3842}
3843
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003844/// Check that the user is calling the appropriate va_start builtin for the
3845/// target and calling convention.
3846static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
3847 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
3848 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
Martin Storsjo022e7822017-07-17 20:49:45 +00003849 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003850 bool IsWindows = TT.isOSWindows();
Martin Storsjo022e7822017-07-17 20:49:45 +00003851 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
3852 if (IsX64 || IsAArch64) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003853 CallingConv CC = CC_C;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003854 if (const FunctionDecl *FD = S.getCurFunctionDecl())
3855 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3856 if (IsMSVAStart) {
3857 // Don't allow this in System V ABI functions.
Martin Storsjo022e7822017-07-17 20:49:45 +00003858 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003859 return S.Diag(Fn->getLocStart(),
3860 diag::err_ms_va_start_used_in_sysv_function);
3861 } else {
Martin Storsjo022e7822017-07-17 20:49:45 +00003862 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003863 // On x64 Windows, don't allow this in System V ABI functions.
3864 // (Yes, that means there's no corresponding way to support variadic
3865 // System V ABI functions on Windows.)
3866 if ((IsWindows && CC == CC_X86_64SysV) ||
Martin Storsjo022e7822017-07-17 20:49:45 +00003867 (!IsWindows && CC == CC_Win64))
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003868 return S.Diag(Fn->getLocStart(),
3869 diag::err_va_start_used_in_wrong_abi_function)
3870 << !IsWindows;
3871 }
3872 return false;
3873 }
3874
3875 if (IsMSVAStart)
Martin Storsjo022e7822017-07-17 20:49:45 +00003876 return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003877 return false;
3878}
3879
3880static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
3881 ParmVarDecl **LastParam = nullptr) {
3882 // Determine whether the current function, block, or obj-c method is variadic
3883 // and get its parameter list.
3884 bool IsVariadic = false;
3885 ArrayRef<ParmVarDecl *> Params;
Reid Klecknerf1deb832017-05-04 19:51:05 +00003886 DeclContext *Caller = S.CurContext;
3887 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
3888 IsVariadic = Block->isVariadic();
3889 Params = Block->parameters();
3890 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003891 IsVariadic = FD->isVariadic();
3892 Params = FD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00003893 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003894 IsVariadic = MD->isVariadic();
3895 // FIXME: This isn't correct for methods (results in bogus warning).
3896 Params = MD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00003897 } else if (isa<CapturedDecl>(Caller)) {
3898 // We don't support va_start in a CapturedDecl.
3899 S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
3900 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003901 } else {
Reid Klecknerf1deb832017-05-04 19:51:05 +00003902 // This must be some other declcontext that parses exprs.
3903 S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
3904 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003905 }
3906
3907 if (!IsVariadic) {
Reid Klecknerf1deb832017-05-04 19:51:05 +00003908 S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003909 return true;
3910 }
3911
3912 if (LastParam)
3913 *LastParam = Params.empty() ? nullptr : Params.back();
3914
3915 return false;
3916}
3917
Charles Davisc7d5c942015-09-17 20:55:33 +00003918/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3919/// for validity. Emit an error and return true on failure; return false
3920/// on success.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003921bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00003922 Expr *Fn = TheCall->getCallee();
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003923
3924 if (checkVAStartABI(*this, BuiltinID, Fn))
3925 return true;
3926
Chris Lattner08464942007-12-28 05:29:59 +00003927 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00003928 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003929 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003930 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3931 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00003932 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003933 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00003934 return true;
3935 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003936
3937 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00003938 return Diag(TheCall->getLocEnd(),
3939 diag::err_typecheck_call_too_few_args_at_least)
3940 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003941 }
3942
John McCall29ad95b2011-08-27 01:09:30 +00003943 // Type-check the first argument normally.
3944 if (checkBuiltinArgument(*this, TheCall, 0))
3945 return true;
3946
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003947 // Check that the current function is variadic, and get its last parameter.
3948 ParmVarDecl *LastParam;
3949 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
Chris Lattner43be2e62007-12-19 23:59:04 +00003950 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003951
Chris Lattner43be2e62007-12-19 23:59:04 +00003952 // Verify that the second argument to the builtin is the last argument of the
3953 // current function or method.
3954 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00003955 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003956
Nico Weber9eea7642013-05-24 23:31:57 +00003957 // These are valid if SecondArgIsLastNamedArgument is false after the next
3958 // block.
3959 QualType Type;
3960 SourceLocation ParamLoc;
Aaron Ballman1de59c52016-04-24 13:30:21 +00003961 bool IsCRegister = false;
Nico Weber9eea7642013-05-24 23:31:57 +00003962
Anders Carlsson6a8350b2008-02-11 04:20:54 +00003963 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3964 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003965 SecondArgIsLastNamedArgument = PV == LastParam;
Nico Weber9eea7642013-05-24 23:31:57 +00003966
3967 Type = PV->getType();
3968 ParamLoc = PV->getLocation();
Aaron Ballman1de59c52016-04-24 13:30:21 +00003969 IsCRegister =
3970 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
Chris Lattner43be2e62007-12-19 23:59:04 +00003971 }
3972 }
Mike Stump11289f42009-09-09 15:08:12 +00003973
Chris Lattner43be2e62007-12-19 23:59:04 +00003974 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00003975 Diag(TheCall->getArg(1)->getLocStart(),
Aaron Ballman05164812016-04-18 18:10:53 +00003976 diag::warn_second_arg_of_va_start_not_last_named_param);
Aaron Ballman1de59c52016-04-24 13:30:21 +00003977 else if (IsCRegister || Type->isReferenceType() ||
Aaron Ballmana4f597f2016-09-15 18:07:51 +00003978 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3979 // Promotable integers are UB, but enumerations need a bit of
3980 // extra checking to see what their promotable type actually is.
3981 if (!Type->isPromotableIntegerType())
3982 return false;
3983 if (!Type->isEnumeralType())
3984 return true;
3985 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3986 return !(ED &&
3987 Context.typesAreCompatible(ED->getPromotionType(), Type));
3988 }()) {
Aaron Ballman1de59c52016-04-24 13:30:21 +00003989 unsigned Reason = 0;
3990 if (Type->isReferenceType()) Reason = 1;
3991 else if (IsCRegister) Reason = 2;
3992 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
Nico Weber9eea7642013-05-24 23:31:57 +00003993 Diag(ParamLoc, diag::note_parameter_type) << Type;
3994 }
3995
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00003996 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00003997 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00003998}
Chris Lattner43be2e62007-12-19 23:59:04 +00003999
Saleem Abdulrasool3450aa72017-09-26 20:12:04 +00004000bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004001 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
4002 // const char *named_addr);
4003
4004 Expr *Func = Call->getCallee();
4005
4006 if (Call->getNumArgs() < 3)
4007 return Diag(Call->getLocEnd(),
4008 diag::err_typecheck_call_too_few_args_at_least)
4009 << 0 /*function call*/ << 3 << Call->getNumArgs();
4010
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004011 // Type-check the first argument normally.
4012 if (checkBuiltinArgument(*this, Call, 0))
4013 return true;
4014
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004015 // Check that the current function is variadic.
4016 if (checkVAStartIsInVariadicFunction(*this, Func))
4017 return true;
4018
Saleem Abdulrasool448e8ad2017-09-26 17:44:10 +00004019 // __va_start on Windows does not validate the parameter qualifiers
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004020
Saleem Abdulrasool448e8ad2017-09-26 17:44:10 +00004021 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
4022 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
4023
4024 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
4025 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
4026
4027 const QualType &ConstCharPtrTy =
4028 Context.getPointerType(Context.CharTy.withConst());
4029 if (!Arg1Ty->isPointerType() ||
4030 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
4031 Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible)
4032 << Arg1->getType() << ConstCharPtrTy
4033 << 1 /* different class */
4034 << 0 /* qualifier difference */
4035 << 3 /* parameter mismatch */
4036 << 2 << Arg1->getType() << ConstCharPtrTy;
4037
4038 const QualType SizeTy = Context.getSizeType();
4039 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
4040 Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible)
4041 << Arg2->getType() << SizeTy
4042 << 1 /* different class */
4043 << 0 /* qualifier difference */
4044 << 3 /* parameter mismatch */
4045 << 3 << Arg2->getType() << SizeTy;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004046
4047 return false;
4048}
4049
Chris Lattner2da14fb2007-12-20 00:26:33 +00004050/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
4051/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00004052bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
4053 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00004054 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00004055 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00004056 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00004057 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004058 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004059 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00004060 << SourceRange(TheCall->getArg(2)->getLocStart(),
4061 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00004062
John Wiegley01296292011-04-08 18:41:53 +00004063 ExprResult OrigArg0 = TheCall->getArg(0);
4064 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00004065
Chris Lattner2da14fb2007-12-20 00:26:33 +00004066 // Do standard promotions between the two arguments, returning their common
4067 // type.
Chris Lattner08464942007-12-28 05:29:59 +00004068 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00004069 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
4070 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00004071
4072 // Make sure any conversions are pushed back into the call; this is
4073 // type safe since unordered compare builtins are declared as "_Bool
4074 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00004075 TheCall->setArg(0, OrigArg0.get());
4076 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00004077
John Wiegley01296292011-04-08 18:41:53 +00004078 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00004079 return false;
4080
Chris Lattner2da14fb2007-12-20 00:26:33 +00004081 // If the common type isn't a real floating type, then the arguments were
4082 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00004083 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00004084 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004085 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00004086 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
4087 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00004088
Chris Lattner2da14fb2007-12-20 00:26:33 +00004089 return false;
4090}
4091
Benjamin Kramer634fc102010-02-15 22:42:31 +00004092/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
4093/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00004094/// to check everything. We expect the last argument to be a floating point
4095/// value.
4096bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
4097 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00004098 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00004099 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00004100 if (TheCall->getNumArgs() > NumArgs)
4101 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004102 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004103 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00004104 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004105 (*(TheCall->arg_end()-1))->getLocEnd());
4106
Benjamin Kramer64aae502010-02-16 10:07:31 +00004107 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00004108
Eli Friedman7e4faac2009-08-31 20:06:00 +00004109 if (OrigArg->isTypeDependent())
4110 return false;
4111
Chris Lattner68784ef2010-05-06 05:50:07 +00004112 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00004113 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00004114 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004115 diag::err_typecheck_call_invalid_unary_fp)
4116 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004117
Neil Hickey88c0fac2016-12-13 16:22:50 +00004118 // If this is an implicit conversion from float -> float or double, remove it.
Chris Lattner68784ef2010-05-06 05:50:07 +00004119 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
Neil Hickey7b5ddab2016-12-14 13:18:48 +00004120 // Only remove standard FloatCasts, leaving other casts inplace
4121 if (Cast->getCastKind() == CK_FloatingCast) {
4122 Expr *CastArg = Cast->getSubExpr();
4123 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
4124 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
4125 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
4126 "promotion from float to either float or double is the only expected cast here");
4127 Cast->setSubExpr(nullptr);
4128 TheCall->setArg(NumArgs-1, CastArg);
4129 }
Chris Lattner68784ef2010-05-06 05:50:07 +00004130 }
4131 }
4132
Eli Friedman7e4faac2009-08-31 20:06:00 +00004133 return false;
4134}
4135
Tony Jiangbbc48e92017-05-24 15:13:32 +00004136// Customized Sema Checking for VSX builtins that have the following signature:
4137// vector [...] builtinName(vector [...], vector [...], const int);
4138// Which takes the same type of vectors (any legal vector type) for the first
4139// two arguments and takes compile time constant for the third argument.
4140// Example builtins are :
4141// vector double vec_xxpermdi(vector double, vector double, int);
4142// vector short vec_xxsldwi(vector short, vector short, int);
4143bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
4144 unsigned ExpectedNumArgs = 3;
4145 if (TheCall->getNumArgs() < ExpectedNumArgs)
4146 return Diag(TheCall->getLocEnd(),
4147 diag::err_typecheck_call_too_few_args_at_least)
4148 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4149 << TheCall->getSourceRange();
4150
4151 if (TheCall->getNumArgs() > ExpectedNumArgs)
4152 return Diag(TheCall->getLocEnd(),
4153 diag::err_typecheck_call_too_many_args_at_most)
4154 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4155 << TheCall->getSourceRange();
4156
4157 // Check the third argument is a compile time constant
4158 llvm::APSInt Value;
4159 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
4160 return Diag(TheCall->getLocStart(),
4161 diag::err_vsx_builtin_nonconstant_argument)
4162 << 3 /* argument index */ << TheCall->getDirectCallee()
4163 << SourceRange(TheCall->getArg(2)->getLocStart(),
4164 TheCall->getArg(2)->getLocEnd());
4165
4166 QualType Arg1Ty = TheCall->getArg(0)->getType();
4167 QualType Arg2Ty = TheCall->getArg(1)->getType();
4168
4169 // Check the type of argument 1 and argument 2 are vectors.
4170 SourceLocation BuiltinLoc = TheCall->getLocStart();
4171 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
4172 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
4173 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
4174 << TheCall->getDirectCallee()
4175 << SourceRange(TheCall->getArg(0)->getLocStart(),
4176 TheCall->getArg(1)->getLocEnd());
4177 }
4178
4179 // Check the first two arguments are the same type.
4180 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
4181 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
4182 << TheCall->getDirectCallee()
4183 << SourceRange(TheCall->getArg(0)->getLocStart(),
4184 TheCall->getArg(1)->getLocEnd());
4185 }
4186
4187 // When default clang type checking is turned off and the customized type
4188 // checking is used, the returning type of the function must be explicitly
4189 // set. Otherwise it is _Bool by default.
4190 TheCall->setType(Arg1Ty);
4191
4192 return false;
4193}
4194
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004195/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
4196// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00004197ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00004198 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004199 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00004200 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00004201 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4202 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004203
Nate Begemana0110022010-06-08 00:16:34 +00004204 // Determine which of the following types of shufflevector we're checking:
4205 // 1) unary, vector mask: (lhs, mask)
Craig Topperb3174a82016-05-18 04:11:25 +00004206 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
Nate Begemana0110022010-06-08 00:16:34 +00004207 QualType resType = TheCall->getArg(0)->getType();
4208 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00004209
Douglas Gregorc25f7662009-05-19 22:10:17 +00004210 if (!TheCall->getArg(0)->isTypeDependent() &&
4211 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00004212 QualType LHSType = TheCall->getArg(0)->getType();
4213 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00004214
Craig Topperbaca3892013-07-29 06:47:04 +00004215 if (!LHSType->isVectorType() || !RHSType->isVectorType())
4216 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004217 diag::err_vec_builtin_non_vector)
4218 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004219 << SourceRange(TheCall->getArg(0)->getLocStart(),
4220 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00004221
Nate Begemana0110022010-06-08 00:16:34 +00004222 numElements = LHSType->getAs<VectorType>()->getNumElements();
4223 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00004224
Nate Begemana0110022010-06-08 00:16:34 +00004225 // Check to see if we have a call with 2 vector arguments, the unary shuffle
4226 // with mask. If so, verify that RHS is an integer vector type with the
4227 // same number of elts as lhs.
4228 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00004229 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00004230 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00004231 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004232 diag::err_vec_builtin_incompatible_vector)
4233 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004234 << SourceRange(TheCall->getArg(1)->getLocStart(),
4235 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00004236 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00004237 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004238 diag::err_vec_builtin_incompatible_vector)
4239 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004240 << SourceRange(TheCall->getArg(0)->getLocStart(),
4241 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00004242 } else if (numElements != numResElements) {
4243 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00004244 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00004245 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00004246 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004247 }
4248
4249 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00004250 if (TheCall->getArg(i)->isTypeDependent() ||
4251 TheCall->getArg(i)->isValueDependent())
4252 continue;
4253
Nate Begemana0110022010-06-08 00:16:34 +00004254 llvm::APSInt Result(32);
4255 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
4256 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004257 diag::err_shufflevector_nonconstant_argument)
4258 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004259
Craig Topper50ad5b72013-08-03 17:40:38 +00004260 // Allow -1 which will be translated to undef in the IR.
4261 if (Result.isSigned() && Result.isAllOnesValue())
4262 continue;
4263
Chris Lattner7ab824e2008-08-10 02:05:13 +00004264 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004265 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004266 diag::err_shufflevector_argument_too_large)
4267 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004268 }
4269
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004270 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004271
Chris Lattner7ab824e2008-08-10 02:05:13 +00004272 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004273 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00004274 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004275 }
4276
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004277 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
4278 TheCall->getCallee()->getLocStart(),
4279 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004280}
Chris Lattner43be2e62007-12-19 23:59:04 +00004281
Hal Finkelc4d7c822013-09-18 03:29:45 +00004282/// SemaConvertVectorExpr - Handle __builtin_convertvector
4283ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
4284 SourceLocation BuiltinLoc,
4285 SourceLocation RParenLoc) {
4286 ExprValueKind VK = VK_RValue;
4287 ExprObjectKind OK = OK_Ordinary;
4288 QualType DstTy = TInfo->getType();
4289 QualType SrcTy = E->getType();
4290
4291 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
4292 return ExprError(Diag(BuiltinLoc,
4293 diag::err_convertvector_non_vector)
4294 << E->getSourceRange());
4295 if (!DstTy->isVectorType() && !DstTy->isDependentType())
4296 return ExprError(Diag(BuiltinLoc,
4297 diag::err_convertvector_non_vector_type));
4298
4299 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
4300 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
4301 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
4302 if (SrcElts != DstElts)
4303 return ExprError(Diag(BuiltinLoc,
4304 diag::err_convertvector_incompatible_vector)
4305 << E->getSourceRange());
4306 }
4307
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004308 return new (Context)
4309 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00004310}
4311
Daniel Dunbarb7257262008-07-21 22:59:13 +00004312/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
4313// This is declared to take (const void*, ...) and can take two
4314// optional constant int args.
4315bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00004316 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004317
Chris Lattner3b054132008-11-19 05:08:23 +00004318 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004319 return Diag(TheCall->getLocEnd(),
4320 diag::err_typecheck_call_too_many_args_at_most)
4321 << 0 /*function call*/ << 3 << NumArgs
4322 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004323
4324 // Argument 0 is checked for us and the remaining arguments must be
4325 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00004326 for (unsigned i = 1; i != NumArgs; ++i)
4327 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004328 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004329
Warren Hunt20e4a5d2014-02-21 23:08:53 +00004330 return false;
4331}
4332
Hal Finkelf0417332014-07-17 14:25:55 +00004333/// SemaBuiltinAssume - Handle __assume (MS Extension).
4334// __assume does not evaluate its arguments, and should warn if its argument
4335// has side effects.
4336bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
4337 Expr *Arg = TheCall->getArg(0);
4338 if (Arg->isInstantiationDependent()) return false;
4339
4340 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00004341 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00004342 << Arg->getSourceRange()
4343 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
4344
4345 return false;
4346}
4347
David Majnemer86b1bfa2016-10-31 18:07:57 +00004348/// Handle __builtin_alloca_with_align. This is declared
David Majnemer51169932016-10-31 05:37:48 +00004349/// as (size_t, size_t) where the second size_t must be a power of 2 greater
4350/// than 8.
4351bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
4352 // The alignment must be a constant integer.
4353 Expr *Arg = TheCall->getArg(1);
4354
4355 // We can't check the value of a dependent argument.
4356 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
David Majnemer86b1bfa2016-10-31 18:07:57 +00004357 if (const auto *UE =
4358 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
4359 if (UE->getKind() == UETT_AlignOf)
4360 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
4361 << Arg->getSourceRange();
4362
David Majnemer51169932016-10-31 05:37:48 +00004363 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
4364
4365 if (!Result.isPowerOf2())
4366 return Diag(TheCall->getLocStart(),
4367 diag::err_alignment_not_power_of_two)
4368 << Arg->getSourceRange();
4369
4370 if (Result < Context.getCharWidth())
4371 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
4372 << (unsigned)Context.getCharWidth()
4373 << Arg->getSourceRange();
4374
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004375 if (Result > std::numeric_limits<int32_t>::max())
David Majnemer51169932016-10-31 05:37:48 +00004376 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004377 << std::numeric_limits<int32_t>::max()
David Majnemer51169932016-10-31 05:37:48 +00004378 << Arg->getSourceRange();
4379 }
4380
4381 return false;
4382}
4383
4384/// Handle __builtin_assume_aligned. This is declared
Hal Finkelbcc06082014-09-07 22:58:14 +00004385/// as (const void*, size_t, ...) and can take one optional constant int arg.
4386bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
4387 unsigned NumArgs = TheCall->getNumArgs();
4388
4389 if (NumArgs > 3)
4390 return Diag(TheCall->getLocEnd(),
4391 diag::err_typecheck_call_too_many_args_at_most)
4392 << 0 /*function call*/ << 3 << NumArgs
4393 << TheCall->getSourceRange();
4394
4395 // The alignment must be a constant integer.
4396 Expr *Arg = TheCall->getArg(1);
4397
4398 // We can't check the value of a dependent argument.
4399 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4400 llvm::APSInt Result;
4401 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4402 return true;
4403
4404 if (!Result.isPowerOf2())
4405 return Diag(TheCall->getLocStart(),
4406 diag::err_alignment_not_power_of_two)
4407 << Arg->getSourceRange();
4408 }
4409
4410 if (NumArgs > 2) {
4411 ExprResult Arg(TheCall->getArg(2));
4412 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4413 Context.getSizeType(), false);
4414 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4415 if (Arg.isInvalid()) return true;
4416 TheCall->setArg(2, Arg.get());
4417 }
Hal Finkelf0417332014-07-17 14:25:55 +00004418
4419 return false;
4420}
4421
Mehdi Amini06d367c2016-10-24 20:39:34 +00004422bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4423 unsigned BuiltinID =
4424 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4425 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4426
4427 unsigned NumArgs = TheCall->getNumArgs();
4428 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4429 if (NumArgs < NumRequiredArgs) {
4430 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4431 << 0 /* function call */ << NumRequiredArgs << NumArgs
4432 << TheCall->getSourceRange();
4433 }
4434 if (NumArgs >= NumRequiredArgs + 0x100) {
4435 return Diag(TheCall->getLocEnd(),
4436 diag::err_typecheck_call_too_many_args_at_most)
4437 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4438 << TheCall->getSourceRange();
4439 }
4440 unsigned i = 0;
4441
4442 // For formatting call, check buffer arg.
4443 if (!IsSizeCall) {
4444 ExprResult Arg(TheCall->getArg(i));
4445 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4446 Context, Context.VoidPtrTy, false);
4447 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4448 if (Arg.isInvalid())
4449 return true;
4450 TheCall->setArg(i, Arg.get());
4451 i++;
4452 }
4453
4454 // Check string literal arg.
4455 unsigned FormatIdx = i;
4456 {
4457 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4458 if (Arg.isInvalid())
4459 return true;
4460 TheCall->setArg(i, Arg.get());
4461 i++;
4462 }
4463
4464 // Make sure variadic args are scalar.
4465 unsigned FirstDataArg = i;
4466 while (i < NumArgs) {
4467 ExprResult Arg = DefaultVariadicArgumentPromotion(
4468 TheCall->getArg(i), VariadicFunction, nullptr);
4469 if (Arg.isInvalid())
4470 return true;
4471 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4472 if (ArgSize.getQuantity() >= 0x100) {
4473 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4474 << i << (int)ArgSize.getQuantity() << 0xff
4475 << TheCall->getSourceRange();
4476 }
4477 TheCall->setArg(i, Arg.get());
4478 i++;
4479 }
4480
4481 // Check formatting specifiers. NOTE: We're only doing this for the non-size
4482 // call to avoid duplicate diagnostics.
4483 if (!IsSizeCall) {
4484 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4485 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4486 bool Success = CheckFormatArguments(
4487 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4488 VariadicFunction, TheCall->getLocStart(), SourceRange(),
4489 CheckedVarArgs);
4490 if (!Success)
4491 return true;
4492 }
4493
4494 if (IsSizeCall) {
4495 TheCall->setType(Context.getSizeType());
4496 } else {
4497 TheCall->setType(Context.VoidPtrTy);
4498 }
4499 return false;
4500}
4501
Eric Christopher8d0c6212010-04-17 02:26:23 +00004502/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4503/// TheCall is a constant expression.
4504bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4505 llvm::APSInt &Result) {
4506 Expr *Arg = TheCall->getArg(ArgNum);
4507 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4508 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4509
4510 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4511
4512 if (!Arg->isIntegerConstantExpr(Result, Context))
4513 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00004514 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00004515
Chris Lattnerd545ad12009-09-23 06:06:36 +00004516 return false;
4517}
4518
Richard Sandiford28940af2014-04-16 08:47:51 +00004519/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4520/// TheCall is a constant expression in the range [Low, High].
4521bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4522 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00004523 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004524
4525 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00004526 Expr *Arg = TheCall->getArg(ArgNum);
4527 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004528 return false;
4529
Eric Christopher8d0c6212010-04-17 02:26:23 +00004530 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00004531 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004532 return true;
4533
Richard Sandiford28940af2014-04-16 08:47:51 +00004534 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00004535 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00004536 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00004537
4538 return false;
4539}
4540
Simon Dardis1f90f2d2016-10-19 17:50:52 +00004541/// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4542/// TheCall is a constant expression is a multiple of Num..
4543bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4544 unsigned Num) {
4545 llvm::APSInt Result;
4546
4547 // We can't check the value of a dependent argument.
4548 Expr *Arg = TheCall->getArg(ArgNum);
4549 if (Arg->isTypeDependent() || Arg->isValueDependent())
4550 return false;
4551
4552 // Check constant-ness first.
4553 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4554 return true;
4555
4556 if (Result.getSExtValue() % Num != 0)
4557 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4558 << Num << Arg->getSourceRange();
4559
4560 return false;
4561}
4562
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004563/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4564/// TheCall is an ARM/AArch64 special register string literal.
4565bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4566 int ArgNum, unsigned ExpectedFieldNum,
4567 bool AllowName) {
4568 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4569 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4570 BuiltinID == ARM::BI__builtin_arm_rsr ||
4571 BuiltinID == ARM::BI__builtin_arm_rsrp ||
4572 BuiltinID == ARM::BI__builtin_arm_wsr ||
4573 BuiltinID == ARM::BI__builtin_arm_wsrp;
4574 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4575 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4576 BuiltinID == AArch64::BI__builtin_arm_rsr ||
4577 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4578 BuiltinID == AArch64::BI__builtin_arm_wsr ||
4579 BuiltinID == AArch64::BI__builtin_arm_wsrp;
4580 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4581
4582 // We can't check the value of a dependent argument.
4583 Expr *Arg = TheCall->getArg(ArgNum);
4584 if (Arg->isTypeDependent() || Arg->isValueDependent())
4585 return false;
4586
4587 // Check if the argument is a string literal.
4588 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4589 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4590 << Arg->getSourceRange();
4591
4592 // Check the type of special register given.
4593 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4594 SmallVector<StringRef, 6> Fields;
4595 Reg.split(Fields, ":");
4596
4597 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4598 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4599 << Arg->getSourceRange();
4600
4601 // If the string is the name of a register then we cannot check that it is
4602 // valid here but if the string is of one the forms described in ACLE then we
4603 // can check that the supplied fields are integers and within the valid
4604 // ranges.
4605 if (Fields.size() > 1) {
4606 bool FiveFields = Fields.size() == 5;
4607
4608 bool ValidString = true;
4609 if (IsARMBuiltin) {
4610 ValidString &= Fields[0].startswith_lower("cp") ||
4611 Fields[0].startswith_lower("p");
4612 if (ValidString)
4613 Fields[0] =
4614 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4615
4616 ValidString &= Fields[2].startswith_lower("c");
4617 if (ValidString)
4618 Fields[2] = Fields[2].drop_front(1);
4619
4620 if (FiveFields) {
4621 ValidString &= Fields[3].startswith_lower("c");
4622 if (ValidString)
4623 Fields[3] = Fields[3].drop_front(1);
4624 }
4625 }
4626
4627 SmallVector<int, 5> Ranges;
4628 if (FiveFields)
Oleg Ranevskyy85d93a82016-11-18 21:00:08 +00004629 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004630 else
4631 Ranges.append({15, 7, 15});
4632
4633 for (unsigned i=0; i<Fields.size(); ++i) {
4634 int IntField;
4635 ValidString &= !Fields[i].getAsInteger(10, IntField);
4636 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4637 }
4638
4639 if (!ValidString)
4640 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4641 << Arg->getSourceRange();
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004642 } else if (IsAArch64Builtin && Fields.size() == 1) {
4643 // If the register name is one of those that appear in the condition below
4644 // and the special register builtin being used is one of the write builtins,
4645 // then we require that the argument provided for writing to the register
4646 // is an integer constant expression. This is because it will be lowered to
4647 // an MSR (immediate) instruction, so we need to know the immediate at
4648 // compile time.
4649 if (TheCall->getNumArgs() != 2)
4650 return false;
4651
4652 std::string RegLower = Reg.lower();
4653 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4654 RegLower != "pan" && RegLower != "uao")
4655 return false;
4656
4657 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4658 }
4659
4660 return false;
4661}
4662
Eli Friedmanc97d0142009-05-03 06:04:26 +00004663/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004664/// This checks that the target supports __builtin_longjmp and
4665/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004666bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004667 if (!Context.getTargetInfo().hasSjLjLowering())
4668 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4669 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4670
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004671 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00004672 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00004673
Eric Christopher8d0c6212010-04-17 02:26:23 +00004674 // TODO: This is less than ideal. Overload this to take a value.
4675 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4676 return true;
4677
4678 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004679 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4680 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4681
4682 return false;
4683}
4684
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004685/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4686/// This checks that the target supports __builtin_setjmp.
4687bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4688 if (!Context.getTargetInfo().hasSjLjLowering())
4689 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4690 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4691 return false;
4692}
4693
Richard Smithd7293d72013-08-05 18:49:43 +00004694namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004695
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004696class UncoveredArgHandler {
4697 enum { Unknown = -1, AllCovered = -2 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004698
4699 signed FirstUncoveredArg = Unknown;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004700 SmallVector<const Expr *, 4> DiagnosticExprs;
4701
4702public:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004703 UncoveredArgHandler() = default;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004704
4705 bool hasUncoveredArg() const {
4706 return (FirstUncoveredArg >= 0);
4707 }
4708
4709 unsigned getUncoveredArg() const {
4710 assert(hasUncoveredArg() && "no uncovered argument");
4711 return FirstUncoveredArg;
4712 }
4713
4714 void setAllCovered() {
4715 // A string has been found with all arguments covered, so clear out
4716 // the diagnostics.
4717 DiagnosticExprs.clear();
4718 FirstUncoveredArg = AllCovered;
4719 }
4720
4721 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4722 assert(NewFirstUncoveredArg >= 0 && "Outside range");
4723
4724 // Don't update if a previous string covers all arguments.
4725 if (FirstUncoveredArg == AllCovered)
4726 return;
4727
4728 // UncoveredArgHandler tracks the highest uncovered argument index
4729 // and with it all the strings that match this index.
4730 if (NewFirstUncoveredArg == FirstUncoveredArg)
4731 DiagnosticExprs.push_back(StrExpr);
4732 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4733 DiagnosticExprs.clear();
4734 DiagnosticExprs.push_back(StrExpr);
4735 FirstUncoveredArg = NewFirstUncoveredArg;
4736 }
4737 }
4738
4739 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4740};
4741
Richard Smithd7293d72013-08-05 18:49:43 +00004742enum StringLiteralCheckType {
4743 SLCT_NotALiteral,
4744 SLCT_UncheckedLiteral,
4745 SLCT_CheckedLiteral
4746};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004747
4748} // namespace
Richard Smithd7293d72013-08-05 18:49:43 +00004749
Stephen Hines648c3692016-09-16 01:07:04 +00004750static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4751 BinaryOperatorKind BinOpKind,
4752 bool AddendIsRight) {
4753 unsigned BitWidth = Offset.getBitWidth();
4754 unsigned AddendBitWidth = Addend.getBitWidth();
4755 // There might be negative interim results.
4756 if (Addend.isUnsigned()) {
4757 Addend = Addend.zext(++AddendBitWidth);
4758 Addend.setIsSigned(true);
4759 }
4760 // Adjust the bit width of the APSInts.
4761 if (AddendBitWidth > BitWidth) {
4762 Offset = Offset.sext(AddendBitWidth);
4763 BitWidth = AddendBitWidth;
4764 } else if (BitWidth > AddendBitWidth) {
4765 Addend = Addend.sext(BitWidth);
4766 }
4767
4768 bool Ov = false;
4769 llvm::APSInt ResOffset = Offset;
4770 if (BinOpKind == BO_Add)
4771 ResOffset = Offset.sadd_ov(Addend, Ov);
4772 else {
4773 assert(AddendIsRight && BinOpKind == BO_Sub &&
4774 "operator must be add or sub with addend on the right");
4775 ResOffset = Offset.ssub_ov(Addend, Ov);
4776 }
4777
4778 // We add an offset to a pointer here so we should support an offset as big as
4779 // possible.
4780 if (Ov) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004781 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
4782 "index (intermediate) result too big");
Stephen Hinesfec73ad2016-09-16 07:21:24 +00004783 Offset = Offset.sext(2 * BitWidth);
Stephen Hines648c3692016-09-16 01:07:04 +00004784 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4785 return;
4786 }
4787
4788 Offset = ResOffset;
4789}
4790
4791namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004792
Stephen Hines648c3692016-09-16 01:07:04 +00004793// This is a wrapper class around StringLiteral to support offsetted string
4794// literals as format strings. It takes the offset into account when returning
4795// the string and its length or the source locations to display notes correctly.
4796class FormatStringLiteral {
4797 const StringLiteral *FExpr;
4798 int64_t Offset;
4799
4800 public:
4801 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4802 : FExpr(fexpr), Offset(Offset) {}
4803
4804 StringRef getString() const {
4805 return FExpr->getString().drop_front(Offset);
4806 }
4807
4808 unsigned getByteLength() const {
4809 return FExpr->getByteLength() - getCharByteWidth() * Offset;
4810 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004811
Stephen Hines648c3692016-09-16 01:07:04 +00004812 unsigned getLength() const { return FExpr->getLength() - Offset; }
4813 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4814
4815 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4816
4817 QualType getType() const { return FExpr->getType(); }
4818
4819 bool isAscii() const { return FExpr->isAscii(); }
4820 bool isWide() const { return FExpr->isWide(); }
4821 bool isUTF8() const { return FExpr->isUTF8(); }
4822 bool isUTF16() const { return FExpr->isUTF16(); }
4823 bool isUTF32() const { return FExpr->isUTF32(); }
4824 bool isPascal() const { return FExpr->isPascal(); }
4825
4826 SourceLocation getLocationOfByte(
4827 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4828 const TargetInfo &Target, unsigned *StartToken = nullptr,
4829 unsigned *StartTokenByteOffset = nullptr) const {
4830 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4831 StartToken, StartTokenByteOffset);
4832 }
4833
4834 SourceLocation getLocStart() const LLVM_READONLY {
4835 return FExpr->getLocStart().getLocWithOffset(Offset);
4836 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004837
Stephen Hines648c3692016-09-16 01:07:04 +00004838 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4839};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004840
4841} // namespace
Stephen Hines648c3692016-09-16 01:07:04 +00004842
4843static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004844 const Expr *OrigFormatExpr,
4845 ArrayRef<const Expr *> Args,
4846 bool HasVAListArg, unsigned format_idx,
4847 unsigned firstDataArg,
4848 Sema::FormatStringType Type,
4849 bool inFunctionCall,
4850 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004851 llvm::SmallBitVector &CheckedVarArgs,
4852 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004853
Richard Smith55ce3522012-06-25 20:30:08 +00004854// Determine if an expression is a string literal or constant string.
4855// If this function returns false on the arguments to a function expecting a
4856// format string, we will usually need to emit a warning.
4857// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00004858static StringLiteralCheckType
4859checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4860 bool HasVAListArg, unsigned format_idx,
4861 unsigned firstDataArg, Sema::FormatStringType Type,
4862 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004863 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004864 UncoveredArgHandler &UncoveredArg,
4865 llvm::APSInt Offset) {
Ted Kremenek808829352010-09-09 03:51:39 +00004866 tryAgain:
Stephen Hines648c3692016-09-16 01:07:04 +00004867 assert(Offset.isSigned() && "invalid offset");
4868
Douglas Gregorc25f7662009-05-19 22:10:17 +00004869 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00004870 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004871
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004872 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00004873
Richard Smithd7293d72013-08-05 18:49:43 +00004874 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00004875 // Technically -Wformat-nonliteral does not warn about this case.
4876 // The behavior of printf and friends in this case is implementation
4877 // dependent. Ideally if the format string cannot be null then
4878 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00004879 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00004880
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004881 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00004882 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004883 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00004884 // The expression is a literal if both sub-expressions were, and it was
4885 // completely checked only if both sub-expressions were checked.
4886 const AbstractConditionalOperator *C =
4887 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004888
4889 // Determine whether it is necessary to check both sub-expressions, for
4890 // example, because the condition expression is a constant that can be
4891 // evaluated at compile time.
4892 bool CheckLeft = true, CheckRight = true;
4893
4894 bool Cond;
4895 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4896 if (Cond)
4897 CheckRight = false;
4898 else
4899 CheckLeft = false;
4900 }
4901
Stephen Hines648c3692016-09-16 01:07:04 +00004902 // We need to maintain the offsets for the right and the left hand side
4903 // separately to check if every possible indexed expression is a valid
4904 // string literal. They might have different offsets for different string
4905 // literals in the end.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004906 StringLiteralCheckType Left;
4907 if (!CheckLeft)
4908 Left = SLCT_UncheckedLiteral;
4909 else {
4910 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4911 HasVAListArg, format_idx, firstDataArg,
4912 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004913 CheckedVarArgs, UncoveredArg, Offset);
4914 if (Left == SLCT_NotALiteral || !CheckRight) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004915 return Left;
Stephen Hines648c3692016-09-16 01:07:04 +00004916 }
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004917 }
4918
Richard Smith55ce3522012-06-25 20:30:08 +00004919 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00004920 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004921 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004922 Type, CallType, InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004923 UncoveredArg, Offset);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004924
4925 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004926 }
4927
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004928 case Stmt::ImplicitCastExprClass:
Ted Kremenek808829352010-09-09 03:51:39 +00004929 E = cast<ImplicitCastExpr>(E)->getSubExpr();
4930 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004931
John McCallc07a0c72011-02-17 10:25:35 +00004932 case Stmt::OpaqueValueExprClass:
4933 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4934 E = src;
4935 goto tryAgain;
4936 }
Richard Smith55ce3522012-06-25 20:30:08 +00004937 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00004938
Ted Kremeneka8890832011-02-24 23:03:04 +00004939 case Stmt::PredefinedExprClass:
4940 // While __func__, etc., are technically not string literals, they
4941 // cannot contain format specifiers and thus are not a security
4942 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00004943 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00004944
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004945 case Stmt::DeclRefExprClass: {
4946 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004947
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004948 // As an exception, do not flag errors for variables binding to
4949 // const string literals.
4950 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4951 bool isConstant = false;
4952 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004953
Richard Smithd7293d72013-08-05 18:49:43 +00004954 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4955 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00004956 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00004957 isConstant = T.isConstant(S.Context) &&
4958 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00004959 } else if (T->isObjCObjectPointerType()) {
4960 // In ObjC, there is usually no "const ObjectPointer" type,
4961 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00004962 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004963 }
Mike Stump11289f42009-09-09 15:08:12 +00004964
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004965 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004966 if (const Expr *Init = VD->getAnyInitializer()) {
4967 // Look through initializers like const char c[] = { "foo" }
4968 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4969 if (InitList->isStringLiteralInit())
4970 Init = InitList->getInit(0)->IgnoreParenImpCasts();
4971 }
Richard Smithd7293d72013-08-05 18:49:43 +00004972 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004973 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004974 firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00004975 /*InFunctionCall*/ false, CheckedVarArgs,
4976 UncoveredArg, Offset);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004977 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004978 }
Mike Stump11289f42009-09-09 15:08:12 +00004979
Anders Carlssonb012ca92009-06-28 19:55:58 +00004980 // For vprintf* functions (i.e., HasVAListArg==true), we add a
4981 // special check to see if the format string is a function parameter
4982 // of the function calling the printf function. If the function
4983 // has an attribute indicating it is a printf-like function, then we
4984 // should suppress warnings concerning non-literals being used in a call
4985 // to a vprintf function. For example:
4986 //
4987 // void
4988 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4989 // va_list ap;
4990 // va_start(ap, fmt);
4991 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
4992 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00004993 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004994 if (HasVAListArg) {
4995 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4996 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4997 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00004998 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004999 // adjust for implicit parameter
5000 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5001 if (MD->isInstance())
5002 ++PVIndex;
5003 // We also check if the formats are compatible.
5004 // We can't pass a 'scanf' string to a 'printf' function.
5005 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00005006 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00005007 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00005008 }
5009 }
5010 }
5011 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005012 }
Mike Stump11289f42009-09-09 15:08:12 +00005013
Richard Smith55ce3522012-06-25 20:30:08 +00005014 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005015 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005016
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00005017 case Stmt::CallExprClass:
5018 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005019 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00005020 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
5021 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
5022 unsigned ArgIndex = FA->getFormatIdx();
5023 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5024 if (MD->isInstance())
5025 --ArgIndex;
5026 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00005027
Richard Smithd7293d72013-08-05 18:49:43 +00005028 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005029 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00005030 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00005031 CheckedVarArgs, UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005032 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5033 unsigned BuiltinID = FD->getBuiltinID();
5034 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
5035 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
5036 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00005037 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005038 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005039 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005040 InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00005041 UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005042 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005043 }
5044 }
Mike Stump11289f42009-09-09 15:08:12 +00005045
Richard Smith55ce3522012-06-25 20:30:08 +00005046 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005047 }
Alex Lorenzd9007142016-10-24 09:42:34 +00005048 case Stmt::ObjCMessageExprClass: {
5049 const auto *ME = cast<ObjCMessageExpr>(E);
5050 if (const auto *ND = ME->getMethodDecl()) {
5051 if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
5052 unsigned ArgIndex = FA->getFormatIdx();
5053 const Expr *Arg = ME->getArg(ArgIndex - 1);
5054 return checkFormatStringExpr(
5055 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
5056 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
5057 }
5058 }
5059
5060 return SLCT_NotALiteral;
5061 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005062 case Stmt::ObjCStringLiteralClass:
5063 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00005064 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005065
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005066 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005067 StrE = ObjCFExpr->getString();
5068 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005069 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005070
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005071 if (StrE) {
Stephen Hines648c3692016-09-16 01:07:04 +00005072 if (Offset.isNegative() || Offset > StrE->getLength()) {
5073 // TODO: It would be better to have an explicit warning for out of
5074 // bounds literals.
5075 return SLCT_NotALiteral;
5076 }
5077 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
5078 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005079 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005080 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00005081 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005082 }
Mike Stump11289f42009-09-09 15:08:12 +00005083
Richard Smith55ce3522012-06-25 20:30:08 +00005084 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005085 }
Stephen Hines648c3692016-09-16 01:07:04 +00005086 case Stmt::BinaryOperatorClass: {
5087 llvm::APSInt LResult;
5088 llvm::APSInt RResult;
5089
5090 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
5091
5092 // A string literal + an int offset is still a string literal.
5093 if (BinOp->isAdditiveOp()) {
5094 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
5095 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
5096
5097 if (LIsInt != RIsInt) {
5098 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
5099
5100 if (LIsInt) {
5101 if (BinOpKind == BO_Add) {
5102 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
5103 E = BinOp->getRHS();
5104 goto tryAgain;
5105 }
5106 } else {
5107 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
5108 E = BinOp->getLHS();
5109 goto tryAgain;
5110 }
5111 }
Stephen Hines648c3692016-09-16 01:07:04 +00005112 }
George Burgess IVd273aab2016-09-22 00:00:26 +00005113
5114 return SLCT_NotALiteral;
Stephen Hines648c3692016-09-16 01:07:04 +00005115 }
5116 case Stmt::UnaryOperatorClass: {
5117 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
5118 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005119 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
Stephen Hines648c3692016-09-16 01:07:04 +00005120 llvm::APSInt IndexResult;
5121 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
5122 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
5123 E = ASE->getBase();
5124 goto tryAgain;
5125 }
5126 }
5127
5128 return SLCT_NotALiteral;
5129 }
Mike Stump11289f42009-09-09 15:08:12 +00005130
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005131 default:
Richard Smith55ce3522012-06-25 20:30:08 +00005132 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005133 }
5134}
5135
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005136Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00005137 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Mehdi Amini06d367c2016-10-24 20:39:34 +00005138 .Case("scanf", FST_Scanf)
5139 .Cases("printf", "printf0", FST_Printf)
5140 .Cases("NSString", "CFString", FST_NSString)
5141 .Case("strftime", FST_Strftime)
5142 .Case("strfmon", FST_Strfmon)
5143 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
5144 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
5145 .Case("os_trace", FST_OSLog)
5146 .Case("os_log", FST_OSLog)
5147 .Default(FST_Unknown);
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005148}
5149
Jordan Rose3e0ec582012-07-19 18:10:23 +00005150/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00005151/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00005152/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005153bool Sema::CheckFormatArguments(const FormatAttr *Format,
5154 ArrayRef<const Expr *> Args,
5155 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005156 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00005157 SourceLocation Loc, SourceRange Range,
5158 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00005159 FormatStringInfo FSI;
5160 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005161 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00005162 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00005163 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00005164 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005165}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00005166
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005167bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005168 bool HasVAListArg, unsigned format_idx,
5169 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005170 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00005171 SourceLocation Loc, SourceRange Range,
5172 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00005173 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005174 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005175 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00005176 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005177 }
Mike Stump11289f42009-09-09 15:08:12 +00005178
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005179 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00005180
Chris Lattnerb87b1b32007-08-10 20:18:51 +00005181 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00005182 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005183 // Dynamically generated format strings are difficult to
5184 // automatically vet at compile time. Requiring that format strings
5185 // are string literals: (1) permits the checking of format strings by
5186 // the compiler and thereby (2) can practically remove the source of
5187 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00005188
Mike Stump11289f42009-09-09 15:08:12 +00005189 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00005190 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00005191 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00005192 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005193 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00005194 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00005195 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
5196 format_idx, firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00005197 /*IsFunctionCall*/ true, CheckedVarArgs,
5198 UncoveredArg,
5199 /*no string offset*/ llvm::APSInt(64, false) = 0);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005200
5201 // Generate a diagnostic where an uncovered argument is detected.
5202 if (UncoveredArg.hasUncoveredArg()) {
5203 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
5204 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
5205 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
5206 }
5207
Richard Smith55ce3522012-06-25 20:30:08 +00005208 if (CT != SLCT_NotALiteral)
5209 // Literal format string found, check done!
5210 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00005211
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00005212 // Strftime is particular as it always uses a single 'time' argument,
5213 // so it is safe to pass a non-literal string.
5214 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00005215 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00005216
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00005217 // Do not emit diag when the string param is a macro expansion and the
5218 // format is either NSString or CFString. This is a hack to prevent
5219 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
5220 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005221 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
5222 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00005223 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00005224
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005225 // If there are no arguments specified, warn with -Wformat-security, otherwise
5226 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005227 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00005228 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
5229 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005230 switch (Type) {
5231 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005232 break;
5233 case FST_Kprintf:
5234 case FST_FreeBSDKPrintf:
5235 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00005236 Diag(FormatLoc, diag::note_format_security_fixit)
5237 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005238 break;
5239 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00005240 Diag(FormatLoc, diag::note_format_security_fixit)
5241 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005242 break;
5243 }
5244 } else {
5245 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005246 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005247 }
Richard Smith55ce3522012-06-25 20:30:08 +00005248 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005249}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005250
Ted Kremenekab278de2010-01-28 23:39:18 +00005251namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005252
Ted Kremenek02087932010-07-16 02:11:22 +00005253class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
5254protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00005255 Sema &S;
Stephen Hines648c3692016-09-16 01:07:04 +00005256 const FormatStringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00005257 const Expr *OrigFormatExpr;
Mehdi Amini06d367c2016-10-24 20:39:34 +00005258 const Sema::FormatStringType FSType;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00005259 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00005260 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00005261 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00005262 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005263 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00005264 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00005265 llvm::SmallBitVector CoveredArgs;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005266 bool usesPositionalArgs = false;
5267 bool atFirstArg = true;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005268 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00005269 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00005270 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005271 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005272
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005273public:
Stephen Hines648c3692016-09-16 01:07:04 +00005274 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005275 const Expr *origFormatExpr,
5276 const Sema::FormatStringType type, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005277 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005278 ArrayRef<const Expr *> Args, unsigned formatIdx,
5279 bool inFunctionCall, Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005280 llvm::SmallBitVector &CheckedVarArgs,
5281 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005282 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
5283 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
5284 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
Mehdi Amini06d367c2016-10-24 20:39:34 +00005285 inFunctionCall(inFunctionCall), CallType(callType),
5286 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00005287 CoveredArgs.resize(numDataArgs);
5288 CoveredArgs.reset();
5289 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005290
Ted Kremenek019d2242010-01-29 01:50:07 +00005291 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005292
Ted Kremenek02087932010-07-16 02:11:22 +00005293 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005294 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005295
Jordan Rose92303592012-09-08 04:00:03 +00005296 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005297 const analyze_format_string::FormatSpecifier &FS,
5298 const analyze_format_string::ConversionSpecifier &CS,
5299 const char *startSpecifier, unsigned specifierLen,
5300 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00005301
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005302 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005303 const analyze_format_string::FormatSpecifier &FS,
5304 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005305
5306 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005307 const analyze_format_string::ConversionSpecifier &CS,
5308 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005309
Craig Toppere14c0f82014-03-12 04:55:44 +00005310 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005311
Craig Toppere14c0f82014-03-12 04:55:44 +00005312 void HandleInvalidPosition(const char *startSpecifier,
5313 unsigned specifierLen,
5314 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005315
Craig Toppere14c0f82014-03-12 04:55:44 +00005316 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005317
Craig Toppere14c0f82014-03-12 04:55:44 +00005318 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005319
Richard Trieu03cf7b72011-10-28 00:41:25 +00005320 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00005321 static void
5322 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
5323 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
5324 bool IsStringLocation, Range StringRange,
5325 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005326
Ted Kremenek02087932010-07-16 02:11:22 +00005327protected:
Ted Kremenekce815422010-07-19 21:25:57 +00005328 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
5329 const char *startSpec,
5330 unsigned specifierLen,
5331 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005332
5333 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
5334 const char *startSpec,
5335 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00005336
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005337 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00005338 CharSourceRange getSpecifierRange(const char *startSpecifier,
5339 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00005340 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005341
Ted Kremenek5739de72010-01-29 01:06:55 +00005342 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005343
5344 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
5345 const analyze_format_string::ConversionSpecifier &CS,
5346 const char *startSpecifier, unsigned specifierLen,
5347 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005348
5349 template <typename Range>
5350 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5351 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00005352 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00005353};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005354
5355} // namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00005356
Ted Kremenek02087932010-07-16 02:11:22 +00005357SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00005358 return OrigFormatExpr->getSourceRange();
5359}
5360
Ted Kremenek02087932010-07-16 02:11:22 +00005361CharSourceRange CheckFormatHandler::
5362getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00005363 SourceLocation Start = getLocationOfByte(startSpecifier);
5364 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
5365
5366 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00005367 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00005368
5369 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005370}
5371
Ted Kremenek02087932010-07-16 02:11:22 +00005372SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines648c3692016-09-16 01:07:04 +00005373 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
5374 S.getLangOpts(), S.Context.getTargetInfo());
Ted Kremenekab278de2010-01-28 23:39:18 +00005375}
5376
Ted Kremenek02087932010-07-16 02:11:22 +00005377void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
5378 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00005379 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
5380 getLocationOfByte(startSpecifier),
5381 /*IsStringLocation*/true,
5382 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00005383}
5384
Jordan Rose92303592012-09-08 04:00:03 +00005385void CheckFormatHandler::HandleInvalidLengthModifier(
5386 const analyze_format_string::FormatSpecifier &FS,
5387 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00005388 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00005389 using namespace analyze_format_string;
5390
5391 const LengthModifier &LM = FS.getLengthModifier();
5392 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5393
5394 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005395 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00005396 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005397 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005398 getLocationOfByte(LM.getStart()),
5399 /*IsStringLocation*/true,
5400 getSpecifierRange(startSpecifier, specifierLen));
5401
5402 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5403 << FixedLM->toString()
5404 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5405
5406 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005407 FixItHint Hint;
5408 if (DiagID == diag::warn_format_nonsensical_length)
5409 Hint = FixItHint::CreateRemoval(LMRange);
5410
5411 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005412 getLocationOfByte(LM.getStart()),
5413 /*IsStringLocation*/true,
5414 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00005415 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00005416 }
5417}
5418
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005419void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00005420 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005421 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005422 using namespace analyze_format_string;
5423
5424 const LengthModifier &LM = FS.getLengthModifier();
5425 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5426
5427 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005428 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00005429 if (FixedLM) {
5430 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5431 << LM.toString() << 0,
5432 getLocationOfByte(LM.getStart()),
5433 /*IsStringLocation*/true,
5434 getSpecifierRange(startSpecifier, specifierLen));
5435
5436 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5437 << FixedLM->toString()
5438 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5439
5440 } else {
5441 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5442 << LM.toString() << 0,
5443 getLocationOfByte(LM.getStart()),
5444 /*IsStringLocation*/true,
5445 getSpecifierRange(startSpecifier, specifierLen));
5446 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005447}
5448
5449void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5450 const analyze_format_string::ConversionSpecifier &CS,
5451 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00005452 using namespace analyze_format_string;
5453
5454 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00005455 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00005456 if (FixedCS) {
5457 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5458 << CS.toString() << /*conversion specifier*/1,
5459 getLocationOfByte(CS.getStart()),
5460 /*IsStringLocation*/true,
5461 getSpecifierRange(startSpecifier, specifierLen));
5462
5463 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5464 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5465 << FixedCS->toString()
5466 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5467 } else {
5468 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5469 << CS.toString() << /*conversion specifier*/1,
5470 getLocationOfByte(CS.getStart()),
5471 /*IsStringLocation*/true,
5472 getSpecifierRange(startSpecifier, specifierLen));
5473 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005474}
5475
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005476void CheckFormatHandler::HandlePosition(const char *startPos,
5477 unsigned posLen) {
5478 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5479 getLocationOfByte(startPos),
5480 /*IsStringLocation*/true,
5481 getSpecifierRange(startPos, posLen));
5482}
5483
Ted Kremenekd1668192010-02-27 01:41:03 +00005484void
Ted Kremenek02087932010-07-16 02:11:22 +00005485CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5486 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005487 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5488 << (unsigned) p,
5489 getLocationOfByte(startPos), /*IsStringLocation*/true,
5490 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005491}
5492
Ted Kremenek02087932010-07-16 02:11:22 +00005493void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00005494 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005495 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5496 getLocationOfByte(startPos),
5497 /*IsStringLocation*/true,
5498 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005499}
5500
Ted Kremenek02087932010-07-16 02:11:22 +00005501void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005502 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005503 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005504 EmitFormatDiagnostic(
5505 S.PDiag(diag::warn_printf_format_string_contains_null_char),
5506 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5507 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005508 }
Ted Kremenek02087932010-07-16 02:11:22 +00005509}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005510
Jordan Rose58bbe422012-07-19 18:10:08 +00005511// Note that this may return NULL if there was an error parsing or building
5512// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00005513const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005514 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00005515}
5516
5517void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005518 // Does the number of data arguments exceed the number of
5519 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00005520 if (!HasVAListArg) {
5521 // Find any arguments that weren't covered.
5522 CoveredArgs.flip();
5523 signed notCoveredArg = CoveredArgs.find_first();
5524 if (notCoveredArg >= 0) {
5525 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005526 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5527 } else {
5528 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00005529 }
5530 }
5531}
5532
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005533void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5534 const Expr *ArgExpr) {
5535 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5536 "Invalid state");
5537
5538 if (!ArgExpr)
5539 return;
5540
5541 SourceLocation Loc = ArgExpr->getLocStart();
5542
5543 if (S.getSourceManager().isInSystemMacro(Loc))
5544 return;
5545
5546 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5547 for (auto E : DiagnosticExprs)
5548 PDiag << E->getSourceRange();
5549
5550 CheckFormatHandler::EmitFormatDiagnostic(
5551 S, IsFunctionCall, DiagnosticExprs[0],
5552 PDiag, Loc, /*IsStringLocation*/false,
5553 DiagnosticExprs[0]->getSourceRange());
5554}
5555
Ted Kremenekce815422010-07-19 21:25:57 +00005556bool
5557CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5558 SourceLocation Loc,
5559 const char *startSpec,
5560 unsigned specifierLen,
5561 const char *csStart,
5562 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00005563 bool keepGoing = true;
5564 if (argIndex < NumDataArgs) {
5565 // Consider the argument coverered, even though the specifier doesn't
5566 // make sense.
5567 CoveredArgs.set(argIndex);
5568 }
5569 else {
5570 // If argIndex exceeds the number of data arguments we
5571 // don't issue a warning because that is just a cascade of warnings (and
5572 // they may have intended '%%' anyway). We don't want to continue processing
5573 // the format string after this point, however, as we will like just get
5574 // gibberish when trying to match arguments.
5575 keepGoing = false;
5576 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005577
5578 StringRef Specifier(csStart, csLen);
5579
5580 // If the specifier in non-printable, it could be the first byte of a UTF-8
5581 // sequence. In that case, print the UTF-8 code point. If not, print the byte
5582 // hex value.
5583 std::string CodePointStr;
5584 if (!llvm::sys::locale::isPrint(*csStart)) {
Justin Lebar90910552016-09-30 00:38:45 +00005585 llvm::UTF32 CodePoint;
5586 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5587 const llvm::UTF8 *E =
5588 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5589 llvm::ConversionResult Result =
5590 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005591
Justin Lebar90910552016-09-30 00:38:45 +00005592 if (Result != llvm::conversionOK) {
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005593 unsigned char FirstChar = *csStart;
Justin Lebar90910552016-09-30 00:38:45 +00005594 CodePoint = (llvm::UTF32)FirstChar;
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005595 }
5596
5597 llvm::raw_string_ostream OS(CodePointStr);
5598 if (CodePoint < 256)
5599 OS << "\\x" << llvm::format("%02x", CodePoint);
5600 else if (CodePoint <= 0xFFFF)
5601 OS << "\\u" << llvm::format("%04x", CodePoint);
5602 else
5603 OS << "\\U" << llvm::format("%08x", CodePoint);
5604 OS.flush();
5605 Specifier = CodePointStr;
5606 }
5607
5608 EmitFormatDiagnostic(
5609 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5610 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5611
Ted Kremenekce815422010-07-19 21:25:57 +00005612 return keepGoing;
5613}
5614
Richard Trieu03cf7b72011-10-28 00:41:25 +00005615void
5616CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5617 const char *startSpec,
5618 unsigned specifierLen) {
5619 EmitFormatDiagnostic(
5620 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5621 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5622}
5623
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005624bool
5625CheckFormatHandler::CheckNumArgs(
5626 const analyze_format_string::FormatSpecifier &FS,
5627 const analyze_format_string::ConversionSpecifier &CS,
5628 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5629
5630 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005631 PartialDiagnostic PDiag = FS.usesPositionalArg()
5632 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5633 << (argIndex+1) << NumDataArgs)
5634 : S.PDiag(diag::warn_printf_insufficient_data_args);
5635 EmitFormatDiagnostic(
5636 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5637 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005638
5639 // Since more arguments than conversion tokens are given, by extension
5640 // all arguments are covered, so mark this as so.
5641 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005642 return false;
5643 }
5644 return true;
5645}
5646
Richard Trieu03cf7b72011-10-28 00:41:25 +00005647template<typename Range>
5648void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5649 SourceLocation Loc,
5650 bool IsStringLocation,
5651 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00005652 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005653 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00005654 Loc, IsStringLocation, StringRange, FixIt);
5655}
5656
5657/// \brief If the format string is not within the funcion call, emit a note
5658/// so that the function call and string are in diagnostic messages.
5659///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005660/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00005661/// call and only one diagnostic message will be produced. Otherwise, an
5662/// extra note will be emitted pointing to location of the format string.
5663///
5664/// \param ArgumentExpr the expression that is passed as the format string
5665/// argument in the function call. Used for getting locations when two
5666/// diagnostics are emitted.
5667///
5668/// \param PDiag the callee should already have provided any strings for the
5669/// diagnostic message. This function only adds locations and fixits
5670/// to diagnostics.
5671///
5672/// \param Loc primary location for diagnostic. If two diagnostics are
5673/// required, one will be at Loc and a new SourceLocation will be created for
5674/// the other one.
5675///
5676/// \param IsStringLocation if true, Loc points to the format string should be
5677/// used for the note. Otherwise, Loc points to the argument list and will
5678/// be used with PDiag.
5679///
5680/// \param StringRange some or all of the string to highlight. This is
5681/// templated so it can accept either a CharSourceRange or a SourceRange.
5682///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005683/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00005684template <typename Range>
5685void CheckFormatHandler::EmitFormatDiagnostic(
5686 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5687 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5688 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00005689 if (InFunctionCall) {
5690 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5691 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005692 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00005693 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005694 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5695 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00005696
5697 const Sema::SemaDiagnosticBuilder &Note =
5698 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5699 diag::note_format_string_defined);
5700
5701 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005702 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005703 }
5704}
5705
Ted Kremenek02087932010-07-16 02:11:22 +00005706//===--- CHECK: Printf format string checking ------------------------------===//
5707
5708namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005709
Ted Kremenek02087932010-07-16 02:11:22 +00005710class CheckPrintfHandler : public CheckFormatHandler {
5711public:
Stephen Hines648c3692016-09-16 01:07:04 +00005712 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005713 const Expr *origFormatExpr,
5714 const Sema::FormatStringType type, unsigned firstDataArg,
5715 unsigned numDataArgs, bool isObjC, const char *beg,
5716 bool hasVAListArg, ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005717 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00005718 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005719 llvm::SmallBitVector &CheckedVarArgs,
5720 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005721 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5722 numDataArgs, beg, hasVAListArg, Args, formatIdx,
5723 inFunctionCall, CallType, CheckedVarArgs,
5724 UncoveredArg) {}
5725
5726 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5727
5728 /// Returns true if '%@' specifiers are allowed in the format string.
5729 bool allowsObjCArg() const {
5730 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5731 FSType == Sema::FST_OSTrace;
5732 }
Jordan Rose3e0ec582012-07-19 18:10:23 +00005733
Ted Kremenek02087932010-07-16 02:11:22 +00005734 bool HandleInvalidPrintfConversionSpecifier(
5735 const analyze_printf::PrintfSpecifier &FS,
5736 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005737 unsigned specifierLen) override;
5738
Ted Kremenek02087932010-07-16 02:11:22 +00005739 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5740 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005741 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005742 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5743 const char *StartSpecifier,
5744 unsigned SpecifierLen,
5745 const Expr *E);
5746
Ted Kremenek02087932010-07-16 02:11:22 +00005747 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5748 const char *startSpecifier, unsigned specifierLen);
5749 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5750 const analyze_printf::OptionalAmount &Amt,
5751 unsigned type,
5752 const char *startSpecifier, unsigned specifierLen);
5753 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5754 const analyze_printf::OptionalFlag &flag,
5755 const char *startSpecifier, unsigned specifierLen);
5756 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5757 const analyze_printf::OptionalFlag &ignoredFlag,
5758 const analyze_printf::OptionalFlag &flag,
5759 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005760 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00005761 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00005762
5763 void HandleEmptyObjCModifierFlag(const char *startFlag,
5764 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005765
Ted Kremenek2b417712015-07-02 05:39:16 +00005766 void HandleInvalidObjCModifierFlag(const char *startFlag,
5767 unsigned flagLen) override;
5768
5769 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5770 const char *flagsEnd,
5771 const char *conversionPosition)
5772 override;
5773};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005774
5775} // namespace
Ted Kremenek02087932010-07-16 02:11:22 +00005776
5777bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5778 const analyze_printf::PrintfSpecifier &FS,
5779 const char *startSpecifier,
5780 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005781 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00005782 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00005783
Ted Kremenekce815422010-07-19 21:25:57 +00005784 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5785 getLocationOfByte(CS.getStart()),
5786 startSpecifier, specifierLen,
5787 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00005788}
5789
Ted Kremenek02087932010-07-16 02:11:22 +00005790bool CheckPrintfHandler::HandleAmount(
5791 const analyze_format_string::OptionalAmount &Amt,
5792 unsigned k, const char *startSpecifier,
5793 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005794 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005795 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00005796 unsigned argIndex = Amt.getArgIndex();
5797 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005798 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5799 << k,
5800 getLocationOfByte(Amt.getStart()),
5801 /*IsStringLocation*/true,
5802 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005803 // Don't do any more checking. We will just emit
5804 // spurious errors.
5805 return false;
5806 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005807
Ted Kremenek5739de72010-01-29 01:06:55 +00005808 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00005809 // Although not in conformance with C99, we also allow the argument to be
5810 // an 'unsigned int' as that is a reasonably safe case. GCC also
5811 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00005812 CoveredArgs.set(argIndex);
5813 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00005814 if (!Arg)
5815 return false;
5816
Ted Kremenek5739de72010-01-29 01:06:55 +00005817 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005818
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005819 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5820 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005821
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005822 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005823 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005824 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00005825 << T << Arg->getSourceRange(),
5826 getLocationOfByte(Amt.getStart()),
5827 /*IsStringLocation*/true,
5828 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005829 // Don't do any more checking. We will just emit
5830 // spurious errors.
5831 return false;
5832 }
5833 }
5834 }
5835 return true;
5836}
Ted Kremenek5739de72010-01-29 01:06:55 +00005837
Tom Careb49ec692010-06-17 19:00:27 +00005838void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00005839 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005840 const analyze_printf::OptionalAmount &Amt,
5841 unsigned type,
5842 const char *startSpecifier,
5843 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005844 const analyze_printf::PrintfConversionSpecifier &CS =
5845 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00005846
Richard Trieu03cf7b72011-10-28 00:41:25 +00005847 FixItHint fixit =
5848 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5849 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5850 Amt.getConstantLength()))
5851 : FixItHint();
5852
5853 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5854 << type << CS.toString(),
5855 getLocationOfByte(Amt.getStart()),
5856 /*IsStringLocation*/true,
5857 getSpecifierRange(startSpecifier, specifierLen),
5858 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00005859}
5860
Ted Kremenek02087932010-07-16 02:11:22 +00005861void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005862 const analyze_printf::OptionalFlag &flag,
5863 const char *startSpecifier,
5864 unsigned specifierLen) {
5865 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005866 const analyze_printf::PrintfConversionSpecifier &CS =
5867 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00005868 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5869 << flag.toString() << CS.toString(),
5870 getLocationOfByte(flag.getPosition()),
5871 /*IsStringLocation*/true,
5872 getSpecifierRange(startSpecifier, specifierLen),
5873 FixItHint::CreateRemoval(
5874 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005875}
5876
5877void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00005878 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005879 const analyze_printf::OptionalFlag &ignoredFlag,
5880 const analyze_printf::OptionalFlag &flag,
5881 const char *startSpecifier,
5882 unsigned specifierLen) {
5883 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005884 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5885 << ignoredFlag.toString() << flag.toString(),
5886 getLocationOfByte(ignoredFlag.getPosition()),
5887 /*IsStringLocation*/true,
5888 getSpecifierRange(startSpecifier, specifierLen),
5889 FixItHint::CreateRemoval(
5890 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005891}
5892
Ted Kremenek2b417712015-07-02 05:39:16 +00005893void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5894 unsigned flagLen) {
5895 // Warn about an empty flag.
5896 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5897 getLocationOfByte(startFlag),
5898 /*IsStringLocation*/true,
5899 getSpecifierRange(startFlag, flagLen));
5900}
5901
5902void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5903 unsigned flagLen) {
5904 // Warn about an invalid flag.
5905 auto Range = getSpecifierRange(startFlag, flagLen);
5906 StringRef flag(startFlag, flagLen);
5907 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5908 getLocationOfByte(startFlag),
5909 /*IsStringLocation*/true,
5910 Range, FixItHint::CreateRemoval(Range));
5911}
5912
5913void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5914 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5915 // Warn about using '[...]' without a '@' conversion.
5916 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5917 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5918 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5919 getLocationOfByte(conversionPosition),
5920 /*IsStringLocation*/true,
5921 Range, FixItHint::CreateRemoval(Range));
5922}
5923
Richard Smith55ce3522012-06-25 20:30:08 +00005924// Determines if the specified is a C++ class or struct containing
5925// a member with the specified name and kind (e.g. a CXXMethodDecl named
5926// "c_str()").
5927template<typename MemberKind>
5928static llvm::SmallPtrSet<MemberKind*, 1>
5929CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5930 const RecordType *RT = Ty->getAs<RecordType>();
5931 llvm::SmallPtrSet<MemberKind*, 1> Results;
5932
5933 if (!RT)
5934 return Results;
5935 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00005936 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00005937 return Results;
5938
Alp Tokerb6cc5922014-05-03 03:45:55 +00005939 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00005940 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00005941 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00005942
5943 // We just need to include all members of the right kind turned up by the
5944 // filter, at this point.
5945 if (S.LookupQualifiedName(R, RT->getDecl()))
5946 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5947 NamedDecl *decl = (*I)->getUnderlyingDecl();
5948 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5949 Results.insert(FK);
5950 }
5951 return Results;
5952}
5953
Richard Smith2868a732014-02-28 01:36:39 +00005954/// Check if we could call '.c_str()' on an object.
5955///
5956/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5957/// allow the call, or if it would be ambiguous).
5958bool Sema::hasCStrMethod(const Expr *E) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005959 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
5960
Richard Smith2868a732014-02-28 01:36:39 +00005961 MethodSet Results =
5962 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5963 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5964 MI != ME; ++MI)
5965 if ((*MI)->getMinRequiredArguments() == 0)
5966 return true;
5967 return false;
5968}
5969
Richard Smith55ce3522012-06-25 20:30:08 +00005970// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005971// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00005972// Returns true when a c_str() conversion method is found.
5973bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00005974 const analyze_printf::ArgType &AT, const Expr *E) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005975 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
Richard Smith55ce3522012-06-25 20:30:08 +00005976
5977 MethodSet Results =
5978 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5979
5980 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5981 MI != ME; ++MI) {
5982 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00005983 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00005984 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00005985 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00005986 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00005987 S.Diag(E->getLocStart(), diag::note_printf_c_str)
5988 << "c_str()"
5989 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5990 return true;
5991 }
5992 }
5993
5994 return false;
5995}
5996
Ted Kremenekab278de2010-01-28 23:39:18 +00005997bool
Ted Kremenek02087932010-07-16 02:11:22 +00005998CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00005999 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00006000 const char *startSpecifier,
6001 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006002 using namespace analyze_format_string;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006003 using namespace analyze_printf;
6004
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006005 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00006006
Ted Kremenek6cd69422010-07-19 22:01:06 +00006007 if (FS.consumesDataArgument()) {
6008 if (atFirstArg) {
6009 atFirstArg = false;
6010 usesPositionalArgs = FS.usesPositionalArg();
6011 }
6012 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006013 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6014 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00006015 return false;
6016 }
Ted Kremenek5739de72010-01-29 01:06:55 +00006017 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006018
Ted Kremenekd1668192010-02-27 01:41:03 +00006019 // First check if the field width, precision, and conversion specifier
6020 // have matching data arguments.
6021 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
6022 startSpecifier, specifierLen)) {
6023 return false;
6024 }
6025
6026 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
6027 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00006028 return false;
6029 }
6030
Ted Kremenek8d9842d2010-01-29 20:55:36 +00006031 if (!CS.consumesDataArgument()) {
6032 // FIXME: Technically specifying a precision or field width here
6033 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00006034 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00006035 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006036
Ted Kremenek4a49d982010-02-26 19:18:41 +00006037 // Consume the argument.
6038 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00006039 if (argIndex < NumDataArgs) {
6040 // The check to see if the argIndex is valid will come later.
6041 // We set the bit here because we may exit early from this
6042 // function if we encounter some other error.
6043 CoveredArgs.set(argIndex);
6044 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00006045
Dimitry Andric6b5ed342015-02-19 22:32:33 +00006046 // FreeBSD kernel extensions.
6047 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
6048 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
6049 // We need at least two arguments.
6050 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
6051 return false;
6052
6053 // Claim the second argument.
6054 CoveredArgs.set(argIndex + 1);
6055
6056 // Type check the first argument (int for %b, pointer for %D)
6057 const Expr *Ex = getDataArg(argIndex);
6058 const analyze_printf::ArgType &AT =
6059 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
6060 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
6061 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
6062 EmitFormatDiagnostic(
6063 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6064 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
6065 << false << Ex->getSourceRange(),
6066 Ex->getLocStart(), /*IsStringLocation*/false,
6067 getSpecifierRange(startSpecifier, specifierLen));
6068
6069 // Type check the second argument (char * for both %b and %D)
6070 Ex = getDataArg(argIndex + 1);
6071 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
6072 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
6073 EmitFormatDiagnostic(
6074 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6075 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
6076 << false << Ex->getSourceRange(),
6077 Ex->getLocStart(), /*IsStringLocation*/false,
6078 getSpecifierRange(startSpecifier, specifierLen));
6079
6080 return true;
6081 }
6082
Ted Kremenek4a49d982010-02-26 19:18:41 +00006083 // Check for using an Objective-C specific conversion specifier
6084 // in a non-ObjC literal.
Mehdi Amini06d367c2016-10-24 20:39:34 +00006085 if (!allowsObjCArg() && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00006086 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6087 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00006088 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006089
Mehdi Amini06d367c2016-10-24 20:39:34 +00006090 // %P can only be used with os_log.
6091 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
6092 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6093 specifierLen);
6094 }
6095
6096 // %n is not allowed with os_log.
6097 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
6098 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
6099 getLocationOfByte(CS.getStart()),
6100 /*IsStringLocation*/ false,
6101 getSpecifierRange(startSpecifier, specifierLen));
6102
6103 return true;
6104 }
6105
6106 // Only scalars are allowed for os_trace.
6107 if (FSType == Sema::FST_OSTrace &&
6108 (CS.getKind() == ConversionSpecifier::PArg ||
6109 CS.getKind() == ConversionSpecifier::sArg ||
6110 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
6111 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6112 specifierLen);
6113 }
6114
6115 // Check for use of public/private annotation outside of os_log().
6116 if (FSType != Sema::FST_OSLog) {
6117 if (FS.isPublic().isSet()) {
6118 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6119 << "public",
6120 getLocationOfByte(FS.isPublic().getPosition()),
6121 /*IsStringLocation*/ false,
6122 getSpecifierRange(startSpecifier, specifierLen));
6123 }
6124 if (FS.isPrivate().isSet()) {
6125 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6126 << "private",
6127 getLocationOfByte(FS.isPrivate().getPosition()),
6128 /*IsStringLocation*/ false,
6129 getSpecifierRange(startSpecifier, specifierLen));
6130 }
6131 }
6132
Tom Careb49ec692010-06-17 19:00:27 +00006133 // Check for invalid use of field width
6134 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00006135 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00006136 startSpecifier, specifierLen);
6137 }
6138
6139 // Check for invalid use of precision
6140 if (!FS.hasValidPrecision()) {
6141 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
6142 startSpecifier, specifierLen);
6143 }
6144
Mehdi Amini06d367c2016-10-24 20:39:34 +00006145 // Precision is mandatory for %P specifier.
6146 if (CS.getKind() == ConversionSpecifier::PArg &&
6147 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
6148 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
6149 getLocationOfByte(startSpecifier),
6150 /*IsStringLocation*/ false,
6151 getSpecifierRange(startSpecifier, specifierLen));
6152 }
6153
Tom Careb49ec692010-06-17 19:00:27 +00006154 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00006155 if (!FS.hasValidThousandsGroupingPrefix())
6156 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006157 if (!FS.hasValidLeadingZeros())
6158 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
6159 if (!FS.hasValidPlusPrefix())
6160 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00006161 if (!FS.hasValidSpacePrefix())
6162 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006163 if (!FS.hasValidAlternativeForm())
6164 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
6165 if (!FS.hasValidLeftJustified())
6166 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
6167
6168 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00006169 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
6170 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
6171 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006172 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
6173 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
6174 startSpecifier, specifierLen);
6175
6176 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006177 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006178 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6179 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006180 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006181 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006182 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006183 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6184 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00006185
Jordan Rose92303592012-09-08 04:00:03 +00006186 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6187 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6188
Ted Kremenek9fcd8302010-01-29 01:43:31 +00006189 // The remaining checks depend on the data arguments.
6190 if (HasVAListArg)
6191 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006192
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006193 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00006194 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006195
Jordan Rose58bbe422012-07-19 18:10:08 +00006196 const Expr *Arg = getDataArg(argIndex);
6197 if (!Arg)
6198 return true;
6199
6200 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00006201}
6202
Jordan Roseaee34382012-09-05 22:56:26 +00006203static bool requiresParensToAddCast(const Expr *E) {
6204 // FIXME: We should have a general way to reason about operator
6205 // precedence and whether parens are actually needed here.
6206 // Take care of a few common cases where they aren't.
6207 const Expr *Inside = E->IgnoreImpCasts();
6208 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
6209 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
6210
6211 switch (Inside->getStmtClass()) {
6212 case Stmt::ArraySubscriptExprClass:
6213 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006214 case Stmt::CharacterLiteralClass:
6215 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006216 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006217 case Stmt::FloatingLiteralClass:
6218 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006219 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006220 case Stmt::ObjCArrayLiteralClass:
6221 case Stmt::ObjCBoolLiteralExprClass:
6222 case Stmt::ObjCBoxedExprClass:
6223 case Stmt::ObjCDictionaryLiteralClass:
6224 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006225 case Stmt::ObjCIvarRefExprClass:
6226 case Stmt::ObjCMessageExprClass:
6227 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006228 case Stmt::ObjCStringLiteralClass:
6229 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006230 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006231 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006232 case Stmt::UnaryOperatorClass:
6233 return false;
6234 default:
6235 return true;
6236 }
6237}
6238
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006239static std::pair<QualType, StringRef>
6240shouldNotPrintDirectly(const ASTContext &Context,
6241 QualType IntendedTy,
6242 const Expr *E) {
6243 // Use a 'while' to peel off layers of typedefs.
6244 QualType TyTy = IntendedTy;
6245 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
6246 StringRef Name = UserTy->getDecl()->getName();
6247 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Saleem Abdulrasoola01ed932017-10-17 17:39:32 +00006248 .Case("CFIndex", Context.getNSIntegerType())
6249 .Case("NSInteger", Context.getNSIntegerType())
6250 .Case("NSUInteger", Context.getNSUIntegerType())
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006251 .Case("SInt32", Context.IntTy)
6252 .Case("UInt32", Context.UnsignedIntTy)
6253 .Default(QualType());
6254
6255 if (!CastTy.isNull())
6256 return std::make_pair(CastTy, Name);
6257
6258 TyTy = UserTy->desugar();
6259 }
6260
6261 // Strip parens if necessary.
6262 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
6263 return shouldNotPrintDirectly(Context,
6264 PE->getSubExpr()->getType(),
6265 PE->getSubExpr());
6266
6267 // If this is a conditional expression, then its result type is constructed
6268 // via usual arithmetic conversions and thus there might be no necessary
6269 // typedef sugar there. Recurse to operands to check for NSInteger &
6270 // Co. usage condition.
6271 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6272 QualType TrueTy, FalseTy;
6273 StringRef TrueName, FalseName;
6274
6275 std::tie(TrueTy, TrueName) =
6276 shouldNotPrintDirectly(Context,
6277 CO->getTrueExpr()->getType(),
6278 CO->getTrueExpr());
6279 std::tie(FalseTy, FalseName) =
6280 shouldNotPrintDirectly(Context,
6281 CO->getFalseExpr()->getType(),
6282 CO->getFalseExpr());
6283
6284 if (TrueTy == FalseTy)
6285 return std::make_pair(TrueTy, TrueName);
6286 else if (TrueTy.isNull())
6287 return std::make_pair(FalseTy, FalseName);
6288 else if (FalseTy.isNull())
6289 return std::make_pair(TrueTy, TrueName);
6290 }
6291
6292 return std::make_pair(QualType(), StringRef());
6293}
6294
Richard Smith55ce3522012-06-25 20:30:08 +00006295bool
6296CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6297 const char *StartSpecifier,
6298 unsigned SpecifierLen,
6299 const Expr *E) {
6300 using namespace analyze_format_string;
6301 using namespace analyze_printf;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006302
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006303 // Now type check the data expression that matches the
6304 // format specifier.
Mehdi Amini06d367c2016-10-24 20:39:34 +00006305 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
Jordan Rose22b74712012-09-05 22:56:19 +00006306 if (!AT.isValid())
6307 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00006308
Jordan Rose598ec092012-12-05 18:44:40 +00006309 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00006310 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
6311 ExprTy = TET->getUnderlyingExpr()->getType();
6312 }
6313
Seth Cantrellb4802962015-03-04 03:12:10 +00006314 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
6315
6316 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00006317 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006318 }
Jordan Rose98709982012-06-04 22:48:57 +00006319
Jordan Rose22b74712012-09-05 22:56:19 +00006320 // Look through argument promotions for our error message's reported type.
6321 // This includes the integral and floating promotions, but excludes array
6322 // and function pointer decay; seeing that an argument intended to be a
6323 // string has type 'char [6]' is probably more confusing than 'char *'.
6324 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6325 if (ICE->getCastKind() == CK_IntegralCast ||
6326 ICE->getCastKind() == CK_FloatingCast) {
6327 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00006328 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00006329
6330 // Check if we didn't match because of an implicit cast from a 'char'
6331 // or 'short' to an 'int'. This is done because printf is a varargs
6332 // function.
6333 if (ICE->getType() == S.Context.IntTy ||
6334 ICE->getType() == S.Context.UnsignedIntTy) {
6335 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00006336 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00006337 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00006338 }
Jordan Rose98709982012-06-04 22:48:57 +00006339 }
Jordan Rose598ec092012-12-05 18:44:40 +00006340 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
6341 // Special case for 'a', which has type 'int' in C.
6342 // Note, however, that we do /not/ want to treat multibyte constants like
6343 // 'MooV' as characters! This form is deprecated but still exists.
6344 if (ExprTy == S.Context.IntTy)
6345 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6346 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00006347 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006348
Jordan Rosebc53ed12014-05-31 04:12:14 +00006349 // Look through enums to their underlying type.
6350 bool IsEnum = false;
6351 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
6352 ExprTy = EnumTy->getDecl()->getIntegerType();
6353 IsEnum = true;
6354 }
6355
Jordan Rose0e5badd2012-12-05 18:44:49 +00006356 // %C in an Objective-C context prints a unichar, not a wchar_t.
6357 // If the argument is an integer of some kind, believe the %C and suggest
6358 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00006359 QualType IntendedTy = ExprTy;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006360 if (isObjCContext() &&
Jordan Rose0e5badd2012-12-05 18:44:49 +00006361 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
6362 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6363 !ExprTy->isCharType()) {
6364 // 'unichar' is defined as a typedef of unsigned short, but we should
6365 // prefer using the typedef if it is visible.
6366 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00006367
6368 // While we are here, check if the value is an IntegerLiteral that happens
6369 // to be within the valid range.
6370 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
6371 const llvm::APInt &V = IL->getValue();
6372 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6373 return true;
6374 }
6375
Jordan Rose0e5badd2012-12-05 18:44:49 +00006376 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
6377 Sema::LookupOrdinaryName);
6378 if (S.LookupName(Result, S.getCurScope())) {
6379 NamedDecl *ND = Result.getFoundDecl();
6380 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
6381 if (TD->getUnderlyingType() == IntendedTy)
6382 IntendedTy = S.Context.getTypedefType(TD);
6383 }
6384 }
6385 }
6386
6387 // Special-case some of Darwin's platform-independence types by suggesting
6388 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006389 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00006390 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006391 QualType CastTy;
6392 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
6393 if (!CastTy.isNull()) {
6394 IntendedTy = CastTy;
6395 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00006396 }
6397 }
6398
Jordan Rose22b74712012-09-05 22:56:19 +00006399 // We may be able to offer a FixItHint if it is a supported type.
6400 PrintfSpecifier fixedFS = FS;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006401 bool success =
6402 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006403
Jordan Rose22b74712012-09-05 22:56:19 +00006404 if (success) {
6405 // Get the fix string from the fixed format specifier
6406 SmallString<16> buf;
6407 llvm::raw_svector_ostream os(buf);
6408 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006409
Jordan Roseaee34382012-09-05 22:56:26 +00006410 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6411
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006412 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00006413 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6414 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6415 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6416 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00006417 // In this case, the specifier is wrong and should be changed to match
6418 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00006419 EmitFormatDiagnostic(S.PDiag(diag)
6420 << AT.getRepresentativeTypeName(S.Context)
6421 << IntendedTy << IsEnum << E->getSourceRange(),
6422 E->getLocStart(),
6423 /*IsStringLocation*/ false, SpecRange,
6424 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00006425 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00006426 // The canonical type for formatting this value is different from the
6427 // actual type of the expression. (This occurs, for example, with Darwin's
6428 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6429 // should be printed as 'long' for 64-bit compatibility.)
6430 // Rather than emitting a normal format/argument mismatch, we want to
6431 // add a cast to the recommended type (and correct the format string
6432 // if necessary).
6433 SmallString<16> CastBuf;
6434 llvm::raw_svector_ostream CastFix(CastBuf);
6435 CastFix << "(";
6436 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6437 CastFix << ")";
6438
6439 SmallVector<FixItHint,4> Hints;
Alexander Shaposhnikov1788a9b2017-09-22 18:36:06 +00006440 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
Jordan Roseaee34382012-09-05 22:56:26 +00006441 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6442
6443 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6444 // If there's already a cast present, just replace it.
6445 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6446 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6447
6448 } else if (!requiresParensToAddCast(E)) {
6449 // If the expression has high enough precedence,
6450 // just write the C-style cast.
6451 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6452 CastFix.str()));
6453 } else {
6454 // Otherwise, add parens around the expression as well as the cast.
6455 CastFix << "(";
6456 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6457 CastFix.str()));
6458
Alp Tokerb6cc5922014-05-03 03:45:55 +00006459 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00006460 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6461 }
6462
Jordan Rose0e5badd2012-12-05 18:44:49 +00006463 if (ShouldNotPrintDirectly) {
6464 // The expression has a type that should not be printed directly.
6465 // We extract the name from the typedef because we don't want to show
6466 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006467 StringRef Name;
6468 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6469 Name = TypedefTy->getDecl()->getName();
6470 else
6471 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00006472 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00006473 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006474 << E->getSourceRange(),
6475 E->getLocStart(), /*IsStringLocation=*/false,
6476 SpecRange, Hints);
6477 } else {
6478 // In this case, the expression could be printed using a different
6479 // specifier, but we've decided that the specifier is probably correct
6480 // and we should cast instead. Just use the normal warning message.
6481 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00006482 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6483 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006484 << E->getSourceRange(),
6485 E->getLocStart(), /*IsStringLocation*/false,
6486 SpecRange, Hints);
6487 }
Jordan Roseaee34382012-09-05 22:56:26 +00006488 }
Jordan Rose22b74712012-09-05 22:56:19 +00006489 } else {
6490 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6491 SpecifierLen);
6492 // Since the warning for passing non-POD types to variadic functions
6493 // was deferred until now, we emit a warning for non-POD
6494 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00006495 switch (S.isValidVarArgType(ExprTy)) {
6496 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00006497 case Sema::VAK_ValidInCXX11: {
6498 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6499 if (match == analyze_printf::ArgType::NoMatchPedantic) {
6500 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6501 }
Richard Smithd7293d72013-08-05 18:49:43 +00006502
Seth Cantrellb4802962015-03-04 03:12:10 +00006503 EmitFormatDiagnostic(
6504 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6505 << IsEnum << CSR << E->getSourceRange(),
6506 E->getLocStart(), /*IsStringLocation*/ false, CSR);
6507 break;
6508 }
Richard Smithd7293d72013-08-05 18:49:43 +00006509 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00006510 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00006511 EmitFormatDiagnostic(
6512 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006513 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00006514 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00006515 << CallType
6516 << AT.getRepresentativeTypeName(S.Context)
6517 << CSR
6518 << E->getSourceRange(),
6519 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00006520 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00006521 break;
6522
6523 case Sema::VAK_Invalid:
6524 if (ExprTy->isObjCObjectType())
6525 EmitFormatDiagnostic(
6526 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6527 << S.getLangOpts().CPlusPlus11
6528 << ExprTy
6529 << CallType
6530 << AT.getRepresentativeTypeName(S.Context)
6531 << CSR
6532 << E->getSourceRange(),
6533 E->getLocStart(), /*IsStringLocation*/false, CSR);
6534 else
6535 // FIXME: If this is an initializer list, suggest removing the braces
6536 // or inserting a cast to the target type.
6537 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6538 << isa<InitListExpr>(E) << ExprTy << CallType
6539 << AT.getRepresentativeTypeName(S.Context)
6540 << E->getSourceRange();
6541 break;
6542 }
6543
6544 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6545 "format string specifier index out of range");
6546 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006547 }
6548
Ted Kremenekab278de2010-01-28 23:39:18 +00006549 return true;
6550}
6551
Ted Kremenek02087932010-07-16 02:11:22 +00006552//===--- CHECK: Scanf format string checking ------------------------------===//
6553
6554namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006555
Ted Kremenek02087932010-07-16 02:11:22 +00006556class CheckScanfHandler : public CheckFormatHandler {
6557public:
Stephen Hines648c3692016-09-16 01:07:04 +00006558 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006559 const Expr *origFormatExpr, Sema::FormatStringType type,
6560 unsigned firstDataArg, unsigned numDataArgs,
6561 const char *beg, bool hasVAListArg,
6562 ArrayRef<const Expr *> Args, unsigned formatIdx,
6563 bool inFunctionCall, Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006564 llvm::SmallBitVector &CheckedVarArgs,
6565 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006566 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6567 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6568 inFunctionCall, CallType, CheckedVarArgs,
6569 UncoveredArg) {}
6570
Ted Kremenek02087932010-07-16 02:11:22 +00006571 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6572 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006573 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00006574
6575 bool HandleInvalidScanfConversionSpecifier(
6576 const analyze_scanf::ScanfSpecifier &FS,
6577 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006578 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006579
Craig Toppere14c0f82014-03-12 04:55:44 +00006580 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00006581};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006582
6583} // namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00006584
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006585void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6586 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006587 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6588 getLocationOfByte(end), /*IsStringLocation*/true,
6589 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006590}
6591
Ted Kremenekce815422010-07-19 21:25:57 +00006592bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6593 const analyze_scanf::ScanfSpecifier &FS,
6594 const char *startSpecifier,
6595 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006596 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00006597 FS.getConversionSpecifier();
6598
6599 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6600 getLocationOfByte(CS.getStart()),
6601 startSpecifier, specifierLen,
6602 CS.getStart(), CS.getLength());
6603}
6604
Ted Kremenek02087932010-07-16 02:11:22 +00006605bool CheckScanfHandler::HandleScanfSpecifier(
6606 const analyze_scanf::ScanfSpecifier &FS,
6607 const char *startSpecifier,
6608 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00006609 using namespace analyze_scanf;
6610 using namespace analyze_format_string;
6611
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006612 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00006613
Ted Kremenek6cd69422010-07-19 22:01:06 +00006614 // Handle case where '%' and '*' don't consume an argument. These shouldn't
6615 // be used to decide if we are using positional arguments consistently.
6616 if (FS.consumesDataArgument()) {
6617 if (atFirstArg) {
6618 atFirstArg = false;
6619 usesPositionalArgs = FS.usesPositionalArg();
6620 }
6621 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006622 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6623 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00006624 return false;
6625 }
Ted Kremenek02087932010-07-16 02:11:22 +00006626 }
6627
6628 // Check if the field with is non-zero.
6629 const OptionalAmount &Amt = FS.getFieldWidth();
6630 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6631 if (Amt.getConstantAmount() == 0) {
6632 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6633 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00006634 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6635 getLocationOfByte(Amt.getStart()),
6636 /*IsStringLocation*/true, R,
6637 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00006638 }
6639 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006640
Ted Kremenek02087932010-07-16 02:11:22 +00006641 if (!FS.consumesDataArgument()) {
6642 // FIXME: Technically specifying a precision or field width here
6643 // makes no sense. Worth issuing a warning at some point.
6644 return true;
6645 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006646
Ted Kremenek02087932010-07-16 02:11:22 +00006647 // Consume the argument.
6648 unsigned argIndex = FS.getArgIndex();
6649 if (argIndex < NumDataArgs) {
6650 // The check to see if the argIndex is valid will come later.
6651 // We set the bit here because we may exit early from this
6652 // function if we encounter some other error.
6653 CoveredArgs.set(argIndex);
6654 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006655
Ted Kremenek4407ea42010-07-20 20:04:47 +00006656 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006657 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006658 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6659 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006660 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006661 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006662 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006663 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6664 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006665
Jordan Rose92303592012-09-08 04:00:03 +00006666 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6667 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6668
Ted Kremenek02087932010-07-16 02:11:22 +00006669 // The remaining checks depend on the data arguments.
6670 if (HasVAListArg)
6671 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006672
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006673 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00006674 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00006675
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006676 // Check that the argument type matches the format specifier.
6677 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00006678 if (!Ex)
6679 return true;
6680
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00006681 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00006682
6683 if (!AT.isValid()) {
6684 return true;
6685 }
6686
Seth Cantrellb4802962015-03-04 03:12:10 +00006687 analyze_format_string::ArgType::MatchKind match =
6688 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00006689 if (match == analyze_format_string::ArgType::Match) {
6690 return true;
6691 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006692
Seth Cantrell79340072015-03-04 05:58:08 +00006693 ScanfSpecifier fixedFS = FS;
6694 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6695 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006696
Seth Cantrell79340072015-03-04 05:58:08 +00006697 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6698 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6699 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6700 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006701
Seth Cantrell79340072015-03-04 05:58:08 +00006702 if (success) {
6703 // Get the fix string from the fixed format specifier.
6704 SmallString<128> buf;
6705 llvm::raw_svector_ostream os(buf);
6706 fixedFS.toString(os);
6707
6708 EmitFormatDiagnostic(
6709 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6710 << Ex->getType() << false << Ex->getSourceRange(),
6711 Ex->getLocStart(),
6712 /*IsStringLocation*/ false,
6713 getSpecifierRange(startSpecifier, specifierLen),
6714 FixItHint::CreateReplacement(
6715 getSpecifierRange(startSpecifier, specifierLen), os.str()));
6716 } else {
6717 EmitFormatDiagnostic(S.PDiag(diag)
6718 << AT.getRepresentativeTypeName(S.Context)
6719 << Ex->getType() << false << Ex->getSourceRange(),
6720 Ex->getLocStart(),
6721 /*IsStringLocation*/ false,
6722 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006723 }
6724
Ted Kremenek02087932010-07-16 02:11:22 +00006725 return true;
6726}
6727
Stephen Hines648c3692016-09-16 01:07:04 +00006728static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006729 const Expr *OrigFormatExpr,
6730 ArrayRef<const Expr *> Args,
6731 bool HasVAListArg, unsigned format_idx,
6732 unsigned firstDataArg,
6733 Sema::FormatStringType Type,
6734 bool inFunctionCall,
6735 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006736 llvm::SmallBitVector &CheckedVarArgs,
6737 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00006738 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00006739 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006740 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006741 S, inFunctionCall, Args[format_idx],
6742 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006743 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006744 return;
6745 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006746
Ted Kremenekab278de2010-01-28 23:39:18 +00006747 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006748 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00006749 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006750 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006751 const ConstantArrayType *T =
6752 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006753 assert(T && "String literal not of constant array type!");
6754 size_t TypeSize = T->getSize().getZExtValue();
6755 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006756 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006757
6758 // Emit a warning if the string literal is truncated and does not contain an
6759 // embedded null character.
6760 if (TypeSize <= StrRef.size() &&
6761 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6762 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006763 S, inFunctionCall, Args[format_idx],
6764 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006765 FExpr->getLocStart(),
6766 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6767 return;
6768 }
6769
Ted Kremenekab278de2010-01-28 23:39:18 +00006770 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00006771 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006772 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006773 S, inFunctionCall, Args[format_idx],
6774 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006775 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006776 return;
6777 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006778
6779 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
Mehdi Amini06d367c2016-10-24 20:39:34 +00006780 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6781 Type == Sema::FST_OSTrace) {
6782 CheckPrintfHandler H(
6783 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6784 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6785 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6786 CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006787
Hans Wennborg23926bd2011-12-15 10:25:47 +00006788 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006789 S.getLangOpts(),
6790 S.Context.getTargetInfo(),
6791 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00006792 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006793 } else if (Type == Sema::FST_Scanf) {
Mehdi Amini06d367c2016-10-24 20:39:34 +00006794 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6795 numDataArgs, Str, HasVAListArg, Args, format_idx,
6796 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006797
Hans Wennborg23926bd2011-12-15 10:25:47 +00006798 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006799 S.getLangOpts(),
6800 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00006801 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006802 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00006803}
6804
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00006805bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6806 // Str - The format string. NOTE: this is NOT null-terminated!
6807 StringRef StrRef = FExpr->getString();
6808 const char *Str = StrRef.data();
6809 // Account for cases where the string literal is truncated in a declaration.
6810 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6811 assert(T && "String literal not of constant array type!");
6812 size_t TypeSize = T->getSize().getZExtValue();
6813 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6814 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6815 getLangOpts(),
6816 Context.getTargetInfo());
6817}
6818
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006819//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6820
6821// Returns the related absolute value function that is larger, of 0 if one
6822// does not exist.
6823static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6824 switch (AbsFunction) {
6825 default:
6826 return 0;
6827
6828 case Builtin::BI__builtin_abs:
6829 return Builtin::BI__builtin_labs;
6830 case Builtin::BI__builtin_labs:
6831 return Builtin::BI__builtin_llabs;
6832 case Builtin::BI__builtin_llabs:
6833 return 0;
6834
6835 case Builtin::BI__builtin_fabsf:
6836 return Builtin::BI__builtin_fabs;
6837 case Builtin::BI__builtin_fabs:
6838 return Builtin::BI__builtin_fabsl;
6839 case Builtin::BI__builtin_fabsl:
6840 return 0;
6841
6842 case Builtin::BI__builtin_cabsf:
6843 return Builtin::BI__builtin_cabs;
6844 case Builtin::BI__builtin_cabs:
6845 return Builtin::BI__builtin_cabsl;
6846 case Builtin::BI__builtin_cabsl:
6847 return 0;
6848
6849 case Builtin::BIabs:
6850 return Builtin::BIlabs;
6851 case Builtin::BIlabs:
6852 return Builtin::BIllabs;
6853 case Builtin::BIllabs:
6854 return 0;
6855
6856 case Builtin::BIfabsf:
6857 return Builtin::BIfabs;
6858 case Builtin::BIfabs:
6859 return Builtin::BIfabsl;
6860 case Builtin::BIfabsl:
6861 return 0;
6862
6863 case Builtin::BIcabsf:
6864 return Builtin::BIcabs;
6865 case Builtin::BIcabs:
6866 return Builtin::BIcabsl;
6867 case Builtin::BIcabsl:
6868 return 0;
6869 }
6870}
6871
6872// Returns the argument type of the absolute value function.
6873static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6874 unsigned AbsType) {
6875 if (AbsType == 0)
6876 return QualType();
6877
6878 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6879 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6880 if (Error != ASTContext::GE_None)
6881 return QualType();
6882
6883 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6884 if (!FT)
6885 return QualType();
6886
6887 if (FT->getNumParams() != 1)
6888 return QualType();
6889
6890 return FT->getParamType(0);
6891}
6892
6893// Returns the best absolute value function, or zero, based on type and
6894// current absolute value function.
6895static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6896 unsigned AbsFunctionKind) {
6897 unsigned BestKind = 0;
6898 uint64_t ArgSize = Context.getTypeSize(ArgType);
6899 for (unsigned Kind = AbsFunctionKind; Kind != 0;
6900 Kind = getLargerAbsoluteValueFunction(Kind)) {
6901 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6902 if (Context.getTypeSize(ParamType) >= ArgSize) {
6903 if (BestKind == 0)
6904 BestKind = Kind;
6905 else if (Context.hasSameType(ParamType, ArgType)) {
6906 BestKind = Kind;
6907 break;
6908 }
6909 }
6910 }
6911 return BestKind;
6912}
6913
6914enum AbsoluteValueKind {
6915 AVK_Integer,
6916 AVK_Floating,
6917 AVK_Complex
6918};
6919
6920static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6921 if (T->isIntegralOrEnumerationType())
6922 return AVK_Integer;
6923 if (T->isRealFloatingType())
6924 return AVK_Floating;
6925 if (T->isAnyComplexType())
6926 return AVK_Complex;
6927
6928 llvm_unreachable("Type not integer, floating, or complex");
6929}
6930
6931// Changes the absolute value function to a different type. Preserves whether
6932// the function is a builtin.
6933static unsigned changeAbsFunction(unsigned AbsKind,
6934 AbsoluteValueKind ValueKind) {
6935 switch (ValueKind) {
6936 case AVK_Integer:
6937 switch (AbsKind) {
6938 default:
6939 return 0;
6940 case Builtin::BI__builtin_fabsf:
6941 case Builtin::BI__builtin_fabs:
6942 case Builtin::BI__builtin_fabsl:
6943 case Builtin::BI__builtin_cabsf:
6944 case Builtin::BI__builtin_cabs:
6945 case Builtin::BI__builtin_cabsl:
6946 return Builtin::BI__builtin_abs;
6947 case Builtin::BIfabsf:
6948 case Builtin::BIfabs:
6949 case Builtin::BIfabsl:
6950 case Builtin::BIcabsf:
6951 case Builtin::BIcabs:
6952 case Builtin::BIcabsl:
6953 return Builtin::BIabs;
6954 }
6955 case AVK_Floating:
6956 switch (AbsKind) {
6957 default:
6958 return 0;
6959 case Builtin::BI__builtin_abs:
6960 case Builtin::BI__builtin_labs:
6961 case Builtin::BI__builtin_llabs:
6962 case Builtin::BI__builtin_cabsf:
6963 case Builtin::BI__builtin_cabs:
6964 case Builtin::BI__builtin_cabsl:
6965 return Builtin::BI__builtin_fabsf;
6966 case Builtin::BIabs:
6967 case Builtin::BIlabs:
6968 case Builtin::BIllabs:
6969 case Builtin::BIcabsf:
6970 case Builtin::BIcabs:
6971 case Builtin::BIcabsl:
6972 return Builtin::BIfabsf;
6973 }
6974 case AVK_Complex:
6975 switch (AbsKind) {
6976 default:
6977 return 0;
6978 case Builtin::BI__builtin_abs:
6979 case Builtin::BI__builtin_labs:
6980 case Builtin::BI__builtin_llabs:
6981 case Builtin::BI__builtin_fabsf:
6982 case Builtin::BI__builtin_fabs:
6983 case Builtin::BI__builtin_fabsl:
6984 return Builtin::BI__builtin_cabsf;
6985 case Builtin::BIabs:
6986 case Builtin::BIlabs:
6987 case Builtin::BIllabs:
6988 case Builtin::BIfabsf:
6989 case Builtin::BIfabs:
6990 case Builtin::BIfabsl:
6991 return Builtin::BIcabsf;
6992 }
6993 }
6994 llvm_unreachable("Unable to convert function");
6995}
6996
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00006997static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006998 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6999 if (!FnInfo)
7000 return 0;
7001
7002 switch (FDecl->getBuiltinID()) {
7003 default:
7004 return 0;
7005 case Builtin::BI__builtin_abs:
7006 case Builtin::BI__builtin_fabs:
7007 case Builtin::BI__builtin_fabsf:
7008 case Builtin::BI__builtin_fabsl:
7009 case Builtin::BI__builtin_labs:
7010 case Builtin::BI__builtin_llabs:
7011 case Builtin::BI__builtin_cabs:
7012 case Builtin::BI__builtin_cabsf:
7013 case Builtin::BI__builtin_cabsl:
7014 case Builtin::BIabs:
7015 case Builtin::BIlabs:
7016 case Builtin::BIllabs:
7017 case Builtin::BIfabs:
7018 case Builtin::BIfabsf:
7019 case Builtin::BIfabsl:
7020 case Builtin::BIcabs:
7021 case Builtin::BIcabsf:
7022 case Builtin::BIcabsl:
7023 return FDecl->getBuiltinID();
7024 }
7025 llvm_unreachable("Unknown Builtin type");
7026}
7027
7028// If the replacement is valid, emit a note with replacement function.
7029// Additionally, suggest including the proper header if not already included.
7030static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00007031 unsigned AbsKind, QualType ArgType) {
7032 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00007033 const char *HeaderName = nullptr;
Mehdi Amini7186a432016-10-11 19:04:24 +00007034 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00007035 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
7036 FunctionName = "std::abs";
7037 if (ArgType->isIntegralOrEnumerationType()) {
7038 HeaderName = "cstdlib";
7039 } else if (ArgType->isRealFloatingType()) {
7040 HeaderName = "cmath";
7041 } else {
7042 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007043 }
Richard Trieubeffb832014-04-15 23:47:53 +00007044
7045 // Lookup all std::abs
7046 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00007047 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00007048 R.suppressDiagnostics();
7049 S.LookupQualifiedName(R, Std);
7050
7051 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007052 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00007053 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
7054 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
7055 } else {
7056 FDecl = dyn_cast<FunctionDecl>(I);
7057 }
7058 if (!FDecl)
7059 continue;
7060
7061 // Found std::abs(), check that they are the right ones.
7062 if (FDecl->getNumParams() != 1)
7063 continue;
7064
7065 // Check that the parameter type can handle the argument.
7066 QualType ParamType = FDecl->getParamDecl(0)->getType();
7067 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
7068 S.Context.getTypeSize(ArgType) <=
7069 S.Context.getTypeSize(ParamType)) {
7070 // Found a function, don't need the header hint.
7071 EmitHeaderHint = false;
7072 break;
7073 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007074 }
Richard Trieubeffb832014-04-15 23:47:53 +00007075 }
7076 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00007077 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00007078 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
7079
7080 if (HeaderName) {
7081 DeclarationName DN(&S.Context.Idents.get(FunctionName));
7082 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
7083 R.suppressDiagnostics();
7084 S.LookupName(R, S.getCurScope());
7085
7086 if (R.isSingleResult()) {
7087 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
7088 if (FD && FD->getBuiltinID() == AbsKind) {
7089 EmitHeaderHint = false;
7090 } else {
7091 return;
7092 }
7093 } else if (!R.empty()) {
7094 return;
7095 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007096 }
7097 }
7098
7099 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00007100 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007101
Richard Trieubeffb832014-04-15 23:47:53 +00007102 if (!HeaderName)
7103 return;
7104
7105 if (!EmitHeaderHint)
7106 return;
7107
Alp Toker5d96e0a2014-07-11 20:53:51 +00007108 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
7109 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00007110}
7111
Richard Trieua7f30b12016-12-06 01:42:28 +00007112template <std::size_t StrLen>
7113static bool IsStdFunction(const FunctionDecl *FDecl,
7114 const char (&Str)[StrLen]) {
Richard Trieubeffb832014-04-15 23:47:53 +00007115 if (!FDecl)
7116 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00007117 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
Richard Trieubeffb832014-04-15 23:47:53 +00007118 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00007119 if (!FDecl->isInStdNamespace())
Richard Trieubeffb832014-04-15 23:47:53 +00007120 return false;
7121
7122 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007123}
7124
7125// Warn when using the wrong abs() function.
7126void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
Richard Trieua7f30b12016-12-06 01:42:28 +00007127 const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007128 if (Call->getNumArgs() != 1)
7129 return;
7130
7131 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieua7f30b12016-12-06 01:42:28 +00007132 bool IsStdAbs = IsStdFunction(FDecl, "abs");
Richard Trieubeffb832014-04-15 23:47:53 +00007133 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007134 return;
7135
7136 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7137 QualType ParamType = Call->getArg(0)->getType();
7138
Alp Toker5d96e0a2014-07-11 20:53:51 +00007139 // Unsigned types cannot be negative. Suggest removing the absolute value
7140 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007141 if (ArgType->isUnsignedIntegerType()) {
Mehdi Amini7186a432016-10-11 19:04:24 +00007142 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00007143 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007144 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
7145 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00007146 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007147 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
7148 return;
7149 }
7150
David Majnemer7f77eb92015-11-15 03:04:34 +00007151 // Taking the absolute value of a pointer is very suspicious, they probably
7152 // wanted to index into an array, dereference a pointer, call a function, etc.
7153 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
7154 unsigned DiagType = 0;
7155 if (ArgType->isFunctionType())
7156 DiagType = 1;
7157 else if (ArgType->isArrayType())
7158 DiagType = 2;
7159
7160 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
7161 return;
7162 }
7163
Richard Trieubeffb832014-04-15 23:47:53 +00007164 // std::abs has overloads which prevent most of the absolute value problems
7165 // from occurring.
7166 if (IsStdAbs)
7167 return;
7168
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007169 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
7170 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
7171
7172 // The argument and parameter are the same kind. Check if they are the right
7173 // size.
7174 if (ArgValueKind == ParamValueKind) {
7175 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
7176 return;
7177
7178 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
7179 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
7180 << FDecl << ArgType << ParamType;
7181
7182 if (NewAbsKind == 0)
7183 return;
7184
7185 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00007186 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007187 return;
7188 }
7189
7190 // ArgValueKind != ParamValueKind
7191 // The wrong type of absolute value function was used. Attempt to find the
7192 // proper one.
7193 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
7194 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
7195 if (NewAbsKind == 0)
7196 return;
7197
7198 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
7199 << FDecl << ParamValueKind << ArgValueKind;
7200
7201 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00007202 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007203}
7204
Richard Trieu67c00712016-12-05 23:41:46 +00007205//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
Richard Trieua7f30b12016-12-06 01:42:28 +00007206void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
7207 const FunctionDecl *FDecl) {
Richard Trieu67c00712016-12-05 23:41:46 +00007208 if (!Call || !FDecl) return;
7209
7210 // Ignore template specializations and macros.
Richard Smith51ec0cf2017-02-21 01:17:38 +00007211 if (inTemplateInstantiation()) return;
Richard Trieu67c00712016-12-05 23:41:46 +00007212 if (Call->getExprLoc().isMacroID()) return;
7213
7214 // Only care about the one template argument, two function parameter std::max
7215 if (Call->getNumArgs() != 2) return;
Richard Trieua7f30b12016-12-06 01:42:28 +00007216 if (!IsStdFunction(FDecl, "max")) return;
Richard Trieu67c00712016-12-05 23:41:46 +00007217 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
7218 if (!ArgList) return;
7219 if (ArgList->size() != 1) return;
7220
7221 // Check that template type argument is unsigned integer.
7222 const auto& TA = ArgList->get(0);
7223 if (TA.getKind() != TemplateArgument::Type) return;
7224 QualType ArgType = TA.getAsType();
7225 if (!ArgType->isUnsignedIntegerType()) return;
7226
7227 // See if either argument is a literal zero.
7228 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
7229 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
7230 if (!MTE) return false;
7231 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
7232 if (!Num) return false;
7233 if (Num->getValue() != 0) return false;
7234 return true;
7235 };
7236
7237 const Expr *FirstArg = Call->getArg(0);
7238 const Expr *SecondArg = Call->getArg(1);
7239 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
7240 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
7241
7242 // Only warn when exactly one argument is zero.
7243 if (IsFirstArgZero == IsSecondArgZero) return;
7244
7245 SourceRange FirstRange = FirstArg->getSourceRange();
7246 SourceRange SecondRange = SecondArg->getSourceRange();
7247
7248 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
7249
7250 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
7251 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
7252
7253 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
7254 SourceRange RemovalRange;
7255 if (IsFirstArgZero) {
7256 RemovalRange = SourceRange(FirstRange.getBegin(),
7257 SecondRange.getBegin().getLocWithOffset(-1));
7258 } else {
7259 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
7260 SecondRange.getEnd());
7261 }
7262
7263 Diag(Call->getExprLoc(), diag::note_remove_max_call)
7264 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
7265 << FixItHint::CreateRemoval(RemovalRange);
7266}
7267
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007268//===--- CHECK: Standard memory functions ---------------------------------===//
7269
Nico Weber0e6daef2013-12-26 23:38:39 +00007270/// \brief Takes the expression passed to the size_t parameter of functions
7271/// such as memcmp, strncat, etc and warns if it's a comparison.
7272///
7273/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
7274static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
7275 IdentifierInfo *FnName,
7276 SourceLocation FnLoc,
7277 SourceLocation RParenLoc) {
7278 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
7279 if (!Size)
7280 return false;
7281
Richard Smithc70f1d62017-12-14 15:16:18 +00007282 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
7283 if (!Size->isComparisonOp() && !Size->isLogicalOp())
Nico Weber0e6daef2013-12-26 23:38:39 +00007284 return false;
7285
Nico Weber0e6daef2013-12-26 23:38:39 +00007286 SourceRange SizeRange = Size->getSourceRange();
7287 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
7288 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00007289 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007290 << FnName << FixItHint::CreateInsertion(
7291 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00007292 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00007293 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00007294 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00007295 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
7296 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00007297
7298 return true;
7299}
7300
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007301/// \brief Determine whether the given type is or contains a dynamic class type
7302/// (e.g., whether it has a vtable).
7303static const CXXRecordDecl *getContainedDynamicClass(QualType T,
7304 bool &IsContained) {
7305 // Look through array types while ignoring qualifiers.
7306 const Type *Ty = T->getBaseElementTypeUnsafe();
7307 IsContained = false;
7308
7309 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
7310 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00007311 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007312 return nullptr;
7313
7314 if (RD->isDynamicClass())
7315 return RD;
7316
7317 // Check all the fields. If any bases were dynamic, the class is dynamic.
7318 // It's impossible for a class to transitively contain itself by value, so
7319 // infinite recursion is impossible.
7320 for (auto *FD : RD->fields()) {
7321 bool SubContained;
7322 if (const CXXRecordDecl *ContainedRD =
7323 getContainedDynamicClass(FD->getType(), SubContained)) {
7324 IsContained = true;
7325 return ContainedRD;
7326 }
7327 }
7328
7329 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00007330}
7331
Chandler Carruth889ed862011-06-21 23:04:20 +00007332/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007333/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00007334static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00007335 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007336 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007337 if (SizeOf->getKind() == UETT_SizeOf && !SizeOf->isArgumentType())
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007338 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007339
Craig Topperc3ec1492014-05-26 06:22:03 +00007340 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007341}
7342
Chandler Carruth889ed862011-06-21 23:04:20 +00007343/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00007344static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007345 if (const UnaryExprOrTypeTraitExpr *SizeOf =
7346 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007347 if (SizeOf->getKind() == UETT_SizeOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007348 return SizeOf->getTypeOfArgument();
7349
7350 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00007351}
7352
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007353/// \brief Check for dangerous or invalid arguments to memset().
7354///
Chandler Carruthac687262011-06-03 06:23:57 +00007355/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007356/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
7357/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007358///
7359/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007360void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00007361 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007362 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00007363 assert(BId != 0);
7364
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007365 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00007366 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007367 unsigned ExpectedNumArgs =
7368 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00007369 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007370 return;
7371
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007372 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00007373 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007374 unsigned LenArg =
7375 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00007376 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007377
Nico Weber0e6daef2013-12-26 23:38:39 +00007378 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
7379 Call->getLocStart(), Call->getRParenLoc()))
7380 return;
7381
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007382 // We have special checking when the length is a sizeof expression.
7383 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
7384 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
7385 llvm::FoldingSetNodeID SizeOfArgID;
7386
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00007387 // Although widely used, 'bzero' is not a standard function. Be more strict
7388 // with the argument types before allowing diagnostics and only allow the
7389 // form bzero(ptr, sizeof(...)).
7390 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7391 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
7392 return;
7393
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007394 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7395 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007396 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007397
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007398 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00007399 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007400 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00007401 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00007402
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007403 // Never warn about void type pointers. This can be used to suppress
7404 // false positives.
7405 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007406 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007407
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007408 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
7409 // actually comparing the expressions for equality. Because computing the
7410 // expression IDs can be expensive, we only do this if the diagnostic is
7411 // enabled.
7412 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007413 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
7414 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007415 // We only compute IDs for expressions if the warning is enabled, and
7416 // cache the sizeof arg's ID.
7417 if (SizeOfArgID == llvm::FoldingSetNodeID())
7418 SizeOfArg->Profile(SizeOfArgID, Context, true);
7419 llvm::FoldingSetNodeID DestID;
7420 Dest->Profile(DestID, Context, true);
7421 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00007422 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
7423 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007424 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00007425 StringRef ReadableName = FnName->getName();
7426
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007427 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00007428 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007429 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00007430 if (!PointeeTy->isIncompleteType() &&
7431 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007432 ActionIdx = 2; // If the pointee's size is sizeof(char),
7433 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00007434
7435 // If the function is defined as a builtin macro, do not show macro
7436 // expansion.
7437 SourceLocation SL = SizeOfArg->getExprLoc();
7438 SourceRange DSR = Dest->getSourceRange();
7439 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007440 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00007441
7442 if (SM.isMacroArgExpansion(SL)) {
7443 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7444 SL = SM.getSpellingLoc(SL);
7445 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7446 SM.getSpellingLoc(DSR.getEnd()));
7447 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7448 SM.getSpellingLoc(SSR.getEnd()));
7449 }
7450
Anna Zaksd08d9152012-05-30 23:14:52 +00007451 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007452 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00007453 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00007454 << PointeeTy
7455 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00007456 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00007457 << SSR);
7458 DiagRuntimeBehavior(SL, SizeOfArg,
7459 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7460 << ActionIdx
7461 << SSR);
7462
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007463 break;
7464 }
7465 }
7466
7467 // Also check for cases where the sizeof argument is the exact same
7468 // type as the memory argument, and where it points to a user-defined
7469 // record type.
7470 if (SizeOfArgTy != QualType()) {
7471 if (PointeeTy->isRecordType() &&
7472 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7473 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7474 PDiag(diag::warn_sizeof_pointer_type_memaccess)
7475 << FnName << SizeOfArgTy << ArgIdx
7476 << PointeeTy << Dest->getSourceRange()
7477 << LenExpr->getSourceRange());
7478 break;
7479 }
Nico Weberc5e73862011-06-14 16:14:58 +00007480 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00007481 } else if (DestTy->isArrayType()) {
7482 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00007483 }
Nico Weberc5e73862011-06-14 16:14:58 +00007484
Nico Weberc44b35e2015-03-21 17:37:46 +00007485 if (PointeeTy == QualType())
7486 continue;
Anna Zaks22122702012-01-17 00:37:07 +00007487
Nico Weberc44b35e2015-03-21 17:37:46 +00007488 // Always complain about dynamic classes.
7489 bool IsContained;
7490 if (const CXXRecordDecl *ContainedRD =
7491 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00007492
Nico Weberc44b35e2015-03-21 17:37:46 +00007493 unsigned OperationType = 0;
7494 // "overwritten" if we're warning about the destination for any call
7495 // but memcmp; otherwise a verb appropriate to the call.
7496 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7497 if (BId == Builtin::BImemcpy)
7498 OperationType = 1;
7499 else if(BId == Builtin::BImemmove)
7500 OperationType = 2;
7501 else if (BId == Builtin::BImemcmp)
7502 OperationType = 3;
7503 }
7504
John McCall31168b02011-06-15 23:02:42 +00007505 DiagRuntimeBehavior(
7506 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00007507 PDiag(diag::warn_dyn_class_memaccess)
7508 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7509 << FnName << IsContained << ContainedRD << OperationType
7510 << Call->getCallee()->getSourceRange());
7511 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7512 BId != Builtin::BImemset)
7513 DiagRuntimeBehavior(
7514 Dest->getExprLoc(), Dest,
7515 PDiag(diag::warn_arc_object_memaccess)
7516 << ArgIdx << FnName << PointeeTy
7517 << Call->getCallee()->getSourceRange());
7518 else
7519 continue;
7520
7521 DiagRuntimeBehavior(
7522 Dest->getExprLoc(), Dest,
7523 PDiag(diag::note_bad_memaccess_silence)
7524 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7525 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007526 }
7527}
7528
Ted Kremenek6865f772011-08-18 20:55:45 +00007529// A little helper routine: ignore addition and subtraction of integer literals.
7530// This intentionally does not ignore all integer constant expressions because
7531// we don't want to remove sizeof().
7532static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7533 Ex = Ex->IgnoreParenCasts();
7534
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007535 while (true) {
Ted Kremenek6865f772011-08-18 20:55:45 +00007536 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7537 if (!BO || !BO->isAdditiveOp())
7538 break;
7539
7540 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7541 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7542
7543 if (isa<IntegerLiteral>(RHS))
7544 Ex = LHS;
7545 else if (isa<IntegerLiteral>(LHS))
7546 Ex = RHS;
7547 else
7548 break;
7549 }
7550
7551 return Ex;
7552}
7553
Anna Zaks13b08572012-08-08 21:42:23 +00007554static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7555 ASTContext &Context) {
7556 // Only handle constant-sized or VLAs, but not flexible members.
7557 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7558 // Only issue the FIXIT for arrays of size > 1.
7559 if (CAT->getSize().getSExtValue() <= 1)
7560 return false;
7561 } else if (!Ty->isVariableArrayType()) {
7562 return false;
7563 }
7564 return true;
7565}
7566
Ted Kremenek6865f772011-08-18 20:55:45 +00007567// Warn if the user has made the 'size' argument to strlcpy or strlcat
7568// be the size of the source, instead of the destination.
7569void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7570 IdentifierInfo *FnName) {
7571
7572 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00007573 unsigned NumArgs = Call->getNumArgs();
7574 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00007575 return;
7576
7577 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7578 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00007579 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00007580
7581 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7582 Call->getLocStart(), Call->getRParenLoc()))
7583 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00007584
7585 // Look for 'strlcpy(dst, x, sizeof(x))'
7586 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7587 CompareWithSrc = Ex;
7588 else {
7589 // Look for 'strlcpy(dst, x, strlen(x))'
7590 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00007591 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7592 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00007593 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7594 }
7595 }
7596
7597 if (!CompareWithSrc)
7598 return;
7599
7600 // Determine if the argument to sizeof/strlen is equal to the source
7601 // argument. In principle there's all kinds of things you could do
7602 // here, for instance creating an == expression and evaluating it with
7603 // EvaluateAsBooleanCondition, but this uses a more direct technique:
7604 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7605 if (!SrcArgDRE)
7606 return;
7607
7608 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7609 if (!CompareWithSrcDRE ||
7610 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7611 return;
7612
7613 const Expr *OriginalSizeArg = Call->getArg(2);
7614 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7615 << OriginalSizeArg->getSourceRange() << FnName;
7616
7617 // Output a FIXIT hint if the destination is an array (rather than a
7618 // pointer to an array). This could be enhanced to handle some
7619 // pointers if we know the actual size, like if DstArg is 'array+2'
7620 // we could say 'sizeof(array)-2'.
7621 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00007622 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00007623 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007624
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007625 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007626 llvm::raw_svector_ostream OS(sizeString);
7627 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007628 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00007629 OS << ")";
7630
7631 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7632 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7633 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00007634}
7635
Anna Zaks314cd092012-02-01 19:08:57 +00007636/// Check if two expressions refer to the same declaration.
7637static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7638 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7639 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7640 return D1->getDecl() == D2->getDecl();
7641 return false;
7642}
7643
7644static const Expr *getStrlenExprArg(const Expr *E) {
7645 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7646 const FunctionDecl *FD = CE->getDirectCallee();
7647 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00007648 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007649 return CE->getArg(0)->IgnoreParenCasts();
7650 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007651 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007652}
7653
7654// Warn on anti-patterns as the 'size' argument to strncat.
7655// The correct size argument should look like following:
7656// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7657void Sema::CheckStrncatArguments(const CallExpr *CE,
7658 IdentifierInfo *FnName) {
7659 // Don't crash if the user has the wrong number of arguments.
7660 if (CE->getNumArgs() < 3)
7661 return;
7662 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7663 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7664 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7665
Nico Weber0e6daef2013-12-26 23:38:39 +00007666 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7667 CE->getRParenLoc()))
7668 return;
7669
Anna Zaks314cd092012-02-01 19:08:57 +00007670 // Identify common expressions, which are wrongly used as the size argument
7671 // to strncat and may lead to buffer overflows.
7672 unsigned PatternType = 0;
7673 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7674 // - sizeof(dst)
7675 if (referToTheSameDecl(SizeOfArg, DstArg))
7676 PatternType = 1;
7677 // - sizeof(src)
7678 else if (referToTheSameDecl(SizeOfArg, SrcArg))
7679 PatternType = 2;
7680 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7681 if (BE->getOpcode() == BO_Sub) {
7682 const Expr *L = BE->getLHS()->IgnoreParenCasts();
7683 const Expr *R = BE->getRHS()->IgnoreParenCasts();
7684 // - sizeof(dst) - strlen(dst)
7685 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7686 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7687 PatternType = 1;
7688 // - sizeof(src) - (anything)
7689 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7690 PatternType = 2;
7691 }
7692 }
7693
7694 if (PatternType == 0)
7695 return;
7696
Anna Zaks5069aa32012-02-03 01:27:37 +00007697 // Generate the diagnostic.
7698 SourceLocation SL = LenArg->getLocStart();
7699 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007700 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00007701
7702 // If the function is defined as a builtin macro, do not show macro expansion.
7703 if (SM.isMacroArgExpansion(SL)) {
7704 SL = SM.getSpellingLoc(SL);
7705 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7706 SM.getSpellingLoc(SR.getEnd()));
7707 }
7708
Anna Zaks13b08572012-08-08 21:42:23 +00007709 // Check if the destination is an array (rather than a pointer to an array).
7710 QualType DstTy = DstArg->getType();
7711 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7712 Context);
7713 if (!isKnownSizeArray) {
7714 if (PatternType == 1)
7715 Diag(SL, diag::warn_strncat_wrong_size) << SR;
7716 else
7717 Diag(SL, diag::warn_strncat_src_size) << SR;
7718 return;
7719 }
7720
Anna Zaks314cd092012-02-01 19:08:57 +00007721 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00007722 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007723 else
Anna Zaks5069aa32012-02-03 01:27:37 +00007724 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007725
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007726 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00007727 llvm::raw_svector_ostream OS(sizeString);
7728 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007729 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007730 OS << ") - ";
7731 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007732 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007733 OS << ") - 1";
7734
Anna Zaks5069aa32012-02-03 01:27:37 +00007735 Diag(SL, diag::note_strncat_wrong_size)
7736 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00007737}
7738
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007739//===--- CHECK: Return Address of Stack Variable --------------------------===//
7740
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007741static const Expr *EvalVal(const Expr *E,
7742 SmallVectorImpl<const DeclRefExpr *> &refVars,
7743 const Decl *ParentDecl);
7744static const Expr *EvalAddr(const Expr *E,
7745 SmallVectorImpl<const DeclRefExpr *> &refVars,
7746 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007747
7748/// CheckReturnStackAddr - Check if a return statement returns the address
7749/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007750static void
7751CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7752 SourceLocation ReturnLoc) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007753 const Expr *stackE = nullptr;
7754 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007755
7756 // Perform checking for returned stack addresses, local blocks,
7757 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00007758 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007759 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007760 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00007761 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007762 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007763 }
7764
Craig Topperc3ec1492014-05-26 06:22:03 +00007765 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007766 return; // Nothing suspicious was found.
7767
Simon Pilgrim750bde62017-03-31 11:00:53 +00007768 // Parameters are initialized in the calling scope, so taking the address
Richard Trieu81b6c562016-08-05 23:24:47 +00007769 // of a parameter reference doesn't need a warning.
7770 for (auto *DRE : refVars)
7771 if (isa<ParmVarDecl>(DRE->getDecl()))
7772 return;
7773
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007774 SourceLocation diagLoc;
7775 SourceRange diagRange;
7776 if (refVars.empty()) {
7777 diagLoc = stackE->getLocStart();
7778 diagRange = stackE->getSourceRange();
7779 } else {
7780 // We followed through a reference variable. 'stackE' contains the
7781 // problematic expression but we will warn at the return statement pointing
7782 // at the reference variable. We will later display the "trail" of
7783 // reference variables using notes.
7784 diagLoc = refVars[0]->getLocStart();
7785 diagRange = refVars[0]->getSourceRange();
7786 }
7787
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007788 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7789 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00007790 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007791 << DR->getDecl()->getDeclName() << diagRange;
7792 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007793 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007794 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007795 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007796 } else { // local temporary.
Richard Trieu81b6c562016-08-05 23:24:47 +00007797 // If there is an LValue->RValue conversion, then the value of the
7798 // reference type is used, not the reference.
7799 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7800 if (ICE->getCastKind() == CK_LValueToRValue) {
7801 return;
7802 }
7803 }
Craig Topperda7b27f2015-11-17 05:40:09 +00007804 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7805 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007806 }
7807
7808 // Display the "trail" of reference variables that we followed until we
7809 // found the problematic expression using notes.
7810 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007811 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007812 // If this var binds to another reference var, show the range of the next
7813 // var, otherwise the var binds to the problematic expression, in which case
7814 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007815 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7816 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007817 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7818 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007819 }
7820}
7821
7822/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7823/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007824/// to a location on the stack, a local block, an address of a label, or a
7825/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007826/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007827/// encounter a subexpression that (1) clearly does not lead to one of the
7828/// above problematic expressions (2) is something we cannot determine leads to
7829/// a problematic expression based on such local checking.
7830///
7831/// Both EvalAddr and EvalVal follow through reference variables to evaluate
7832/// the expression that they point to. Such variables are added to the
7833/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007834///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00007835/// EvalAddr processes expressions that are pointers that are used as
7836/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007837/// At the base case of the recursion is a check for the above problematic
7838/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007839///
7840/// This implementation handles:
7841///
7842/// * pointer-to-pointer casts
7843/// * implicit conversions from array references to pointers
7844/// * taking the address of fields
7845/// * arbitrary interplay between "&" and "*" operators
7846/// * pointer arithmetic from an address of a stack variable
7847/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007848static const Expr *EvalAddr(const Expr *E,
7849 SmallVectorImpl<const DeclRefExpr *> &refVars,
7850 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007851 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00007852 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007853
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007854 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00007855 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00007856 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007857 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00007858 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00007859
Peter Collingbourne91147592011-04-15 00:35:48 +00007860 E = E->IgnoreParens();
7861
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007862 // Our "symbolic interpreter" is just a dispatch off the currently
7863 // viewed AST node. We then recursively traverse the AST by calling
7864 // EvalAddr and EvalVal appropriately.
7865 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007866 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007867 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007868
Richard Smith40f08eb2014-01-30 22:05:38 +00007869 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00007870 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00007871 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00007872
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007873 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007874 // If this is a reference variable, follow through to the expression that
7875 // it points to.
7876 if (V->hasLocalStorage() &&
7877 V->getType()->isReferenceType() && V->hasInit()) {
7878 // Add the reference variable to the "trail".
7879 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007880 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007881 }
7882
Craig Topperc3ec1492014-05-26 06:22:03 +00007883 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007884 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007885
Chris Lattner934edb22007-12-28 05:31:15 +00007886 case Stmt::UnaryOperatorClass: {
7887 // The only unary operator that make sense to handle here
7888 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007889 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007890
John McCalle3027922010-08-25 11:45:40 +00007891 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007892 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007893 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007894 }
Mike Stump11289f42009-09-09 15:08:12 +00007895
Chris Lattner934edb22007-12-28 05:31:15 +00007896 case Stmt::BinaryOperatorClass: {
7897 // Handle pointer arithmetic. All other binary operators are not valid
7898 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007899 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00007900 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00007901
John McCalle3027922010-08-25 11:45:40 +00007902 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00007903 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007904
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007905 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00007906
7907 // Determine which argument is the real pointer base. It could be
7908 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007909 if (!Base->getType()->isPointerType())
7910 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00007911
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007912 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007913 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007914 }
Steve Naroff2752a172008-09-10 19:17:48 +00007915
Chris Lattner934edb22007-12-28 05:31:15 +00007916 // For conditional operators we need to see if either the LHS or RHS are
7917 // valid DeclRefExpr*s. If one of them is valid, we return it.
7918 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007919 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007920
Chris Lattner934edb22007-12-28 05:31:15 +00007921 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007922 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007923 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007924 // In C++, we can have a throw-expression, which has 'void' type.
7925 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007926 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007927 return LHS;
7928 }
Chris Lattner934edb22007-12-28 05:31:15 +00007929
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007930 // In C++, we can have a throw-expression, which has 'void' type.
7931 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00007932 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007933
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007934 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007935 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007936
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007937 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00007938 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007939 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00007940 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007941
7942 case Stmt::AddrLabelExprClass:
7943 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00007944
John McCall28fc7092011-11-10 05:35:25 +00007945 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007946 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7947 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00007948
Ted Kremenekc3b4c522008-08-07 00:49:01 +00007949 // For casts, we need to handle conversions from arrays to
7950 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00007951 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00007952 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00007953 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00007954 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00007955 case Stmt::CXXStaticCastExprClass:
7956 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00007957 case Stmt::CXXConstCastExprClass:
7958 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007959 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00007960 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00007961 case CK_LValueToRValue:
7962 case CK_NoOp:
7963 case CK_BaseToDerived:
7964 case CK_DerivedToBase:
7965 case CK_UncheckedDerivedToBase:
7966 case CK_Dynamic:
7967 case CK_CPointerToObjCPointerCast:
7968 case CK_BlockPointerToObjCPointerCast:
7969 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007970 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007971
7972 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007973 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007974
Richard Trieudadefde2014-07-02 04:39:38 +00007975 case CK_BitCast:
7976 if (SubExpr->getType()->isAnyPointerType() ||
7977 SubExpr->getType()->isBlockPointerType() ||
7978 SubExpr->getType()->isObjCQualifiedIdType())
7979 return EvalAddr(SubExpr, refVars, ParentDecl);
7980 else
7981 return nullptr;
7982
Eli Friedman8195ad72012-02-23 23:04:32 +00007983 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007984 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00007985 }
Chris Lattner934edb22007-12-28 05:31:15 +00007986 }
Mike Stump11289f42009-09-09 15:08:12 +00007987
Douglas Gregorfe314812011-06-21 17:03:29 +00007988 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007989 if (const Expr *Result =
7990 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7991 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00007992 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00007993 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007994
Chris Lattner934edb22007-12-28 05:31:15 +00007995 // Everything else: we simply don't reason about them.
7996 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007997 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00007998 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007999}
Mike Stump11289f42009-09-09 15:08:12 +00008000
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008001/// EvalVal - This function is complements EvalAddr in the mutual recursion.
8002/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008003static const Expr *EvalVal(const Expr *E,
8004 SmallVectorImpl<const DeclRefExpr *> &refVars,
8005 const Decl *ParentDecl) {
8006 do {
8007 // We should only be called for evaluating non-pointer expressions, or
8008 // expressions with a pointer type that are not used as references but
8009 // instead
8010 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00008011
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008012 // Our "symbolic interpreter" is just a dispatch off the currently
8013 // viewed AST node. We then recursively traverse the AST by calling
8014 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00008015
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008016 E = E->IgnoreParens();
8017 switch (E->getStmtClass()) {
8018 case Stmt::ImplicitCastExprClass: {
8019 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
8020 if (IE->getValueKind() == VK_LValue) {
8021 E = IE->getSubExpr();
8022 continue;
8023 }
Craig Topperc3ec1492014-05-26 06:22:03 +00008024 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008025 }
Richard Smith40f08eb2014-01-30 22:05:38 +00008026
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008027 case Stmt::ExprWithCleanupsClass:
8028 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
8029 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008030
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008031 case Stmt::DeclRefExprClass: {
8032 // When we hit a DeclRefExpr we are looking at code that refers to a
8033 // variable's name. If it's not a reference variable we check if it has
8034 // local storage within the function, and if so, return the expression.
8035 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
8036
8037 // If we leave the immediate function, the lifetime isn't about to end.
8038 if (DR->refersToEnclosingVariableOrCapture())
8039 return nullptr;
8040
8041 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
8042 // Check if it refers to itself, e.g. "int& i = i;".
8043 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008044 return DR;
8045
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008046 if (V->hasLocalStorage()) {
8047 if (!V->getType()->isReferenceType())
8048 return DR;
8049
8050 // Reference variable, follow through to the expression that
8051 // it points to.
8052 if (V->hasInit()) {
8053 // Add the reference variable to the "trail".
8054 refVars.push_back(DR);
8055 return EvalVal(V->getInit(), refVars, V);
8056 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008057 }
8058 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008059
8060 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008061 }
Mike Stump11289f42009-09-09 15:08:12 +00008062
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008063 case Stmt::UnaryOperatorClass: {
8064 // The only unary operator that make sense to handle here
8065 // is Deref. All others don't resolve to a "name." This includes
8066 // handling all sorts of rvalues passed to a unary operator.
8067 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00008068
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008069 if (U->getOpcode() == UO_Deref)
8070 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00008071
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008072 return nullptr;
8073 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008074
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008075 case Stmt::ArraySubscriptExprClass: {
8076 // Array subscripts are potential references to data on the stack. We
8077 // retrieve the DeclRefExpr* for the array variable if it indeed
8078 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00008079 const auto *ASE = cast<ArraySubscriptExpr>(E);
8080 if (ASE->isTypeDependent())
8081 return nullptr;
8082 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008083 }
Mike Stump11289f42009-09-09 15:08:12 +00008084
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008085 case Stmt::OMPArraySectionExprClass: {
8086 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
8087 ParentDecl);
8088 }
Mike Stump11289f42009-09-09 15:08:12 +00008089
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008090 case Stmt::ConditionalOperatorClass: {
8091 // For conditional operators we need to see if either the LHS or RHS are
8092 // non-NULL Expr's. If one is non-NULL, we return it.
8093 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00008094
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008095 // Handle the GNU extension for missing LHS.
8096 if (const Expr *LHSExpr = C->getLHS()) {
8097 // In C++, we can have a throw-expression, which has 'void' type.
8098 if (!LHSExpr->getType()->isVoidType())
8099 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
8100 return LHS;
8101 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008102
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008103 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008104 if (C->getRHS()->getType()->isVoidType())
8105 return nullptr;
8106
8107 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008108 }
8109
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008110 // Accesses to members are potential references to data on the stack.
8111 case Stmt::MemberExprClass: {
8112 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00008113
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008114 // Check for indirect access. We only want direct field accesses.
8115 if (M->isArrow())
8116 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008117
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008118 // Check whether the member type is itself a reference, in which case
8119 // we're not going to refer to the member, but to what the member refers
8120 // to.
8121 if (M->getMemberDecl()->getType()->isReferenceType())
8122 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008123
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008124 return EvalVal(M->getBase(), refVars, ParentDecl);
8125 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00008126
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008127 case Stmt::MaterializeTemporaryExprClass:
8128 if (const Expr *Result =
8129 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8130 refVars, ParentDecl))
8131 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008132 return E;
8133
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008134 default:
8135 // Check that we don't return or take the address of a reference to a
8136 // temporary. This is only useful in C++.
8137 if (!E->isTypeDependent() && E->isRValue())
8138 return E;
8139
8140 // Everything else: we simply don't reason about them.
8141 return nullptr;
8142 }
8143 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008144}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008145
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008146void
8147Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
8148 SourceLocation ReturnLoc,
8149 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00008150 const AttrVec *Attrs,
8151 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008152 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
8153
8154 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00008155 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
8156 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00008157 CheckNonNullExpr(*this, RetValExp))
8158 Diag(ReturnLoc, diag::warn_null_ret)
8159 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00008160
8161 // C++11 [basic.stc.dynamic.allocation]p4:
8162 // If an allocation function declared with a non-throwing
8163 // exception-specification fails to allocate storage, it shall return
8164 // a null pointer. Any other allocation function that fails to allocate
8165 // storage shall indicate failure only by throwing an exception [...]
8166 if (FD) {
8167 OverloadedOperatorKind Op = FD->getOverloadedOperator();
8168 if (Op == OO_New || Op == OO_Array_New) {
8169 const FunctionProtoType *Proto
8170 = FD->getType()->castAs<FunctionProtoType>();
8171 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
8172 CheckNonNullExpr(*this, RetValExp))
8173 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
8174 << FD << getLangOpts().CPlusPlus11;
8175 }
8176 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008177}
8178
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008179//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
8180
8181/// Check for comparisons of floating point operands using != and ==.
8182/// Issue a warning if these are no self-comparisons, as they are not likely
8183/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00008184void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00008185 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
8186 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008187
8188 // Special case: check for x == x (which is OK).
8189 // Do not emit warnings for such cases.
8190 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
8191 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
8192 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00008193 return;
Mike Stump11289f42009-09-09 15:08:12 +00008194
Ted Kremenekeda40e22007-11-29 00:59:04 +00008195 // Special case: check for comparisons against literals that can be exactly
8196 // represented by APFloat. In such cases, do not emit a warning. This
8197 // is a heuristic: often comparison against such literals are used to
8198 // detect if a value in a variable has not changed. This clearly can
8199 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00008200 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
8201 if (FLL->isExact())
8202 return;
8203 } else
8204 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
8205 if (FLR->isExact())
8206 return;
Mike Stump11289f42009-09-09 15:08:12 +00008207
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008208 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00008209 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00008210 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00008211 return;
Mike Stump11289f42009-09-09 15:08:12 +00008212
David Blaikie1f4ff152012-07-16 20:47:22 +00008213 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00008214 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00008215 return;
Mike Stump11289f42009-09-09 15:08:12 +00008216
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008217 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00008218 Diag(Loc, diag::warn_floatingpoint_eq)
8219 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008220}
John McCallca01b222010-01-04 23:21:16 +00008221
John McCall70aa5392010-01-06 05:24:50 +00008222//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
8223//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00008224
John McCall70aa5392010-01-06 05:24:50 +00008225namespace {
John McCallca01b222010-01-04 23:21:16 +00008226
John McCall70aa5392010-01-06 05:24:50 +00008227/// Structure recording the 'active' range of an integer-valued
8228/// expression.
8229struct IntRange {
8230 /// The number of bits active in the int.
8231 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00008232
John McCall70aa5392010-01-06 05:24:50 +00008233 /// True if the int is known not to have negative values.
8234 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00008235
John McCall70aa5392010-01-06 05:24:50 +00008236 IntRange(unsigned Width, bool NonNegative)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008237 : Width(Width), NonNegative(NonNegative) {}
John McCallca01b222010-01-04 23:21:16 +00008238
John McCall817d4af2010-11-10 23:38:19 +00008239 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00008240 static IntRange forBoolType() {
8241 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00008242 }
8243
John McCall817d4af2010-11-10 23:38:19 +00008244 /// Returns the range of an opaque value of the given integral type.
8245 static IntRange forValueOfType(ASTContext &C, QualType T) {
8246 return forValueOfCanonicalType(C,
8247 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00008248 }
8249
John McCall817d4af2010-11-10 23:38:19 +00008250 /// Returns the range of an opaque value of a canonical integral type.
8251 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00008252 assert(T->isCanonicalUnqualified());
8253
8254 if (const VectorType *VT = dyn_cast<VectorType>(T))
8255 T = VT->getElementType().getTypePtr();
8256 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8257 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008258 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8259 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00008260
Roman Lebedevca1aaac2017-10-21 16:44:03 +00008261 if (!C.getLangOpts().CPlusPlus) {
8262 // For enum types in C code, use the underlying datatype.
8263 if (const EnumType *ET = dyn_cast<EnumType>(T))
8264 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
8265 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
8266 // For enum types in C++, use the known bit width of the enumerators.
David Majnemer6a426652013-06-07 22:07:20 +00008267 EnumDecl *Enum = ET->getDecl();
Richard Smith371e9e8a2017-12-06 03:00:51 +00008268 // In C++11, enums can have a fixed underlying type. Use this type to
8269 // compute the range.
8270 if (Enum->isFixed()) {
Erich Keane69dbbb02017-09-21 19:58:55 +00008271 return IntRange(C.getIntWidth(QualType(T, 0)),
8272 !ET->isSignedIntegerOrEnumerationType());
Richard Smith371e9e8a2017-12-06 03:00:51 +00008273 }
John McCall18a2c2c2010-11-09 22:22:12 +00008274
David Majnemer6a426652013-06-07 22:07:20 +00008275 unsigned NumPositive = Enum->getNumPositiveBits();
8276 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00008277
David Majnemer6a426652013-06-07 22:07:20 +00008278 if (NumNegative == 0)
8279 return IntRange(NumPositive, true/*NonNegative*/);
8280 else
8281 return IntRange(std::max(NumPositive + 1, NumNegative),
8282 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00008283 }
John McCall70aa5392010-01-06 05:24:50 +00008284
8285 const BuiltinType *BT = cast<BuiltinType>(T);
8286 assert(BT->isInteger());
8287
8288 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8289 }
8290
John McCall817d4af2010-11-10 23:38:19 +00008291 /// Returns the "target" range of a canonical integral type, i.e.
8292 /// the range of values expressible in the type.
8293 ///
8294 /// This matches forValueOfCanonicalType except that enums have the
8295 /// full range of their type, not the range of their enumerators.
8296 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
8297 assert(T->isCanonicalUnqualified());
8298
8299 if (const VectorType *VT = dyn_cast<VectorType>(T))
8300 T = VT->getElementType().getTypePtr();
8301 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8302 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008303 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8304 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008305 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00008306 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008307
8308 const BuiltinType *BT = cast<BuiltinType>(T);
8309 assert(BT->isInteger());
8310
8311 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8312 }
8313
8314 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00008315 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00008316 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00008317 L.NonNegative && R.NonNegative);
8318 }
8319
John McCall817d4af2010-11-10 23:38:19 +00008320 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00008321 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00008322 return IntRange(std::min(L.Width, R.Width),
8323 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00008324 }
8325};
8326
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008327} // namespace
8328
8329static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
8330 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008331 if (value.isSigned() && value.isNegative())
8332 return IntRange(value.getMinSignedBits(), false);
8333
8334 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00008335 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008336
8337 // isNonNegative() just checks the sign bit without considering
8338 // signedness.
8339 return IntRange(value.getActiveBits(), true);
8340}
8341
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008342static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
8343 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008344 if (result.isInt())
8345 return GetValueRange(C, result.getInt(), MaxWidth);
8346
8347 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00008348 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
8349 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
8350 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
8351 R = IntRange::join(R, El);
8352 }
John McCall70aa5392010-01-06 05:24:50 +00008353 return R;
8354 }
8355
8356 if (result.isComplexInt()) {
8357 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
8358 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
8359 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00008360 }
8361
8362 // This can happen with lossless casts to intptr_t of "based" lvalues.
8363 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00008364 // FIXME: The only reason we need to pass the type in here is to get
8365 // the sign right on this one case. It would be nice if APValue
8366 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008367 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00008368 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00008369}
John McCall70aa5392010-01-06 05:24:50 +00008370
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008371static QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008372 QualType Ty = E->getType();
8373 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
8374 Ty = AtomicRHS->getValueType();
8375 return Ty;
8376}
8377
John McCall70aa5392010-01-06 05:24:50 +00008378/// Pseudo-evaluate the given integer expression, estimating the
8379/// range of values it might take.
8380///
8381/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008382static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008383 E = E->IgnoreParens();
8384
8385 // Try a full evaluation first.
8386 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00008387 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00008388 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008389
8390 // I think we only want to look through implicit casts here; if the
8391 // user has an explicit widening cast, we should treat the value as
8392 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008393 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00008394 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00008395 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
8396
Eli Friedmane6d33952013-07-08 20:20:06 +00008397 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00008398
George Burgess IVdf1ed002016-01-13 01:52:39 +00008399 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
8400 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00008401
John McCall70aa5392010-01-06 05:24:50 +00008402 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00008403 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00008404 return OutputTypeRange;
8405
8406 IntRange SubRange
8407 = GetExprRange(C, CE->getSubExpr(),
8408 std::min(MaxWidth, OutputTypeRange.Width));
8409
8410 // Bail out if the subexpr's range is as wide as the cast type.
8411 if (SubRange.Width >= OutputTypeRange.Width)
8412 return OutputTypeRange;
8413
8414 // Otherwise, we take the smaller width, and we're non-negative if
8415 // either the output type or the subexpr is.
8416 return IntRange(SubRange.Width,
8417 SubRange.NonNegative || OutputTypeRange.NonNegative);
8418 }
8419
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008420 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008421 // If we can fold the condition, just take that operand.
8422 bool CondResult;
8423 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
8424 return GetExprRange(C, CondResult ? CO->getTrueExpr()
8425 : CO->getFalseExpr(),
8426 MaxWidth);
8427
8428 // Otherwise, conservatively merge.
8429 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
8430 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
8431 return IntRange::join(L, R);
8432 }
8433
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008434 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008435 switch (BO->getOpcode()) {
Richard Smithc70f1d62017-12-14 15:16:18 +00008436 case BO_Cmp:
8437 llvm_unreachable("builtin <=> should have class type");
John McCall70aa5392010-01-06 05:24:50 +00008438
8439 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00008440 case BO_LAnd:
8441 case BO_LOr:
8442 case BO_LT:
8443 case BO_GT:
8444 case BO_LE:
8445 case BO_GE:
8446 case BO_EQ:
8447 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00008448 return IntRange::forBoolType();
8449
John McCallc3688382011-07-13 06:35:24 +00008450 // The type of the assignments is the type of the LHS, so the RHS
8451 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00008452 case BO_MulAssign:
8453 case BO_DivAssign:
8454 case BO_RemAssign:
8455 case BO_AddAssign:
8456 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00008457 case BO_XorAssign:
8458 case BO_OrAssign:
8459 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00008460 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00008461
John McCallc3688382011-07-13 06:35:24 +00008462 // Simple assignments just pass through the RHS, which will have
8463 // been coerced to the LHS type.
8464 case BO_Assign:
8465 // TODO: bitfields?
8466 return GetExprRange(C, BO->getRHS(), MaxWidth);
8467
John McCall70aa5392010-01-06 05:24:50 +00008468 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008469 case BO_PtrMemD:
8470 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00008471 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008472
John McCall2ce81ad2010-01-06 22:07:33 +00008473 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00008474 case BO_And:
8475 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00008476 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8477 GetExprRange(C, BO->getRHS(), MaxWidth));
8478
John McCall70aa5392010-01-06 05:24:50 +00008479 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00008480 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00008481 // ...except that we want to treat '1 << (blah)' as logically
8482 // positive. It's an important idiom.
8483 if (IntegerLiteral *I
8484 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8485 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008486 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00008487 return IntRange(R.Width, /*NonNegative*/ true);
8488 }
8489 }
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008490 LLVM_FALLTHROUGH;
John McCall1bff9932010-04-07 01:14:35 +00008491
John McCalle3027922010-08-25 11:45:40 +00008492 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00008493 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008494
John McCall2ce81ad2010-01-06 22:07:33 +00008495 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00008496 case BO_Shr:
8497 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00008498 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8499
8500 // If the shift amount is a positive constant, drop the width by
8501 // that much.
8502 llvm::APSInt shift;
8503 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8504 shift.isNonNegative()) {
8505 unsigned zext = shift.getZExtValue();
8506 if (zext >= L.Width)
8507 L.Width = (L.NonNegative ? 0 : 1);
8508 else
8509 L.Width -= zext;
8510 }
8511
8512 return L;
8513 }
8514
8515 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00008516 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00008517 return GetExprRange(C, BO->getRHS(), MaxWidth);
8518
John McCall2ce81ad2010-01-06 22:07:33 +00008519 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00008520 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00008521 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00008522 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008523 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00008524
John McCall51431812011-07-14 22:39:48 +00008525 // The width of a division result is mostly determined by the size
8526 // of the LHS.
8527 case BO_Div: {
8528 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008529 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008530 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8531
8532 // If the divisor is constant, use that.
8533 llvm::APSInt divisor;
8534 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8535 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8536 if (log2 >= L.Width)
8537 L.Width = (L.NonNegative ? 0 : 1);
8538 else
8539 L.Width = std::min(L.Width - log2, MaxWidth);
8540 return L;
8541 }
8542
8543 // Otherwise, just use the LHS's width.
8544 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8545 return IntRange(L.Width, L.NonNegative && R.NonNegative);
8546 }
8547
8548 // The result of a remainder can't be larger than the result of
8549 // either side.
8550 case BO_Rem: {
8551 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008552 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008553 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8554 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8555
8556 IntRange meet = IntRange::meet(L, R);
8557 meet.Width = std::min(meet.Width, MaxWidth);
8558 return meet;
8559 }
8560
8561 // The default behavior is okay for these.
8562 case BO_Mul:
8563 case BO_Add:
8564 case BO_Xor:
8565 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00008566 break;
8567 }
8568
John McCall51431812011-07-14 22:39:48 +00008569 // The default case is to treat the operation as if it were closed
8570 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00008571 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8572 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8573 return IntRange::join(L, R);
8574 }
8575
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008576 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008577 switch (UO->getOpcode()) {
8578 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00008579 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00008580 return IntRange::forBoolType();
8581
8582 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008583 case UO_Deref:
8584 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00008585 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008586
8587 default:
8588 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8589 }
8590 }
8591
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008592 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00008593 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8594
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008595 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00008596 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00008597 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00008598
Eli Friedmane6d33952013-07-08 20:20:06 +00008599 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008600}
John McCall263a48b2010-01-04 23:31:57 +00008601
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008602static IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008603 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00008604}
8605
John McCall263a48b2010-01-04 23:31:57 +00008606/// Checks whether the given value, which currently has the given
8607/// source semantics, has the same value when coerced through the
8608/// target semantics.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008609static bool IsSameFloatAfterCast(const llvm::APFloat &value,
8610 const llvm::fltSemantics &Src,
8611 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008612 llvm::APFloat truncated = value;
8613
8614 bool ignored;
8615 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8616 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8617
8618 return truncated.bitwiseIsEqual(value);
8619}
8620
8621/// Checks whether the given value, which currently has the given
8622/// source semantics, has the same value when coerced through the
8623/// target semantics.
8624///
8625/// The value might be a vector of floats (or a complex number).
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008626static bool IsSameFloatAfterCast(const APValue &value,
8627 const llvm::fltSemantics &Src,
8628 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008629 if (value.isFloat())
8630 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8631
8632 if (value.isVector()) {
8633 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8634 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8635 return false;
8636 return true;
8637 }
8638
8639 assert(value.isComplexFloat());
8640 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8641 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8642}
8643
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008644static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008645
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008646static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00008647 // Suppress cases where we are comparing against an enum constant.
8648 if (const DeclRefExpr *DR =
8649 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8650 if (isa<EnumConstantDecl>(DR->getDecl()))
Roman Lebedev6de129e2017-10-15 20:13:17 +00008651 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +00008652
8653 // Suppress cases where the '0' value is expanded from a macro.
8654 if (E->getLocStart().isMacroID())
Roman Lebedev6de129e2017-10-15 20:13:17 +00008655 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +00008656
Roman Lebedev6de129e2017-10-15 20:13:17 +00008657 return false;
8658}
8659
Richard Smith692f66ab2017-12-06 19:23:19 +00008660static bool isKnownToHaveUnsignedValue(Expr *E) {
8661 return E->getType()->isIntegerType() &&
Roman Lebedev6de129e2017-10-15 20:13:17 +00008662 (!E->getType()->isSignedIntegerType() ||
8663 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
8664}
8665
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008666namespace {
Richard Smitha5370fb2017-12-08 22:57:11 +00008667/// The promoted range of values of a type. In general this has the
8668/// following structure:
8669///
8670/// |-----------| . . . |-----------|
8671/// ^ ^ ^ ^
8672/// Min HoleMin HoleMax Max
8673///
8674/// ... where there is only a hole if a signed type is promoted to unsigned
8675/// (in which case Min and Max are the smallest and largest representable
8676/// values).
8677struct PromotedRange {
8678 // Min, or HoleMax if there is a hole.
8679 llvm::APSInt PromotedMin;
8680 // Max, or HoleMin if there is a hole.
8681 llvm::APSInt PromotedMax;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008682
Richard Smitha5370fb2017-12-08 22:57:11 +00008683 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
8684 if (R.Width == 0)
8685 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
8686 else if (R.Width >= BitWidth && !Unsigned) {
8687 // Promotion made the type *narrower*. This happens when promoting
8688 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
8689 // Treat all values of 'signed int' as being in range for now.
8690 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
8691 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
8692 } else {
8693 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
8694 .extOrTrunc(BitWidth);
8695 PromotedMin.setIsUnsigned(Unsigned);
8696
8697 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
8698 .extOrTrunc(BitWidth);
8699 PromotedMax.setIsUnsigned(Unsigned);
8700 }
8701 }
8702
8703 // Determine whether this range is contiguous (has no hole).
8704 bool isContiguous() const { return PromotedMin <= PromotedMax; }
8705
8706 // Where a constant value is within the range.
8707 enum ComparisonResult {
8708 LT = 0x1,
8709 LE = 0x2,
8710 GT = 0x4,
8711 GE = 0x8,
8712 EQ = 0x10,
8713 NE = 0x20,
8714 InRangeFlag = 0x40,
8715
8716 Less = LE | LT | NE,
8717 Min = LE | InRangeFlag,
8718 InRange = InRangeFlag,
8719 Max = GE | InRangeFlag,
8720 Greater = GE | GT | NE,
8721
8722 OnlyValue = LE | GE | EQ | InRangeFlag,
8723 InHole = NE
8724 };
8725
8726 ComparisonResult compare(const llvm::APSInt &Value) const {
8727 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
8728 Value.isUnsigned() == PromotedMin.isUnsigned());
8729 if (!isContiguous()) {
8730 assert(Value.isUnsigned() && "discontiguous range for signed compare");
8731 if (Value.isMinValue()) return Min;
8732 if (Value.isMaxValue()) return Max;
8733 if (Value >= PromotedMin) return InRange;
8734 if (Value <= PromotedMax) return InRange;
8735 return InHole;
8736 }
8737
8738 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
8739 case -1: return Less;
8740 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
8741 case 1:
8742 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
8743 case -1: return InRange;
8744 case 0: return Max;
8745 case 1: return Greater;
8746 }
8747 }
8748
8749 llvm_unreachable("impossible compare result");
8750 }
8751
Richard Smithc70f1d62017-12-14 15:16:18 +00008752 static llvm::Optional<StringRef>
8753 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
8754 if (Op == BO_Cmp) {
8755 ComparisonResult LTFlag = LT, GTFlag = GT;
8756 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
8757
8758 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
8759 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
8760 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
8761 return llvm::None;
8762 }
8763
Richard Smitha5370fb2017-12-08 22:57:11 +00008764 ComparisonResult TrueFlag, FalseFlag;
8765 if (Op == BO_EQ) {
8766 TrueFlag = EQ;
8767 FalseFlag = NE;
8768 } else if (Op == BO_NE) {
8769 TrueFlag = NE;
8770 FalseFlag = EQ;
8771 } else {
8772 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
8773 TrueFlag = LT;
8774 FalseFlag = GE;
8775 } else {
8776 TrueFlag = GT;
8777 FalseFlag = LE;
8778 }
8779 if (Op == BO_GE || Op == BO_LE)
8780 std::swap(TrueFlag, FalseFlag);
8781 }
8782 if (R & TrueFlag)
Richard Smithc70f1d62017-12-14 15:16:18 +00008783 return StringRef("true");
Richard Smitha5370fb2017-12-08 22:57:11 +00008784 if (R & FalseFlag)
Richard Smithc70f1d62017-12-14 15:16:18 +00008785 return StringRef("false");
Richard Smitha5370fb2017-12-08 22:57:11 +00008786 return llvm::None;
8787 }
Roman Lebedev6de129e2017-10-15 20:13:17 +00008788};
John McCallcc7e5bf2010-05-06 08:58:33 +00008789}
8790
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008791static bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00008792 // Strip off implicit integral promotions.
8793 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008794 if (ICE->getCastKind() != CK_IntegralCast &&
8795 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00008796 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008797 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00008798 }
8799
8800 return E->getType()->isEnumeralType();
8801}
8802
Richard Smith692f66ab2017-12-06 19:23:19 +00008803static int classifyConstantValue(Expr *Constant) {
8804 // The values of this enumeration are used in the diagnostics
8805 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
8806 enum ConstantValueKind {
8807 Miscellaneous = 0,
8808 LiteralTrue,
8809 LiteralFalse
8810 };
8811 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
8812 return BL->getValue() ? ConstantValueKind::LiteralTrue
8813 : ConstantValueKind::LiteralFalse;
8814 return ConstantValueKind::Miscellaneous;
8815}
8816
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008817static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
8818 Expr *Constant, Expr *Other,
8819 const llvm::APSInt &Value,
8820 bool RhsConstant) {
Hans Wennborg5bb88e02017-12-08 05:19:12 +00008821 if (S.inTemplateInstantiation())
8822 return false;
8823
Richard Smitha5370fb2017-12-08 22:57:11 +00008824 Expr *OriginalOther = Other;
8825
Hans Wennborg5bb88e02017-12-08 05:19:12 +00008826 Constant = Constant->IgnoreParenImpCasts();
8827 Other = Other->IgnoreParenImpCasts();
8828
Richard Smitha5370fb2017-12-08 22:57:11 +00008829 // Suppress warnings on tautological comparisons between values of the same
8830 // enumeration type. There are only two ways we could warn on this:
8831 // - If the constant is outside the range of representable values of
8832 // the enumeration. In such a case, we should warn about the cast
8833 // to enumeration type, not about the comparison.
8834 // - If the constant is the maximum / minimum in-range value. For an
8835 // enumeratin type, such comparisons can be meaningful and useful.
8836 if (Constant->getType()->isEnumeralType() &&
8837 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
8838 return false;
8839
Hans Wennborg5bb88e02017-12-08 05:19:12 +00008840 // TODO: Investigate using GetExprRange() to get tighter bounds
8841 // on the bit ranges.
8842 QualType OtherT = Other->getType();
8843 if (const auto *AT = OtherT->getAs<AtomicType>())
8844 OtherT = AT->getValueType();
8845 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8846
8847 // Whether we're treating Other as being a bool because of the form of
8848 // expression despite it having another type (typically 'int' in C).
8849 bool OtherIsBooleanDespiteType =
8850 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
8851 if (OtherIsBooleanDespiteType)
8852 OtherRange = IntRange::forBoolType();
8853
Richard Smitha5370fb2017-12-08 22:57:11 +00008854 // Determine the promoted range of the other type and see if a comparison of
8855 // the constant against that range is tautological.
8856 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
8857 Value.isUnsigned());
8858 auto Cmp = OtherPromotedRange.compare(Value);
8859 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
8860 if (!Result)
8861 return false;
Hans Wennborg5791ce72017-12-08 16:54:08 +00008862
Richard Smitha5370fb2017-12-08 22:57:11 +00008863 // Suppress the diagnostic for an in-range comparison if the constant comes
8864 // from a macro or enumerator. We don't want to diagnose
8865 //
8866 // some_long_value <= INT_MAX
8867 //
8868 // when sizeof(int) == sizeof(long).
8869 bool InRange = Cmp & PromotedRange::InRangeFlag;
8870 if (InRange && IsEnumConstOrFromMacro(S, Constant))
8871 return false;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008872
8873 // If this is a comparison to an enum constant, include that
8874 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00008875 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008876 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8877 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8878
Richard Smitha5370fb2017-12-08 22:57:11 +00008879 // Should be enough for uint128 (39 decimal digits)
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008880 SmallString<64> PrettySourceValue;
8881 llvm::raw_svector_ostream OS(PrettySourceValue);
8882 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00008883 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008884 else
8885 OS << Value;
8886
Richard Smitha5370fb2017-12-08 22:57:11 +00008887 // FIXME: We use a somewhat different formatting for the in-range cases and
8888 // cases involving boolean values for historical reasons. We should pick a
8889 // consistent way of presenting these diagnostics.
8890 if (!InRange || Other->isKnownToHaveBooleanValue()) {
8891 S.DiagRuntimeBehavior(
8892 E->getOperatorLoc(), E,
8893 S.PDiag(!InRange ? diag::warn_out_of_range_compare
8894 : diag::warn_tautological_bool_compare)
8895 << OS.str() << classifyConstantValue(Constant)
8896 << OtherT << OtherIsBooleanDespiteType << *Result
8897 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
8898 } else {
8899 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
8900 ? (HasEnumType(OriginalOther)
8901 ? diag::warn_unsigned_enum_always_true_comparison
8902 : diag::warn_unsigned_always_true_comparison)
8903 : diag::warn_tautological_constant_compare;
Roman Lebedev6de129e2017-10-15 20:13:17 +00008904
Richard Smitha5370fb2017-12-08 22:57:11 +00008905 S.Diag(E->getOperatorLoc(), Diag)
8906 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
8907 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8908 }
8909
8910 return true;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008911}
8912
John McCallcc7e5bf2010-05-06 08:58:33 +00008913/// Analyze the operands of the given comparison. Implements the
8914/// fallback case from AnalyzeComparison.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008915static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00008916 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8917 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00008918}
John McCall263a48b2010-01-04 23:31:57 +00008919
John McCallca01b222010-01-04 23:21:16 +00008920/// \brief Implements -Wsign-compare.
8921///
Richard Trieu82402a02011-09-15 21:56:47 +00008922/// \param E the binary operator to check for warnings
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008923static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008924 // The type the comparison is being performed in.
8925 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00008926
8927 // Only analyze comparison operators where both sides have been converted to
8928 // the same type.
8929 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8930 return AnalyzeImpConvsInComparison(S, E);
8931
8932 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00008933 if (E->isValueDependent())
8934 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008935
Roman Lebedev6de129e2017-10-15 20:13:17 +00008936 Expr *LHS = E->getLHS();
8937 Expr *RHS = E->getRHS();
8938
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008939 if (T->isIntegralType(S.Context)) {
8940 llvm::APSInt RHSValue;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008941 llvm::APSInt LHSValue;
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008942
Roman Lebedev6de129e2017-10-15 20:13:17 +00008943 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
8944 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
Roman Lebedevbd1fc222017-10-12 20:16:51 +00008945
Roman Lebedev6de129e2017-10-15 20:13:17 +00008946 // We don't care about expressions whose result is a constant.
8947 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8948 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6f405db2017-10-12 22:03:20 +00008949
Roman Lebedev6de129e2017-10-15 20:13:17 +00008950 // We only care about expressions where just one side is literal
8951 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
8952 // Is the constant on the RHS or LHS?
8953 const bool RhsConstant = IsRHSIntegralLiteral;
8954 Expr *Const = RhsConstant ? RHS : LHS;
8955 Expr *Other = RhsConstant ? LHS : RHS;
8956 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
8957
8958 // Check whether an integer constant comparison results in a value
8959 // of 'true' or 'false'.
Roman Lebedev6de129e2017-10-15 20:13:17 +00008960 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
8961 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6de129e2017-10-15 20:13:17 +00008962 }
8963 }
8964
8965 if (!T->hasUnsignedIntegerRepresentation()) {
8966 // We don't do anything special if this isn't an unsigned integral
8967 // comparison: we're only interested in integral comparisons, and
8968 // signed comparisons only happen in cases we don't care to warn about.
Roman Lebedev6f405db2017-10-12 22:03:20 +00008969 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6de129e2017-10-15 20:13:17 +00008970 }
8971
8972 LHS = LHS->IgnoreParenImpCasts();
8973 RHS = RHS->IgnoreParenImpCasts();
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008974
John McCallcc7e5bf2010-05-06 08:58:33 +00008975 // Check to see if one of the (unmodified) operands is of different
8976 // signedness.
8977 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00008978 if (LHS->getType()->hasSignedIntegerRepresentation()) {
8979 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00008980 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00008981 signedOperand = LHS;
8982 unsignedOperand = RHS;
8983 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
8984 signedOperand = RHS;
8985 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00008986 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00008987 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008988 }
8989
John McCallcc7e5bf2010-05-06 08:58:33 +00008990 // Otherwise, calculate the effective range of the signed operand.
8991 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00008992
John McCallcc7e5bf2010-05-06 08:58:33 +00008993 // Go ahead and analyze implicit conversions in the operands. Note
8994 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00008995 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
8996 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00008997
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008998 // If the signed range is non-negative, -Wsign-compare won't fire.
John McCallcc7e5bf2010-05-06 08:58:33 +00008999 if (signedRange.NonNegative)
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009000 return;
John McCallca01b222010-01-04 23:21:16 +00009001
9002 // For (in)equality comparisons, if the unsigned operand is a
9003 // constant which cannot collide with a overflowed signed operand,
9004 // then reinterpreting the signed operand as unsigned will not
9005 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00009006 if (E->isEqualityOp()) {
9007 unsigned comparisonWidth = S.Context.getIntWidth(T);
9008 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00009009
John McCallcc7e5bf2010-05-06 08:58:33 +00009010 // We should never be unable to prove that the unsigned operand is
9011 // non-negative.
9012 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
9013
9014 if (unsignedRange.Width < comparisonWidth)
9015 return;
9016 }
9017
Douglas Gregorbfb4a212012-05-01 01:53:49 +00009018 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
9019 S.PDiag(diag::warn_mixed_sign_comparison)
9020 << LHS->getType() << RHS->getType()
9021 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00009022}
9023
John McCall1f425642010-11-11 03:21:53 +00009024/// Analyzes an attempt to assign the given value to a bitfield.
9025///
9026/// Returns true if there was something fishy about the attempt.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009027static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
9028 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00009029 assert(Bitfield->isBitField());
9030 if (Bitfield->isInvalidDecl())
9031 return false;
9032
John McCalldeebbcf2010-11-11 05:33:51 +00009033 // White-list bool bitfields.
Reid Klecknerad425622016-11-16 23:40:00 +00009034 QualType BitfieldType = Bitfield->getType();
9035 if (BitfieldType->isBooleanType())
9036 return false;
9037
9038 if (BitfieldType->isEnumeralType()) {
9039 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
9040 // If the underlying enum type was not explicitly specified as an unsigned
9041 // type and the enum contain only positive values, MSVC++ will cause an
9042 // inconsistency by storing this as a signed type.
9043 if (S.getLangOpts().CPlusPlus11 &&
9044 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
9045 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
9046 BitfieldEnumDecl->getNumNegativeBits() == 0) {
9047 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
9048 << BitfieldEnumDecl->getNameAsString();
9049 }
9050 }
9051
John McCalldeebbcf2010-11-11 05:33:51 +00009052 if (Bitfield->getType()->isBooleanType())
9053 return false;
9054
Douglas Gregor789adec2011-02-04 13:09:01 +00009055 // Ignore value- or type-dependent expressions.
9056 if (Bitfield->getBitWidth()->isValueDependent() ||
9057 Bitfield->getBitWidth()->isTypeDependent() ||
9058 Init->isValueDependent() ||
9059 Init->isTypeDependent())
9060 return false;
9061
John McCall1f425642010-11-11 03:21:53 +00009062 Expr *OriginalInit = Init->IgnoreParenImpCasts();
Reid Kleckner329f24d2017-03-14 18:01:02 +00009063 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00009064
Richard Smith5fab0c92011-12-28 19:48:30 +00009065 llvm::APSInt Value;
Reid Kleckner329f24d2017-03-14 18:01:02 +00009066 if (!OriginalInit->EvaluateAsInt(Value, S.Context,
9067 Expr::SE_AllowSideEffects)) {
9068 // The RHS is not constant. If the RHS has an enum type, make sure the
9069 // bitfield is wide enough to hold all the values of the enum without
9070 // truncation.
9071 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
9072 EnumDecl *ED = EnumTy->getDecl();
9073 bool SignedBitfield = BitfieldType->isSignedIntegerType();
9074
9075 // Enum types are implicitly signed on Windows, so check if there are any
9076 // negative enumerators to see if the enum was intended to be signed or
9077 // not.
9078 bool SignedEnum = ED->getNumNegativeBits() > 0;
9079
9080 // Check for surprising sign changes when assigning enum values to a
9081 // bitfield of different signedness. If the bitfield is signed and we
9082 // have exactly the right number of bits to store this unsigned enum,
9083 // suggest changing the enum to an unsigned type. This typically happens
9084 // on Windows where unfixed enums always use an underlying type of 'int'.
9085 unsigned DiagID = 0;
9086 if (SignedEnum && !SignedBitfield) {
9087 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
9088 } else if (SignedBitfield && !SignedEnum &&
9089 ED->getNumPositiveBits() == FieldWidth) {
9090 DiagID = diag::warn_signed_bitfield_enum_conversion;
9091 }
9092
9093 if (DiagID) {
9094 S.Diag(InitLoc, DiagID) << Bitfield << ED;
9095 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
9096 SourceRange TypeRange =
9097 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
9098 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
9099 << SignedEnum << TypeRange;
9100 }
9101
9102 // Compute the required bitwidth. If the enum has negative values, we need
9103 // one more bit than the normal number of positive bits to represent the
9104 // sign bit.
9105 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
9106 ED->getNumNegativeBits())
9107 : ED->getNumPositiveBits();
9108
9109 // Check the bitwidth.
9110 if (BitsNeeded > FieldWidth) {
9111 Expr *WidthExpr = Bitfield->getBitWidth();
9112 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
9113 << Bitfield << ED;
9114 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
9115 << BitsNeeded << ED << WidthExpr->getSourceRange();
9116 }
9117 }
9118
John McCall1f425642010-11-11 03:21:53 +00009119 return false;
Reid Kleckner329f24d2017-03-14 18:01:02 +00009120 }
John McCall1f425642010-11-11 03:21:53 +00009121
John McCall1f425642010-11-11 03:21:53 +00009122 unsigned OriginalWidth = Value.getBitWidth();
John McCall1f425642010-11-11 03:21:53 +00009123
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00009124 if (!Value.isSigned() || Value.isNegative())
Richard Trieu7561ed02016-08-05 02:39:30 +00009125 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00009126 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
9127 OriginalWidth = Value.getMinSignedBits();
Richard Trieu7561ed02016-08-05 02:39:30 +00009128
John McCall1f425642010-11-11 03:21:53 +00009129 if (OriginalWidth <= FieldWidth)
9130 return false;
9131
Eli Friedmanc267a322012-01-26 23:11:39 +00009132 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00009133 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Reid Klecknerad425622016-11-16 23:40:00 +00009134 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00009135
Eli Friedmanc267a322012-01-26 23:11:39 +00009136 // Check whether the stored value is equal to the original value.
9137 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00009138 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00009139 return false;
9140
Eli Friedmanc267a322012-01-26 23:11:39 +00009141 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00009142 // therefore don't strictly fit into a signed bitfield of width 1.
9143 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00009144 return false;
9145
John McCall1f425642010-11-11 03:21:53 +00009146 std::string PrettyValue = Value.toString(10);
9147 std::string PrettyTrunc = TruncatedValue.toString(10);
9148
9149 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
9150 << PrettyValue << PrettyTrunc << OriginalInit->getType()
9151 << Init->getSourceRange();
9152
9153 return true;
9154}
9155
John McCalld2a53122010-11-09 23:24:47 +00009156/// Analyze the given simple or compound assignment for warning-worthy
9157/// operations.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009158static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00009159 // Just recurse on the LHS.
9160 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9161
9162 // We want to recurse on the RHS as normal unless we're assigning to
9163 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00009164 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009165 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00009166 E->getOperatorLoc())) {
9167 // Recurse, ignoring any implicit conversions on the RHS.
9168 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
9169 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00009170 }
9171 }
9172
9173 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9174}
9175
John McCall263a48b2010-01-04 23:31:57 +00009176/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009177static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
9178 SourceLocation CContext, unsigned diag,
9179 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00009180 if (pruneControlFlow) {
9181 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9182 S.PDiag(diag)
9183 << SourceType << T << E->getSourceRange()
9184 << SourceRange(CContext));
9185 return;
9186 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00009187 S.Diag(E->getExprLoc(), diag)
9188 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
9189}
9190
Chandler Carruth7f3654f2011-04-05 06:47:57 +00009191/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009192static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
9193 SourceLocation CContext,
9194 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00009195 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00009196}
9197
Richard Trieube234c32016-04-21 21:04:55 +00009198
9199/// Diagnose an implicit cast from a floating point value to an integer value.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009200static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
9201 SourceLocation CContext) {
Richard Trieube234c32016-04-21 21:04:55 +00009202 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
Richard Smith51ec0cf2017-02-21 01:17:38 +00009203 const bool PruneWarnings = S.inTemplateInstantiation();
Richard Trieube234c32016-04-21 21:04:55 +00009204
9205 Expr *InnerE = E->IgnoreParenImpCasts();
9206 // We also want to warn on, e.g., "int i = -1.234"
9207 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
9208 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
9209 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
9210
9211 const bool IsLiteral =
9212 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
9213
9214 llvm::APFloat Value(0.0);
9215 bool IsConstant =
9216 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
9217 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00009218 return DiagnoseImpCast(S, E, T, CContext,
9219 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00009220 }
9221
Chandler Carruth016ef402011-04-10 08:36:24 +00009222 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00009223
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00009224 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
9225 T->hasUnsignedIntegerRepresentation());
Richard Trieube234c32016-04-21 21:04:55 +00009226 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
9227 &isExact) == llvm::APFloat::opOK &&
Richard Trieu891f0f12016-04-22 22:14:32 +00009228 isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00009229 if (IsLiteral) return;
9230 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
9231 PruneWarnings);
9232 }
9233
9234 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00009235 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00009236 // Warn on floating point literal to integer.
9237 DiagID = diag::warn_impcast_literal_float_to_integer;
9238 } else if (IntegerValue == 0) {
9239 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
9240 return DiagnoseImpCast(S, E, T, CContext,
9241 diag::warn_impcast_float_integer, PruneWarnings);
9242 }
9243 // Warn on non-zero to zero conversion.
9244 DiagID = diag::warn_impcast_float_to_integer_zero;
9245 } else {
9246 if (IntegerValue.isUnsigned()) {
9247 if (!IntegerValue.isMaxValue()) {
9248 return DiagnoseImpCast(S, E, T, CContext,
9249 diag::warn_impcast_float_integer, PruneWarnings);
9250 }
9251 } else { // IntegerValue.isSigned()
9252 if (!IntegerValue.isMaxSignedValue() &&
9253 !IntegerValue.isMinSignedValue()) {
9254 return DiagnoseImpCast(S, E, T, CContext,
9255 diag::warn_impcast_float_integer, PruneWarnings);
9256 }
9257 }
9258 // Warn on evaluatable floating point expression to integer conversion.
9259 DiagID = diag::warn_impcast_float_to_integer;
9260 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009261
Eli Friedman07185912013-08-29 23:44:43 +00009262 // FIXME: Force the precision of the source value down so we don't print
9263 // digits which are usually useless (we don't really care here if we
9264 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
9265 // would automatically print the shortest representation, but it's a bit
9266 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00009267 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00009268 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
9269 precision = (precision * 59 + 195) / 196;
9270 Value.toString(PrettySourceValue, precision);
9271
David Blaikie9b88cc02012-05-15 17:18:27 +00009272 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00009273 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00009274 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00009275 else
David Blaikie9b88cc02012-05-15 17:18:27 +00009276 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00009277
Richard Trieube234c32016-04-21 21:04:55 +00009278 if (PruneWarnings) {
9279 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9280 S.PDiag(DiagID)
9281 << E->getType() << T.getUnqualifiedType()
9282 << PrettySourceValue << PrettyTargetValue
9283 << E->getSourceRange() << SourceRange(CContext));
9284 } else {
9285 S.Diag(E->getExprLoc(), DiagID)
9286 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
9287 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
9288 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009289}
9290
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009291static std::string PrettyPrintInRange(const llvm::APSInt &Value,
9292 IntRange Range) {
John McCall18a2c2c2010-11-09 22:22:12 +00009293 if (!Range.Width) return "0";
9294
9295 llvm::APSInt ValueInRange = Value;
9296 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00009297 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00009298 return ValueInRange.toString(10);
9299}
9300
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009301static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009302 if (!isa<ImplicitCastExpr>(Ex))
9303 return false;
9304
9305 Expr *InnerE = Ex->IgnoreParenImpCasts();
9306 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
9307 const Type *Source =
9308 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
9309 if (Target->isDependentType())
9310 return false;
9311
9312 const BuiltinType *FloatCandidateBT =
9313 dyn_cast<BuiltinType>(ToBool ? Source : Target);
9314 const Type *BoolCandidateType = ToBool ? Target : Source;
9315
9316 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
9317 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
9318}
9319
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009320static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
9321 SourceLocation CC) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009322 unsigned NumArgs = TheCall->getNumArgs();
9323 for (unsigned i = 0; i < NumArgs; ++i) {
9324 Expr *CurrA = TheCall->getArg(i);
9325 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
9326 continue;
9327
9328 bool IsSwapped = ((i > 0) &&
9329 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
9330 IsSwapped |= ((i < (NumArgs - 1)) &&
9331 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
9332 if (IsSwapped) {
9333 // Warn on this floating-point to bool conversion.
9334 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
9335 CurrA->getType(), CC,
9336 diag::warn_impcast_floating_point_to_bool);
9337 }
9338 }
9339}
9340
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009341static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
9342 SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00009343 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
9344 E->getExprLoc()))
9345 return;
9346
Richard Trieu09d6b802016-01-08 23:35:06 +00009347 // Don't warn on functions which have return type nullptr_t.
9348 if (isa<CallExpr>(E))
9349 return;
9350
Richard Trieu5b993502014-10-15 03:42:06 +00009351 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
9352 const Expr::NullPointerConstantKind NullKind =
9353 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
9354 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
9355 return;
9356
9357 // Return if target type is a safe conversion.
9358 if (T->isAnyPointerType() || T->isBlockPointerType() ||
9359 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
9360 return;
9361
9362 SourceLocation Loc = E->getSourceRange().getBegin();
9363
Richard Trieu0a5e1662016-02-13 00:58:53 +00009364 // Venture through the macro stacks to get to the source of macro arguments.
9365 // The new location is a better location than the complete location that was
9366 // passed in.
9367 while (S.SourceMgr.isMacroArgExpansion(Loc))
9368 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
9369
9370 while (S.SourceMgr.isMacroArgExpansion(CC))
9371 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
9372
Richard Trieu5b993502014-10-15 03:42:06 +00009373 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00009374 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
9375 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
9376 Loc, S.SourceMgr, S.getLangOpts());
9377 if (MacroName == "NULL")
9378 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00009379 }
9380
9381 // Only warn if the null and context location are in the same macro expansion.
9382 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
9383 return;
9384
9385 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009386 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
Richard Trieu5b993502014-10-15 03:42:06 +00009387 << FixItHint::CreateReplacement(Loc,
9388 S.getFixItZeroLiteralForType(T, Loc));
9389}
9390
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009391static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9392 ObjCArrayLiteral *ArrayLiteral);
9393
9394static void
9395checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9396 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00009397
9398/// Check a single element within a collection literal against the
9399/// target element type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009400static void checkObjCCollectionLiteralElement(Sema &S,
9401 QualType TargetElementType,
9402 Expr *Element,
9403 unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009404 // Skip a bitcast to 'id' or qualified 'id'.
9405 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
9406 if (ICE->getCastKind() == CK_BitCast &&
9407 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
9408 Element = ICE->getSubExpr();
9409 }
9410
9411 QualType ElementType = Element->getType();
9412 ExprResult ElementResult(Element);
9413 if (ElementType->getAs<ObjCObjectPointerType>() &&
9414 S.CheckSingleAssignmentConstraints(TargetElementType,
9415 ElementResult,
9416 false, false)
9417 != Sema::Compatible) {
9418 S.Diag(Element->getLocStart(),
9419 diag::warn_objc_collection_literal_element)
9420 << ElementType << ElementKind << TargetElementType
9421 << Element->getSourceRange();
9422 }
9423
9424 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
9425 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
9426 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
9427 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
9428}
9429
9430/// Check an Objective-C array literal being converted to the given
9431/// target type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009432static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9433 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009434 if (!S.NSArrayDecl)
9435 return;
9436
9437 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9438 if (!TargetObjCPtr)
9439 return;
9440
9441 if (TargetObjCPtr->isUnspecialized() ||
9442 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9443 != S.NSArrayDecl->getCanonicalDecl())
9444 return;
9445
9446 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9447 if (TypeArgs.size() != 1)
9448 return;
9449
9450 QualType TargetElementType = TypeArgs[0];
9451 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
9452 checkObjCCollectionLiteralElement(S, TargetElementType,
9453 ArrayLiteral->getElement(I),
9454 0);
9455 }
9456}
9457
9458/// Check an Objective-C dictionary literal being converted to the given
9459/// target type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009460static void
9461checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9462 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009463 if (!S.NSDictionaryDecl)
9464 return;
9465
9466 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9467 if (!TargetObjCPtr)
9468 return;
9469
9470 if (TargetObjCPtr->isUnspecialized() ||
9471 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9472 != S.NSDictionaryDecl->getCanonicalDecl())
9473 return;
9474
9475 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9476 if (TypeArgs.size() != 2)
9477 return;
9478
9479 QualType TargetKeyType = TypeArgs[0];
9480 QualType TargetObjectType = TypeArgs[1];
9481 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
9482 auto Element = DictionaryLiteral->getKeyValueElement(I);
9483 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
9484 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
9485 }
9486}
9487
Richard Trieufc404c72016-02-05 23:02:38 +00009488// Helper function to filter out cases for constant width constant conversion.
9489// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009490static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
9491 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00009492 // If initializing from a constant, and the constant starts with '0',
9493 // then it is a binary, octal, or hexadecimal. Allow these constants
9494 // to fill all the bits, even if there is a sign change.
9495 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
9496 const char FirstLiteralCharacter =
9497 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
9498 if (FirstLiteralCharacter == '0')
9499 return false;
9500 }
9501
9502 // If the CC location points to a '{', and the type is char, then assume
9503 // assume it is an array initialization.
9504 if (CC.isValid() && T->isCharType()) {
9505 const char FirstContextCharacter =
9506 S.getSourceManager().getCharacterData(CC)[0];
9507 if (FirstContextCharacter == '{')
9508 return false;
9509 }
9510
9511 return true;
9512}
9513
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009514static void
9515CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
9516 bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009517 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00009518
John McCallcc7e5bf2010-05-06 08:58:33 +00009519 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
9520 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
9521 if (Source == Target) return;
9522 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00009523
Chandler Carruthc22845a2011-07-26 05:40:03 +00009524 // If the conversion context location is invalid don't complain. We also
9525 // don't want to emit a warning if the issue occurs from the expansion of
9526 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
9527 // delay this check as long as possible. Once we detect we are in that
9528 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009529 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00009530 return;
9531
Richard Trieu021baa32011-09-23 20:10:00 +00009532 // Diagnose implicit casts to bool.
9533 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
9534 if (isa<StringLiteral>(E))
9535 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00009536 // and expressions, for instance, assert(0 && "error here"), are
9537 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00009538 return DiagnoseImpCast(S, E, T, CC,
9539 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00009540 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
9541 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
9542 // This covers the literal expressions that evaluate to Objective-C
9543 // objects.
9544 return DiagnoseImpCast(S, E, T, CC,
9545 diag::warn_impcast_objective_c_literal_to_bool);
9546 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00009547 if (Source->isPointerType() || Source->canDecayToPointerType()) {
9548 // Warn on pointer to bool conversion that is always true.
9549 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
9550 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00009551 }
Richard Trieu021baa32011-09-23 20:10:00 +00009552 }
John McCall263a48b2010-01-04 23:31:57 +00009553
Douglas Gregor5054cb02015-07-07 03:58:22 +00009554 // Check implicit casts from Objective-C collection literals to specialized
9555 // collection types, e.g., NSArray<NSString *> *.
9556 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
9557 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
9558 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
9559 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
9560
John McCall263a48b2010-01-04 23:31:57 +00009561 // Strip vector types.
9562 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009563 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009564 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009565 return;
John McCallacf0ee52010-10-08 02:01:28 +00009566 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009567 }
Chris Lattneree7286f2011-06-14 04:51:15 +00009568
9569 // If the vector cast is cast between two vectors of the same size, it is
9570 // a bitcast, not a conversion.
9571 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
9572 return;
John McCall263a48b2010-01-04 23:31:57 +00009573
9574 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
9575 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
9576 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00009577 if (auto VecTy = dyn_cast<VectorType>(Target))
9578 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00009579
9580 // Strip complex types.
9581 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009582 if (!isa<ComplexType>(Target)) {
Tim Northover02416372017-08-08 23:18:05 +00009583 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009584 return;
9585
Tim Northover02416372017-08-08 23:18:05 +00009586 return DiagnoseImpCast(S, E, T, CC,
9587 S.getLangOpts().CPlusPlus
9588 ? diag::err_impcast_complex_scalar
9589 : diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009590 }
John McCall263a48b2010-01-04 23:31:57 +00009591
9592 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
9593 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
9594 }
9595
9596 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
9597 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
9598
9599 // If the source is floating point...
9600 if (SourceBT && SourceBT->isFloatingPoint()) {
9601 // ...and the target is floating point...
9602 if (TargetBT && TargetBT->isFloatingPoint()) {
9603 // ...then warn if we're dropping FP rank.
9604
9605 // Builtin FP kinds are ordered by increasing FP rank.
9606 if (SourceBT->getKind() > TargetBT->getKind()) {
9607 // Don't warn about float constants that are precisely
9608 // representable in the target type.
9609 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00009610 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00009611 // Value might be a float, a float vector, or a float complex.
9612 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00009613 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9614 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00009615 return;
9616 }
9617
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009618 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009619 return;
9620
John McCallacf0ee52010-10-08 02:01:28 +00009621 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00009622 }
9623 // ... or possibly if we're increasing rank, too
9624 else if (TargetBT->getKind() > SourceBT->getKind()) {
9625 if (S.SourceMgr.isInSystemMacro(CC))
9626 return;
9627
9628 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00009629 }
9630 return;
9631 }
9632
Richard Trieube234c32016-04-21 21:04:55 +00009633 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00009634 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009635 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009636 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00009637
Richard Trieube234c32016-04-21 21:04:55 +00009638 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00009639 }
John McCall263a48b2010-01-04 23:31:57 +00009640
Richard Smith54894fd2015-12-30 01:06:52 +00009641 // Detect the case where a call result is converted from floating-point to
9642 // to bool, and the final argument to the call is converted from bool, to
9643 // discover this typo:
9644 //
9645 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
9646 //
9647 // FIXME: This is an incredibly special case; is there some more general
9648 // way to detect this class of misplaced-parentheses bug?
9649 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009650 // Check last argument of function call to see if it is an
9651 // implicit cast from a type matching the type the result
9652 // is being cast to.
9653 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00009654 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009655 Expr *LastA = CEx->getArg(NumArgs - 1);
9656 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00009657 if (isa<ImplicitCastExpr>(LastA) &&
9658 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009659 // Warn on this floating-point to bool conversion
9660 DiagnoseImpCast(S, E, T, CC,
9661 diag::warn_impcast_floating_point_to_bool);
9662 }
9663 }
9664 }
John McCall263a48b2010-01-04 23:31:57 +00009665 return;
9666 }
9667
Richard Trieu5b993502014-10-15 03:42:06 +00009668 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00009669
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00009670 S.DiscardMisalignedMemberAddress(Target, E);
9671
David Blaikie9366d2b2012-06-19 21:19:06 +00009672 if (!Source->isIntegerType() || !Target->isIntegerType())
9673 return;
9674
David Blaikie7555b6a2012-05-15 16:56:36 +00009675 // TODO: remove this early return once the false positives for constant->bool
9676 // in templates, macros, etc, are reduced or removed.
9677 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9678 return;
9679
John McCallcc7e5bf2010-05-06 08:58:33 +00009680 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00009681 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00009682
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009683 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00009684 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009685 // TODO: this should happen for bitfield stores, too.
9686 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00009687 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009688 if (S.SourceMgr.isInSystemMacro(CC))
9689 return;
9690
John McCall18a2c2c2010-11-09 22:22:12 +00009691 std::string PrettySourceValue = Value.toString(10);
9692 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009693
Ted Kremenek33ba9952011-10-22 02:37:33 +00009694 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9695 S.PDiag(diag::warn_impcast_integer_precision_constant)
9696 << PrettySourceValue << PrettyTargetValue
9697 << E->getType() << T << E->getSourceRange()
9698 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00009699 return;
9700 }
9701
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009702 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9703 if (S.SourceMgr.isInSystemMacro(CC))
9704 return;
9705
David Blaikie9455da02012-04-12 22:40:54 +00009706 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00009707 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9708 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00009709 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00009710 }
9711
Richard Trieudcb55572016-01-29 23:51:16 +00009712 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9713 SourceRange.NonNegative && Source->isSignedIntegerType()) {
9714 // Warn when doing a signed to signed conversion, warn if the positive
9715 // source value is exactly the width of the target type, which will
9716 // cause a negative value to be stored.
9717
9718 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00009719 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9720 !S.SourceMgr.isInSystemMacro(CC)) {
9721 if (isSameWidthConstantConversion(S, E, T, CC)) {
9722 std::string PrettySourceValue = Value.toString(10);
9723 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00009724
Richard Trieufc404c72016-02-05 23:02:38 +00009725 S.DiagRuntimeBehavior(
9726 E->getExprLoc(), E,
9727 S.PDiag(diag::warn_impcast_integer_precision_constant)
9728 << PrettySourceValue << PrettyTargetValue << E->getType() << T
9729 << E->getSourceRange() << clang::SourceRange(CC));
9730 return;
Richard Trieudcb55572016-01-29 23:51:16 +00009731 }
9732 }
Richard Trieufc404c72016-02-05 23:02:38 +00009733
Richard Trieudcb55572016-01-29 23:51:16 +00009734 // Fall through for non-constants to give a sign conversion warning.
9735 }
9736
John McCallcc7e5bf2010-05-06 08:58:33 +00009737 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9738 (!TargetRange.NonNegative && SourceRange.NonNegative &&
9739 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009740 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009741 return;
9742
John McCallcc7e5bf2010-05-06 08:58:33 +00009743 unsigned DiagID = diag::warn_impcast_integer_sign;
9744
9745 // Traditionally, gcc has warned about this under -Wsign-compare.
9746 // We also want to warn about it in -Wconversion.
9747 // So if -Wconversion is off, use a completely identical diagnostic
9748 // in the sign-compare group.
9749 // The conditional-checking code will
9750 if (ICContext) {
9751 DiagID = diag::warn_impcast_integer_sign_conditional;
9752 *ICContext = true;
9753 }
9754
John McCallacf0ee52010-10-08 02:01:28 +00009755 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00009756 }
9757
Douglas Gregora78f1932011-02-22 02:45:07 +00009758 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00009759 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9760 // type, to give us better diagnostics.
9761 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00009762 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00009763 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9764 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9765 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9766 SourceType = S.Context.getTypeDeclType(Enum);
9767 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9768 }
9769 }
9770
Douglas Gregora78f1932011-02-22 02:45:07 +00009771 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9772 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00009773 if (SourceEnum->getDecl()->hasNameForLinkage() &&
9774 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009775 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009776 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009777 return;
9778
Douglas Gregor364f7db2011-03-12 00:14:31 +00009779 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00009780 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009781 }
John McCall263a48b2010-01-04 23:31:57 +00009782}
9783
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009784static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9785 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009786
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009787static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
9788 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009789 E = E->IgnoreParenImpCasts();
9790
9791 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00009792 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009793
John McCallacf0ee52010-10-08 02:01:28 +00009794 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009795 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009796 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00009797}
9798
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009799static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9800 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00009801 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00009802
9803 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00009804 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9805 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009806
9807 // If -Wconversion would have warned about either of the candidates
9808 // for a signedness conversion to the context type...
9809 if (!Suspicious) return;
9810
9811 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009812 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00009813 return;
9814
John McCallcc7e5bf2010-05-06 08:58:33 +00009815 // ...then check whether it would have warned about either of the
9816 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00009817 if (E->getType() == T) return;
9818
9819 Suspicious = false;
9820 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
9821 E->getType(), CC, &Suspicious);
9822 if (!Suspicious)
9823 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00009824 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009825}
9826
Richard Trieu65724892014-11-15 06:37:39 +00009827/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9828/// Input argument E is a logical expression.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009829static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00009830 if (S.getLangOpts().Bool)
9831 return;
9832 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
9833}
9834
John McCallcc7e5bf2010-05-06 08:58:33 +00009835/// AnalyzeImplicitConversions - Find and report any interesting
9836/// implicit conversions in the given expression. There are a couple
9837/// of competing diagnostics here, -Wconversion and -Wsign-compare.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009838static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
9839 SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00009840 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00009841 Expr *E = OrigE->IgnoreParenImpCasts();
9842
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00009843 if (E->isTypeDependent() || E->isValueDependent())
9844 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00009845
John McCallcc7e5bf2010-05-06 08:58:33 +00009846 // For conditional operators, we analyze the arguments as if they
9847 // were being fed directly into the output.
9848 if (isa<ConditionalOperator>(E)) {
9849 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00009850 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009851 return;
9852 }
9853
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009854 // Check implicit argument conversions for function calls.
9855 if (CallExpr *Call = dyn_cast<CallExpr>(E))
9856 CheckImplicitArgumentConversions(S, Call, CC);
9857
John McCallcc7e5bf2010-05-06 08:58:33 +00009858 // Go ahead and check any implicit conversions we might have skipped.
9859 // The non-canonical typecheck is just an optimization;
9860 // CheckImplicitConversion will filter out dead implicit conversions.
9861 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009862 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009863
9864 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00009865
9866 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
9867 // The bound subexpressions in a PseudoObjectExpr are not reachable
9868 // as transitive children.
9869 // FIXME: Use a more uniform representation for this.
9870 for (auto *SE : POE->semantics())
9871 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9872 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00009873 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00009874
John McCallcc7e5bf2010-05-06 08:58:33 +00009875 // Skip past explicit casts.
9876 if (isa<ExplicitCastExpr>(E)) {
9877 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00009878 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009879 }
9880
John McCalld2a53122010-11-09 23:24:47 +00009881 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9882 // Do a somewhat different check with comparison operators.
9883 if (BO->isComparisonOp())
9884 return AnalyzeComparison(S, BO);
9885
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009886 // And with simple assignments.
9887 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00009888 return AnalyzeAssignment(S, BO);
9889 }
John McCallcc7e5bf2010-05-06 08:58:33 +00009890
9891 // These break the otherwise-useful invariant below. Fortunately,
9892 // we don't really need to recurse into them, because any internal
9893 // expressions should have been analyzed already when they were
9894 // built into statements.
9895 if (isa<StmtExpr>(E)) return;
9896
9897 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00009898 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00009899
9900 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00009901 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00009902 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00009903 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00009904 for (Stmt *SubStmt : E->children()) {
9905 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00009906 if (!ChildExpr)
9907 continue;
9908
Richard Trieu955231d2014-01-25 01:10:35 +00009909 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00009910 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00009911 // Ignore checking string literals that are in logical and operators.
9912 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00009913 continue;
9914 AnalyzeImplicitConversions(S, ChildExpr, CC);
9915 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009916
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009917 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00009918 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
9919 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009920 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00009921
9922 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
9923 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009924 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009925 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009926
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009927 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
9928 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00009929 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009930}
9931
Anastasia Stulova0df4ac32016-11-14 17:39:58 +00009932/// Diagnose integer type and any valid implicit convertion to it.
9933static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
9934 // Taking into account implicit conversions,
9935 // allow any integer.
9936 if (!E->getType()->isIntegerType()) {
9937 S.Diag(E->getLocStart(),
9938 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
9939 return true;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009940 }
Anastasia Stulova0df4ac32016-11-14 17:39:58 +00009941 // Potentially emit standard warnings for implicit conversions if enabled
9942 // using -Wconversion.
9943 CheckImplicitConversion(S, E, IntT, E->getLocStart());
9944 return false;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009945}
9946
Richard Trieuc1888e02014-06-28 23:25:37 +00009947// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
9948// Returns true when emitting a warning about taking the address of a reference.
9949static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +00009950 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +00009951 E = E->IgnoreParenImpCasts();
9952
9953 const FunctionDecl *FD = nullptr;
9954
9955 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9956 if (!DRE->getDecl()->getType()->isReferenceType())
9957 return false;
9958 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9959 if (!M->getMemberDecl()->getType()->isReferenceType())
9960 return false;
9961 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00009962 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00009963 return false;
9964 FD = Call->getDirectCallee();
9965 } else {
9966 return false;
9967 }
9968
9969 SemaRef.Diag(E->getExprLoc(), PD);
9970
9971 // If possible, point to location of function.
9972 if (FD) {
9973 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
9974 }
9975
9976 return true;
9977}
9978
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009979// Returns true if the SourceLocation is expanded from any macro body.
9980// Returns false if the SourceLocation is invalid, is from not in a macro
9981// expansion, or is from expanded from a top-level macro argument.
9982static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
9983 if (Loc.isInvalid())
9984 return false;
9985
9986 while (Loc.isMacroID()) {
9987 if (SM.isMacroBodyExpansion(Loc))
9988 return true;
9989 Loc = SM.getImmediateMacroCallerLoc(Loc);
9990 }
9991
9992 return false;
9993}
9994
Richard Trieu3bb8b562014-02-26 02:36:06 +00009995/// \brief Diagnose pointers that are always non-null.
9996/// \param E the expression containing the pointer
9997/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
9998/// compared to a null pointer
9999/// \param IsEqual True when the comparison is equal to a null pointer
10000/// \param Range Extra SourceRange to highlight in the diagnostic
10001void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
10002 Expr::NullPointerConstantKind NullKind,
10003 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +000010004 if (!E)
10005 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010006
10007 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +000010008 if (E->getExprLoc().isMacroID()) {
10009 const SourceManager &SM = getSourceManager();
10010 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
10011 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +000010012 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +000010013 }
Richard Trieu3bb8b562014-02-26 02:36:06 +000010014 E = E->IgnoreImpCasts();
10015
10016 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
10017
Richard Trieuf7432752014-06-06 21:39:26 +000010018 if (isa<CXXThisExpr>(E)) {
10019 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
10020 : diag::warn_this_bool_conversion;
10021 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
10022 return;
10023 }
10024
Richard Trieu3bb8b562014-02-26 02:36:06 +000010025 bool IsAddressOf = false;
10026
10027 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10028 if (UO->getOpcode() != UO_AddrOf)
10029 return;
10030 IsAddressOf = true;
10031 E = UO->getSubExpr();
10032 }
10033
Richard Trieuc1888e02014-06-28 23:25:37 +000010034 if (IsAddressOf) {
10035 unsigned DiagID = IsCompare
10036 ? diag::warn_address_of_reference_null_compare
10037 : diag::warn_address_of_reference_bool_conversion;
10038 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
10039 << IsEqual;
10040 if (CheckForReference(*this, E, PD)) {
10041 return;
10042 }
10043 }
10044
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010045 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
10046 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +000010047 std::string Str;
10048 llvm::raw_string_ostream S(Str);
10049 E->printPretty(S, nullptr, getPrintingPolicy());
10050 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
10051 : diag::warn_cast_nonnull_to_bool;
10052 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
10053 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010054 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +000010055 };
10056
10057 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
10058 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
10059 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010060 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
10061 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000010062 return;
10063 }
10064 }
10065 }
10066
Richard Trieu3bb8b562014-02-26 02:36:06 +000010067 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +000010068 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010069 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
10070 D = R->getDecl();
10071 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10072 D = M->getMemberDecl();
10073 }
10074
10075 // Weak Decls can be null.
10076 if (!D || D->isWeak())
10077 return;
George Burgess IV850269a2015-12-08 22:02:00 +000010078
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010079 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +000010080 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
10081 if (getCurFunction() &&
10082 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010083 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
10084 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000010085 return;
10086 }
10087
10088 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +000010089 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +000010090 assert(ParamIter != FD->param_end());
10091 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
10092
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010093 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
10094 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010095 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +000010096 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010097 }
George Burgess IV850269a2015-12-08 22:02:00 +000010098
10099 for (unsigned ArgNo : NonNull->args()) {
10100 if (ArgNo == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010101 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010102 return;
10103 }
George Burgess IV850269a2015-12-08 22:02:00 +000010104 }
10105 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010106 }
10107 }
George Burgess IV850269a2015-12-08 22:02:00 +000010108 }
10109
Richard Trieu3bb8b562014-02-26 02:36:06 +000010110 QualType T = D->getType();
10111 const bool IsArray = T->isArrayType();
10112 const bool IsFunction = T->isFunctionType();
10113
Richard Trieuc1888e02014-06-28 23:25:37 +000010114 // Address of function is used to silence the function warning.
10115 if (IsAddressOf && IsFunction) {
10116 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010117 }
10118
10119 // Found nothing.
10120 if (!IsAddressOf && !IsFunction && !IsArray)
10121 return;
10122
10123 // Pretty print the expression for the diagnostic.
10124 std::string Str;
10125 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +000010126 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +000010127
10128 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
10129 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +000010130 enum {
10131 AddressOf,
10132 FunctionPointer,
10133 ArrayPointer
10134 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010135 if (IsAddressOf)
10136 DiagType = AddressOf;
10137 else if (IsFunction)
10138 DiagType = FunctionPointer;
10139 else if (IsArray)
10140 DiagType = ArrayPointer;
10141 else
10142 llvm_unreachable("Could not determine diagnostic.");
10143 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
10144 << Range << IsEqual;
10145
10146 if (!IsFunction)
10147 return;
10148
10149 // Suggest '&' to silence the function warning.
10150 Diag(E->getExprLoc(), diag::note_function_warning_silence)
10151 << FixItHint::CreateInsertion(E->getLocStart(), "&");
10152
10153 // Check to see if '()' fixit should be emitted.
10154 QualType ReturnType;
10155 UnresolvedSet<4> NonTemplateOverloads;
10156 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
10157 if (ReturnType.isNull())
10158 return;
10159
10160 if (IsCompare) {
10161 // There are two cases here. If there is null constant, the only suggest
10162 // for a pointer return type. If the null is 0, then suggest if the return
10163 // type is a pointer or an integer type.
10164 if (!ReturnType->isPointerType()) {
10165 if (NullKind == Expr::NPCK_ZeroExpression ||
10166 NullKind == Expr::NPCK_ZeroLiteral) {
10167 if (!ReturnType->isIntegerType())
10168 return;
10169 } else {
10170 return;
10171 }
10172 }
10173 } else { // !IsCompare
10174 // For function to bool, only suggest if the function pointer has bool
10175 // return type.
10176 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
10177 return;
10178 }
10179 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +000010180 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +000010181}
10182
John McCallcc7e5bf2010-05-06 08:58:33 +000010183/// Diagnoses "dangerous" implicit conversions within the given
10184/// expression (which is a full expression). Implements -Wconversion
10185/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +000010186///
10187/// \param CC the "context" location of the implicit conversion, i.e.
10188/// the most location of the syntactic entity requiring the implicit
10189/// conversion
10190void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010191 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +000010192 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +000010193 return;
10194
10195 // Don't diagnose for value- or type-dependent expressions.
10196 if (E->isTypeDependent() || E->isValueDependent())
10197 return;
10198
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010199 // Check for array bounds violations in cases where the check isn't triggered
10200 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
10201 // ArraySubscriptExpr is on the RHS of a variable initialization.
10202 CheckArrayAccess(E);
10203
John McCallacf0ee52010-10-08 02:01:28 +000010204 // This is not the right CC for (e.g.) a variable initialization.
10205 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010206}
10207
Richard Trieu65724892014-11-15 06:37:39 +000010208/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10209/// Input argument E is a logical expression.
10210void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
10211 ::CheckBoolLikeConversion(*this, E, CC);
10212}
10213
Richard Smith9f7df0c2017-06-26 23:19:32 +000010214/// Diagnose when expression is an integer constant expression and its evaluation
10215/// results in integer overflow
10216void Sema::CheckForIntOverflow (Expr *E) {
10217 // Use a work list to deal with nested struct initializers.
10218 SmallVector<Expr *, 2> Exprs(1, E);
10219
10220 do {
10221 Expr *E = Exprs.pop_back_val();
10222
10223 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
10224 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
10225 continue;
10226 }
10227
10228 if (auto InitList = dyn_cast<InitListExpr>(E))
10229 Exprs.append(InitList->inits().begin(), InitList->inits().end());
10230
10231 if (isa<ObjCBoxedExpr>(E))
10232 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
10233 } while (!Exprs.empty());
10234}
10235
Richard Smithc406cb72013-01-17 01:17:56 +000010236namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010237
Richard Smithc406cb72013-01-17 01:17:56 +000010238/// \brief Visitor for expressions which looks for unsequenced operations on the
10239/// same object.
10240class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010241 using Base = EvaluatedExprVisitor<SequenceChecker>;
Richard Smithe3dbfe02013-06-30 10:40:20 +000010242
Richard Smithc406cb72013-01-17 01:17:56 +000010243 /// \brief A tree of sequenced regions within an expression. Two regions are
10244 /// unsequenced if one is an ancestor or a descendent of the other. When we
10245 /// finish processing an expression with sequencing, such as a comma
10246 /// expression, we fold its tree nodes into its parent, since they are
10247 /// unsequenced with respect to nodes we will visit later.
10248 class SequenceTree {
10249 struct Value {
10250 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
10251 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +000010252 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +000010253 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010254 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +000010255
10256 public:
10257 /// \brief A region within an expression which may be sequenced with respect
10258 /// to some other region.
10259 class Seq {
Richard Smithc406cb72013-01-17 01:17:56 +000010260 friend class SequenceTree;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010261
10262 unsigned Index = 0;
10263
10264 explicit Seq(unsigned N) : Index(N) {}
10265
Richard Smithc406cb72013-01-17 01:17:56 +000010266 public:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010267 Seq() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010268 };
10269
10270 SequenceTree() { Values.push_back(Value(0)); }
10271 Seq root() const { return Seq(0); }
10272
10273 /// \brief Create a new sequence of operations, which is an unsequenced
10274 /// subset of \p Parent. This sequence of operations is sequenced with
10275 /// respect to other children of \p Parent.
10276 Seq allocate(Seq Parent) {
10277 Values.push_back(Value(Parent.Index));
10278 return Seq(Values.size() - 1);
10279 }
10280
10281 /// \brief Merge a sequence of operations into its parent.
10282 void merge(Seq S) {
10283 Values[S.Index].Merged = true;
10284 }
10285
10286 /// \brief Determine whether two operations are unsequenced. This operation
10287 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
10288 /// should have been merged into its parent as appropriate.
10289 bool isUnsequenced(Seq Cur, Seq Old) {
10290 unsigned C = representative(Cur.Index);
10291 unsigned Target = representative(Old.Index);
10292 while (C >= Target) {
10293 if (C == Target)
10294 return true;
10295 C = Values[C].Parent;
10296 }
10297 return false;
10298 }
10299
10300 private:
10301 /// \brief Pick a representative for a sequence.
10302 unsigned representative(unsigned K) {
10303 if (Values[K].Merged)
10304 // Perform path compression as we go.
10305 return Values[K].Parent = representative(Values[K].Parent);
10306 return K;
10307 }
10308 };
10309
10310 /// An object for which we can track unsequenced uses.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010311 using Object = NamedDecl *;
Richard Smithc406cb72013-01-17 01:17:56 +000010312
10313 /// Different flavors of object usage which we track. We only track the
10314 /// least-sequenced usage of each kind.
10315 enum UsageKind {
10316 /// A read of an object. Multiple unsequenced reads are OK.
10317 UK_Use,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010318
Richard Smithc406cb72013-01-17 01:17:56 +000010319 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +000010320 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +000010321 UK_ModAsValue,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010322
Richard Smithc406cb72013-01-17 01:17:56 +000010323 /// A modification of an object which is not sequenced before the value
10324 /// computation of the expression, such as n++.
10325 UK_ModAsSideEffect,
10326
10327 UK_Count = UK_ModAsSideEffect + 1
10328 };
10329
10330 struct Usage {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010331 Expr *Use = nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000010332 SequenceTree::Seq Seq;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010333
10334 Usage() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010335 };
10336
10337 struct UsageInfo {
Richard Smithc406cb72013-01-17 01:17:56 +000010338 Usage Uses[UK_Count];
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010339
Richard Smithc406cb72013-01-17 01:17:56 +000010340 /// Have we issued a diagnostic for this variable already?
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010341 bool Diagnosed = false;
10342
10343 UsageInfo() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010344 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010345 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
Richard Smithc406cb72013-01-17 01:17:56 +000010346
10347 Sema &SemaRef;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010348
Richard Smithc406cb72013-01-17 01:17:56 +000010349 /// Sequenced regions within the expression.
10350 SequenceTree Tree;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010351
Richard Smithc406cb72013-01-17 01:17:56 +000010352 /// Declaration modifications and references which we have seen.
10353 UsageInfoMap UsageMap;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010354
Richard Smithc406cb72013-01-17 01:17:56 +000010355 /// The region we are currently within.
10356 SequenceTree::Seq Region;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010357
Richard Smithc406cb72013-01-17 01:17:56 +000010358 /// Filled in with declarations which were modified as a side-effect
10359 /// (that is, post-increment operations).
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010360 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
10361
Richard Smithd33f5202013-01-17 23:18:09 +000010362 /// Expressions to check later. We defer checking these to reduce
10363 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010364 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +000010365
10366 /// RAII object wrapping the visitation of a sequenced subexpression of an
10367 /// expression. At the end of this process, the side-effects of the evaluation
10368 /// become sequenced with respect to the value computation of the result, so
10369 /// we downgrade any UK_ModAsSideEffect within the evaluation to
10370 /// UK_ModAsValue.
10371 struct SequencedSubexpression {
10372 SequencedSubexpression(SequenceChecker &Self)
10373 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
10374 Self.ModAsSideEffect = &ModAsSideEffect;
10375 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010376
Richard Smithc406cb72013-01-17 01:17:56 +000010377 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +000010378 for (auto &M : llvm::reverse(ModAsSideEffect)) {
10379 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +000010380 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +000010381 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
10382 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +000010383 }
10384 Self.ModAsSideEffect = OldModAsSideEffect;
10385 }
10386
10387 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010388 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010389 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +000010390 };
10391
Richard Smith40238f02013-06-20 22:21:56 +000010392 /// RAII object wrapping the visitation of a subexpression which we might
10393 /// choose to evaluate as a constant. If any subexpression is evaluated and
10394 /// found to be non-constant, this allows us to suppress the evaluation of
10395 /// the outer expression.
10396 class EvaluationTracker {
10397 public:
10398 EvaluationTracker(SequenceChecker &Self)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010399 : Self(Self), Prev(Self.EvalTracker) {
Richard Smith40238f02013-06-20 22:21:56 +000010400 Self.EvalTracker = this;
10401 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010402
Richard Smith40238f02013-06-20 22:21:56 +000010403 ~EvaluationTracker() {
10404 Self.EvalTracker = Prev;
10405 if (Prev)
10406 Prev->EvalOK &= EvalOK;
10407 }
10408
10409 bool evaluate(const Expr *E, bool &Result) {
10410 if (!EvalOK || E->isValueDependent())
10411 return false;
10412 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
10413 return EvalOK;
10414 }
10415
10416 private:
10417 SequenceChecker &Self;
10418 EvaluationTracker *Prev;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010419 bool EvalOK = true;
10420 } *EvalTracker = nullptr;
Richard Smith40238f02013-06-20 22:21:56 +000010421
Richard Smithc406cb72013-01-17 01:17:56 +000010422 /// \brief Find the object which is produced by the specified expression,
10423 /// if any.
10424 Object getObject(Expr *E, bool Mod) const {
10425 E = E->IgnoreParenCasts();
10426 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10427 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
10428 return getObject(UO->getSubExpr(), Mod);
10429 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10430 if (BO->getOpcode() == BO_Comma)
10431 return getObject(BO->getRHS(), Mod);
10432 if (Mod && BO->isAssignmentOp())
10433 return getObject(BO->getLHS(), Mod);
10434 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10435 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
10436 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
10437 return ME->getMemberDecl();
10438 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10439 // FIXME: If this is a reference, map through to its value.
10440 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +000010441 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000010442 }
10443
10444 /// \brief Note that an object was modified or used by an expression.
10445 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
10446 Usage &U = UI.Uses[UK];
10447 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
10448 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
10449 ModAsSideEffect->push_back(std::make_pair(O, U));
10450 U.Use = Ref;
10451 U.Seq = Region;
10452 }
10453 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010454
Richard Smithc406cb72013-01-17 01:17:56 +000010455 /// \brief Check whether a modification or use conflicts with a prior usage.
10456 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
10457 bool IsModMod) {
10458 if (UI.Diagnosed)
10459 return;
10460
10461 const Usage &U = UI.Uses[OtherKind];
10462 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
10463 return;
10464
10465 Expr *Mod = U.Use;
10466 Expr *ModOrUse = Ref;
10467 if (OtherKind == UK_Use)
10468 std::swap(Mod, ModOrUse);
10469
10470 SemaRef.Diag(Mod->getExprLoc(),
10471 IsModMod ? diag::warn_unsequenced_mod_mod
10472 : diag::warn_unsequenced_mod_use)
10473 << O << SourceRange(ModOrUse->getExprLoc());
10474 UI.Diagnosed = true;
10475 }
10476
10477 void notePreUse(Object O, Expr *Use) {
10478 UsageInfo &U = UsageMap[O];
10479 // Uses conflict with other modifications.
10480 checkUsage(O, U, Use, UK_ModAsValue, false);
10481 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010482
Richard Smithc406cb72013-01-17 01:17:56 +000010483 void notePostUse(Object O, Expr *Use) {
10484 UsageInfo &U = UsageMap[O];
10485 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
10486 addUsage(U, O, Use, UK_Use);
10487 }
10488
10489 void notePreMod(Object O, Expr *Mod) {
10490 UsageInfo &U = UsageMap[O];
10491 // Modifications conflict with other modifications and with uses.
10492 checkUsage(O, U, Mod, UK_ModAsValue, true);
10493 checkUsage(O, U, Mod, UK_Use, false);
10494 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010495
Richard Smithc406cb72013-01-17 01:17:56 +000010496 void notePostMod(Object O, Expr *Use, UsageKind UK) {
10497 UsageInfo &U = UsageMap[O];
10498 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
10499 addUsage(U, O, Use, UK);
10500 }
10501
10502public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010503 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010504 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
Richard Smithc406cb72013-01-17 01:17:56 +000010505 Visit(E);
10506 }
10507
10508 void VisitStmt(Stmt *S) {
10509 // Skip all statements which aren't expressions for now.
10510 }
10511
10512 void VisitExpr(Expr *E) {
10513 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +000010514 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +000010515 }
10516
10517 void VisitCastExpr(CastExpr *E) {
10518 Object O = Object();
10519 if (E->getCastKind() == CK_LValueToRValue)
10520 O = getObject(E->getSubExpr(), false);
10521
10522 if (O)
10523 notePreUse(O, E);
10524 VisitExpr(E);
10525 if (O)
10526 notePostUse(O, E);
10527 }
10528
10529 void VisitBinComma(BinaryOperator *BO) {
10530 // C++11 [expr.comma]p1:
10531 // Every value computation and side effect associated with the left
10532 // expression is sequenced before every value computation and side
10533 // effect associated with the right expression.
10534 SequenceTree::Seq LHS = Tree.allocate(Region);
10535 SequenceTree::Seq RHS = Tree.allocate(Region);
10536 SequenceTree::Seq OldRegion = Region;
10537
10538 {
10539 SequencedSubexpression SeqLHS(*this);
10540 Region = LHS;
10541 Visit(BO->getLHS());
10542 }
10543
10544 Region = RHS;
10545 Visit(BO->getRHS());
10546
10547 Region = OldRegion;
10548
10549 // Forget that LHS and RHS are sequenced. They are both unsequenced
10550 // with respect to other stuff.
10551 Tree.merge(LHS);
10552 Tree.merge(RHS);
10553 }
10554
10555 void VisitBinAssign(BinaryOperator *BO) {
10556 // The modification is sequenced after the value computation of the LHS
10557 // and RHS, so check it before inspecting the operands and update the
10558 // map afterwards.
10559 Object O = getObject(BO->getLHS(), true);
10560 if (!O)
10561 return VisitExpr(BO);
10562
10563 notePreMod(O, BO);
10564
10565 // C++11 [expr.ass]p7:
10566 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
10567 // only once.
10568 //
10569 // Therefore, for a compound assignment operator, O is considered used
10570 // everywhere except within the evaluation of E1 itself.
10571 if (isa<CompoundAssignOperator>(BO))
10572 notePreUse(O, BO);
10573
10574 Visit(BO->getLHS());
10575
10576 if (isa<CompoundAssignOperator>(BO))
10577 notePostUse(O, BO);
10578
10579 Visit(BO->getRHS());
10580
Richard Smith83e37bee2013-06-26 23:16:51 +000010581 // C++11 [expr.ass]p1:
10582 // the assignment is sequenced [...] before the value computation of the
10583 // assignment expression.
10584 // C11 6.5.16/3 has no such rule.
10585 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10586 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010587 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010588
Richard Smithc406cb72013-01-17 01:17:56 +000010589 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
10590 VisitBinAssign(CAO);
10591 }
10592
10593 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10594 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10595 void VisitUnaryPreIncDec(UnaryOperator *UO) {
10596 Object O = getObject(UO->getSubExpr(), true);
10597 if (!O)
10598 return VisitExpr(UO);
10599
10600 notePreMod(O, UO);
10601 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +000010602 // C++11 [expr.pre.incr]p1:
10603 // the expression ++x is equivalent to x+=1
10604 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10605 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010606 }
10607
10608 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10609 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10610 void VisitUnaryPostIncDec(UnaryOperator *UO) {
10611 Object O = getObject(UO->getSubExpr(), true);
10612 if (!O)
10613 return VisitExpr(UO);
10614
10615 notePreMod(O, UO);
10616 Visit(UO->getSubExpr());
10617 notePostMod(O, UO, UK_ModAsSideEffect);
10618 }
10619
10620 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
10621 void VisitBinLOr(BinaryOperator *BO) {
10622 // The side-effects of the LHS of an '&&' are sequenced before the
10623 // value computation of the RHS, and hence before the value computation
10624 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10625 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +000010626 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010627 {
10628 SequencedSubexpression Sequenced(*this);
10629 Visit(BO->getLHS());
10630 }
10631
10632 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010633 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010634 if (!Result)
10635 Visit(BO->getRHS());
10636 } else {
10637 // Check for unsequenced operations in the RHS, treating it as an
10638 // entirely separate evaluation.
10639 //
10640 // FIXME: If there are operations in the RHS which are unsequenced
10641 // with respect to operations outside the RHS, and those operations
10642 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +000010643 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010644 }
Richard Smithc406cb72013-01-17 01:17:56 +000010645 }
10646 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +000010647 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010648 {
10649 SequencedSubexpression Sequenced(*this);
10650 Visit(BO->getLHS());
10651 }
10652
10653 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010654 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010655 if (Result)
10656 Visit(BO->getRHS());
10657 } else {
Richard Smithd33f5202013-01-17 23:18:09 +000010658 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010659 }
Richard Smithc406cb72013-01-17 01:17:56 +000010660 }
10661
10662 // Only visit the condition, unless we can be sure which subexpression will
10663 // be chosen.
10664 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +000010665 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +000010666 {
10667 SequencedSubexpression Sequenced(*this);
10668 Visit(CO->getCond());
10669 }
Richard Smithc406cb72013-01-17 01:17:56 +000010670
10671 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010672 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +000010673 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010674 else {
Richard Smithd33f5202013-01-17 23:18:09 +000010675 WorkList.push_back(CO->getTrueExpr());
10676 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010677 }
Richard Smithc406cb72013-01-17 01:17:56 +000010678 }
10679
Richard Smithe3dbfe02013-06-30 10:40:20 +000010680 void VisitCallExpr(CallExpr *CE) {
10681 // C++11 [intro.execution]p15:
10682 // When calling a function [...], every value computation and side effect
10683 // associated with any argument expression, or with the postfix expression
10684 // designating the called function, is sequenced before execution of every
10685 // expression or statement in the body of the function [and thus before
10686 // the value computation of its result].
10687 SequencedSubexpression Sequenced(*this);
10688 Base::VisitCallExpr(CE);
10689
10690 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10691 }
10692
Richard Smithc406cb72013-01-17 01:17:56 +000010693 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +000010694 // This is a call, so all subexpressions are sequenced before the result.
10695 SequencedSubexpression Sequenced(*this);
10696
Richard Smithc406cb72013-01-17 01:17:56 +000010697 if (!CCE->isListInitialization())
10698 return VisitExpr(CCE);
10699
10700 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010701 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010702 SequenceTree::Seq Parent = Region;
10703 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10704 E = CCE->arg_end();
10705 I != E; ++I) {
10706 Region = Tree.allocate(Parent);
10707 Elts.push_back(Region);
10708 Visit(*I);
10709 }
10710
10711 // Forget that the initializers are sequenced.
10712 Region = Parent;
10713 for (unsigned I = 0; I < Elts.size(); ++I)
10714 Tree.merge(Elts[I]);
10715 }
10716
10717 void VisitInitListExpr(InitListExpr *ILE) {
10718 if (!SemaRef.getLangOpts().CPlusPlus11)
10719 return VisitExpr(ILE);
10720
10721 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010722 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010723 SequenceTree::Seq Parent = Region;
10724 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10725 Expr *E = ILE->getInit(I);
10726 if (!E) continue;
10727 Region = Tree.allocate(Parent);
10728 Elts.push_back(Region);
10729 Visit(E);
10730 }
10731
10732 // Forget that the initializers are sequenced.
10733 Region = Parent;
10734 for (unsigned I = 0; I < Elts.size(); ++I)
10735 Tree.merge(Elts[I]);
10736 }
10737};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010738
10739} // namespace
Richard Smithc406cb72013-01-17 01:17:56 +000010740
10741void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010742 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +000010743 WorkList.push_back(E);
10744 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +000010745 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +000010746 SequenceChecker(*this, Item, WorkList);
10747 }
Richard Smithc406cb72013-01-17 01:17:56 +000010748}
10749
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010750void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10751 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +000010752 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +000010753 if (!E->isInstantiationDependent())
10754 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010755 if (!IsConstexpr && !E->isValueDependent())
Richard Smith9f7df0c2017-06-26 23:19:32 +000010756 CheckForIntOverflow(E);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000010757 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +000010758}
10759
John McCall1f425642010-11-11 03:21:53 +000010760void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10761 FieldDecl *BitField,
10762 Expr *Init) {
10763 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10764}
10765
David Majnemer61a5bbf2015-04-07 22:08:51 +000010766static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
10767 SourceLocation Loc) {
10768 if (!PType->isVariablyModifiedType())
10769 return;
10770 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10771 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10772 return;
10773 }
David Majnemerdf8f73f2015-04-09 19:53:25 +000010774 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10775 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10776 return;
10777 }
David Majnemer61a5bbf2015-04-07 22:08:51 +000010778 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10779 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10780 return;
10781 }
10782
10783 const ArrayType *AT = S.Context.getAsArrayType(PType);
10784 if (!AT)
10785 return;
10786
10787 if (AT->getSizeModifier() != ArrayType::Star) {
10788 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
10789 return;
10790 }
10791
10792 S.Diag(Loc, diag::err_array_star_in_function_definition);
10793}
10794
Mike Stump0c2ec772010-01-21 03:59:47 +000010795/// CheckParmsForFunctionDef - Check that the parameters of the given
10796/// function are appropriate for the definition of a function. This
10797/// takes care of any checks that cannot be performed on the
10798/// declaration itself, e.g., that the types of each of the function
10799/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +000010800bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +000010801 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010802 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +000010803 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010804 // C99 6.7.5.3p4: the parameters in a parameter type list in a
10805 // function declarator that is part of a function definition of
10806 // that function shall not have incomplete type.
10807 //
10808 // This is also C++ [dcl.fct]p6.
10809 if (!Param->isInvalidDecl() &&
10810 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000010811 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010812 Param->setInvalidDecl();
10813 HasInvalidParm = true;
10814 }
10815
10816 // C99 6.9.1p5: If the declarator includes a parameter type list, the
10817 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +000010818 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +000010819 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +000010820 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000010821 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +000010822 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +000010823
10824 // C99 6.7.5.3p12:
10825 // If the function declarator is not part of a definition of that
10826 // function, parameters may have incomplete type and may use the [*]
10827 // notation in their sequences of declarator specifiers to specify
10828 // variable length array types.
10829 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +000010830 // FIXME: This diagnostic should point the '[*]' if source-location
10831 // information is added for it.
10832 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010833
10834 // MSVC destroys objects passed by value in the callee. Therefore a
10835 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010836 // object's destructor. However, we don't perform any direct access check
10837 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +000010838 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
10839 .getCXXABI()
10840 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +000010841 if (!Param->isInvalidDecl()) {
10842 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
10843 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
10844 if (!ClassDecl->isInvalidDecl() &&
10845 !ClassDecl->hasIrrelevantDestructor() &&
10846 !ClassDecl->isDependentContext()) {
10847 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10848 MarkFunctionReferenced(Param->getLocation(), Destructor);
10849 DiagnoseUseOfDecl(Destructor, Param->getLocation());
10850 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010851 }
10852 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010853 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010854
10855 // Parameters with the pass_object_size attribute only need to be marked
10856 // constant at function definitions. Because we lack information about
10857 // whether we're on a declaration or definition when we're instantiating the
10858 // attribute, we need to check for constness here.
10859 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
10860 if (!Param->getType().isConstQualified())
10861 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10862 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +000010863 }
10864
10865 return HasInvalidParm;
10866}
John McCall2b5c1b22010-08-12 21:44:57 +000010867
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000010868/// A helper function to get the alignment of a Decl referred to by DeclRefExpr
10869/// or MemberExpr.
10870static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
10871 ASTContext &Context) {
10872 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
10873 return Context.getDeclAlign(DRE->getDecl());
10874
10875 if (const auto *ME = dyn_cast<MemberExpr>(E))
10876 return Context.getDeclAlign(ME->getMemberDecl());
10877
10878 return TypeAlign;
10879}
10880
John McCall2b5c1b22010-08-12 21:44:57 +000010881/// CheckCastAlign - Implements -Wcast-align, which warns when a
10882/// pointer cast increases the alignment requirements.
10883void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
10884 // This is actually a lot of work to potentially be doing on every
10885 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010886 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +000010887 return;
10888
10889 // Ignore dependent types.
10890 if (T->isDependentType() || Op->getType()->isDependentType())
10891 return;
10892
10893 // Require that the destination be a pointer type.
10894 const PointerType *DestPtr = T->getAs<PointerType>();
10895 if (!DestPtr) return;
10896
10897 // If the destination has alignment 1, we're done.
10898 QualType DestPointee = DestPtr->getPointeeType();
10899 if (DestPointee->isIncompleteType()) return;
10900 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
10901 if (DestAlign.isOne()) return;
10902
10903 // Require that the source be a pointer type.
10904 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
10905 if (!SrcPtr) return;
10906 QualType SrcPointee = SrcPtr->getPointeeType();
10907
10908 // Whitelist casts from cv void*. We already implicitly
10909 // whitelisted casts to cv void*, since they have alignment 1.
10910 // Also whitelist casts involving incomplete types, which implicitly
10911 // includes 'void'.
10912 if (SrcPointee->isIncompleteType()) return;
10913
10914 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000010915
10916 if (auto *CE = dyn_cast<CastExpr>(Op)) {
10917 if (CE->getCastKind() == CK_ArrayToPointerDecay)
10918 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
10919 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
10920 if (UO->getOpcode() == UO_AddrOf)
10921 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
10922 }
10923
John McCall2b5c1b22010-08-12 21:44:57 +000010924 if (SrcAlign >= DestAlign) return;
10925
10926 Diag(TRange.getBegin(), diag::warn_cast_align)
10927 << Op->getType() << T
10928 << static_cast<unsigned>(SrcAlign.getQuantity())
10929 << static_cast<unsigned>(DestAlign.getQuantity())
10930 << TRange << Op->getSourceRange();
10931}
10932
Chandler Carruth28389f02011-08-05 09:10:50 +000010933/// \brief Check whether this array fits the idiom of a size-one tail padded
10934/// array member of a struct.
10935///
10936/// We avoid emitting out-of-bounds access warnings for such arrays as they are
10937/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +000010938static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +000010939 const NamedDecl *ND) {
10940 if (Size != 1 || !ND) return false;
10941
10942 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
10943 if (!FD) return false;
10944
10945 // Don't consider sizes resulting from macro expansions or template argument
10946 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +000010947
10948 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010949 while (TInfo) {
10950 TypeLoc TL = TInfo->getTypeLoc();
10951 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +000010952 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
10953 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010954 TInfo = TDL->getTypeSourceInfo();
10955 continue;
10956 }
David Blaikie6adc78e2013-02-18 22:06:02 +000010957 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
10958 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +000010959 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
10960 return false;
10961 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010962 break;
Sean Callanan06a48a62012-05-04 18:22:53 +000010963 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010964
10965 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +000010966 if (!RD) return false;
10967 if (RD->isUnion()) return false;
10968 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10969 if (!CRD->isStandardLayout()) return false;
10970 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010971
Benjamin Kramer8c543672011-08-06 03:04:42 +000010972 // See if this is the last field decl in the record.
10973 const Decl *D = FD;
10974 while ((D = D->getNextDeclInContext()))
10975 if (isa<FieldDecl>(D))
10976 return false;
10977 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +000010978}
10979
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010980void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010981 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +000010982 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010983 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010984 if (IndexExpr->isValueDependent())
10985 return;
10986
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010987 const Type *EffectiveType =
10988 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010989 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010990 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010991 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010992 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +000010993 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +000010994
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010995 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +000010996 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +000010997 return;
Richard Smith13f67182011-12-16 19:31:14 +000010998 if (IndexNegated)
10999 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +000011000
Craig Topperc3ec1492014-05-26 06:22:03 +000011001 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +000011002 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
11003 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +000011004 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +000011005 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +000011006
Ted Kremeneke4b316c2011-02-23 23:06:04 +000011007 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011008 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +000011009 if (!size.isStrictlyPositive())
11010 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011011
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000011012 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +000011013 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011014 // Make sure we're comparing apples to apples when comparing index to size
11015 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
11016 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +000011017 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +000011018 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011019 if (ptrarith_typesize != array_typesize) {
11020 // There's a cast to a different size type involved
11021 uint64_t ratio = array_typesize / ptrarith_typesize;
11022 // TODO: Be smarter about handling cases where array_typesize is not a
11023 // multiple of ptrarith_typesize
11024 if (ptrarith_typesize * ratio == array_typesize)
11025 size *= llvm::APInt(size.getBitWidth(), ratio);
11026 }
11027 }
11028
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011029 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011030 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011031 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011032 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011033
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011034 // For array subscripting the index must be less than size, but for pointer
11035 // arithmetic also allow the index (offset) to be equal to size since
11036 // computing the next address after the end of the array is legal and
11037 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011038 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +000011039 return;
11040
11041 // Also don't warn for arrays of size 1 which are members of some
11042 // structure. These are often used to approximate flexible arrays in C89
11043 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011044 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +000011045 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011046
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011047 // Suppress the warning if the subscript expression (as identified by the
11048 // ']' location) and the index expression are both from macro expansions
11049 // within a system header.
11050 if (ASE) {
11051 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
11052 ASE->getRBracketLoc());
11053 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
11054 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
11055 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +000011056 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011057 return;
11058 }
11059 }
11060
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011061 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011062 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011063 DiagID = diag::warn_array_index_exceeds_bounds;
11064
11065 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11066 PDiag(DiagID) << index.toString(10, true)
11067 << size.toString(10, true)
11068 << (unsigned)size.getLimitedValue(~0U)
11069 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011070 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011071 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011072 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011073 DiagID = diag::warn_ptr_arith_precedes_bounds;
11074 if (index.isNegative()) index = -index;
11075 }
11076
11077 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11078 PDiag(DiagID) << index.toString(10, true)
11079 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +000011080 }
Chandler Carruth1af88f12011-02-17 21:10:52 +000011081
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000011082 if (!ND) {
11083 // Try harder to find a NamedDecl to point at in the note.
11084 while (const ArraySubscriptExpr *ASE =
11085 dyn_cast<ArraySubscriptExpr>(BaseExpr))
11086 BaseExpr = ASE->getBase()->IgnoreParenCasts();
11087 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
11088 ND = dyn_cast<NamedDecl>(DRE->getDecl());
11089 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
11090 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
11091 }
11092
Chandler Carruth1af88f12011-02-17 21:10:52 +000011093 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011094 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
11095 PDiag(diag::note_array_index_out_of_bounds)
11096 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +000011097}
11098
Ted Kremenekdf26df72011-03-01 18:41:00 +000011099void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011100 int AllowOnePastEnd = 0;
11101 while (expr) {
11102 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +000011103 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011104 case Stmt::ArraySubscriptExprClass: {
11105 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011106 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011107 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +000011108 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011109 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +000011110 case Stmt::OMPArraySectionExprClass: {
11111 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
11112 if (ASE->getLowerBound())
11113 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
11114 /*ASE=*/nullptr, AllowOnePastEnd > 0);
11115 return;
11116 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011117 case Stmt::UnaryOperatorClass: {
11118 // Only unwrap the * and & unary operators
11119 const UnaryOperator *UO = cast<UnaryOperator>(expr);
11120 expr = UO->getSubExpr();
11121 switch (UO->getOpcode()) {
11122 case UO_AddrOf:
11123 AllowOnePastEnd++;
11124 break;
11125 case UO_Deref:
11126 AllowOnePastEnd--;
11127 break;
11128 default:
11129 return;
11130 }
11131 break;
11132 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011133 case Stmt::ConditionalOperatorClass: {
11134 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
11135 if (const Expr *lhs = cond->getLHS())
11136 CheckArrayAccess(lhs);
11137 if (const Expr *rhs = cond->getRHS())
11138 CheckArrayAccess(rhs);
11139 return;
11140 }
Daniel Marjamaki20a209e2017-02-28 14:53:50 +000011141 case Stmt::CXXOperatorCallExprClass: {
11142 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
11143 for (const auto *Arg : OCE->arguments())
11144 CheckArrayAccess(Arg);
11145 return;
11146 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011147 default:
11148 return;
11149 }
Peter Collingbourne91147592011-04-15 00:35:48 +000011150 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011151}
John McCall31168b02011-06-15 23:02:42 +000011152
11153//===--- CHECK: Objective-C retain cycles ----------------------------------//
11154
11155namespace {
John McCall31168b02011-06-15 23:02:42 +000011156
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011157struct RetainCycleOwner {
11158 VarDecl *Variable = nullptr;
11159 SourceRange Range;
11160 SourceLocation Loc;
11161 bool Indirect = false;
11162
11163 RetainCycleOwner() = default;
11164
11165 void setLocsFrom(Expr *e) {
11166 Loc = e->getExprLoc();
11167 Range = e->getSourceRange();
11168 }
11169};
11170
11171} // namespace
John McCall31168b02011-06-15 23:02:42 +000011172
11173/// Consider whether capturing the given variable can possibly lead to
11174/// a retain cycle.
11175static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000011176 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +000011177 // lifetime. In MRR, it's captured strongly if the variable is
11178 // __block and has an appropriate type.
11179 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11180 return false;
11181
11182 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011183 if (ref)
11184 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +000011185 return true;
11186}
11187
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011188static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +000011189 while (true) {
11190 e = e->IgnoreParens();
11191 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
11192 switch (cast->getCastKind()) {
11193 case CK_BitCast:
11194 case CK_LValueBitCast:
11195 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +000011196 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +000011197 e = cast->getSubExpr();
11198 continue;
11199
John McCall31168b02011-06-15 23:02:42 +000011200 default:
11201 return false;
11202 }
11203 }
11204
11205 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
11206 ObjCIvarDecl *ivar = ref->getDecl();
11207 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11208 return false;
11209
11210 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011211 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +000011212 return false;
11213
11214 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
11215 owner.Indirect = true;
11216 return true;
11217 }
11218
11219 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
11220 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
11221 if (!var) return false;
11222 return considerVariable(var, ref, owner);
11223 }
11224
John McCall31168b02011-06-15 23:02:42 +000011225 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
11226 if (member->isArrow()) return false;
11227
11228 // Don't count this as an indirect ownership.
11229 e = member->getBase();
11230 continue;
11231 }
11232
John McCallfe96e0b2011-11-06 09:01:30 +000011233 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
11234 // Only pay attention to pseudo-objects on property references.
11235 ObjCPropertyRefExpr *pre
11236 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
11237 ->IgnoreParens());
11238 if (!pre) return false;
11239 if (pre->isImplicitProperty()) return false;
11240 ObjCPropertyDecl *property = pre->getExplicitProperty();
11241 if (!property->isRetaining() &&
11242 !(property->getPropertyIvarDecl() &&
11243 property->getPropertyIvarDecl()->getType()
11244 .getObjCLifetime() == Qualifiers::OCL_Strong))
11245 return false;
11246
11247 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011248 if (pre->isSuperReceiver()) {
11249 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
11250 if (!owner.Variable)
11251 return false;
11252 owner.Loc = pre->getLocation();
11253 owner.Range = pre->getSourceRange();
11254 return true;
11255 }
John McCallfe96e0b2011-11-06 09:01:30 +000011256 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
11257 ->getSourceExpr());
11258 continue;
11259 }
11260
John McCall31168b02011-06-15 23:02:42 +000011261 // Array ivars?
11262
11263 return false;
11264 }
11265}
11266
11267namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011268
John McCall31168b02011-06-15 23:02:42 +000011269 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011270 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +000011271 VarDecl *Variable;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011272 Expr *Capturer = nullptr;
11273 bool VarWillBeReased = false;
11274
11275 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
11276 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
11277 Context(Context), Variable(variable) {}
John McCall31168b02011-06-15 23:02:42 +000011278
11279 void VisitDeclRefExpr(DeclRefExpr *ref) {
11280 if (ref->getDecl() == Variable && !Capturer)
11281 Capturer = ref;
11282 }
11283
John McCall31168b02011-06-15 23:02:42 +000011284 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
11285 if (Capturer) return;
11286 Visit(ref->getBase());
11287 if (Capturer && ref->isFreeIvar())
11288 Capturer = ref;
11289 }
11290
11291 void VisitBlockExpr(BlockExpr *block) {
11292 // Look inside nested blocks
11293 if (block->getBlockDecl()->capturesVariable(Variable))
11294 Visit(block->getBlockDecl()->getBody());
11295 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +000011296
11297 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
11298 if (Capturer) return;
11299 if (OVE->getSourceExpr())
11300 Visit(OVE->getSourceExpr());
11301 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011302
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011303 void VisitBinaryOperator(BinaryOperator *BinOp) {
11304 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
11305 return;
11306 Expr *LHS = BinOp->getLHS();
11307 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
11308 if (DRE->getDecl() != Variable)
11309 return;
11310 if (Expr *RHS = BinOp->getRHS()) {
11311 RHS = RHS->IgnoreParenCasts();
11312 llvm::APSInt Value;
11313 VarWillBeReased =
11314 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
11315 }
11316 }
11317 }
John McCall31168b02011-06-15 23:02:42 +000011318 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011319
11320} // namespace
John McCall31168b02011-06-15 23:02:42 +000011321
11322/// Check whether the given argument is a block which captures a
11323/// variable.
11324static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
11325 assert(owner.Variable && owner.Loc.isValid());
11326
11327 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000011328
11329 // Look through [^{...} copy] and Block_copy(^{...}).
11330 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
11331 Selector Cmd = ME->getSelector();
11332 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
11333 e = ME->getInstanceReceiver();
11334 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000011335 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000011336 e = e->IgnoreParenCasts();
11337 }
11338 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
11339 if (CE->getNumArgs() == 1) {
11340 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000011341 if (Fn) {
11342 const IdentifierInfo *FnI = Fn->getIdentifier();
11343 if (FnI && FnI->isStr("_Block_copy")) {
11344 e = CE->getArg(0)->IgnoreParenCasts();
11345 }
11346 }
Jordan Rose67e887c2012-09-17 17:54:30 +000011347 }
11348 }
11349
John McCall31168b02011-06-15 23:02:42 +000011350 BlockExpr *block = dyn_cast<BlockExpr>(e);
11351 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000011352 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000011353
11354 FindCaptureVisitor visitor(S.Context, owner.Variable);
11355 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011356 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000011357}
11358
11359static void diagnoseRetainCycle(Sema &S, Expr *capturer,
11360 RetainCycleOwner &owner) {
11361 assert(capturer);
11362 assert(owner.Variable && owner.Loc.isValid());
11363
11364 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
11365 << owner.Variable << capturer->getSourceRange();
11366 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
11367 << owner.Indirect << owner.Range;
11368}
11369
11370/// Check for a keyword selector that starts with the word 'add' or
11371/// 'set'.
11372static bool isSetterLikeSelector(Selector sel) {
11373 if (sel.isUnarySelector()) return false;
11374
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011375 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000011376 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011377 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000011378 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011379 else if (str.startswith("add")) {
11380 // Specially whitelist 'addOperationWithBlock:'.
11381 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
11382 return false;
11383 str = str.substr(3);
11384 }
John McCall31168b02011-06-15 23:02:42 +000011385 else
11386 return false;
11387
11388 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000011389 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000011390}
11391
Benjamin Kramer3a743452015-03-09 15:03:32 +000011392static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
11393 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011394 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
11395 Message->getReceiverInterface(),
11396 NSAPI::ClassId_NSMutableArray);
11397 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011398 return None;
11399 }
11400
11401 Selector Sel = Message->getSelector();
11402
11403 Optional<NSAPI::NSArrayMethodKind> MKOpt =
11404 S.NSAPIObj->getNSArrayMethodKind(Sel);
11405 if (!MKOpt) {
11406 return None;
11407 }
11408
11409 NSAPI::NSArrayMethodKind MK = *MKOpt;
11410
11411 switch (MK) {
11412 case NSAPI::NSMutableArr_addObject:
11413 case NSAPI::NSMutableArr_insertObjectAtIndex:
11414 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
11415 return 0;
11416 case NSAPI::NSMutableArr_replaceObjectAtIndex:
11417 return 1;
11418
11419 default:
11420 return None;
11421 }
11422
11423 return None;
11424}
11425
11426static
11427Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
11428 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011429 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
11430 Message->getReceiverInterface(),
11431 NSAPI::ClassId_NSMutableDictionary);
11432 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011433 return None;
11434 }
11435
11436 Selector Sel = Message->getSelector();
11437
11438 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
11439 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
11440 if (!MKOpt) {
11441 return None;
11442 }
11443
11444 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
11445
11446 switch (MK) {
11447 case NSAPI::NSMutableDict_setObjectForKey:
11448 case NSAPI::NSMutableDict_setValueForKey:
11449 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
11450 return 0;
11451
11452 default:
11453 return None;
11454 }
11455
11456 return None;
11457}
11458
11459static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011460 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
11461 Message->getReceiverInterface(),
11462 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000011463
Alex Denisov5dfac812015-08-06 04:51:14 +000011464 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
11465 Message->getReceiverInterface(),
11466 NSAPI::ClassId_NSMutableOrderedSet);
11467 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011468 return None;
11469 }
11470
11471 Selector Sel = Message->getSelector();
11472
11473 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
11474 if (!MKOpt) {
11475 return None;
11476 }
11477
11478 NSAPI::NSSetMethodKind MK = *MKOpt;
11479
11480 switch (MK) {
11481 case NSAPI::NSMutableSet_addObject:
11482 case NSAPI::NSOrderedSet_setObjectAtIndex:
11483 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
11484 case NSAPI::NSOrderedSet_insertObjectAtIndex:
11485 return 0;
11486 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
11487 return 1;
11488 }
11489
11490 return None;
11491}
11492
11493void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
11494 if (!Message->isInstanceMessage()) {
11495 return;
11496 }
11497
11498 Optional<int> ArgOpt;
11499
11500 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
11501 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
11502 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
11503 return;
11504 }
11505
11506 int ArgIndex = *ArgOpt;
11507
Alex Denisove1d882c2015-03-04 17:55:52 +000011508 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
11509 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
11510 Arg = OE->getSourceExpr()->IgnoreImpCasts();
11511 }
11512
Alex Denisov5dfac812015-08-06 04:51:14 +000011513 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011514 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011515 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011516 Diag(Message->getSourceRange().getBegin(),
11517 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +000011518 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +000011519 }
11520 }
Alex Denisov5dfac812015-08-06 04:51:14 +000011521 } else {
11522 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
11523
11524 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
11525 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
11526 }
11527
11528 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
11529 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11530 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
11531 ValueDecl *Decl = ReceiverRE->getDecl();
11532 Diag(Message->getSourceRange().getBegin(),
11533 diag::warn_objc_circular_container)
11534 << Decl->getName() << Decl->getName();
11535 if (!ArgRE->isObjCSelfExpr()) {
11536 Diag(Decl->getLocation(),
11537 diag::note_objc_circular_container_declared_here)
11538 << Decl->getName();
11539 }
11540 }
11541 }
11542 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
11543 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
11544 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
11545 ObjCIvarDecl *Decl = IvarRE->getDecl();
11546 Diag(Message->getSourceRange().getBegin(),
11547 diag::warn_objc_circular_container)
11548 << Decl->getName() << Decl->getName();
11549 Diag(Decl->getLocation(),
11550 diag::note_objc_circular_container_declared_here)
11551 << Decl->getName();
11552 }
Alex Denisove1d882c2015-03-04 17:55:52 +000011553 }
11554 }
11555 }
Alex Denisove1d882c2015-03-04 17:55:52 +000011556}
11557
John McCall31168b02011-06-15 23:02:42 +000011558/// Check a message send to see if it's likely to cause a retain cycle.
11559void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
11560 // Only check instance methods whose selector looks like a setter.
11561 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
11562 return;
11563
11564 // Try to find a variable that the receiver is strongly owned by.
11565 RetainCycleOwner owner;
11566 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011567 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000011568 return;
11569 } else {
11570 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
11571 owner.Variable = getCurMethodDecl()->getSelfDecl();
11572 owner.Loc = msg->getSuperLoc();
11573 owner.Range = msg->getSuperLoc();
11574 }
11575
11576 // Check whether the receiver is captured by any of the arguments.
Alex Lorenz42a97a92017-11-17 20:44:25 +000011577 const ObjCMethodDecl *MD = msg->getMethodDecl();
11578 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
11579 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
11580 // noescape blocks should not be retained by the method.
11581 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
11582 continue;
John McCall31168b02011-06-15 23:02:42 +000011583 return diagnoseRetainCycle(*this, capturer, owner);
Alex Lorenz42a97a92017-11-17 20:44:25 +000011584 }
11585 }
John McCall31168b02011-06-15 23:02:42 +000011586}
11587
11588/// Check a property assign to see if it's likely to cause a retain cycle.
11589void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
11590 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011591 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000011592 return;
11593
11594 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
11595 diagnoseRetainCycle(*this, capturer, owner);
11596}
11597
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011598void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
11599 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000011600 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011601 return;
11602
11603 // Because we don't have an expression for the variable, we have to set the
11604 // location explicitly here.
11605 Owner.Loc = Var->getLocation();
11606 Owner.Range = Var->getSourceRange();
11607
11608 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
11609 diagnoseRetainCycle(*this, Capturer, Owner);
11610}
11611
Ted Kremenek9304da92012-12-21 08:04:28 +000011612static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
11613 Expr *RHS, bool isProperty) {
11614 // Check if RHS is an Objective-C object literal, which also can get
11615 // immediately zapped in a weak reference. Note that we explicitly
11616 // allow ObjCStringLiterals, since those are designed to never really die.
11617 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011618
Ted Kremenek64873352012-12-21 22:46:35 +000011619 // This enum needs to match with the 'select' in
11620 // warn_objc_arc_literal_assign (off-by-1).
11621 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
11622 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
11623 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011624
11625 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000011626 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000011627 << (isProperty ? 0 : 1)
11628 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011629
11630 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000011631}
11632
Ted Kremenekc1f014a2012-12-21 19:45:30 +000011633static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
11634 Qualifiers::ObjCLifetime LT,
11635 Expr *RHS, bool isProperty) {
11636 // Strip off any implicit cast added to get to the one ARC-specific.
11637 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11638 if (cast->getCastKind() == CK_ARCConsumeObject) {
11639 S.Diag(Loc, diag::warn_arc_retained_assign)
11640 << (LT == Qualifiers::OCL_ExplicitNone)
11641 << (isProperty ? 0 : 1)
11642 << RHS->getSourceRange();
11643 return true;
11644 }
11645 RHS = cast->getSubExpr();
11646 }
11647
11648 if (LT == Qualifiers::OCL_Weak &&
11649 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
11650 return true;
11651
11652 return false;
11653}
11654
Ted Kremenekb36234d2012-12-21 08:04:20 +000011655bool Sema::checkUnsafeAssigns(SourceLocation Loc,
11656 QualType LHS, Expr *RHS) {
11657 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
11658
11659 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
11660 return false;
11661
11662 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
11663 return true;
11664
11665 return false;
11666}
11667
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011668void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
11669 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011670 QualType LHSType;
11671 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000011672 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011673 ObjCPropertyRefExpr *PRE
11674 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11675 if (PRE && !PRE->isImplicitProperty()) {
11676 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11677 if (PD)
11678 LHSType = PD->getType();
11679 }
11680
11681 if (LHSType.isNull())
11682 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000011683
11684 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
11685
11686 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011687 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000011688 getCurFunction()->markSafeWeakUse(LHS);
11689 }
11690
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011691 if (checkUnsafeAssigns(Loc, LHSType, RHS))
11692 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000011693
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011694 // FIXME. Check for other life times.
11695 if (LT != Qualifiers::OCL_None)
11696 return;
11697
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011698 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011699 if (PRE->isImplicitProperty())
11700 return;
11701 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11702 if (!PD)
11703 return;
11704
Bill Wendling44426052012-12-20 19:22:21 +000011705 unsigned Attributes = PD->getPropertyAttributes();
11706 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011707 // when 'assign' attribute was not explicitly specified
11708 // by user, ignore it and rely on property type itself
11709 // for lifetime info.
11710 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11711 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11712 LHSType->isObjCRetainableType())
11713 return;
11714
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011715 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000011716 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011717 Diag(Loc, diag::warn_arc_retained_property_assign)
11718 << RHS->getSourceRange();
11719 return;
11720 }
11721 RHS = cast->getSubExpr();
11722 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011723 }
Bill Wendling44426052012-12-20 19:22:21 +000011724 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000011725 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11726 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000011727 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011728 }
11729}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011730
11731//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11732
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011733static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11734 SourceLocation StmtLoc,
11735 const NullStmt *Body) {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011736 // Do not warn if the body is a macro that expands to nothing, e.g:
11737 //
11738 // #define CALL(x)
11739 // if (condition)
11740 // CALL(0);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011741 if (Body->hasLeadingEmptyMacro())
11742 return false;
11743
11744 // Get line numbers of statement and body.
11745 bool StmtLineInvalid;
Hans Wennborg95419752017-11-20 17:38:16 +000011746 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011747 &StmtLineInvalid);
11748 if (StmtLineInvalid)
11749 return false;
11750
11751 bool BodyLineInvalid;
11752 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11753 &BodyLineInvalid);
11754 if (BodyLineInvalid)
11755 return false;
11756
11757 // Warn if null statement and body are on the same line.
11758 if (StmtLine != BodyLine)
11759 return false;
11760
11761 return true;
11762}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011763
11764void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
11765 const Stmt *Body,
11766 unsigned DiagID) {
11767 // Since this is a syntactic check, don't emit diagnostic for template
11768 // instantiations, this just adds noise.
11769 if (CurrentInstantiationScope)
11770 return;
11771
11772 // The body should be a null statement.
11773 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11774 if (!NBody)
11775 return;
11776
11777 // Do the usual checks.
11778 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11779 return;
11780
11781 Diag(NBody->getSemiLoc(), DiagID);
11782 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11783}
11784
11785void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
11786 const Stmt *PossibleBody) {
11787 assert(!CurrentInstantiationScope); // Ensured by caller
11788
11789 SourceLocation StmtLoc;
11790 const Stmt *Body;
11791 unsigned DiagID;
11792 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11793 StmtLoc = FS->getRParenLoc();
11794 Body = FS->getBody();
11795 DiagID = diag::warn_empty_for_body;
11796 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11797 StmtLoc = WS->getCond()->getSourceRange().getEnd();
11798 Body = WS->getBody();
11799 DiagID = diag::warn_empty_while_body;
11800 } else
11801 return; // Neither `for' nor `while'.
11802
11803 // The body should be a null statement.
11804 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11805 if (!NBody)
11806 return;
11807
11808 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011809 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011810 return;
11811
11812 // Do the usual checks.
11813 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11814 return;
11815
11816 // `for(...);' and `while(...);' are popular idioms, so in order to keep
11817 // noise level low, emit diagnostics only if for/while is followed by a
11818 // CompoundStmt, e.g.:
11819 // for (int i = 0; i < n; i++);
11820 // {
11821 // a(i);
11822 // }
11823 // or if for/while is followed by a statement with more indentation
11824 // than for/while itself:
11825 // for (int i = 0; i < n; i++);
11826 // a(i);
11827 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
11828 if (!ProbableTypo) {
11829 bool BodyColInvalid;
11830 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
11831 PossibleBody->getLocStart(),
11832 &BodyColInvalid);
11833 if (BodyColInvalid)
11834 return;
11835
11836 bool StmtColInvalid;
11837 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
11838 S->getLocStart(),
11839 &StmtColInvalid);
11840 if (StmtColInvalid)
11841 return;
11842
11843 if (BodyCol > StmtCol)
11844 ProbableTypo = true;
11845 }
11846
11847 if (ProbableTypo) {
11848 Diag(NBody->getSemiLoc(), DiagID);
11849 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11850 }
11851}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011852
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011853//===--- CHECK: Warn on self move with std::move. -------------------------===//
11854
11855/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
11856void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
11857 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011858 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11859 return;
11860
Richard Smith51ec0cf2017-02-21 01:17:38 +000011861 if (inTemplateInstantiation())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011862 return;
11863
11864 // Strip parens and casts away.
11865 LHSExpr = LHSExpr->IgnoreParenImpCasts();
11866 RHSExpr = RHSExpr->IgnoreParenImpCasts();
11867
11868 // Check for a call expression
11869 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
11870 if (!CE || CE->getNumArgs() != 1)
11871 return;
11872
11873 // Check for a call to std::move
Nico Weberb688d132017-09-28 16:16:39 +000011874 if (!CE->isCallToStdMove())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011875 return;
11876
11877 // Get argument from std::move
11878 RHSExpr = CE->getArg(0);
11879
11880 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11881 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11882
11883 // Two DeclRefExpr's, check that the decls are the same.
11884 if (LHSDeclRef && RHSDeclRef) {
11885 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11886 return;
11887 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11888 RHSDeclRef->getDecl()->getCanonicalDecl())
11889 return;
11890
11891 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11892 << LHSExpr->getSourceRange()
11893 << RHSExpr->getSourceRange();
11894 return;
11895 }
11896
11897 // Member variables require a different approach to check for self moves.
11898 // MemberExpr's are the same if every nested MemberExpr refers to the same
11899 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
11900 // the base Expr's are CXXThisExpr's.
11901 const Expr *LHSBase = LHSExpr;
11902 const Expr *RHSBase = RHSExpr;
11903 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
11904 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
11905 if (!LHSME || !RHSME)
11906 return;
11907
11908 while (LHSME && RHSME) {
11909 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
11910 RHSME->getMemberDecl()->getCanonicalDecl())
11911 return;
11912
11913 LHSBase = LHSME->getBase();
11914 RHSBase = RHSME->getBase();
11915 LHSME = dyn_cast<MemberExpr>(LHSBase);
11916 RHSME = dyn_cast<MemberExpr>(RHSBase);
11917 }
11918
11919 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
11920 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
11921 if (LHSDeclRef && RHSDeclRef) {
11922 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11923 return;
11924 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11925 RHSDeclRef->getDecl()->getCanonicalDecl())
11926 return;
11927
11928 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11929 << LHSExpr->getSourceRange()
11930 << RHSExpr->getSourceRange();
11931 return;
11932 }
11933
11934 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
11935 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11936 << LHSExpr->getSourceRange()
11937 << RHSExpr->getSourceRange();
11938}
11939
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011940//===--- Layout compatibility ----------------------------------------------//
11941
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011942static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011943
11944/// \brief Check if two enumeration types are layout-compatible.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011945static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011946 // C++11 [dcl.enum] p8:
11947 // Two enumeration types are layout-compatible if they have the same
11948 // underlying type.
11949 return ED1->isComplete() && ED2->isComplete() &&
11950 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
11951}
11952
11953/// \brief Check if two fields are layout-compatible.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011954static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
11955 FieldDecl *Field2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011956 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
11957 return false;
11958
11959 if (Field1->isBitField() != Field2->isBitField())
11960 return false;
11961
11962 if (Field1->isBitField()) {
11963 // Make sure that the bit-fields are the same length.
11964 unsigned Bits1 = Field1->getBitWidthValue(C);
11965 unsigned Bits2 = Field2->getBitWidthValue(C);
11966
11967 if (Bits1 != Bits2)
11968 return false;
11969 }
11970
11971 return true;
11972}
11973
11974/// \brief Check if two standard-layout structs are layout-compatible.
11975/// (C++11 [class.mem] p17)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011976static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
11977 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011978 // If both records are C++ classes, check that base classes match.
11979 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
11980 // If one of records is a CXXRecordDecl we are in C++ mode,
11981 // thus the other one is a CXXRecordDecl, too.
11982 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
11983 // Check number of base classes.
11984 if (D1CXX->getNumBases() != D2CXX->getNumBases())
11985 return false;
11986
11987 // Check the base classes.
11988 for (CXXRecordDecl::base_class_const_iterator
11989 Base1 = D1CXX->bases_begin(),
11990 BaseEnd1 = D1CXX->bases_end(),
11991 Base2 = D2CXX->bases_begin();
11992 Base1 != BaseEnd1;
11993 ++Base1, ++Base2) {
11994 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
11995 return false;
11996 }
11997 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
11998 // If only RD2 is a C++ class, it should have zero base classes.
11999 if (D2CXX->getNumBases() > 0)
12000 return false;
12001 }
12002
12003 // Check the fields.
12004 RecordDecl::field_iterator Field2 = RD2->field_begin(),
12005 Field2End = RD2->field_end(),
12006 Field1 = RD1->field_begin(),
12007 Field1End = RD1->field_end();
12008 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
12009 if (!isLayoutCompatible(C, *Field1, *Field2))
12010 return false;
12011 }
12012 if (Field1 != Field1End || Field2 != Field2End)
12013 return false;
12014
12015 return true;
12016}
12017
12018/// \brief Check if two standard-layout unions are layout-compatible.
12019/// (C++11 [class.mem] p18)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012020static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
12021 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012022 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012023 for (auto *Field2 : RD2->fields())
12024 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012025
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012026 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012027 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
12028 I = UnmatchedFields.begin(),
12029 E = UnmatchedFields.end();
12030
12031 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012032 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012033 bool Result = UnmatchedFields.erase(*I);
12034 (void) Result;
12035 assert(Result);
12036 break;
12037 }
12038 }
12039 if (I == E)
12040 return false;
12041 }
12042
12043 return UnmatchedFields.empty();
12044}
12045
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012046static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
12047 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012048 if (RD1->isUnion() != RD2->isUnion())
12049 return false;
12050
12051 if (RD1->isUnion())
12052 return isLayoutCompatibleUnion(C, RD1, RD2);
12053 else
12054 return isLayoutCompatibleStruct(C, RD1, RD2);
12055}
12056
12057/// \brief Check if two types are layout-compatible in C++11 sense.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012058static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012059 if (T1.isNull() || T2.isNull())
12060 return false;
12061
12062 // C++11 [basic.types] p11:
12063 // If two types T1 and T2 are the same type, then T1 and T2 are
12064 // layout-compatible types.
12065 if (C.hasSameType(T1, T2))
12066 return true;
12067
12068 T1 = T1.getCanonicalType().getUnqualifiedType();
12069 T2 = T2.getCanonicalType().getUnqualifiedType();
12070
12071 const Type::TypeClass TC1 = T1->getTypeClass();
12072 const Type::TypeClass TC2 = T2->getTypeClass();
12073
12074 if (TC1 != TC2)
12075 return false;
12076
12077 if (TC1 == Type::Enum) {
12078 return isLayoutCompatible(C,
12079 cast<EnumType>(T1)->getDecl(),
12080 cast<EnumType>(T2)->getDecl());
12081 } else if (TC1 == Type::Record) {
12082 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
12083 return false;
12084
12085 return isLayoutCompatible(C,
12086 cast<RecordType>(T1)->getDecl(),
12087 cast<RecordType>(T2)->getDecl());
12088 }
12089
12090 return false;
12091}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012092
12093//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
12094
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012095/// \brief Given a type tag expression find the type tag itself.
12096///
12097/// \param TypeExpr Type tag expression, as it appears in user's code.
12098///
12099/// \param VD Declaration of an identifier that appears in a type tag.
12100///
12101/// \param MagicValue Type tag magic value.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012102static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
12103 const ValueDecl **VD, uint64_t *MagicValue) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012104 while(true) {
12105 if (!TypeExpr)
12106 return false;
12107
12108 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
12109
12110 switch (TypeExpr->getStmtClass()) {
12111 case Stmt::UnaryOperatorClass: {
12112 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
12113 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
12114 TypeExpr = UO->getSubExpr();
12115 continue;
12116 }
12117 return false;
12118 }
12119
12120 case Stmt::DeclRefExprClass: {
12121 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
12122 *VD = DRE->getDecl();
12123 return true;
12124 }
12125
12126 case Stmt::IntegerLiteralClass: {
12127 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
12128 llvm::APInt MagicValueAPInt = IL->getValue();
12129 if (MagicValueAPInt.getActiveBits() <= 64) {
12130 *MagicValue = MagicValueAPInt.getZExtValue();
12131 return true;
12132 } else
12133 return false;
12134 }
12135
12136 case Stmt::BinaryConditionalOperatorClass:
12137 case Stmt::ConditionalOperatorClass: {
12138 const AbstractConditionalOperator *ACO =
12139 cast<AbstractConditionalOperator>(TypeExpr);
12140 bool Result;
12141 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
12142 if (Result)
12143 TypeExpr = ACO->getTrueExpr();
12144 else
12145 TypeExpr = ACO->getFalseExpr();
12146 continue;
12147 }
12148 return false;
12149 }
12150
12151 case Stmt::BinaryOperatorClass: {
12152 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
12153 if (BO->getOpcode() == BO_Comma) {
12154 TypeExpr = BO->getRHS();
12155 continue;
12156 }
12157 return false;
12158 }
12159
12160 default:
12161 return false;
12162 }
12163 }
12164}
12165
12166/// \brief Retrieve the C type corresponding to type tag TypeExpr.
12167///
12168/// \param TypeExpr Expression that specifies a type tag.
12169///
12170/// \param MagicValues Registered magic values.
12171///
12172/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
12173/// kind.
12174///
12175/// \param TypeInfo Information about the corresponding C type.
12176///
12177/// \returns true if the corresponding C type was found.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012178static bool GetMatchingCType(
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012179 const IdentifierInfo *ArgumentKind,
12180 const Expr *TypeExpr, const ASTContext &Ctx,
12181 const llvm::DenseMap<Sema::TypeTagMagicValue,
12182 Sema::TypeTagData> *MagicValues,
12183 bool &FoundWrongKind,
12184 Sema::TypeTagData &TypeInfo) {
12185 FoundWrongKind = false;
12186
12187 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000012188 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012189
12190 uint64_t MagicValue;
12191
12192 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
12193 return false;
12194
12195 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000012196 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012197 if (I->getArgumentKind() != ArgumentKind) {
12198 FoundWrongKind = true;
12199 return false;
12200 }
12201 TypeInfo.Type = I->getMatchingCType();
12202 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
12203 TypeInfo.MustBeNull = I->getMustBeNull();
12204 return true;
12205 }
12206 return false;
12207 }
12208
12209 if (!MagicValues)
12210 return false;
12211
12212 llvm::DenseMap<Sema::TypeTagMagicValue,
12213 Sema::TypeTagData>::const_iterator I =
12214 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
12215 if (I == MagicValues->end())
12216 return false;
12217
12218 TypeInfo = I->second;
12219 return true;
12220}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012221
12222void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
12223 uint64_t MagicValue, QualType Type,
12224 bool LayoutCompatible,
12225 bool MustBeNull) {
12226 if (!TypeTagForDatatypeMagicValues)
12227 TypeTagForDatatypeMagicValues.reset(
12228 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
12229
12230 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
12231 (*TypeTagForDatatypeMagicValues)[Magic] =
12232 TypeTagData(Type, LayoutCompatible, MustBeNull);
12233}
12234
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012235static bool IsSameCharType(QualType T1, QualType T2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012236 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
12237 if (!BT1)
12238 return false;
12239
12240 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
12241 if (!BT2)
12242 return false;
12243
12244 BuiltinType::Kind T1Kind = BT1->getKind();
12245 BuiltinType::Kind T2Kind = BT2->getKind();
12246
12247 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
12248 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
12249 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
12250 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
12251}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012252
12253void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012254 const ArrayRef<const Expr *> ExprArgs,
12255 SourceLocation CallSiteLoc) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012256 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
12257 bool IsPointerAttr = Attr->getIsPointer();
12258
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012259 // Retrieve the argument representing the 'type_tag'.
12260 if (Attr->getTypeTagIdx() >= ExprArgs.size()) {
12261 // Add 1 to display the user's specified value.
12262 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
12263 << 0 << Attr->getTypeTagIdx() + 1;
12264 return;
12265 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012266 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
12267 bool FoundWrongKind;
12268 TypeTagData TypeInfo;
12269 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
12270 TypeTagForDatatypeMagicValues.get(),
12271 FoundWrongKind, TypeInfo)) {
12272 if (FoundWrongKind)
12273 Diag(TypeTagExpr->getExprLoc(),
12274 diag::warn_type_tag_for_datatype_wrong_kind)
12275 << TypeTagExpr->getSourceRange();
12276 return;
12277 }
12278
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012279 // Retrieve the argument representing the 'arg_idx'.
12280 if (Attr->getArgumentIdx() >= ExprArgs.size()) {
12281 // Add 1 to display the user's specified value.
12282 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
12283 << 1 << Attr->getArgumentIdx() + 1;
12284 return;
12285 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012286 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
12287 if (IsPointerAttr) {
12288 // Skip implicit cast of pointer to `void *' (as a function argument).
12289 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000012290 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000012291 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012292 ArgumentExpr = ICE->getSubExpr();
12293 }
12294 QualType ArgumentType = ArgumentExpr->getType();
12295
12296 // Passing a `void*' pointer shouldn't trigger a warning.
12297 if (IsPointerAttr && ArgumentType->isVoidPointerType())
12298 return;
12299
12300 if (TypeInfo.MustBeNull) {
12301 // Type tag with matching void type requires a null pointer.
12302 if (!ArgumentExpr->isNullPointerConstant(Context,
12303 Expr::NPC_ValueDependentIsNotNull)) {
12304 Diag(ArgumentExpr->getExprLoc(),
12305 diag::warn_type_safety_null_pointer_required)
12306 << ArgumentKind->getName()
12307 << ArgumentExpr->getSourceRange()
12308 << TypeTagExpr->getSourceRange();
12309 }
12310 return;
12311 }
12312
12313 QualType RequiredType = TypeInfo.Type;
12314 if (IsPointerAttr)
12315 RequiredType = Context.getPointerType(RequiredType);
12316
12317 bool mismatch = false;
12318 if (!TypeInfo.LayoutCompatible) {
12319 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
12320
12321 // C++11 [basic.fundamental] p1:
12322 // Plain char, signed char, and unsigned char are three distinct types.
12323 //
12324 // But we treat plain `char' as equivalent to `signed char' or `unsigned
12325 // char' depending on the current char signedness mode.
12326 if (mismatch)
12327 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
12328 RequiredType->getPointeeType())) ||
12329 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
12330 mismatch = false;
12331 } else
12332 if (IsPointerAttr)
12333 mismatch = !isLayoutCompatible(Context,
12334 ArgumentType->getPointeeType(),
12335 RequiredType->getPointeeType());
12336 else
12337 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
12338
12339 if (mismatch)
12340 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000012341 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012342 << TypeInfo.LayoutCompatible << RequiredType
12343 << ArgumentExpr->getSourceRange()
12344 << TypeTagExpr->getSourceRange();
12345}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012346
12347void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
12348 CharUnits Alignment) {
12349 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
12350}
12351
12352void Sema::DiagnoseMisalignedMembers() {
12353 for (MisalignedMember &m : MisalignedMembers) {
Alex Lorenz014181e2016-10-05 09:27:48 +000012354 const NamedDecl *ND = m.RD;
12355 if (ND->getName().empty()) {
12356 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
12357 ND = TD;
12358 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012359 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
Alex Lorenz014181e2016-10-05 09:27:48 +000012360 << m.MD << ND << m.E->getSourceRange();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012361 }
12362 MisalignedMembers.clear();
12363}
12364
12365void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012366 E = E->IgnoreParens();
12367 if (!T->isPointerType() && !T->isIntegerType())
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012368 return;
12369 if (isa<UnaryOperator>(E) &&
12370 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
12371 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12372 if (isa<MemberExpr>(Op)) {
12373 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
12374 MisalignedMember(Op));
12375 if (MA != MisalignedMembers.end() &&
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012376 (T->isIntegerType() ||
Roger Ferrer Ibanezd80d6c52017-12-07 09:23:50 +000012377 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
12378 Context.getTypeAlignInChars(
12379 T->getPointeeType()) <= MA->Alignment))))
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012380 MisalignedMembers.erase(MA);
12381 }
12382 }
12383}
12384
12385void Sema::RefersToMemberWithReducedAlignment(
12386 Expr *E,
Benjamin Kramera8c3e672016-12-12 14:41:19 +000012387 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
12388 Action) {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012389 const auto *ME = dyn_cast<MemberExpr>(E);
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012390 if (!ME)
12391 return;
12392
Roger Ferrer Ibanez9f963472017-03-13 13:18:21 +000012393 // No need to check expressions with an __unaligned-qualified type.
12394 if (E->getType().getQualifiers().hasUnaligned())
12395 return;
12396
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012397 // For a chain of MemberExpr like "a.b.c.d" this list
12398 // will keep FieldDecl's like [d, c, b].
12399 SmallVector<FieldDecl *, 4> ReverseMemberChain;
12400 const MemberExpr *TopME = nullptr;
12401 bool AnyIsPacked = false;
12402 do {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012403 QualType BaseType = ME->getBase()->getType();
12404 if (ME->isArrow())
12405 BaseType = BaseType->getPointeeType();
12406 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
Olivier Goffart67049f02017-07-07 09:38:59 +000012407 if (RD->isInvalidDecl())
12408 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012409
12410 ValueDecl *MD = ME->getMemberDecl();
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012411 auto *FD = dyn_cast<FieldDecl>(MD);
12412 // We do not care about non-data members.
12413 if (!FD || FD->isInvalidDecl())
12414 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012415
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012416 AnyIsPacked =
12417 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
12418 ReverseMemberChain.push_back(FD);
12419
12420 TopME = ME;
12421 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
12422 } while (ME);
12423 assert(TopME && "We did not compute a topmost MemberExpr!");
12424
12425 // Not the scope of this diagnostic.
12426 if (!AnyIsPacked)
12427 return;
12428
12429 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
12430 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
12431 // TODO: The innermost base of the member expression may be too complicated.
12432 // For now, just disregard these cases. This is left for future
12433 // improvement.
12434 if (!DRE && !isa<CXXThisExpr>(TopBase))
12435 return;
12436
12437 // Alignment expected by the whole expression.
12438 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
12439
12440 // No need to do anything else with this case.
12441 if (ExpectedAlignment.isOne())
12442 return;
12443
12444 // Synthesize offset of the whole access.
12445 CharUnits Offset;
12446 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
12447 I++) {
12448 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
12449 }
12450
12451 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
12452 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
12453 ReverseMemberChain.back()->getParent()->getTypeForDecl());
12454
12455 // The base expression of the innermost MemberExpr may give
12456 // stronger guarantees than the class containing the member.
12457 if (DRE && !TopME->isArrow()) {
12458 const ValueDecl *VD = DRE->getDecl();
12459 if (!VD->getType()->isReferenceType())
12460 CompleteObjectAlignment =
12461 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
12462 }
12463
12464 // Check if the synthesized offset fulfills the alignment.
12465 if (Offset % ExpectedAlignment != 0 ||
12466 // It may fulfill the offset it but the effective alignment may still be
12467 // lower than the expected expression alignment.
12468 CompleteObjectAlignment < ExpectedAlignment) {
12469 // If this happens, we want to determine a sensible culprit of this.
12470 // Intuitively, watching the chain of member expressions from right to
12471 // left, we start with the required alignment (as required by the field
12472 // type) but some packed attribute in that chain has reduced the alignment.
12473 // It may happen that another packed structure increases it again. But if
12474 // we are here such increase has not been enough. So pointing the first
12475 // FieldDecl that either is packed or else its RecordDecl is,
12476 // seems reasonable.
12477 FieldDecl *FD = nullptr;
12478 CharUnits Alignment;
12479 for (FieldDecl *FDI : ReverseMemberChain) {
12480 if (FDI->hasAttr<PackedAttr>() ||
12481 FDI->getParent()->hasAttr<PackedAttr>()) {
12482 FD = FDI;
12483 Alignment = std::min(
12484 Context.getTypeAlignInChars(FD->getType()),
12485 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
12486 break;
12487 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012488 }
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012489 assert(FD && "We did not find a packed FieldDecl!");
12490 Action(E, FD->getParent(), FD, Alignment);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012491 }
12492}
12493
12494void Sema::CheckAddressOfPackedMember(Expr *rhs) {
12495 using namespace std::placeholders;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012496
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012497 RefersToMemberWithReducedAlignment(
12498 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
12499 _2, _3, _4));
12500}