1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements extra semantic analysis beyond what is enforced
11 //  by the C type system.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "clang/AST/APValue.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/AttrIterator.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/Decl.h"
21 #include "clang/AST/DeclBase.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/DeclarationName.h"
25 #include "clang/AST/EvaluatedExprVisitor.h"
26 #include "clang/AST/Expr.h"
27 #include "clang/AST/ExprCXX.h"
28 #include "clang/AST/ExprObjC.h"
29 #include "clang/AST/ExprOpenMP.h"
30 #include "clang/AST/NSAPI.h"
31 #include "clang/AST/NonTrivialTypeVisitor.h"
32 #include "clang/AST/OperationKinds.h"
33 #include "clang/AST/Stmt.h"
34 #include "clang/AST/TemplateBase.h"
35 #include "clang/AST/Type.h"
36 #include "clang/AST/TypeLoc.h"
37 #include "clang/AST/UnresolvedSet.h"
38 #include "clang/Analysis/Analyses/FormatString.h"
39 #include "clang/Basic/AddressSpaces.h"
40 #include "clang/Basic/CharInfo.h"
41 #include "clang/Basic/Diagnostic.h"
42 #include "clang/Basic/IdentifierTable.h"
43 #include "clang/Basic/LLVM.h"
44 #include "clang/Basic/LangOptions.h"
45 #include "clang/Basic/OpenCLOptions.h"
46 #include "clang/Basic/OperatorKinds.h"
47 #include "clang/Basic/PartialDiagnostic.h"
48 #include "clang/Basic/SourceLocation.h"
49 #include "clang/Basic/SourceManager.h"
50 #include "clang/Basic/Specifiers.h"
51 #include "clang/Basic/SyncScope.h"
52 #include "clang/Basic/TargetBuiltins.h"
53 #include "clang/Basic/TargetCXXABI.h"
54 #include "clang/Basic/TargetInfo.h"
55 #include "clang/Basic/TypeTraits.h"
56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
57 #include "clang/Sema/Initialization.h"
58 #include "clang/Sema/Lookup.h"
59 #include "clang/Sema/Ownership.h"
60 #include "clang/Sema/Scope.h"
61 #include "clang/Sema/ScopeInfo.h"
62 #include "clang/Sema/Sema.h"
63 #include "clang/Sema/SemaInternal.h"
64 #include "llvm/ADT/APFloat.h"
65 #include "llvm/ADT/APInt.h"
66 #include "llvm/ADT/APSInt.h"
67 #include "llvm/ADT/ArrayRef.h"
68 #include "llvm/ADT/DenseMap.h"
69 #include "llvm/ADT/FoldingSet.h"
70 #include "llvm/ADT/None.h"
71 #include "llvm/ADT/Optional.h"
72 #include "llvm/ADT/STLExtras.h"
73 #include "llvm/ADT/SmallBitVector.h"
74 #include "llvm/ADT/SmallPtrSet.h"
75 #include "llvm/ADT/SmallString.h"
76 #include "llvm/ADT/SmallVector.h"
77 #include "llvm/ADT/StringRef.h"
78 #include "llvm/ADT/StringSwitch.h"
79 #include "llvm/ADT/Triple.h"
80 #include "llvm/Support/AtomicOrdering.h"
81 #include "llvm/Support/Casting.h"
82 #include "llvm/Support/Compiler.h"
83 #include "llvm/Support/ConvertUTF.h"
84 #include "llvm/Support/ErrorHandling.h"
85 #include "llvm/Support/Format.h"
86 #include "llvm/Support/Locale.h"
87 #include "llvm/Support/MathExtras.h"
88 #include "llvm/Support/raw_ostream.h"
89 #include <algorithm>
90 #include <cassert>
91 #include <cstddef>
92 #include <cstdint>
93 #include <functional>
94 #include <limits>
95 #include <string>
96 #include <tuple>
97 #include <utility>
98 
99 using namespace clang;
100 using namespace sema;
101 
102 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
103                                                     unsigned ByteNo) const {
104   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
105                                Context.getTargetInfo());
106 }
107 
108 /// Checks that a call expression's argument count is the desired number.
109 /// This is useful when doing custom type-checking.  Returns true on error.
110 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
111   unsigned argCount = call->getNumArgs();
112   if (argCount == desiredArgCount) return false;
113 
114   if (argCount < desiredArgCount)
115     return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
116         << 0 /*function call*/ << desiredArgCount << argCount
117         << call->getSourceRange();
118 
119   // Highlight all the excess arguments.
120   SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
121                     call->getArg(argCount - 1)->getLocEnd());
122 
123   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
124     << 0 /*function call*/ << desiredArgCount << argCount
125     << call->getArg(1)->getSourceRange();
126 }
127 
128 /// Check that the first argument to __builtin_annotation is an integer
129 /// and the second argument is a non-wide string literal.
130 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
131   if (checkArgCount(S, TheCall, 2))
132     return true;
133 
134   // First argument should be an integer.
135   Expr *ValArg = TheCall->getArg(0);
136   QualType Ty = ValArg->getType();
137   if (!Ty->isIntegerType()) {
138     S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
139       << ValArg->getSourceRange();
140     return true;
141   }
142 
143   // Second argument should be a constant string.
144   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
145   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
146   if (!Literal || !Literal->isAscii()) {
147     S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
148       << StrArg->getSourceRange();
149     return true;
150   }
151 
152   TheCall->setType(Ty);
153   return false;
154 }
155 
156 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
157   // We need at least one argument.
158   if (TheCall->getNumArgs() < 1) {
159     S.Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
160         << 0 << 1 << TheCall->getNumArgs()
161         << TheCall->getCallee()->getSourceRange();
162     return true;
163   }
164 
165   // All arguments should be wide string literals.
166   for (Expr *Arg : TheCall->arguments()) {
167     auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
168     if (!Literal || !Literal->isWide()) {
169       S.Diag(Arg->getLocStart(), diag::err_msvc_annotation_wide_str)
170           << Arg->getSourceRange();
171       return true;
172     }
173   }
174 
175   return false;
176 }
177 
178 /// Check that the argument to __builtin_addressof is a glvalue, and set the
179 /// result type to the corresponding pointer type.
180 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
181   if (checkArgCount(S, TheCall, 1))
182     return true;
183 
184   ExprResult Arg(TheCall->getArg(0));
185   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
186   if (ResultType.isNull())
187     return true;
188 
189   TheCall->setArg(0, Arg.get());
190   TheCall->setType(ResultType);
191   return false;
192 }
193 
194 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
195   if (checkArgCount(S, TheCall, 3))
196     return true;
197 
198   // First two arguments should be integers.
199   for (unsigned I = 0; I < 2; ++I) {
200     Expr *Arg = TheCall->getArg(I);
201     QualType Ty = Arg->getType();
202     if (!Ty->isIntegerType()) {
203       S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
204           << Ty << Arg->getSourceRange();
205       return true;
206     }
207   }
208 
209   // Third argument should be a pointer to a non-const integer.
210   // IRGen correctly handles volatile, restrict, and address spaces, and
211   // the other qualifiers aren't possible.
212   {
213     Expr *Arg = TheCall->getArg(2);
214     QualType Ty = Arg->getType();
215     const auto *PtrTy = Ty->getAs<PointerType>();
216     if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
217           !PtrTy->getPointeeType().isConstQualified())) {
218       S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
219           << Ty << Arg->getSourceRange();
220       return true;
221     }
222   }
223 
224   return false;
225 }
226 
227 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
228 		                  CallExpr *TheCall, unsigned SizeIdx,
229                                   unsigned DstSizeIdx) {
230   if (TheCall->getNumArgs() <= SizeIdx ||
231       TheCall->getNumArgs() <= DstSizeIdx)
232     return;
233 
234   const Expr *SizeArg = TheCall->getArg(SizeIdx);
235   const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
236 
237   llvm::APSInt Size, DstSize;
238 
239   // find out if both sizes are known at compile time
240   if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
241       !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
242     return;
243 
244   if (Size.ule(DstSize))
245     return;
246 
247   // confirmed overflow so generate the diagnostic.
248   IdentifierInfo *FnName = FDecl->getIdentifier();
249   SourceLocation SL = TheCall->getLocStart();
250   SourceRange SR = TheCall->getSourceRange();
251 
252   S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
253 }
254 
255 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
256   if (checkArgCount(S, BuiltinCall, 2))
257     return true;
258 
259   SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
260   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
261   Expr *Call = BuiltinCall->getArg(0);
262   Expr *Chain = BuiltinCall->getArg(1);
263 
264   if (Call->getStmtClass() != Stmt::CallExprClass) {
265     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
266         << Call->getSourceRange();
267     return true;
268   }
269 
270   auto CE = cast<CallExpr>(Call);
271   if (CE->getCallee()->getType()->isBlockPointerType()) {
272     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
273         << Call->getSourceRange();
274     return true;
275   }
276 
277   const Decl *TargetDecl = CE->getCalleeDecl();
278   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
279     if (FD->getBuiltinID()) {
280       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
281           << Call->getSourceRange();
282       return true;
283     }
284 
285   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
286     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
287         << Call->getSourceRange();
288     return true;
289   }
290 
291   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
292   if (ChainResult.isInvalid())
293     return true;
294   if (!ChainResult.get()->getType()->isPointerType()) {
295     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
296         << Chain->getSourceRange();
297     return true;
298   }
299 
300   QualType ReturnTy = CE->getCallReturnType(S.Context);
301   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
302   QualType BuiltinTy = S.Context.getFunctionType(
303       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
304   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
305 
306   Builtin =
307       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
308 
309   BuiltinCall->setType(CE->getType());
310   BuiltinCall->setValueKind(CE->getValueKind());
311   BuiltinCall->setObjectKind(CE->getObjectKind());
312   BuiltinCall->setCallee(Builtin);
313   BuiltinCall->setArg(1, ChainResult.get());
314 
315   return false;
316 }
317 
318 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
319                                      Scope::ScopeFlags NeededScopeFlags,
320                                      unsigned DiagID) {
321   // Scopes aren't available during instantiation. Fortunately, builtin
322   // functions cannot be template args so they cannot be formed through template
323   // instantiation. Therefore checking once during the parse is sufficient.
324   if (SemaRef.inTemplateInstantiation())
325     return false;
326 
327   Scope *S = SemaRef.getCurScope();
328   while (S && !S->isSEHExceptScope())
329     S = S->getParent();
330   if (!S || !(S->getFlags() & NeededScopeFlags)) {
331     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
332     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
333         << DRE->getDecl()->getIdentifier();
334     return true;
335   }
336 
337   return false;
338 }
339 
340 static inline bool isBlockPointer(Expr *Arg) {
341   return Arg->getType()->isBlockPointerType();
342 }
343 
344 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
345 /// void*, which is a requirement of device side enqueue.
346 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
347   const BlockPointerType *BPT =
348       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
349   ArrayRef<QualType> Params =
350       BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
351   unsigned ArgCounter = 0;
352   bool IllegalParams = false;
353   // Iterate through the block parameters until either one is found that is not
354   // a local void*, or the block is valid.
355   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
356        I != E; ++I, ++ArgCounter) {
357     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
358         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
359             LangAS::opencl_local) {
360       // Get the location of the error. If a block literal has been passed
361       // (BlockExpr) then we can point straight to the offending argument,
362       // else we just point to the variable reference.
363       SourceLocation ErrorLoc;
364       if (isa<BlockExpr>(BlockArg)) {
365         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
366         ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
367       } else if (isa<DeclRefExpr>(BlockArg)) {
368         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
369       }
370       S.Diag(ErrorLoc,
371              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
372       IllegalParams = true;
373     }
374   }
375 
376   return IllegalParams;
377 }
378 
379 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
380   if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
381     S.Diag(Call->getLocStart(), diag::err_opencl_requires_extension)
382           << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
383     return true;
384   }
385   return false;
386 }
387 
388 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
389   if (checkArgCount(S, TheCall, 2))
390     return true;
391 
392   if (checkOpenCLSubgroupExt(S, TheCall))
393     return true;
394 
395   // First argument is an ndrange_t type.
396   Expr *NDRangeArg = TheCall->getArg(0);
397   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
398     S.Diag(NDRangeArg->getLocStart(),
399            diag::err_opencl_builtin_expected_type)
400         << TheCall->getDirectCallee() << "'ndrange_t'";
401     return true;
402   }
403 
404   Expr *BlockArg = TheCall->getArg(1);
405   if (!isBlockPointer(BlockArg)) {
406     S.Diag(BlockArg->getLocStart(),
407            diag::err_opencl_builtin_expected_type)
408         << TheCall->getDirectCallee() << "block";
409     return true;
410   }
411   return checkOpenCLBlockArgs(S, BlockArg);
412 }
413 
414 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
415 /// get_kernel_work_group_size
416 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
417 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
418   if (checkArgCount(S, TheCall, 1))
419     return true;
420 
421   Expr *BlockArg = TheCall->getArg(0);
422   if (!isBlockPointer(BlockArg)) {
423     S.Diag(BlockArg->getLocStart(),
424            diag::err_opencl_builtin_expected_type)
425         << TheCall->getDirectCallee() << "block";
426     return true;
427   }
428   return checkOpenCLBlockArgs(S, BlockArg);
429 }
430 
431 /// Diagnose integer type and any valid implicit conversion to it.
432 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
433                                       const QualType &IntType);
434 
435 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
436                                             unsigned Start, unsigned End) {
437   bool IllegalParams = false;
438   for (unsigned I = Start; I <= End; ++I)
439     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
440                                               S.Context.getSizeType());
441   return IllegalParams;
442 }
443 
444 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
445 /// 'local void*' parameter of passed block.
446 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
447                                            Expr *BlockArg,
448                                            unsigned NumNonVarArgs) {
449   const BlockPointerType *BPT =
450       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
451   unsigned NumBlockParams =
452       BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
453   unsigned TotalNumArgs = TheCall->getNumArgs();
454 
455   // For each argument passed to the block, a corresponding uint needs to
456   // be passed to describe the size of the local memory.
457   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
458     S.Diag(TheCall->getLocStart(),
459            diag::err_opencl_enqueue_kernel_local_size_args);
460     return true;
461   }
462 
463   // Check that the sizes of the local memory are specified by integers.
464   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
465                                          TotalNumArgs - 1);
466 }
467 
468 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
469 /// overload formats specified in Table 6.13.17.1.
470 /// int enqueue_kernel(queue_t queue,
471 ///                    kernel_enqueue_flags_t flags,
472 ///                    const ndrange_t ndrange,
473 ///                    void (^block)(void))
474 /// int enqueue_kernel(queue_t queue,
475 ///                    kernel_enqueue_flags_t flags,
476 ///                    const ndrange_t ndrange,
477 ///                    uint num_events_in_wait_list,
478 ///                    clk_event_t *event_wait_list,
479 ///                    clk_event_t *event_ret,
480 ///                    void (^block)(void))
481 /// int enqueue_kernel(queue_t queue,
482 ///                    kernel_enqueue_flags_t flags,
483 ///                    const ndrange_t ndrange,
484 ///                    void (^block)(local void*, ...),
485 ///                    uint size0, ...)
486 /// int enqueue_kernel(queue_t queue,
487 ///                    kernel_enqueue_flags_t flags,
488 ///                    const ndrange_t ndrange,
489 ///                    uint num_events_in_wait_list,
490 ///                    clk_event_t *event_wait_list,
491 ///                    clk_event_t *event_ret,
492 ///                    void (^block)(local void*, ...),
493 ///                    uint size0, ...)
494 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
495   unsigned NumArgs = TheCall->getNumArgs();
496 
497   if (NumArgs < 4) {
498     S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
499     return true;
500   }
501 
502   Expr *Arg0 = TheCall->getArg(0);
503   Expr *Arg1 = TheCall->getArg(1);
504   Expr *Arg2 = TheCall->getArg(2);
505   Expr *Arg3 = TheCall->getArg(3);
506 
507   // First argument always needs to be a queue_t type.
508   if (!Arg0->getType()->isQueueT()) {
509     S.Diag(TheCall->getArg(0)->getLocStart(),
510            diag::err_opencl_builtin_expected_type)
511         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
512     return true;
513   }
514 
515   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
516   if (!Arg1->getType()->isIntegerType()) {
517     S.Diag(TheCall->getArg(1)->getLocStart(),
518            diag::err_opencl_builtin_expected_type)
519         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
520     return true;
521   }
522 
523   // Third argument is always an ndrange_t type.
524   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
525     S.Diag(TheCall->getArg(2)->getLocStart(),
526            diag::err_opencl_builtin_expected_type)
527         << TheCall->getDirectCallee() << "'ndrange_t'";
528     return true;
529   }
530 
531   // With four arguments, there is only one form that the function could be
532   // called in: no events and no variable arguments.
533   if (NumArgs == 4) {
534     // check that the last argument is the right block type.
535     if (!isBlockPointer(Arg3)) {
536       S.Diag(Arg3->getLocStart(), diag::err_opencl_builtin_expected_type)
537           << TheCall->getDirectCallee() << "block";
538       return true;
539     }
540     // we have a block type, check the prototype
541     const BlockPointerType *BPT =
542         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
543     if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
544       S.Diag(Arg3->getLocStart(),
545              diag::err_opencl_enqueue_kernel_blocks_no_args);
546       return true;
547     }
548     return false;
549   }
550   // we can have block + varargs.
551   if (isBlockPointer(Arg3))
552     return (checkOpenCLBlockArgs(S, Arg3) ||
553             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
554   // last two cases with either exactly 7 args or 7 args and varargs.
555   if (NumArgs >= 7) {
556     // check common block argument.
557     Expr *Arg6 = TheCall->getArg(6);
558     if (!isBlockPointer(Arg6)) {
559       S.Diag(Arg6->getLocStart(), diag::err_opencl_builtin_expected_type)
560           << TheCall->getDirectCallee() << "block";
561       return true;
562     }
563     if (checkOpenCLBlockArgs(S, Arg6))
564       return true;
565 
566     // Forth argument has to be any integer type.
567     if (!Arg3->getType()->isIntegerType()) {
568       S.Diag(TheCall->getArg(3)->getLocStart(),
569              diag::err_opencl_builtin_expected_type)
570           << TheCall->getDirectCallee() << "integer";
571       return true;
572     }
573     // check remaining common arguments.
574     Expr *Arg4 = TheCall->getArg(4);
575     Expr *Arg5 = TheCall->getArg(5);
576 
577     // Fifth argument is always passed as a pointer to clk_event_t.
578     if (!Arg4->isNullPointerConstant(S.Context,
579                                      Expr::NPC_ValueDependentIsNotNull) &&
580         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
581       S.Diag(TheCall->getArg(4)->getLocStart(),
582              diag::err_opencl_builtin_expected_type)
583           << TheCall->getDirectCallee()
584           << S.Context.getPointerType(S.Context.OCLClkEventTy);
585       return true;
586     }
587 
588     // Sixth argument is always passed as a pointer to clk_event_t.
589     if (!Arg5->isNullPointerConstant(S.Context,
590                                      Expr::NPC_ValueDependentIsNotNull) &&
591         !(Arg5->getType()->isPointerType() &&
592           Arg5->getType()->getPointeeType()->isClkEventT())) {
593       S.Diag(TheCall->getArg(5)->getLocStart(),
594              diag::err_opencl_builtin_expected_type)
595           << TheCall->getDirectCallee()
596           << S.Context.getPointerType(S.Context.OCLClkEventTy);
597       return true;
598     }
599 
600     if (NumArgs == 7)
601       return false;
602 
603     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
604   }
605 
606   // None of the specific case has been detected, give generic error
607   S.Diag(TheCall->getLocStart(),
608          diag::err_opencl_enqueue_kernel_incorrect_args);
609   return true;
610 }
611 
612 /// Returns OpenCL access qual.
613 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
614     return D->getAttr<OpenCLAccessAttr>();
615 }
616 
617 /// Returns true if pipe element type is different from the pointer.
618 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
619   const Expr *Arg0 = Call->getArg(0);
620   // First argument type should always be pipe.
621   if (!Arg0->getType()->isPipeType()) {
622     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
623         << Call->getDirectCallee() << Arg0->getSourceRange();
624     return true;
625   }
626   OpenCLAccessAttr *AccessQual =
627       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
628   // Validates the access qualifier is compatible with the call.
629   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
630   // read_only and write_only, and assumed to be read_only if no qualifier is
631   // specified.
632   switch (Call->getDirectCallee()->getBuiltinID()) {
633   case Builtin::BIread_pipe:
634   case Builtin::BIreserve_read_pipe:
635   case Builtin::BIcommit_read_pipe:
636   case Builtin::BIwork_group_reserve_read_pipe:
637   case Builtin::BIsub_group_reserve_read_pipe:
638   case Builtin::BIwork_group_commit_read_pipe:
639   case Builtin::BIsub_group_commit_read_pipe:
640     if (!(!AccessQual || AccessQual->isReadOnly())) {
641       S.Diag(Arg0->getLocStart(),
642              diag::err_opencl_builtin_pipe_invalid_access_modifier)
643           << "read_only" << Arg0->getSourceRange();
644       return true;
645     }
646     break;
647   case Builtin::BIwrite_pipe:
648   case Builtin::BIreserve_write_pipe:
649   case Builtin::BIcommit_write_pipe:
650   case Builtin::BIwork_group_reserve_write_pipe:
651   case Builtin::BIsub_group_reserve_write_pipe:
652   case Builtin::BIwork_group_commit_write_pipe:
653   case Builtin::BIsub_group_commit_write_pipe:
654     if (!(AccessQual && AccessQual->isWriteOnly())) {
655       S.Diag(Arg0->getLocStart(),
656              diag::err_opencl_builtin_pipe_invalid_access_modifier)
657           << "write_only" << Arg0->getSourceRange();
658       return true;
659     }
660     break;
661   default:
662     break;
663   }
664   return false;
665 }
666 
667 /// Returns true if pipe element type is different from the pointer.
668 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
669   const Expr *Arg0 = Call->getArg(0);
670   const Expr *ArgIdx = Call->getArg(Idx);
671   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
672   const QualType EltTy = PipeTy->getElementType();
673   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
674   // The Idx argument should be a pointer and the type of the pointer and
675   // the type of pipe element should also be the same.
676   if (!ArgTy ||
677       !S.Context.hasSameType(
678           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
679     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
680         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
681         << ArgIdx->getType() << ArgIdx->getSourceRange();
682     return true;
683   }
684   return false;
685 }
686 
687 // \brief Performs semantic analysis for the read/write_pipe call.
688 // \param S Reference to the semantic analyzer.
689 // \param Call A pointer to the builtin call.
690 // \return True if a semantic error has been found, false otherwise.
691 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
692   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
693   // functions have two forms.
694   switch (Call->getNumArgs()) {
695   case 2:
696     if (checkOpenCLPipeArg(S, Call))
697       return true;
698     // The call with 2 arguments should be
699     // read/write_pipe(pipe T, T*).
700     // Check packet type T.
701     if (checkOpenCLPipePacketType(S, Call, 1))
702       return true;
703     break;
704 
705   case 4: {
706     if (checkOpenCLPipeArg(S, Call))
707       return true;
708     // The call with 4 arguments should be
709     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
710     // Check reserve_id_t.
711     if (!Call->getArg(1)->getType()->isReserveIDT()) {
712       S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
713           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
714           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
715       return true;
716     }
717 
718     // Check the index.
719     const Expr *Arg2 = Call->getArg(2);
720     if (!Arg2->getType()->isIntegerType() &&
721         !Arg2->getType()->isUnsignedIntegerType()) {
722       S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
723           << Call->getDirectCallee() << S.Context.UnsignedIntTy
724           << Arg2->getType() << Arg2->getSourceRange();
725       return true;
726     }
727 
728     // Check packet type T.
729     if (checkOpenCLPipePacketType(S, Call, 3))
730       return true;
731   } break;
732   default:
733     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
734         << Call->getDirectCallee() << Call->getSourceRange();
735     return true;
736   }
737 
738   return false;
739 }
740 
741 // \brief Performs a semantic analysis on the {work_group_/sub_group_
742 //        /_}reserve_{read/write}_pipe
743 // \param S Reference to the semantic analyzer.
744 // \param Call The call to the builtin function to be analyzed.
745 // \return True if a semantic error was found, false otherwise.
746 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
747   if (checkArgCount(S, Call, 2))
748     return true;
749 
750   if (checkOpenCLPipeArg(S, Call))
751     return true;
752 
753   // Check the reserve size.
754   if (!Call->getArg(1)->getType()->isIntegerType() &&
755       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
756     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
757         << Call->getDirectCallee() << S.Context.UnsignedIntTy
758         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
759     return true;
760   }
761 
762   // Since return type of reserve_read/write_pipe built-in function is
763   // reserve_id_t, which is not defined in the builtin def file , we used int
764   // as return type and need to override the return type of these functions.
765   Call->setType(S.Context.OCLReserveIDTy);
766 
767   return false;
768 }
769 
770 // \brief Performs a semantic analysis on {work_group_/sub_group_
771 //        /_}commit_{read/write}_pipe
772 // \param S Reference to the semantic analyzer.
773 // \param Call The call to the builtin function to be analyzed.
774 // \return True if a semantic error was found, false otherwise.
775 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
776   if (checkArgCount(S, Call, 2))
777     return true;
778 
779   if (checkOpenCLPipeArg(S, Call))
780     return true;
781 
782   // Check reserve_id_t.
783   if (!Call->getArg(1)->getType()->isReserveIDT()) {
784     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
785         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
786         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
787     return true;
788   }
789 
790   return false;
791 }
792 
793 // \brief Performs a semantic analysis on the call to built-in Pipe
794 //        Query Functions.
795 // \param S Reference to the semantic analyzer.
796 // \param Call The call to the builtin function to be analyzed.
797 // \return True if a semantic error was found, false otherwise.
798 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
799   if (checkArgCount(S, Call, 1))
800     return true;
801 
802   if (!Call->getArg(0)->getType()->isPipeType()) {
803     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
804         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
805     return true;
806   }
807 
808   return false;
809 }
810 
811 // \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
812 // \brief Performs semantic analysis for the to_global/local/private call.
813 // \param S Reference to the semantic analyzer.
814 // \param BuiltinID ID of the builtin function.
815 // \param Call A pointer to the builtin call.
816 // \return True if a semantic error has been found, false otherwise.
817 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
818                                     CallExpr *Call) {
819   if (Call->getNumArgs() != 1) {
820     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
821         << Call->getDirectCallee() << Call->getSourceRange();
822     return true;
823   }
824 
825   auto RT = Call->getArg(0)->getType();
826   if (!RT->isPointerType() || RT->getPointeeType()
827       .getAddressSpace() == LangAS::opencl_constant) {
828     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
829         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
830     return true;
831   }
832 
833   RT = RT->getPointeeType();
834   auto Qual = RT.getQualifiers();
835   switch (BuiltinID) {
836   case Builtin::BIto_global:
837     Qual.setAddressSpace(LangAS::opencl_global);
838     break;
839   case Builtin::BIto_local:
840     Qual.setAddressSpace(LangAS::opencl_local);
841     break;
842   case Builtin::BIto_private:
843     Qual.setAddressSpace(LangAS::opencl_private);
844     break;
845   default:
846     llvm_unreachable("Invalid builtin function");
847   }
848   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
849       RT.getUnqualifiedType(), Qual)));
850 
851   return false;
852 }
853 
854 ExprResult
855 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
856                                CallExpr *TheCall) {
857   ExprResult TheCallResult(TheCall);
858 
859   // Find out if any arguments are required to be integer constant expressions.
860   unsigned ICEArguments = 0;
861   ASTContext::GetBuiltinTypeError Error;
862   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
863   if (Error != ASTContext::GE_None)
864     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
865 
866   // If any arguments are required to be ICE's, check and diagnose.
867   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
868     // Skip arguments not required to be ICE's.
869     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
870 
871     llvm::APSInt Result;
872     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
873       return true;
874     ICEArguments &= ~(1 << ArgNo);
875   }
876 
877   switch (BuiltinID) {
878   case Builtin::BI__builtin___CFStringMakeConstantString:
879     assert(TheCall->getNumArgs() == 1 &&
880            "Wrong # arguments to builtin CFStringMakeConstantString");
881     if (CheckObjCString(TheCall->getArg(0)))
882       return ExprError();
883     break;
884   case Builtin::BI__builtin_ms_va_start:
885   case Builtin::BI__builtin_stdarg_start:
886   case Builtin::BI__builtin_va_start:
887     if (SemaBuiltinVAStart(BuiltinID, TheCall))
888       return ExprError();
889     break;
890   case Builtin::BI__va_start: {
891     switch (Context.getTargetInfo().getTriple().getArch()) {
892     case llvm::Triple::arm:
893     case llvm::Triple::thumb:
894       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
895         return ExprError();
896       break;
897     default:
898       if (SemaBuiltinVAStart(BuiltinID, TheCall))
899         return ExprError();
900       break;
901     }
902     break;
903   }
904   case Builtin::BI__builtin_isgreater:
905   case Builtin::BI__builtin_isgreaterequal:
906   case Builtin::BI__builtin_isless:
907   case Builtin::BI__builtin_islessequal:
908   case Builtin::BI__builtin_islessgreater:
909   case Builtin::BI__builtin_isunordered:
910     if (SemaBuiltinUnorderedCompare(TheCall))
911       return ExprError();
912     break;
913   case Builtin::BI__builtin_fpclassify:
914     if (SemaBuiltinFPClassification(TheCall, 6))
915       return ExprError();
916     break;
917   case Builtin::BI__builtin_isfinite:
918   case Builtin::BI__builtin_isinf:
919   case Builtin::BI__builtin_isinf_sign:
920   case Builtin::BI__builtin_isnan:
921   case Builtin::BI__builtin_isnormal:
922     if (SemaBuiltinFPClassification(TheCall, 1))
923       return ExprError();
924     break;
925   case Builtin::BI__builtin_shufflevector:
926     return SemaBuiltinShuffleVector(TheCall);
927     // TheCall will be freed by the smart pointer here, but that's fine, since
928     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
929   case Builtin::BI__builtin_prefetch:
930     if (SemaBuiltinPrefetch(TheCall))
931       return ExprError();
932     break;
933   case Builtin::BI__builtin_alloca_with_align:
934     if (SemaBuiltinAllocaWithAlign(TheCall))
935       return ExprError();
936     break;
937   case Builtin::BI__assume:
938   case Builtin::BI__builtin_assume:
939     if (SemaBuiltinAssume(TheCall))
940       return ExprError();
941     break;
942   case Builtin::BI__builtin_assume_aligned:
943     if (SemaBuiltinAssumeAligned(TheCall))
944       return ExprError();
945     break;
946   case Builtin::BI__builtin_object_size:
947     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
948       return ExprError();
949     break;
950   case Builtin::BI__builtin_longjmp:
951     if (SemaBuiltinLongjmp(TheCall))
952       return ExprError();
953     break;
954   case Builtin::BI__builtin_setjmp:
955     if (SemaBuiltinSetjmp(TheCall))
956       return ExprError();
957     break;
958   case Builtin::BI_setjmp:
959   case Builtin::BI_setjmpex:
960     if (checkArgCount(*this, TheCall, 1))
961       return true;
962     break;
963   case Builtin::BI__builtin_classify_type:
964     if (checkArgCount(*this, TheCall, 1)) return true;
965     TheCall->setType(Context.IntTy);
966     break;
967   case Builtin::BI__builtin_constant_p:
968     if (checkArgCount(*this, TheCall, 1)) return true;
969     TheCall->setType(Context.IntTy);
970     break;
971   case Builtin::BI__sync_fetch_and_add:
972   case Builtin::BI__sync_fetch_and_add_1:
973   case Builtin::BI__sync_fetch_and_add_2:
974   case Builtin::BI__sync_fetch_and_add_4:
975   case Builtin::BI__sync_fetch_and_add_8:
976   case Builtin::BI__sync_fetch_and_add_16:
977   case Builtin::BI__sync_fetch_and_sub:
978   case Builtin::BI__sync_fetch_and_sub_1:
979   case Builtin::BI__sync_fetch_and_sub_2:
980   case Builtin::BI__sync_fetch_and_sub_4:
981   case Builtin::BI__sync_fetch_and_sub_8:
982   case Builtin::BI__sync_fetch_and_sub_16:
983   case Builtin::BI__sync_fetch_and_or:
984   case Builtin::BI__sync_fetch_and_or_1:
985   case Builtin::BI__sync_fetch_and_or_2:
986   case Builtin::BI__sync_fetch_and_or_4:
987   case Builtin::BI__sync_fetch_and_or_8:
988   case Builtin::BI__sync_fetch_and_or_16:
989   case Builtin::BI__sync_fetch_and_and:
990   case Builtin::BI__sync_fetch_and_and_1:
991   case Builtin::BI__sync_fetch_and_and_2:
992   case Builtin::BI__sync_fetch_and_and_4:
993   case Builtin::BI__sync_fetch_and_and_8:
994   case Builtin::BI__sync_fetch_and_and_16:
995   case Builtin::BI__sync_fetch_and_xor:
996   case Builtin::BI__sync_fetch_and_xor_1:
997   case Builtin::BI__sync_fetch_and_xor_2:
998   case Builtin::BI__sync_fetch_and_xor_4:
999   case Builtin::BI__sync_fetch_and_xor_8:
1000   case Builtin::BI__sync_fetch_and_xor_16:
1001   case Builtin::BI__sync_fetch_and_nand:
1002   case Builtin::BI__sync_fetch_and_nand_1:
1003   case Builtin::BI__sync_fetch_and_nand_2:
1004   case Builtin::BI__sync_fetch_and_nand_4:
1005   case Builtin::BI__sync_fetch_and_nand_8:
1006   case Builtin::BI__sync_fetch_and_nand_16:
1007   case Builtin::BI__sync_add_and_fetch:
1008   case Builtin::BI__sync_add_and_fetch_1:
1009   case Builtin::BI__sync_add_and_fetch_2:
1010   case Builtin::BI__sync_add_and_fetch_4:
1011   case Builtin::BI__sync_add_and_fetch_8:
1012   case Builtin::BI__sync_add_and_fetch_16:
1013   case Builtin::BI__sync_sub_and_fetch:
1014   case Builtin::BI__sync_sub_and_fetch_1:
1015   case Builtin::BI__sync_sub_and_fetch_2:
1016   case Builtin::BI__sync_sub_and_fetch_4:
1017   case Builtin::BI__sync_sub_and_fetch_8:
1018   case Builtin::BI__sync_sub_and_fetch_16:
1019   case Builtin::BI__sync_and_and_fetch:
1020   case Builtin::BI__sync_and_and_fetch_1:
1021   case Builtin::BI__sync_and_and_fetch_2:
1022   case Builtin::BI__sync_and_and_fetch_4:
1023   case Builtin::BI__sync_and_and_fetch_8:
1024   case Builtin::BI__sync_and_and_fetch_16:
1025   case Builtin::BI__sync_or_and_fetch:
1026   case Builtin::BI__sync_or_and_fetch_1:
1027   case Builtin::BI__sync_or_and_fetch_2:
1028   case Builtin::BI__sync_or_and_fetch_4:
1029   case Builtin::BI__sync_or_and_fetch_8:
1030   case Builtin::BI__sync_or_and_fetch_16:
1031   case Builtin::BI__sync_xor_and_fetch:
1032   case Builtin::BI__sync_xor_and_fetch_1:
1033   case Builtin::BI__sync_xor_and_fetch_2:
1034   case Builtin::BI__sync_xor_and_fetch_4:
1035   case Builtin::BI__sync_xor_and_fetch_8:
1036   case Builtin::BI__sync_xor_and_fetch_16:
1037   case Builtin::BI__sync_nand_and_fetch:
1038   case Builtin::BI__sync_nand_and_fetch_1:
1039   case Builtin::BI__sync_nand_and_fetch_2:
1040   case Builtin::BI__sync_nand_and_fetch_4:
1041   case Builtin::BI__sync_nand_and_fetch_8:
1042   case Builtin::BI__sync_nand_and_fetch_16:
1043   case Builtin::BI__sync_val_compare_and_swap:
1044   case Builtin::BI__sync_val_compare_and_swap_1:
1045   case Builtin::BI__sync_val_compare_and_swap_2:
1046   case Builtin::BI__sync_val_compare_and_swap_4:
1047   case Builtin::BI__sync_val_compare_and_swap_8:
1048   case Builtin::BI__sync_val_compare_and_swap_16:
1049   case Builtin::BI__sync_bool_compare_and_swap:
1050   case Builtin::BI__sync_bool_compare_and_swap_1:
1051   case Builtin::BI__sync_bool_compare_and_swap_2:
1052   case Builtin::BI__sync_bool_compare_and_swap_4:
1053   case Builtin::BI__sync_bool_compare_and_swap_8:
1054   case Builtin::BI__sync_bool_compare_and_swap_16:
1055   case Builtin::BI__sync_lock_test_and_set:
1056   case Builtin::BI__sync_lock_test_and_set_1:
1057   case Builtin::BI__sync_lock_test_and_set_2:
1058   case Builtin::BI__sync_lock_test_and_set_4:
1059   case Builtin::BI__sync_lock_test_and_set_8:
1060   case Builtin::BI__sync_lock_test_and_set_16:
1061   case Builtin::BI__sync_lock_release:
1062   case Builtin::BI__sync_lock_release_1:
1063   case Builtin::BI__sync_lock_release_2:
1064   case Builtin::BI__sync_lock_release_4:
1065   case Builtin::BI__sync_lock_release_8:
1066   case Builtin::BI__sync_lock_release_16:
1067   case Builtin::BI__sync_swap:
1068   case Builtin::BI__sync_swap_1:
1069   case Builtin::BI__sync_swap_2:
1070   case Builtin::BI__sync_swap_4:
1071   case Builtin::BI__sync_swap_8:
1072   case Builtin::BI__sync_swap_16:
1073     return SemaBuiltinAtomicOverloaded(TheCallResult);
1074   case Builtin::BI__builtin_nontemporal_load:
1075   case Builtin::BI__builtin_nontemporal_store:
1076     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1077 #define BUILTIN(ID, TYPE, ATTRS)
1078 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1079   case Builtin::BI##ID: \
1080     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1081 #include "clang/Basic/Builtins.def"
1082   case Builtin::BI__annotation:
1083     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1084       return ExprError();
1085     break;
1086   case Builtin::BI__builtin_annotation:
1087     if (SemaBuiltinAnnotation(*this, TheCall))
1088       return ExprError();
1089     break;
1090   case Builtin::BI__builtin_addressof:
1091     if (SemaBuiltinAddressof(*this, TheCall))
1092       return ExprError();
1093     break;
1094   case Builtin::BI__builtin_add_overflow:
1095   case Builtin::BI__builtin_sub_overflow:
1096   case Builtin::BI__builtin_mul_overflow:
1097     if (SemaBuiltinOverflow(*this, TheCall))
1098       return ExprError();
1099     break;
1100   case Builtin::BI__builtin_operator_new:
1101   case Builtin::BI__builtin_operator_delete: {
1102     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1103     ExprResult Res =
1104         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1105     if (Res.isInvalid())
1106       CorrectDelayedTyposInExpr(TheCallResult.get());
1107     return Res;
1108   }
1109   case Builtin::BI__builtin_dump_struct: {
1110     // We first want to ensure we are called with 2 arguments
1111     if (checkArgCount(*this, TheCall, 2))
1112       return ExprError();
1113     // Ensure that the first argument is of type 'struct XX *'
1114     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1115     const QualType PtrArgType = PtrArg->getType();
1116     if (!PtrArgType->isPointerType() ||
1117         !PtrArgType->getPointeeType()->isRecordType()) {
1118       Diag(PtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1119           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1120           << "structure pointer";
1121       return ExprError();
1122     }
1123 
1124     // Ensure that the second argument is of type 'FunctionType'
1125     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1126     const QualType FnPtrArgType = FnPtrArg->getType();
1127     if (!FnPtrArgType->isPointerType()) {
1128       Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1129           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1130           << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1131       return ExprError();
1132     }
1133 
1134     const auto *FuncType =
1135         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1136 
1137     if (!FuncType) {
1138       Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1139           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1140           << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1141       return ExprError();
1142     }
1143 
1144     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1145       if (!FT->getNumParams()) {
1146         Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1147             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1148             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1149         return ExprError();
1150       }
1151       QualType PT = FT->getParamType(0);
1152       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1153           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1154           !PT->getPointeeType().isConstQualified()) {
1155         Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1156             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1157             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1158         return ExprError();
1159       }
1160     }
1161 
1162     TheCall->setType(Context.IntTy);
1163     break;
1164   }
1165 
1166   // check secure string manipulation functions where overflows
1167   // are detectable at compile time
1168   case Builtin::BI__builtin___memcpy_chk:
1169   case Builtin::BI__builtin___memmove_chk:
1170   case Builtin::BI__builtin___memset_chk:
1171   case Builtin::BI__builtin___strlcat_chk:
1172   case Builtin::BI__builtin___strlcpy_chk:
1173   case Builtin::BI__builtin___strncat_chk:
1174   case Builtin::BI__builtin___strncpy_chk:
1175   case Builtin::BI__builtin___stpncpy_chk:
1176     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
1177     break;
1178   case Builtin::BI__builtin___memccpy_chk:
1179     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
1180     break;
1181   case Builtin::BI__builtin___snprintf_chk:
1182   case Builtin::BI__builtin___vsnprintf_chk:
1183     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
1184     break;
1185   case Builtin::BI__builtin_call_with_static_chain:
1186     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1187       return ExprError();
1188     break;
1189   case Builtin::BI__exception_code:
1190   case Builtin::BI_exception_code:
1191     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1192                                  diag::err_seh___except_block))
1193       return ExprError();
1194     break;
1195   case Builtin::BI__exception_info:
1196   case Builtin::BI_exception_info:
1197     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1198                                  diag::err_seh___except_filter))
1199       return ExprError();
1200     break;
1201   case Builtin::BI__GetExceptionInfo:
1202     if (checkArgCount(*this, TheCall, 1))
1203       return ExprError();
1204 
1205     if (CheckCXXThrowOperand(
1206             TheCall->getLocStart(),
1207             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1208             TheCall))
1209       return ExprError();
1210 
1211     TheCall->setType(Context.VoidPtrTy);
1212     break;
1213   // OpenCL v2.0, s6.13.16 - Pipe functions
1214   case Builtin::BIread_pipe:
1215   case Builtin::BIwrite_pipe:
1216     // Since those two functions are declared with var args, we need a semantic
1217     // check for the argument.
1218     if (SemaBuiltinRWPipe(*this, TheCall))
1219       return ExprError();
1220     TheCall->setType(Context.IntTy);
1221     break;
1222   case Builtin::BIreserve_read_pipe:
1223   case Builtin::BIreserve_write_pipe:
1224   case Builtin::BIwork_group_reserve_read_pipe:
1225   case Builtin::BIwork_group_reserve_write_pipe:
1226     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1227       return ExprError();
1228     break;
1229   case Builtin::BIsub_group_reserve_read_pipe:
1230   case Builtin::BIsub_group_reserve_write_pipe:
1231     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1232         SemaBuiltinReserveRWPipe(*this, TheCall))
1233       return ExprError();
1234     break;
1235   case Builtin::BIcommit_read_pipe:
1236   case Builtin::BIcommit_write_pipe:
1237   case Builtin::BIwork_group_commit_read_pipe:
1238   case Builtin::BIwork_group_commit_write_pipe:
1239     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1240       return ExprError();
1241     break;
1242   case Builtin::BIsub_group_commit_read_pipe:
1243   case Builtin::BIsub_group_commit_write_pipe:
1244     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1245         SemaBuiltinCommitRWPipe(*this, TheCall))
1246       return ExprError();
1247     break;
1248   case Builtin::BIget_pipe_num_packets:
1249   case Builtin::BIget_pipe_max_packets:
1250     if (SemaBuiltinPipePackets(*this, TheCall))
1251       return ExprError();
1252     TheCall->setType(Context.UnsignedIntTy);
1253     break;
1254   case Builtin::BIto_global:
1255   case Builtin::BIto_local:
1256   case Builtin::BIto_private:
1257     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1258       return ExprError();
1259     break;
1260   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1261   case Builtin::BIenqueue_kernel:
1262     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1263       return ExprError();
1264     break;
1265   case Builtin::BIget_kernel_work_group_size:
1266   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1267     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1268       return ExprError();
1269     break;
1270   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1271   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1272     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1273       return ExprError();
1274     break;
1275   case Builtin::BI__builtin_os_log_format:
1276   case Builtin::BI__builtin_os_log_format_buffer_size:
1277     if (SemaBuiltinOSLogFormat(TheCall))
1278       return ExprError();
1279     break;
1280   }
1281 
1282   // Since the target specific builtins for each arch overlap, only check those
1283   // of the arch we are compiling for.
1284   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1285     switch (Context.getTargetInfo().getTriple().getArch()) {
1286       case llvm::Triple::arm:
1287       case llvm::Triple::armeb:
1288       case llvm::Triple::thumb:
1289       case llvm::Triple::thumbeb:
1290         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1291           return ExprError();
1292         break;
1293       case llvm::Triple::aarch64:
1294       case llvm::Triple::aarch64_be:
1295         if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1296           return ExprError();
1297         break;
1298       case llvm::Triple::mips:
1299       case llvm::Triple::mipsel:
1300       case llvm::Triple::mips64:
1301       case llvm::Triple::mips64el:
1302         if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1303           return ExprError();
1304         break;
1305       case llvm::Triple::systemz:
1306         if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1307           return ExprError();
1308         break;
1309       case llvm::Triple::x86:
1310       case llvm::Triple::x86_64:
1311         if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1312           return ExprError();
1313         break;
1314       case llvm::Triple::ppc:
1315       case llvm::Triple::ppc64:
1316       case llvm::Triple::ppc64le:
1317         if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1318           return ExprError();
1319         break;
1320       default:
1321         break;
1322     }
1323   }
1324 
1325   return TheCallResult;
1326 }
1327 
1328 // Get the valid immediate range for the specified NEON type code.
1329 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1330   NeonTypeFlags Type(t);
1331   int IsQuad = ForceQuad ? true : Type.isQuad();
1332   switch (Type.getEltType()) {
1333   case NeonTypeFlags::Int8:
1334   case NeonTypeFlags::Poly8:
1335     return shift ? 7 : (8 << IsQuad) - 1;
1336   case NeonTypeFlags::Int16:
1337   case NeonTypeFlags::Poly16:
1338     return shift ? 15 : (4 << IsQuad) - 1;
1339   case NeonTypeFlags::Int32:
1340     return shift ? 31 : (2 << IsQuad) - 1;
1341   case NeonTypeFlags::Int64:
1342   case NeonTypeFlags::Poly64:
1343     return shift ? 63 : (1 << IsQuad) - 1;
1344   case NeonTypeFlags::Poly128:
1345     return shift ? 127 : (1 << IsQuad) - 1;
1346   case NeonTypeFlags::Float16:
1347     assert(!shift && "cannot shift float types!");
1348     return (4 << IsQuad) - 1;
1349   case NeonTypeFlags::Float32:
1350     assert(!shift && "cannot shift float types!");
1351     return (2 << IsQuad) - 1;
1352   case NeonTypeFlags::Float64:
1353     assert(!shift && "cannot shift float types!");
1354     return (1 << IsQuad) - 1;
1355   }
1356   llvm_unreachable("Invalid NeonTypeFlag!");
1357 }
1358 
1359 /// getNeonEltType - Return the QualType corresponding to the elements of
1360 /// the vector type specified by the NeonTypeFlags.  This is used to check
1361 /// the pointer arguments for Neon load/store intrinsics.
1362 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1363                                bool IsPolyUnsigned, bool IsInt64Long) {
1364   switch (Flags.getEltType()) {
1365   case NeonTypeFlags::Int8:
1366     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1367   case NeonTypeFlags::Int16:
1368     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1369   case NeonTypeFlags::Int32:
1370     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1371   case NeonTypeFlags::Int64:
1372     if (IsInt64Long)
1373       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1374     else
1375       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1376                                 : Context.LongLongTy;
1377   case NeonTypeFlags::Poly8:
1378     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1379   case NeonTypeFlags::Poly16:
1380     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1381   case NeonTypeFlags::Poly64:
1382     if (IsInt64Long)
1383       return Context.UnsignedLongTy;
1384     else
1385       return Context.UnsignedLongLongTy;
1386   case NeonTypeFlags::Poly128:
1387     break;
1388   case NeonTypeFlags::Float16:
1389     return Context.HalfTy;
1390   case NeonTypeFlags::Float32:
1391     return Context.FloatTy;
1392   case NeonTypeFlags::Float64:
1393     return Context.DoubleTy;
1394   }
1395   llvm_unreachable("Invalid NeonTypeFlag!");
1396 }
1397 
1398 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1399   llvm::APSInt Result;
1400   uint64_t mask = 0;
1401   unsigned TV = 0;
1402   int PtrArgNum = -1;
1403   bool HasConstPtr = false;
1404   switch (BuiltinID) {
1405 #define GET_NEON_OVERLOAD_CHECK
1406 #include "clang/Basic/arm_neon.inc"
1407 #include "clang/Basic/arm_fp16.inc"
1408 #undef GET_NEON_OVERLOAD_CHECK
1409   }
1410 
1411   // For NEON intrinsics which are overloaded on vector element type, validate
1412   // the immediate which specifies which variant to emit.
1413   unsigned ImmArg = TheCall->getNumArgs()-1;
1414   if (mask) {
1415     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1416       return true;
1417 
1418     TV = Result.getLimitedValue(64);
1419     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1420       return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
1421         << TheCall->getArg(ImmArg)->getSourceRange();
1422   }
1423 
1424   if (PtrArgNum >= 0) {
1425     // Check that pointer arguments have the specified type.
1426     Expr *Arg = TheCall->getArg(PtrArgNum);
1427     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1428       Arg = ICE->getSubExpr();
1429     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1430     QualType RHSTy = RHS.get()->getType();
1431 
1432     llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
1433     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1434                           Arch == llvm::Triple::aarch64_be;
1435     bool IsInt64Long =
1436         Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1437     QualType EltTy =
1438         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
1439     if (HasConstPtr)
1440       EltTy = EltTy.withConst();
1441     QualType LHSTy = Context.getPointerType(EltTy);
1442     AssignConvertType ConvTy;
1443     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1444     if (RHS.isInvalid())
1445       return true;
1446     if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1447                                  RHS.get(), AA_Assigning))
1448       return true;
1449   }
1450 
1451   // For NEON intrinsics which take an immediate value as part of the
1452   // instruction, range check them here.
1453   unsigned i = 0, l = 0, u = 0;
1454   switch (BuiltinID) {
1455   default:
1456     return false;
1457 #define GET_NEON_IMMEDIATE_CHECK
1458 #include "clang/Basic/arm_neon.inc"
1459 #include "clang/Basic/arm_fp16.inc"
1460 #undef GET_NEON_IMMEDIATE_CHECK
1461   }
1462 
1463   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1464 }
1465 
1466 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1467                                         unsigned MaxWidth) {
1468   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1469           BuiltinID == ARM::BI__builtin_arm_ldaex ||
1470           BuiltinID == ARM::BI__builtin_arm_strex ||
1471           BuiltinID == ARM::BI__builtin_arm_stlex ||
1472           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1473           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1474           BuiltinID == AArch64::BI__builtin_arm_strex ||
1475           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1476          "unexpected ARM builtin");
1477   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1478                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1479                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1480                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
1481 
1482   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1483 
1484   // Ensure that we have the proper number of arguments.
1485   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1486     return true;
1487 
1488   // Inspect the pointer argument of the atomic builtin.  This should always be
1489   // a pointer type, whose element is an integral scalar or pointer type.
1490   // Because it is a pointer type, we don't have to worry about any implicit
1491   // casts here.
1492   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1493   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1494   if (PointerArgRes.isInvalid())
1495     return true;
1496   PointerArg = PointerArgRes.get();
1497 
1498   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1499   if (!pointerType) {
1500     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1501       << PointerArg->getType() << PointerArg->getSourceRange();
1502     return true;
1503   }
1504 
1505   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1506   // task is to insert the appropriate casts into the AST. First work out just
1507   // what the appropriate type is.
1508   QualType ValType = pointerType->getPointeeType();
1509   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1510   if (IsLdrex)
1511     AddrType.addConst();
1512 
1513   // Issue a warning if the cast is dodgy.
1514   CastKind CastNeeded = CK_NoOp;
1515   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1516     CastNeeded = CK_BitCast;
1517     Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1518       << PointerArg->getType()
1519       << Context.getPointerType(AddrType)
1520       << AA_Passing << PointerArg->getSourceRange();
1521   }
1522 
1523   // Finally, do the cast and replace the argument with the corrected version.
1524   AddrType = Context.getPointerType(AddrType);
1525   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1526   if (PointerArgRes.isInvalid())
1527     return true;
1528   PointerArg = PointerArgRes.get();
1529 
1530   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1531 
1532   // In general, we allow ints, floats and pointers to be loaded and stored.
1533   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1534       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1535     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1536       << PointerArg->getType() << PointerArg->getSourceRange();
1537     return true;
1538   }
1539 
1540   // But ARM doesn't have instructions to deal with 128-bit versions.
1541   if (Context.getTypeSize(ValType) > MaxWidth) {
1542     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
1543     Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1544       << PointerArg->getType() << PointerArg->getSourceRange();
1545     return true;
1546   }
1547 
1548   switch (ValType.getObjCLifetime()) {
1549   case Qualifiers::OCL_None:
1550   case Qualifiers::OCL_ExplicitNone:
1551     // okay
1552     break;
1553 
1554   case Qualifiers::OCL_Weak:
1555   case Qualifiers::OCL_Strong:
1556   case Qualifiers::OCL_Autoreleasing:
1557     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1558       << ValType << PointerArg->getSourceRange();
1559     return true;
1560   }
1561 
1562   if (IsLdrex) {
1563     TheCall->setType(ValType);
1564     return false;
1565   }
1566 
1567   // Initialize the argument to be stored.
1568   ExprResult ValArg = TheCall->getArg(0);
1569   InitializedEntity Entity = InitializedEntity::InitializeParameter(
1570       Context, ValType, /*consume*/ false);
1571   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1572   if (ValArg.isInvalid())
1573     return true;
1574   TheCall->setArg(0, ValArg.get());
1575 
1576   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1577   // but the custom checker bypasses all default analysis.
1578   TheCall->setType(Context.IntTy);
1579   return false;
1580 }
1581 
1582 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1583   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1584       BuiltinID == ARM::BI__builtin_arm_ldaex ||
1585       BuiltinID == ARM::BI__builtin_arm_strex ||
1586       BuiltinID == ARM::BI__builtin_arm_stlex) {
1587     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1588   }
1589 
1590   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1591     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1592       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1593   }
1594 
1595   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1596       BuiltinID == ARM::BI__builtin_arm_wsr64)
1597     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1598 
1599   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1600       BuiltinID == ARM::BI__builtin_arm_rsrp ||
1601       BuiltinID == ARM::BI__builtin_arm_wsr ||
1602       BuiltinID == ARM::BI__builtin_arm_wsrp)
1603     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1604 
1605   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1606     return true;
1607 
1608   // For intrinsics which take an immediate value as part of the instruction,
1609   // range check them here.
1610   // FIXME: VFP Intrinsics should error if VFP not present.
1611   switch (BuiltinID) {
1612   default: return false;
1613   case ARM::BI__builtin_arm_ssat:
1614     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
1615   case ARM::BI__builtin_arm_usat:
1616     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
1617   case ARM::BI__builtin_arm_ssat16:
1618     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
1619   case ARM::BI__builtin_arm_usat16:
1620     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
1621   case ARM::BI__builtin_arm_vcvtr_f:
1622   case ARM::BI__builtin_arm_vcvtr_d:
1623     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
1624   case ARM::BI__builtin_arm_dmb:
1625   case ARM::BI__builtin_arm_dsb:
1626   case ARM::BI__builtin_arm_isb:
1627   case ARM::BI__builtin_arm_dbg:
1628     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
1629   }
1630 }
1631 
1632 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1633                                          CallExpr *TheCall) {
1634   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1635       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1636       BuiltinID == AArch64::BI__builtin_arm_strex ||
1637       BuiltinID == AArch64::BI__builtin_arm_stlex) {
1638     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1639   }
1640 
1641   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1642     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1643       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1644       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1645       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1646   }
1647 
1648   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1649       BuiltinID == AArch64::BI__builtin_arm_wsr64)
1650     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1651 
1652   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1653       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1654       BuiltinID == AArch64::BI__builtin_arm_wsr ||
1655       BuiltinID == AArch64::BI__builtin_arm_wsrp)
1656     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1657 
1658   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1659     return true;
1660 
1661   // For intrinsics which take an immediate value as part of the instruction,
1662   // range check them here.
1663   unsigned i = 0, l = 0, u = 0;
1664   switch (BuiltinID) {
1665   default: return false;
1666   case AArch64::BI__builtin_arm_dmb:
1667   case AArch64::BI__builtin_arm_dsb:
1668   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1669   }
1670 
1671   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1672 }
1673 
1674 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1675 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1676 // ordering for DSP is unspecified. MSA is ordered by the data format used
1677 // by the underlying instruction i.e., df/m, df/n and then by size.
1678 //
1679 // FIXME: The size tests here should instead be tablegen'd along with the
1680 //        definitions from include/clang/Basic/BuiltinsMips.def.
1681 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
1682 //        be too.
1683 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1684   unsigned i = 0, l = 0, u = 0, m = 0;
1685   switch (BuiltinID) {
1686   default: return false;
1687   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1688   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
1689   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1690   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1691   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1692   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1693   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
1694   // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1695   // df/m field.
1696   // These intrinsics take an unsigned 3 bit immediate.
1697   case Mips::BI__builtin_msa_bclri_b:
1698   case Mips::BI__builtin_msa_bnegi_b:
1699   case Mips::BI__builtin_msa_bseti_b:
1700   case Mips::BI__builtin_msa_sat_s_b:
1701   case Mips::BI__builtin_msa_sat_u_b:
1702   case Mips::BI__builtin_msa_slli_b:
1703   case Mips::BI__builtin_msa_srai_b:
1704   case Mips::BI__builtin_msa_srari_b:
1705   case Mips::BI__builtin_msa_srli_b:
1706   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1707   case Mips::BI__builtin_msa_binsli_b:
1708   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1709   // These intrinsics take an unsigned 4 bit immediate.
1710   case Mips::BI__builtin_msa_bclri_h:
1711   case Mips::BI__builtin_msa_bnegi_h:
1712   case Mips::BI__builtin_msa_bseti_h:
1713   case Mips::BI__builtin_msa_sat_s_h:
1714   case Mips::BI__builtin_msa_sat_u_h:
1715   case Mips::BI__builtin_msa_slli_h:
1716   case Mips::BI__builtin_msa_srai_h:
1717   case Mips::BI__builtin_msa_srari_h:
1718   case Mips::BI__builtin_msa_srli_h:
1719   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1720   case Mips::BI__builtin_msa_binsli_h:
1721   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
1722   // These intrinsics take an unsigned 5 bit immediate.
1723   // The first block of intrinsics actually have an unsigned 5 bit field,
1724   // not a df/n field.
1725   case Mips::BI__builtin_msa_clei_u_b:
1726   case Mips::BI__builtin_msa_clei_u_h:
1727   case Mips::BI__builtin_msa_clei_u_w:
1728   case Mips::BI__builtin_msa_clei_u_d:
1729   case Mips::BI__builtin_msa_clti_u_b:
1730   case Mips::BI__builtin_msa_clti_u_h:
1731   case Mips::BI__builtin_msa_clti_u_w:
1732   case Mips::BI__builtin_msa_clti_u_d:
1733   case Mips::BI__builtin_msa_maxi_u_b:
1734   case Mips::BI__builtin_msa_maxi_u_h:
1735   case Mips::BI__builtin_msa_maxi_u_w:
1736   case Mips::BI__builtin_msa_maxi_u_d:
1737   case Mips::BI__builtin_msa_mini_u_b:
1738   case Mips::BI__builtin_msa_mini_u_h:
1739   case Mips::BI__builtin_msa_mini_u_w:
1740   case Mips::BI__builtin_msa_mini_u_d:
1741   case Mips::BI__builtin_msa_addvi_b:
1742   case Mips::BI__builtin_msa_addvi_h:
1743   case Mips::BI__builtin_msa_addvi_w:
1744   case Mips::BI__builtin_msa_addvi_d:
1745   case Mips::BI__builtin_msa_bclri_w:
1746   case Mips::BI__builtin_msa_bnegi_w:
1747   case Mips::BI__builtin_msa_bseti_w:
1748   case Mips::BI__builtin_msa_sat_s_w:
1749   case Mips::BI__builtin_msa_sat_u_w:
1750   case Mips::BI__builtin_msa_slli_w:
1751   case Mips::BI__builtin_msa_srai_w:
1752   case Mips::BI__builtin_msa_srari_w:
1753   case Mips::BI__builtin_msa_srli_w:
1754   case Mips::BI__builtin_msa_srlri_w:
1755   case Mips::BI__builtin_msa_subvi_b:
1756   case Mips::BI__builtin_msa_subvi_h:
1757   case Mips::BI__builtin_msa_subvi_w:
1758   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1759   case Mips::BI__builtin_msa_binsli_w:
1760   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1761   // These intrinsics take an unsigned 6 bit immediate.
1762   case Mips::BI__builtin_msa_bclri_d:
1763   case Mips::BI__builtin_msa_bnegi_d:
1764   case Mips::BI__builtin_msa_bseti_d:
1765   case Mips::BI__builtin_msa_sat_s_d:
1766   case Mips::BI__builtin_msa_sat_u_d:
1767   case Mips::BI__builtin_msa_slli_d:
1768   case Mips::BI__builtin_msa_srai_d:
1769   case Mips::BI__builtin_msa_srari_d:
1770   case Mips::BI__builtin_msa_srli_d:
1771   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1772   case Mips::BI__builtin_msa_binsli_d:
1773   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1774   // These intrinsics take a signed 5 bit immediate.
1775   case Mips::BI__builtin_msa_ceqi_b:
1776   case Mips::BI__builtin_msa_ceqi_h:
1777   case Mips::BI__builtin_msa_ceqi_w:
1778   case Mips::BI__builtin_msa_ceqi_d:
1779   case Mips::BI__builtin_msa_clti_s_b:
1780   case Mips::BI__builtin_msa_clti_s_h:
1781   case Mips::BI__builtin_msa_clti_s_w:
1782   case Mips::BI__builtin_msa_clti_s_d:
1783   case Mips::BI__builtin_msa_clei_s_b:
1784   case Mips::BI__builtin_msa_clei_s_h:
1785   case Mips::BI__builtin_msa_clei_s_w:
1786   case Mips::BI__builtin_msa_clei_s_d:
1787   case Mips::BI__builtin_msa_maxi_s_b:
1788   case Mips::BI__builtin_msa_maxi_s_h:
1789   case Mips::BI__builtin_msa_maxi_s_w:
1790   case Mips::BI__builtin_msa_maxi_s_d:
1791   case Mips::BI__builtin_msa_mini_s_b:
1792   case Mips::BI__builtin_msa_mini_s_h:
1793   case Mips::BI__builtin_msa_mini_s_w:
1794   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
1795   // These intrinsics take an unsigned 8 bit immediate.
1796   case Mips::BI__builtin_msa_andi_b:
1797   case Mips::BI__builtin_msa_nori_b:
1798   case Mips::BI__builtin_msa_ori_b:
1799   case Mips::BI__builtin_msa_shf_b:
1800   case Mips::BI__builtin_msa_shf_h:
1801   case Mips::BI__builtin_msa_shf_w:
1802   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
1803   case Mips::BI__builtin_msa_bseli_b:
1804   case Mips::BI__builtin_msa_bmnzi_b:
1805   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
1806   // df/n format
1807   // These intrinsics take an unsigned 4 bit immediate.
1808   case Mips::BI__builtin_msa_copy_s_b:
1809   case Mips::BI__builtin_msa_copy_u_b:
1810   case Mips::BI__builtin_msa_insve_b:
1811   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
1812   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
1813   // These intrinsics take an unsigned 3 bit immediate.
1814   case Mips::BI__builtin_msa_copy_s_h:
1815   case Mips::BI__builtin_msa_copy_u_h:
1816   case Mips::BI__builtin_msa_insve_h:
1817   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
1818   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1819   // These intrinsics take an unsigned 2 bit immediate.
1820   case Mips::BI__builtin_msa_copy_s_w:
1821   case Mips::BI__builtin_msa_copy_u_w:
1822   case Mips::BI__builtin_msa_insve_w:
1823   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
1824   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1825   // These intrinsics take an unsigned 1 bit immediate.
1826   case Mips::BI__builtin_msa_copy_s_d:
1827   case Mips::BI__builtin_msa_copy_u_d:
1828   case Mips::BI__builtin_msa_insve_d:
1829   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
1830   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1831   // Memory offsets and immediate loads.
1832   // These intrinsics take a signed 10 bit immediate.
1833   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
1834   case Mips::BI__builtin_msa_ldi_h:
1835   case Mips::BI__builtin_msa_ldi_w:
1836   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1837   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1838   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1839   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1840   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1841   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1842   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1843   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1844   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
1845   }
1846 
1847   if (!m)
1848     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1849 
1850   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1851          SemaBuiltinConstantArgMultiple(TheCall, i, m);
1852 }
1853 
1854 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1855   unsigned i = 0, l = 0, u = 0;
1856   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1857                       BuiltinID == PPC::BI__builtin_divdeu ||
1858                       BuiltinID == PPC::BI__builtin_bpermd;
1859   bool IsTarget64Bit = Context.getTargetInfo()
1860                               .getTypeWidth(Context
1861                                             .getTargetInfo()
1862                                             .getIntPtrType()) == 64;
1863   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1864                        BuiltinID == PPC::BI__builtin_divweu ||
1865                        BuiltinID == PPC::BI__builtin_divde ||
1866                        BuiltinID == PPC::BI__builtin_divdeu;
1867 
1868   if (Is64BitBltin && !IsTarget64Bit)
1869       return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1870              << TheCall->getSourceRange();
1871 
1872   if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1873       (BuiltinID == PPC::BI__builtin_bpermd &&
1874        !Context.getTargetInfo().hasFeature("bpermd")))
1875     return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1876            << TheCall->getSourceRange();
1877 
1878   switch (BuiltinID) {
1879   default: return false;
1880   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1881   case PPC::BI__builtin_altivec_crypto_vshasigmad:
1882     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1883            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1884   case PPC::BI__builtin_tbegin:
1885   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1886   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1887   case PPC::BI__builtin_tabortwc:
1888   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1889   case PPC::BI__builtin_tabortwci:
1890   case PPC::BI__builtin_tabortdci:
1891     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1892            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1893   case PPC::BI__builtin_vsx_xxpermdi:
1894   case PPC::BI__builtin_vsx_xxsldwi:
1895     return SemaBuiltinVSX(TheCall);
1896   }
1897   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1898 }
1899 
1900 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1901                                            CallExpr *TheCall) {
1902   if (BuiltinID == SystemZ::BI__builtin_tabort) {
1903     Expr *Arg = TheCall->getArg(0);
1904     llvm::APSInt AbortCode(32);
1905     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1906         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1907       return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1908              << Arg->getSourceRange();
1909   }
1910 
1911   // For intrinsics which take an immediate value as part of the instruction,
1912   // range check them here.
1913   unsigned i = 0, l = 0, u = 0;
1914   switch (BuiltinID) {
1915   default: return false;
1916   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1917   case SystemZ::BI__builtin_s390_verimb:
1918   case SystemZ::BI__builtin_s390_verimh:
1919   case SystemZ::BI__builtin_s390_verimf:
1920   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1921   case SystemZ::BI__builtin_s390_vfaeb:
1922   case SystemZ::BI__builtin_s390_vfaeh:
1923   case SystemZ::BI__builtin_s390_vfaef:
1924   case SystemZ::BI__builtin_s390_vfaebs:
1925   case SystemZ::BI__builtin_s390_vfaehs:
1926   case SystemZ::BI__builtin_s390_vfaefs:
1927   case SystemZ::BI__builtin_s390_vfaezb:
1928   case SystemZ::BI__builtin_s390_vfaezh:
1929   case SystemZ::BI__builtin_s390_vfaezf:
1930   case SystemZ::BI__builtin_s390_vfaezbs:
1931   case SystemZ::BI__builtin_s390_vfaezhs:
1932   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1933   case SystemZ::BI__builtin_s390_vfisb:
1934   case SystemZ::BI__builtin_s390_vfidb:
1935     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1936            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1937   case SystemZ::BI__builtin_s390_vftcisb:
1938   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1939   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1940   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1941   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1942   case SystemZ::BI__builtin_s390_vstrcb:
1943   case SystemZ::BI__builtin_s390_vstrch:
1944   case SystemZ::BI__builtin_s390_vstrcf:
1945   case SystemZ::BI__builtin_s390_vstrczb:
1946   case SystemZ::BI__builtin_s390_vstrczh:
1947   case SystemZ::BI__builtin_s390_vstrczf:
1948   case SystemZ::BI__builtin_s390_vstrcbs:
1949   case SystemZ::BI__builtin_s390_vstrchs:
1950   case SystemZ::BI__builtin_s390_vstrcfs:
1951   case SystemZ::BI__builtin_s390_vstrczbs:
1952   case SystemZ::BI__builtin_s390_vstrczhs:
1953   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1954   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
1955   case SystemZ::BI__builtin_s390_vfminsb:
1956   case SystemZ::BI__builtin_s390_vfmaxsb:
1957   case SystemZ::BI__builtin_s390_vfmindb:
1958   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
1959   }
1960   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1961 }
1962 
1963 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1964 /// This checks that the target supports __builtin_cpu_supports and
1965 /// that the string argument is constant and valid.
1966 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1967   Expr *Arg = TheCall->getArg(0);
1968 
1969   // Check if the argument is a string literal.
1970   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1971     return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1972            << Arg->getSourceRange();
1973 
1974   // Check the contents of the string.
1975   StringRef Feature =
1976       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1977   if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1978     return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1979            << Arg->getSourceRange();
1980   return false;
1981 }
1982 
1983 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
1984 /// This checks that the target supports __builtin_cpu_is and
1985 /// that the string argument is constant and valid.
1986 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
1987   Expr *Arg = TheCall->getArg(0);
1988 
1989   // Check if the argument is a string literal.
1990   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1991     return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1992            << Arg->getSourceRange();
1993 
1994   // Check the contents of the string.
1995   StringRef Feature =
1996       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1997   if (!S.Context.getTargetInfo().validateCpuIs(Feature))
1998     return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is)
1999            << Arg->getSourceRange();
2000   return false;
2001 }
2002 
2003 // Check if the rounding mode is legal.
2004 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
2005   // Indicates if this instruction has rounding control or just SAE.
2006   bool HasRC = false;
2007 
2008   unsigned ArgNum = 0;
2009   switch (BuiltinID) {
2010   default:
2011     return false;
2012   case X86::BI__builtin_ia32_vcvttsd2si32:
2013   case X86::BI__builtin_ia32_vcvttsd2si64:
2014   case X86::BI__builtin_ia32_vcvttsd2usi32:
2015   case X86::BI__builtin_ia32_vcvttsd2usi64:
2016   case X86::BI__builtin_ia32_vcvttss2si32:
2017   case X86::BI__builtin_ia32_vcvttss2si64:
2018   case X86::BI__builtin_ia32_vcvttss2usi32:
2019   case X86::BI__builtin_ia32_vcvttss2usi64:
2020     ArgNum = 1;
2021     break;
2022   case X86::BI__builtin_ia32_cvtps2pd512_mask:
2023   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
2024   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
2025   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
2026   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
2027   case X86::BI__builtin_ia32_cvttps2dq512_mask:
2028   case X86::BI__builtin_ia32_cvttps2qq512_mask:
2029   case X86::BI__builtin_ia32_cvttps2udq512_mask:
2030   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
2031   case X86::BI__builtin_ia32_exp2pd_mask:
2032   case X86::BI__builtin_ia32_exp2ps_mask:
2033   case X86::BI__builtin_ia32_getexppd512_mask:
2034   case X86::BI__builtin_ia32_getexpps512_mask:
2035   case X86::BI__builtin_ia32_rcp28pd_mask:
2036   case X86::BI__builtin_ia32_rcp28ps_mask:
2037   case X86::BI__builtin_ia32_rsqrt28pd_mask:
2038   case X86::BI__builtin_ia32_rsqrt28ps_mask:
2039   case X86::BI__builtin_ia32_vcomisd:
2040   case X86::BI__builtin_ia32_vcomiss:
2041   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
2042     ArgNum = 3;
2043     break;
2044   case X86::BI__builtin_ia32_cmppd512_mask:
2045   case X86::BI__builtin_ia32_cmpps512_mask:
2046   case X86::BI__builtin_ia32_cmpsd_mask:
2047   case X86::BI__builtin_ia32_cmpss_mask:
2048   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
2049   case X86::BI__builtin_ia32_getexpsd128_round_mask:
2050   case X86::BI__builtin_ia32_getexpss128_round_mask:
2051   case X86::BI__builtin_ia32_maxpd512_mask:
2052   case X86::BI__builtin_ia32_maxps512_mask:
2053   case X86::BI__builtin_ia32_maxsd_round_mask:
2054   case X86::BI__builtin_ia32_maxss_round_mask:
2055   case X86::BI__builtin_ia32_minpd512_mask:
2056   case X86::BI__builtin_ia32_minps512_mask:
2057   case X86::BI__builtin_ia32_minsd_round_mask:
2058   case X86::BI__builtin_ia32_minss_round_mask:
2059   case X86::BI__builtin_ia32_rcp28sd_round_mask:
2060   case X86::BI__builtin_ia32_rcp28ss_round_mask:
2061   case X86::BI__builtin_ia32_reducepd512_mask:
2062   case X86::BI__builtin_ia32_reduceps512_mask:
2063   case X86::BI__builtin_ia32_rndscalepd_mask:
2064   case X86::BI__builtin_ia32_rndscaleps_mask:
2065   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
2066   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
2067     ArgNum = 4;
2068     break;
2069   case X86::BI__builtin_ia32_fixupimmpd512_mask:
2070   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2071   case X86::BI__builtin_ia32_fixupimmps512_mask:
2072   case X86::BI__builtin_ia32_fixupimmps512_maskz:
2073   case X86::BI__builtin_ia32_fixupimmsd_mask:
2074   case X86::BI__builtin_ia32_fixupimmsd_maskz:
2075   case X86::BI__builtin_ia32_fixupimmss_mask:
2076   case X86::BI__builtin_ia32_fixupimmss_maskz:
2077   case X86::BI__builtin_ia32_rangepd512_mask:
2078   case X86::BI__builtin_ia32_rangeps512_mask:
2079   case X86::BI__builtin_ia32_rangesd128_round_mask:
2080   case X86::BI__builtin_ia32_rangess128_round_mask:
2081   case X86::BI__builtin_ia32_reducesd_mask:
2082   case X86::BI__builtin_ia32_reducess_mask:
2083   case X86::BI__builtin_ia32_rndscalesd_round_mask:
2084   case X86::BI__builtin_ia32_rndscaless_round_mask:
2085     ArgNum = 5;
2086     break;
2087   case X86::BI__builtin_ia32_vcvtsd2si64:
2088   case X86::BI__builtin_ia32_vcvtsd2si32:
2089   case X86::BI__builtin_ia32_vcvtsd2usi32:
2090   case X86::BI__builtin_ia32_vcvtsd2usi64:
2091   case X86::BI__builtin_ia32_vcvtss2si32:
2092   case X86::BI__builtin_ia32_vcvtss2si64:
2093   case X86::BI__builtin_ia32_vcvtss2usi32:
2094   case X86::BI__builtin_ia32_vcvtss2usi64:
2095     ArgNum = 1;
2096     HasRC = true;
2097     break;
2098   case X86::BI__builtin_ia32_cvtsi2sd64:
2099   case X86::BI__builtin_ia32_cvtsi2ss32:
2100   case X86::BI__builtin_ia32_cvtsi2ss64:
2101   case X86::BI__builtin_ia32_cvtusi2sd64:
2102   case X86::BI__builtin_ia32_cvtusi2ss32:
2103   case X86::BI__builtin_ia32_cvtusi2ss64:
2104     ArgNum = 2;
2105     HasRC = true;
2106     break;
2107   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
2108   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
2109   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
2110   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
2111   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
2112   case X86::BI__builtin_ia32_cvtps2qq512_mask:
2113   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
2114   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
2115   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
2116   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
2117   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
2118   case X86::BI__builtin_ia32_sqrtpd512_mask:
2119   case X86::BI__builtin_ia32_sqrtps512_mask:
2120     ArgNum = 3;
2121     HasRC = true;
2122     break;
2123   case X86::BI__builtin_ia32_addpd512_mask:
2124   case X86::BI__builtin_ia32_addps512_mask:
2125   case X86::BI__builtin_ia32_divpd512_mask:
2126   case X86::BI__builtin_ia32_divps512_mask:
2127   case X86::BI__builtin_ia32_mulpd512_mask:
2128   case X86::BI__builtin_ia32_mulps512_mask:
2129   case X86::BI__builtin_ia32_subpd512_mask:
2130   case X86::BI__builtin_ia32_subps512_mask:
2131   case X86::BI__builtin_ia32_addss_round_mask:
2132   case X86::BI__builtin_ia32_addsd_round_mask:
2133   case X86::BI__builtin_ia32_divss_round_mask:
2134   case X86::BI__builtin_ia32_divsd_round_mask:
2135   case X86::BI__builtin_ia32_mulss_round_mask:
2136   case X86::BI__builtin_ia32_mulsd_round_mask:
2137   case X86::BI__builtin_ia32_subss_round_mask:
2138   case X86::BI__builtin_ia32_subsd_round_mask:
2139   case X86::BI__builtin_ia32_scalefpd512_mask:
2140   case X86::BI__builtin_ia32_scalefps512_mask:
2141   case X86::BI__builtin_ia32_scalefsd_round_mask:
2142   case X86::BI__builtin_ia32_scalefss_round_mask:
2143   case X86::BI__builtin_ia32_getmantpd512_mask:
2144   case X86::BI__builtin_ia32_getmantps512_mask:
2145   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
2146   case X86::BI__builtin_ia32_sqrtsd_round_mask:
2147   case X86::BI__builtin_ia32_sqrtss_round_mask:
2148   case X86::BI__builtin_ia32_vfmaddpd512_mask:
2149   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
2150   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
2151   case X86::BI__builtin_ia32_vfmaddps512_mask:
2152   case X86::BI__builtin_ia32_vfmaddps512_mask3:
2153   case X86::BI__builtin_ia32_vfmaddps512_maskz:
2154   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
2155   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
2156   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
2157   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
2158   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
2159   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
2160   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
2161   case X86::BI__builtin_ia32_vfmsubps512_mask3:
2162   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
2163   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
2164   case X86::BI__builtin_ia32_vfnmaddpd512_mask:
2165   case X86::BI__builtin_ia32_vfnmaddps512_mask:
2166   case X86::BI__builtin_ia32_vfnmsubpd512_mask:
2167   case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
2168   case X86::BI__builtin_ia32_vfnmsubps512_mask:
2169   case X86::BI__builtin_ia32_vfnmsubps512_mask3:
2170   case X86::BI__builtin_ia32_vfmaddsd3_mask:
2171   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
2172   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
2173   case X86::BI__builtin_ia32_vfmaddss3_mask:
2174   case X86::BI__builtin_ia32_vfmaddss3_maskz:
2175   case X86::BI__builtin_ia32_vfmaddss3_mask3:
2176     ArgNum = 4;
2177     HasRC = true;
2178     break;
2179   case X86::BI__builtin_ia32_getmantsd_round_mask:
2180   case X86::BI__builtin_ia32_getmantss_round_mask:
2181     ArgNum = 5;
2182     HasRC = true;
2183     break;
2184   }
2185 
2186   llvm::APSInt Result;
2187 
2188   // We can't check the value of a dependent argument.
2189   Expr *Arg = TheCall->getArg(ArgNum);
2190   if (Arg->isTypeDependent() || Arg->isValueDependent())
2191     return false;
2192 
2193   // Check constant-ness first.
2194   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2195     return true;
2196 
2197   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
2198   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
2199   // combined with ROUND_NO_EXC.
2200   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
2201       Result == 8/*ROUND_NO_EXC*/ ||
2202       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
2203     return false;
2204 
2205   return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
2206     << Arg->getSourceRange();
2207 }
2208 
2209 // Check if the gather/scatter scale is legal.
2210 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
2211                                              CallExpr *TheCall) {
2212   unsigned ArgNum = 0;
2213   switch (BuiltinID) {
2214   default:
2215     return false;
2216   case X86::BI__builtin_ia32_gatherpfdpd:
2217   case X86::BI__builtin_ia32_gatherpfdps:
2218   case X86::BI__builtin_ia32_gatherpfqpd:
2219   case X86::BI__builtin_ia32_gatherpfqps:
2220   case X86::BI__builtin_ia32_scatterpfdpd:
2221   case X86::BI__builtin_ia32_scatterpfdps:
2222   case X86::BI__builtin_ia32_scatterpfqpd:
2223   case X86::BI__builtin_ia32_scatterpfqps:
2224     ArgNum = 3;
2225     break;
2226   case X86::BI__builtin_ia32_gatherd_pd:
2227   case X86::BI__builtin_ia32_gatherd_pd256:
2228   case X86::BI__builtin_ia32_gatherq_pd:
2229   case X86::BI__builtin_ia32_gatherq_pd256:
2230   case X86::BI__builtin_ia32_gatherd_ps:
2231   case X86::BI__builtin_ia32_gatherd_ps256:
2232   case X86::BI__builtin_ia32_gatherq_ps:
2233   case X86::BI__builtin_ia32_gatherq_ps256:
2234   case X86::BI__builtin_ia32_gatherd_q:
2235   case X86::BI__builtin_ia32_gatherd_q256:
2236   case X86::BI__builtin_ia32_gatherq_q:
2237   case X86::BI__builtin_ia32_gatherq_q256:
2238   case X86::BI__builtin_ia32_gatherd_d:
2239   case X86::BI__builtin_ia32_gatherd_d256:
2240   case X86::BI__builtin_ia32_gatherq_d:
2241   case X86::BI__builtin_ia32_gatherq_d256:
2242   case X86::BI__builtin_ia32_gather3div2df:
2243   case X86::BI__builtin_ia32_gather3div2di:
2244   case X86::BI__builtin_ia32_gather3div4df:
2245   case X86::BI__builtin_ia32_gather3div4di:
2246   case X86::BI__builtin_ia32_gather3div4sf:
2247   case X86::BI__builtin_ia32_gather3div4si:
2248   case X86::BI__builtin_ia32_gather3div8sf:
2249   case X86::BI__builtin_ia32_gather3div8si:
2250   case X86::BI__builtin_ia32_gather3siv2df:
2251   case X86::BI__builtin_ia32_gather3siv2di:
2252   case X86::BI__builtin_ia32_gather3siv4df:
2253   case X86::BI__builtin_ia32_gather3siv4di:
2254   case X86::BI__builtin_ia32_gather3siv4sf:
2255   case X86::BI__builtin_ia32_gather3siv4si:
2256   case X86::BI__builtin_ia32_gather3siv8sf:
2257   case X86::BI__builtin_ia32_gather3siv8si:
2258   case X86::BI__builtin_ia32_gathersiv8df:
2259   case X86::BI__builtin_ia32_gathersiv16sf:
2260   case X86::BI__builtin_ia32_gatherdiv8df:
2261   case X86::BI__builtin_ia32_gatherdiv16sf:
2262   case X86::BI__builtin_ia32_gathersiv8di:
2263   case X86::BI__builtin_ia32_gathersiv16si:
2264   case X86::BI__builtin_ia32_gatherdiv8di:
2265   case X86::BI__builtin_ia32_gatherdiv16si:
2266   case X86::BI__builtin_ia32_scatterdiv2df:
2267   case X86::BI__builtin_ia32_scatterdiv2di:
2268   case X86::BI__builtin_ia32_scatterdiv4df:
2269   case X86::BI__builtin_ia32_scatterdiv4di:
2270   case X86::BI__builtin_ia32_scatterdiv4sf:
2271   case X86::BI__builtin_ia32_scatterdiv4si:
2272   case X86::BI__builtin_ia32_scatterdiv8sf:
2273   case X86::BI__builtin_ia32_scatterdiv8si:
2274   case X86::BI__builtin_ia32_scattersiv2df:
2275   case X86::BI__builtin_ia32_scattersiv2di:
2276   case X86::BI__builtin_ia32_scattersiv4df:
2277   case X86::BI__builtin_ia32_scattersiv4di:
2278   case X86::BI__builtin_ia32_scattersiv4sf:
2279   case X86::BI__builtin_ia32_scattersiv4si:
2280   case X86::BI__builtin_ia32_scattersiv8sf:
2281   case X86::BI__builtin_ia32_scattersiv8si:
2282   case X86::BI__builtin_ia32_scattersiv8df:
2283   case X86::BI__builtin_ia32_scattersiv16sf:
2284   case X86::BI__builtin_ia32_scatterdiv8df:
2285   case X86::BI__builtin_ia32_scatterdiv16sf:
2286   case X86::BI__builtin_ia32_scattersiv8di:
2287   case X86::BI__builtin_ia32_scattersiv16si:
2288   case X86::BI__builtin_ia32_scatterdiv8di:
2289   case X86::BI__builtin_ia32_scatterdiv16si:
2290     ArgNum = 4;
2291     break;
2292   }
2293 
2294   llvm::APSInt Result;
2295 
2296   // We can't check the value of a dependent argument.
2297   Expr *Arg = TheCall->getArg(ArgNum);
2298   if (Arg->isTypeDependent() || Arg->isValueDependent())
2299     return false;
2300 
2301   // Check constant-ness first.
2302   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2303     return true;
2304 
2305   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
2306     return false;
2307 
2308   return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
2309     << Arg->getSourceRange();
2310 }
2311 
2312 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2313   if (BuiltinID == X86::BI__builtin_cpu_supports)
2314     return SemaBuiltinCpuSupports(*this, TheCall);
2315 
2316   if (BuiltinID == X86::BI__builtin_cpu_is)
2317     return SemaBuiltinCpuIs(*this, TheCall);
2318 
2319   // If the intrinsic has rounding or SAE make sure its valid.
2320   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2321     return true;
2322 
2323   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
2324   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
2325     return true;
2326 
2327   // For intrinsics which take an immediate value as part of the instruction,
2328   // range check them here.
2329   int i = 0, l = 0, u = 0;
2330   switch (BuiltinID) {
2331   default:
2332     return false;
2333   case X86::BI_mm_prefetch:
2334     i = 1; l = 0; u = 7;
2335     break;
2336   case X86::BI__builtin_ia32_sha1rnds4:
2337   case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2338   case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2339   case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2340   case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
2341     i = 2; l = 0; u = 3;
2342     break;
2343   case X86::BI__builtin_ia32_vpermil2pd:
2344   case X86::BI__builtin_ia32_vpermil2pd256:
2345   case X86::BI__builtin_ia32_vpermil2ps:
2346   case X86::BI__builtin_ia32_vpermil2ps256:
2347     i = 3; l = 0; u = 3;
2348     break;
2349   case X86::BI__builtin_ia32_cmpb128_mask:
2350   case X86::BI__builtin_ia32_cmpw128_mask:
2351   case X86::BI__builtin_ia32_cmpd128_mask:
2352   case X86::BI__builtin_ia32_cmpq128_mask:
2353   case X86::BI__builtin_ia32_cmpb256_mask:
2354   case X86::BI__builtin_ia32_cmpw256_mask:
2355   case X86::BI__builtin_ia32_cmpd256_mask:
2356   case X86::BI__builtin_ia32_cmpq256_mask:
2357   case X86::BI__builtin_ia32_cmpb512_mask:
2358   case X86::BI__builtin_ia32_cmpw512_mask:
2359   case X86::BI__builtin_ia32_cmpd512_mask:
2360   case X86::BI__builtin_ia32_cmpq512_mask:
2361   case X86::BI__builtin_ia32_ucmpb128_mask:
2362   case X86::BI__builtin_ia32_ucmpw128_mask:
2363   case X86::BI__builtin_ia32_ucmpd128_mask:
2364   case X86::BI__builtin_ia32_ucmpq128_mask:
2365   case X86::BI__builtin_ia32_ucmpb256_mask:
2366   case X86::BI__builtin_ia32_ucmpw256_mask:
2367   case X86::BI__builtin_ia32_ucmpd256_mask:
2368   case X86::BI__builtin_ia32_ucmpq256_mask:
2369   case X86::BI__builtin_ia32_ucmpb512_mask:
2370   case X86::BI__builtin_ia32_ucmpw512_mask:
2371   case X86::BI__builtin_ia32_ucmpd512_mask:
2372   case X86::BI__builtin_ia32_ucmpq512_mask:
2373   case X86::BI__builtin_ia32_vpcomub:
2374   case X86::BI__builtin_ia32_vpcomuw:
2375   case X86::BI__builtin_ia32_vpcomud:
2376   case X86::BI__builtin_ia32_vpcomuq:
2377   case X86::BI__builtin_ia32_vpcomb:
2378   case X86::BI__builtin_ia32_vpcomw:
2379   case X86::BI__builtin_ia32_vpcomd:
2380   case X86::BI__builtin_ia32_vpcomq:
2381     i = 2; l = 0; u = 7;
2382     break;
2383   case X86::BI__builtin_ia32_roundps:
2384   case X86::BI__builtin_ia32_roundpd:
2385   case X86::BI__builtin_ia32_roundps256:
2386   case X86::BI__builtin_ia32_roundpd256:
2387     i = 1; l = 0; u = 15;
2388     break;
2389   case X86::BI__builtin_ia32_roundss:
2390   case X86::BI__builtin_ia32_roundsd:
2391   case X86::BI__builtin_ia32_rangepd128_mask:
2392   case X86::BI__builtin_ia32_rangepd256_mask:
2393   case X86::BI__builtin_ia32_rangepd512_mask:
2394   case X86::BI__builtin_ia32_rangeps128_mask:
2395   case X86::BI__builtin_ia32_rangeps256_mask:
2396   case X86::BI__builtin_ia32_rangeps512_mask:
2397   case X86::BI__builtin_ia32_getmantsd_round_mask:
2398   case X86::BI__builtin_ia32_getmantss_round_mask:
2399     i = 2; l = 0; u = 15;
2400     break;
2401   case X86::BI__builtin_ia32_cmpps:
2402   case X86::BI__builtin_ia32_cmpss:
2403   case X86::BI__builtin_ia32_cmppd:
2404   case X86::BI__builtin_ia32_cmpsd:
2405   case X86::BI__builtin_ia32_cmpps256:
2406   case X86::BI__builtin_ia32_cmppd256:
2407   case X86::BI__builtin_ia32_cmpps128_mask:
2408   case X86::BI__builtin_ia32_cmppd128_mask:
2409   case X86::BI__builtin_ia32_cmpps256_mask:
2410   case X86::BI__builtin_ia32_cmppd256_mask:
2411   case X86::BI__builtin_ia32_cmpps512_mask:
2412   case X86::BI__builtin_ia32_cmppd512_mask:
2413   case X86::BI__builtin_ia32_cmpsd_mask:
2414   case X86::BI__builtin_ia32_cmpss_mask:
2415     i = 2; l = 0; u = 31;
2416     break;
2417   case X86::BI__builtin_ia32_vcvtps2ph:
2418   case X86::BI__builtin_ia32_vcvtps2ph_mask:
2419   case X86::BI__builtin_ia32_vcvtps2ph256:
2420   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
2421   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
2422   case X86::BI__builtin_ia32_rndscaleps_128_mask:
2423   case X86::BI__builtin_ia32_rndscalepd_128_mask:
2424   case X86::BI__builtin_ia32_rndscaleps_256_mask:
2425   case X86::BI__builtin_ia32_rndscalepd_256_mask:
2426   case X86::BI__builtin_ia32_rndscaleps_mask:
2427   case X86::BI__builtin_ia32_rndscalepd_mask:
2428   case X86::BI__builtin_ia32_reducepd128_mask:
2429   case X86::BI__builtin_ia32_reducepd256_mask:
2430   case X86::BI__builtin_ia32_reducepd512_mask:
2431   case X86::BI__builtin_ia32_reduceps128_mask:
2432   case X86::BI__builtin_ia32_reduceps256_mask:
2433   case X86::BI__builtin_ia32_reduceps512_mask:
2434   case X86::BI__builtin_ia32_prold512_mask:
2435   case X86::BI__builtin_ia32_prolq512_mask:
2436   case X86::BI__builtin_ia32_prold128_mask:
2437   case X86::BI__builtin_ia32_prold256_mask:
2438   case X86::BI__builtin_ia32_prolq128_mask:
2439   case X86::BI__builtin_ia32_prolq256_mask:
2440   case X86::BI__builtin_ia32_prord128_mask:
2441   case X86::BI__builtin_ia32_prord256_mask:
2442   case X86::BI__builtin_ia32_prorq128_mask:
2443   case X86::BI__builtin_ia32_prorq256_mask:
2444   case X86::BI__builtin_ia32_fpclasspd128_mask:
2445   case X86::BI__builtin_ia32_fpclasspd256_mask:
2446   case X86::BI__builtin_ia32_fpclassps128_mask:
2447   case X86::BI__builtin_ia32_fpclassps256_mask:
2448   case X86::BI__builtin_ia32_fpclassps512_mask:
2449   case X86::BI__builtin_ia32_fpclasspd512_mask:
2450   case X86::BI__builtin_ia32_fpclasssd_mask:
2451   case X86::BI__builtin_ia32_fpclassss_mask:
2452     i = 1; l = 0; u = 255;
2453     break;
2454   case X86::BI__builtin_ia32_palignr128:
2455   case X86::BI__builtin_ia32_palignr256:
2456   case X86::BI__builtin_ia32_palignr512_mask:
2457   case X86::BI__builtin_ia32_vcomisd:
2458   case X86::BI__builtin_ia32_vcomiss:
2459   case X86::BI__builtin_ia32_shuf_f32x4_mask:
2460   case X86::BI__builtin_ia32_shuf_f64x2_mask:
2461   case X86::BI__builtin_ia32_shuf_i32x4_mask:
2462   case X86::BI__builtin_ia32_shuf_i64x2_mask:
2463   case X86::BI__builtin_ia32_dbpsadbw128_mask:
2464   case X86::BI__builtin_ia32_dbpsadbw256_mask:
2465   case X86::BI__builtin_ia32_dbpsadbw512_mask:
2466   case X86::BI__builtin_ia32_vpshldd128_mask:
2467   case X86::BI__builtin_ia32_vpshldd256_mask:
2468   case X86::BI__builtin_ia32_vpshldd512_mask:
2469   case X86::BI__builtin_ia32_vpshldq128_mask:
2470   case X86::BI__builtin_ia32_vpshldq256_mask:
2471   case X86::BI__builtin_ia32_vpshldq512_mask:
2472   case X86::BI__builtin_ia32_vpshldw128_mask:
2473   case X86::BI__builtin_ia32_vpshldw256_mask:
2474   case X86::BI__builtin_ia32_vpshldw512_mask:
2475   case X86::BI__builtin_ia32_vpshrdd128_mask:
2476   case X86::BI__builtin_ia32_vpshrdd256_mask:
2477   case X86::BI__builtin_ia32_vpshrdd512_mask:
2478   case X86::BI__builtin_ia32_vpshrdq128_mask:
2479   case X86::BI__builtin_ia32_vpshrdq256_mask:
2480   case X86::BI__builtin_ia32_vpshrdq512_mask:
2481   case X86::BI__builtin_ia32_vpshrdw128_mask:
2482   case X86::BI__builtin_ia32_vpshrdw256_mask:
2483   case X86::BI__builtin_ia32_vpshrdw512_mask:
2484     i = 2; l = 0; u = 255;
2485     break;
2486   case X86::BI__builtin_ia32_fixupimmpd512_mask:
2487   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2488   case X86::BI__builtin_ia32_fixupimmps512_mask:
2489   case X86::BI__builtin_ia32_fixupimmps512_maskz:
2490   case X86::BI__builtin_ia32_fixupimmsd_mask:
2491   case X86::BI__builtin_ia32_fixupimmsd_maskz:
2492   case X86::BI__builtin_ia32_fixupimmss_mask:
2493   case X86::BI__builtin_ia32_fixupimmss_maskz:
2494   case X86::BI__builtin_ia32_fixupimmpd128_mask:
2495   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2496   case X86::BI__builtin_ia32_fixupimmpd256_mask:
2497   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2498   case X86::BI__builtin_ia32_fixupimmps128_mask:
2499   case X86::BI__builtin_ia32_fixupimmps128_maskz:
2500   case X86::BI__builtin_ia32_fixupimmps256_mask:
2501   case X86::BI__builtin_ia32_fixupimmps256_maskz:
2502   case X86::BI__builtin_ia32_pternlogd512_mask:
2503   case X86::BI__builtin_ia32_pternlogd512_maskz:
2504   case X86::BI__builtin_ia32_pternlogq512_mask:
2505   case X86::BI__builtin_ia32_pternlogq512_maskz:
2506   case X86::BI__builtin_ia32_pternlogd128_mask:
2507   case X86::BI__builtin_ia32_pternlogd128_maskz:
2508   case X86::BI__builtin_ia32_pternlogd256_mask:
2509   case X86::BI__builtin_ia32_pternlogd256_maskz:
2510   case X86::BI__builtin_ia32_pternlogq128_mask:
2511   case X86::BI__builtin_ia32_pternlogq128_maskz:
2512   case X86::BI__builtin_ia32_pternlogq256_mask:
2513   case X86::BI__builtin_ia32_pternlogq256_maskz:
2514     i = 3; l = 0; u = 255;
2515     break;
2516   case X86::BI__builtin_ia32_gatherpfdpd:
2517   case X86::BI__builtin_ia32_gatherpfdps:
2518   case X86::BI__builtin_ia32_gatherpfqpd:
2519   case X86::BI__builtin_ia32_gatherpfqps:
2520   case X86::BI__builtin_ia32_scatterpfdpd:
2521   case X86::BI__builtin_ia32_scatterpfdps:
2522   case X86::BI__builtin_ia32_scatterpfqpd:
2523   case X86::BI__builtin_ia32_scatterpfqps:
2524     i = 4; l = 2; u = 3;
2525     break;
2526   case X86::BI__builtin_ia32_rndscalesd_round_mask:
2527   case X86::BI__builtin_ia32_rndscaless_round_mask:
2528     i = 4; l = 0; u = 255;
2529     break;
2530   }
2531   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2532 }
2533 
2534 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2535 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
2536 /// Returns true when the format fits the function and the FormatStringInfo has
2537 /// been populated.
2538 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2539                                FormatStringInfo *FSI) {
2540   FSI->HasVAListArg = Format->getFirstArg() == 0;
2541   FSI->FormatIdx = Format->getFormatIdx() - 1;
2542   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
2543 
2544   // The way the format attribute works in GCC, the implicit this argument
2545   // of member functions is counted. However, it doesn't appear in our own
2546   // lists, so decrement format_idx in that case.
2547   if (IsCXXMember) {
2548     if(FSI->FormatIdx == 0)
2549       return false;
2550     --FSI->FormatIdx;
2551     if (FSI->FirstDataArg != 0)
2552       --FSI->FirstDataArg;
2553   }
2554   return true;
2555 }
2556 
2557 /// Checks if a the given expression evaluates to null.
2558 ///
2559 /// \brief Returns true if the value evaluates to null.
2560 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
2561   // If the expression has non-null type, it doesn't evaluate to null.
2562   if (auto nullability
2563         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2564     if (*nullability == NullabilityKind::NonNull)
2565       return false;
2566   }
2567 
2568   // As a special case, transparent unions initialized with zero are
2569   // considered null for the purposes of the nonnull attribute.
2570   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
2571     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2572       if (const CompoundLiteralExpr *CLE =
2573           dyn_cast<CompoundLiteralExpr>(Expr))
2574         if (const InitListExpr *ILE =
2575             dyn_cast<InitListExpr>(CLE->getInitializer()))
2576           Expr = ILE->getInit(0);
2577   }
2578 
2579   bool Result;
2580   return (!Expr->isValueDependent() &&
2581           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2582           !Result);
2583 }
2584 
2585 static void CheckNonNullArgument(Sema &S,
2586                                  const Expr *ArgExpr,
2587                                  SourceLocation CallSiteLoc) {
2588   if (CheckNonNullExpr(S, ArgExpr))
2589     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2590            S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
2591 }
2592 
2593 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2594   FormatStringInfo FSI;
2595   if ((GetFormatStringType(Format) == FST_NSString) &&
2596       getFormatStringInfo(Format, false, &FSI)) {
2597     Idx = FSI.FormatIdx;
2598     return true;
2599   }
2600   return false;
2601 }
2602 
2603 /// \brief Diagnose use of %s directive in an NSString which is being passed
2604 /// as formatting string to formatting method.
2605 static void
2606 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2607                                         const NamedDecl *FDecl,
2608                                         Expr **Args,
2609                                         unsigned NumArgs) {
2610   unsigned Idx = 0;
2611   bool Format = false;
2612   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2613   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
2614     Idx = 2;
2615     Format = true;
2616   }
2617   else
2618     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2619       if (S.GetFormatNSStringIdx(I, Idx)) {
2620         Format = true;
2621         break;
2622       }
2623     }
2624   if (!Format || NumArgs <= Idx)
2625     return;
2626   const Expr *FormatExpr = Args[Idx];
2627   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2628     FormatExpr = CSCE->getSubExpr();
2629   const StringLiteral *FormatString;
2630   if (const ObjCStringLiteral *OSL =
2631       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2632     FormatString = OSL->getString();
2633   else
2634     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2635   if (!FormatString)
2636     return;
2637   if (S.FormatStringHasSArg(FormatString)) {
2638     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2639       << "%s" << 1 << 1;
2640     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2641       << FDecl->getDeclName();
2642   }
2643 }
2644 
2645 /// Determine whether the given type has a non-null nullability annotation.
2646 static bool isNonNullType(ASTContext &ctx, QualType type) {
2647   if (auto nullability = type->getNullability(ctx))
2648     return *nullability == NullabilityKind::NonNull;
2649 
2650   return false;
2651 }
2652 
2653 static void CheckNonNullArguments(Sema &S,
2654                                   const NamedDecl *FDecl,
2655                                   const FunctionProtoType *Proto,
2656                                   ArrayRef<const Expr *> Args,
2657                                   SourceLocation CallSiteLoc) {
2658   assert((FDecl || Proto) && "Need a function declaration or prototype");
2659 
2660   // Check the attributes attached to the method/function itself.
2661   llvm::SmallBitVector NonNullArgs;
2662   if (FDecl) {
2663     // Handle the nonnull attribute on the function/method declaration itself.
2664     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2665       if (!NonNull->args_size()) {
2666         // Easy case: all pointer arguments are nonnull.
2667         for (const auto *Arg : Args)
2668           if (S.isValidPointerAttrType(Arg->getType()))
2669             CheckNonNullArgument(S, Arg, CallSiteLoc);
2670         return;
2671       }
2672 
2673       for (const ParamIdx &Idx : NonNull->args()) {
2674         unsigned IdxAST = Idx.getASTIndex();
2675         if (IdxAST >= Args.size())
2676           continue;
2677         if (NonNullArgs.empty())
2678           NonNullArgs.resize(Args.size());
2679         NonNullArgs.set(IdxAST);
2680       }
2681     }
2682   }
2683 
2684   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2685     // Handle the nonnull attribute on the parameters of the
2686     // function/method.
2687     ArrayRef<ParmVarDecl*> parms;
2688     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2689       parms = FD->parameters();
2690     else
2691       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2692 
2693     unsigned ParamIndex = 0;
2694     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2695          I != E; ++I, ++ParamIndex) {
2696       const ParmVarDecl *PVD = *I;
2697       if (PVD->hasAttr<NonNullAttr>() ||
2698           isNonNullType(S.Context, PVD->getType())) {
2699         if (NonNullArgs.empty())
2700           NonNullArgs.resize(Args.size());
2701 
2702         NonNullArgs.set(ParamIndex);
2703       }
2704     }
2705   } else {
2706     // If we have a non-function, non-method declaration but no
2707     // function prototype, try to dig out the function prototype.
2708     if (!Proto) {
2709       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2710         QualType type = VD->getType().getNonReferenceType();
2711         if (auto pointerType = type->getAs<PointerType>())
2712           type = pointerType->getPointeeType();
2713         else if (auto blockType = type->getAs<BlockPointerType>())
2714           type = blockType->getPointeeType();
2715         // FIXME: data member pointers?
2716 
2717         // Dig out the function prototype, if there is one.
2718         Proto = type->getAs<FunctionProtoType>();
2719       }
2720     }
2721 
2722     // Fill in non-null argument information from the nullability
2723     // information on the parameter types (if we have them).
2724     if (Proto) {
2725       unsigned Index = 0;
2726       for (auto paramType : Proto->getParamTypes()) {
2727         if (isNonNullType(S.Context, paramType)) {
2728           if (NonNullArgs.empty())
2729             NonNullArgs.resize(Args.size());
2730 
2731           NonNullArgs.set(Index);
2732         }
2733 
2734         ++Index;
2735       }
2736     }
2737   }
2738 
2739   // Check for non-null arguments.
2740   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2741        ArgIndex != ArgIndexEnd; ++ArgIndex) {
2742     if (NonNullArgs[ArgIndex])
2743       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
2744   }
2745 }
2746 
2747 /// Handles the checks for format strings, non-POD arguments to vararg
2748 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
2749 /// attributes.
2750 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2751                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
2752                      bool IsMemberFunction, SourceLocation Loc,
2753                      SourceRange Range, VariadicCallType CallType) {
2754   // FIXME: We should check as much as we can in the template definition.
2755   if (CurContext->isDependentContext())
2756     return;
2757 
2758   // Printf and scanf checking.
2759   llvm::SmallBitVector CheckedVarArgs;
2760   if (FDecl) {
2761     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2762       // Only create vector if there are format attributes.
2763       CheckedVarArgs.resize(Args.size());
2764 
2765       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
2766                            CheckedVarArgs);
2767     }
2768   }
2769 
2770   // Refuse POD arguments that weren't caught by the format string
2771   // checks above.
2772   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
2773   if (CallType != VariadicDoesNotApply &&
2774       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
2775     unsigned NumParams = Proto ? Proto->getNumParams()
2776                        : FDecl && isa<FunctionDecl>(FDecl)
2777                            ? cast<FunctionDecl>(FDecl)->getNumParams()
2778                        : FDecl && isa<ObjCMethodDecl>(FDecl)
2779                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
2780                        : 0;
2781 
2782     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
2783       // Args[ArgIdx] can be null in malformed code.
2784       if (const Expr *Arg = Args[ArgIdx]) {
2785         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2786           checkVariadicArgument(Arg, CallType);
2787       }
2788     }
2789   }
2790 
2791   if (FDecl || Proto) {
2792     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
2793 
2794     // Type safety checking.
2795     if (FDecl) {
2796       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2797         CheckArgumentWithTypeTag(I, Args, Loc);
2798     }
2799   }
2800 
2801   if (FD)
2802     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
2803 }
2804 
2805 /// CheckConstructorCall - Check a constructor call for correctness and safety
2806 /// properties not enforced by the C type system.
2807 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2808                                 ArrayRef<const Expr *> Args,
2809                                 const FunctionProtoType *Proto,
2810                                 SourceLocation Loc) {
2811   VariadicCallType CallType =
2812     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
2813   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
2814             Loc, SourceRange(), CallType);
2815 }
2816 
2817 /// CheckFunctionCall - Check a direct function call for various correctness
2818 /// and safety properties not strictly enforced by the C type system.
2819 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2820                              const FunctionProtoType *Proto) {
2821   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2822                               isa<CXXMethodDecl>(FDecl);
2823   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2824                           IsMemberOperatorCall;
2825   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2826                                                   TheCall->getCallee());
2827   Expr** Args = TheCall->getArgs();
2828   unsigned NumArgs = TheCall->getNumArgs();
2829 
2830   Expr *ImplicitThis = nullptr;
2831   if (IsMemberOperatorCall) {
2832     // If this is a call to a member operator, hide the first argument
2833     // from checkCall.
2834     // FIXME: Our choice of AST representation here is less than ideal.
2835     ImplicitThis = Args[0];
2836     ++Args;
2837     --NumArgs;
2838   } else if (IsMemberFunction)
2839     ImplicitThis =
2840         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
2841 
2842   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
2843             IsMemberFunction, TheCall->getRParenLoc(),
2844             TheCall->getCallee()->getSourceRange(), CallType);
2845 
2846   IdentifierInfo *FnInfo = FDecl->getIdentifier();
2847   // None of the checks below are needed for functions that don't have
2848   // simple names (e.g., C++ conversion functions).
2849   if (!FnInfo)
2850     return false;
2851 
2852   CheckAbsoluteValueFunction(TheCall, FDecl);
2853   CheckMaxUnsignedZero(TheCall, FDecl);
2854 
2855   if (getLangOpts().ObjC1)
2856     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
2857 
2858   unsigned CMId = FDecl->getMemoryFunctionKind();
2859   if (CMId == 0)
2860     return false;
2861 
2862   // Handle memory setting and copying functions.
2863   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
2864     CheckStrlcpycatArguments(TheCall, FnInfo);
2865   else if (CMId == Builtin::BIstrncat)
2866     CheckStrncatArguments(TheCall, FnInfo);
2867   else
2868     CheckMemaccessArguments(TheCall, CMId, FnInfo);
2869 
2870   return false;
2871 }
2872 
2873 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
2874                                ArrayRef<const Expr *> Args) {
2875   VariadicCallType CallType =
2876       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
2877 
2878   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
2879             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
2880             CallType);
2881 
2882   return false;
2883 }
2884 
2885 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2886                             const FunctionProtoType *Proto) {
2887   QualType Ty;
2888   if (const auto *V = dyn_cast<VarDecl>(NDecl))
2889     Ty = V->getType().getNonReferenceType();
2890   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
2891     Ty = F->getType().getNonReferenceType();
2892   else
2893     return false;
2894 
2895   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2896       !Ty->isFunctionProtoType())
2897     return false;
2898 
2899   VariadicCallType CallType;
2900   if (!Proto || !Proto->isVariadic()) {
2901     CallType = VariadicDoesNotApply;
2902   } else if (Ty->isBlockPointerType()) {
2903     CallType = VariadicBlock;
2904   } else { // Ty->isFunctionPointerType()
2905     CallType = VariadicFunction;
2906   }
2907 
2908   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
2909             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2910             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2911             TheCall->getCallee()->getSourceRange(), CallType);
2912 
2913   return false;
2914 }
2915 
2916 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2917 /// such as function pointers returned from functions.
2918 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
2919   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
2920                                                   TheCall->getCallee());
2921   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
2922             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2923             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2924             TheCall->getCallee()->getSourceRange(), CallType);
2925 
2926   return false;
2927 }
2928 
2929 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
2930   if (!llvm::isValidAtomicOrderingCABI(Ordering))
2931     return false;
2932 
2933   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
2934   switch (Op) {
2935   case AtomicExpr::AO__c11_atomic_init:
2936   case AtomicExpr::AO__opencl_atomic_init:
2937     llvm_unreachable("There is no ordering argument for an init");
2938 
2939   case AtomicExpr::AO__c11_atomic_load:
2940   case AtomicExpr::AO__opencl_atomic_load:
2941   case AtomicExpr::AO__atomic_load_n:
2942   case AtomicExpr::AO__atomic_load:
2943     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2944            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2945 
2946   case AtomicExpr::AO__c11_atomic_store:
2947   case AtomicExpr::AO__opencl_atomic_store:
2948   case AtomicExpr::AO__atomic_store:
2949   case AtomicExpr::AO__atomic_store_n:
2950     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2951            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2952            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2953 
2954   default:
2955     return true;
2956   }
2957 }
2958 
2959 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2960                                          AtomicExpr::AtomicOp Op) {
2961   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2962   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2963 
2964   // All the non-OpenCL operations take one of the following forms.
2965   // The OpenCL operations take the __c11 forms with one extra argument for
2966   // synchronization scope.
2967   enum {
2968     // C    __c11_atomic_init(A *, C)
2969     Init,
2970 
2971     // C    __c11_atomic_load(A *, int)
2972     Load,
2973 
2974     // void __atomic_load(A *, CP, int)
2975     LoadCopy,
2976 
2977     // void __atomic_store(A *, CP, int)
2978     Copy,
2979 
2980     // C    __c11_atomic_add(A *, M, int)
2981     Arithmetic,
2982 
2983     // C    __atomic_exchange_n(A *, CP, int)
2984     Xchg,
2985 
2986     // void __atomic_exchange(A *, C *, CP, int)
2987     GNUXchg,
2988 
2989     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2990     C11CmpXchg,
2991 
2992     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2993     GNUCmpXchg
2994   } Form = Init;
2995 
2996   const unsigned NumForm = GNUCmpXchg + 1;
2997   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2998   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
2999   // where:
3000   //   C is an appropriate type,
3001   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
3002   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
3003   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
3004   //   the int parameters are for orderings.
3005 
3006   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
3007       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
3008       "need to update code for modified forms");
3009   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
3010                     AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
3011                         AtomicExpr::AO__atomic_load,
3012                 "need to update code for modified C11 atomics");
3013   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
3014                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
3015   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
3016                Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
3017                IsOpenCL;
3018   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
3019              Op == AtomicExpr::AO__atomic_store_n ||
3020              Op == AtomicExpr::AO__atomic_exchange_n ||
3021              Op == AtomicExpr::AO__atomic_compare_exchange_n;
3022   bool IsAddSub = false;
3023 
3024   switch (Op) {
3025   case AtomicExpr::AO__c11_atomic_init:
3026   case AtomicExpr::AO__opencl_atomic_init:
3027     Form = Init;
3028     break;
3029 
3030   case AtomicExpr::AO__c11_atomic_load:
3031   case AtomicExpr::AO__opencl_atomic_load:
3032   case AtomicExpr::AO__atomic_load_n:
3033     Form = Load;
3034     break;
3035 
3036   case AtomicExpr::AO__atomic_load:
3037     Form = LoadCopy;
3038     break;
3039 
3040   case AtomicExpr::AO__c11_atomic_store:
3041   case AtomicExpr::AO__opencl_atomic_store:
3042   case AtomicExpr::AO__atomic_store:
3043   case AtomicExpr::AO__atomic_store_n:
3044     Form = Copy;
3045     break;
3046 
3047   case AtomicExpr::AO__c11_atomic_fetch_add:
3048   case AtomicExpr::AO__c11_atomic_fetch_sub:
3049   case AtomicExpr::AO__opencl_atomic_fetch_add:
3050   case AtomicExpr::AO__opencl_atomic_fetch_sub:
3051   case AtomicExpr::AO__opencl_atomic_fetch_min:
3052   case AtomicExpr::AO__opencl_atomic_fetch_max:
3053   case AtomicExpr::AO__atomic_fetch_add:
3054   case AtomicExpr::AO__atomic_fetch_sub:
3055   case AtomicExpr::AO__atomic_add_fetch:
3056   case AtomicExpr::AO__atomic_sub_fetch:
3057     IsAddSub = true;
3058     LLVM_FALLTHROUGH;
3059   case AtomicExpr::AO__c11_atomic_fetch_and:
3060   case AtomicExpr::AO__c11_atomic_fetch_or:
3061   case AtomicExpr::AO__c11_atomic_fetch_xor:
3062   case AtomicExpr::AO__opencl_atomic_fetch_and:
3063   case AtomicExpr::AO__opencl_atomic_fetch_or:
3064   case AtomicExpr::AO__opencl_atomic_fetch_xor:
3065   case AtomicExpr::AO__atomic_fetch_and:
3066   case AtomicExpr::AO__atomic_fetch_or:
3067   case AtomicExpr::AO__atomic_fetch_xor:
3068   case AtomicExpr::AO__atomic_fetch_nand:
3069   case AtomicExpr::AO__atomic_and_fetch:
3070   case AtomicExpr::AO__atomic_or_fetch:
3071   case AtomicExpr::AO__atomic_xor_fetch:
3072   case AtomicExpr::AO__atomic_nand_fetch:
3073     Form = Arithmetic;
3074     break;
3075 
3076   case AtomicExpr::AO__c11_atomic_exchange:
3077   case AtomicExpr::AO__opencl_atomic_exchange:
3078   case AtomicExpr::AO__atomic_exchange_n:
3079     Form = Xchg;
3080     break;
3081 
3082   case AtomicExpr::AO__atomic_exchange:
3083     Form = GNUXchg;
3084     break;
3085 
3086   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3087   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
3088   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
3089   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
3090     Form = C11CmpXchg;
3091     break;
3092 
3093   case AtomicExpr::AO__atomic_compare_exchange:
3094   case AtomicExpr::AO__atomic_compare_exchange_n:
3095     Form = GNUCmpXchg;
3096     break;
3097   }
3098 
3099   unsigned AdjustedNumArgs = NumArgs[Form];
3100   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
3101     ++AdjustedNumArgs;
3102   // Check we have the right number of arguments.
3103   if (TheCall->getNumArgs() < AdjustedNumArgs) {
3104     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3105       << 0 << AdjustedNumArgs << TheCall->getNumArgs()
3106       << TheCall->getCallee()->getSourceRange();
3107     return ExprError();
3108   } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
3109     Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(),
3110          diag::err_typecheck_call_too_many_args)
3111       << 0 << AdjustedNumArgs << TheCall->getNumArgs()
3112       << TheCall->getCallee()->getSourceRange();
3113     return ExprError();
3114   }
3115 
3116   // Inspect the first argument of the atomic operation.
3117   Expr *Ptr = TheCall->getArg(0);
3118   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
3119   if (ConvertedPtr.isInvalid())
3120     return ExprError();
3121 
3122   Ptr = ConvertedPtr.get();
3123   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
3124   if (!pointerType) {
3125     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3126       << Ptr->getType() << Ptr->getSourceRange();
3127     return ExprError();
3128   }
3129 
3130   // For a __c11 builtin, this should be a pointer to an _Atomic type.
3131   QualType AtomTy = pointerType->getPointeeType(); // 'A'
3132   QualType ValType = AtomTy; // 'C'
3133   if (IsC11) {
3134     if (!AtomTy->isAtomicType()) {
3135       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
3136         << Ptr->getType() << Ptr->getSourceRange();
3137       return ExprError();
3138     }
3139     if (AtomTy.isConstQualified() ||
3140         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
3141       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
3142           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
3143           << Ptr->getSourceRange();
3144       return ExprError();
3145     }
3146     ValType = AtomTy->getAs<AtomicType>()->getValueType();
3147   } else if (Form != Load && Form != LoadCopy) {
3148     if (ValType.isConstQualified()) {
3149       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
3150         << Ptr->getType() << Ptr->getSourceRange();
3151       return ExprError();
3152     }
3153   }
3154 
3155   // For an arithmetic operation, the implied arithmetic must be well-formed.
3156   if (Form == Arithmetic) {
3157     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
3158     if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
3159       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3160         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3161       return ExprError();
3162     }
3163     if (!IsAddSub && !ValType->isIntegerType()) {
3164       Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
3165         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3166       return ExprError();
3167     }
3168     if (IsC11 && ValType->isPointerType() &&
3169         RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
3170                             diag::err_incomplete_type)) {
3171       return ExprError();
3172     }
3173   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
3174     // For __atomic_*_n operations, the value type must be a scalar integral or
3175     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
3176     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3177       << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3178     return ExprError();
3179   }
3180 
3181   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
3182       !AtomTy->isScalarType()) {
3183     // For GNU atomics, require a trivially-copyable type. This is not part of
3184     // the GNU atomics specification, but we enforce it for sanity.
3185     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
3186       << Ptr->getType() << Ptr->getSourceRange();
3187     return ExprError();
3188   }
3189 
3190   switch (ValType.getObjCLifetime()) {
3191   case Qualifiers::OCL_None:
3192   case Qualifiers::OCL_ExplicitNone:
3193     // okay
3194     break;
3195 
3196   case Qualifiers::OCL_Weak:
3197   case Qualifiers::OCL_Strong:
3198   case Qualifiers::OCL_Autoreleasing:
3199     // FIXME: Can this happen? By this point, ValType should be known
3200     // to be trivially copyable.
3201     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3202       << ValType << Ptr->getSourceRange();
3203     return ExprError();
3204   }
3205 
3206   // atomic_fetch_or takes a pointer to a volatile 'A'.  We shouldn't let the
3207   // volatile-ness of the pointee-type inject itself into the result or the
3208   // other operands. Similarly atomic_load can take a pointer to a const 'A'.
3209   ValType.removeLocalVolatile();
3210   ValType.removeLocalConst();
3211   QualType ResultType = ValType;
3212   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
3213       Form == Init)
3214     ResultType = Context.VoidTy;
3215   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
3216     ResultType = Context.BoolTy;
3217 
3218   // The type of a parameter passed 'by value'. In the GNU atomics, such
3219   // arguments are actually passed as pointers.
3220   QualType ByValType = ValType; // 'CP'
3221   if (!IsC11 && !IsN)
3222     ByValType = Ptr->getType();
3223 
3224   // The first argument --- the pointer --- has a fixed type; we
3225   // deduce the types of the rest of the arguments accordingly.  Walk
3226   // the remaining arguments, converting them to the deduced value type.
3227   for (unsigned i = 1; i != TheCall->getNumArgs(); ++i) {
3228     QualType Ty;
3229     if (i < NumVals[Form] + 1) {
3230       switch (i) {
3231       case 1:
3232         // The second argument is the non-atomic operand. For arithmetic, this
3233         // is always passed by value, and for a compare_exchange it is always
3234         // passed by address. For the rest, GNU uses by-address and C11 uses
3235         // by-value.
3236         assert(Form != Load);
3237         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
3238           Ty = ValType;
3239         else if (Form == Copy || Form == Xchg)
3240           Ty = ByValType;
3241         else if (Form == Arithmetic)
3242           Ty = Context.getPointerDiffType();
3243         else {
3244           Expr *ValArg = TheCall->getArg(i);
3245           // Treat this argument as _Nonnull as we want to show a warning if
3246           // NULL is passed into it.
3247           CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
3248           LangAS AS = LangAS::Default;
3249           // Keep address space of non-atomic pointer type.
3250           if (const PointerType *PtrTy =
3251                   ValArg->getType()->getAs<PointerType>()) {
3252             AS = PtrTy->getPointeeType().getAddressSpace();
3253           }
3254           Ty = Context.getPointerType(
3255               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
3256         }
3257         break;
3258       case 2:
3259         // The third argument to compare_exchange / GNU exchange is a
3260         // (pointer to a) desired value.
3261         Ty = ByValType;
3262         break;
3263       case 3:
3264         // The fourth argument to GNU compare_exchange is a 'weak' flag.
3265         Ty = Context.BoolTy;
3266         break;
3267       }
3268     } else {
3269       // The order(s) and scope are always converted to int.
3270       Ty = Context.IntTy;
3271     }
3272 
3273     InitializedEntity Entity =
3274         InitializedEntity::InitializeParameter(Context, Ty, false);
3275     ExprResult Arg = TheCall->getArg(i);
3276     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3277     if (Arg.isInvalid())
3278       return true;
3279     TheCall->setArg(i, Arg.get());
3280   }
3281 
3282   // Permute the arguments into a 'consistent' order.
3283   SmallVector<Expr*, 5> SubExprs;
3284   SubExprs.push_back(Ptr);
3285   switch (Form) {
3286   case Init:
3287     // Note, AtomicExpr::getVal1() has a special case for this atomic.
3288     SubExprs.push_back(TheCall->getArg(1)); // Val1
3289     break;
3290   case Load:
3291     SubExprs.push_back(TheCall->getArg(1)); // Order
3292     break;
3293   case LoadCopy:
3294   case Copy:
3295   case Arithmetic:
3296   case Xchg:
3297     SubExprs.push_back(TheCall->getArg(2)); // Order
3298     SubExprs.push_back(TheCall->getArg(1)); // Val1
3299     break;
3300   case GNUXchg:
3301     // Note, AtomicExpr::getVal2() has a special case for this atomic.
3302     SubExprs.push_back(TheCall->getArg(3)); // Order
3303     SubExprs.push_back(TheCall->getArg(1)); // Val1
3304     SubExprs.push_back(TheCall->getArg(2)); // Val2
3305     break;
3306   case C11CmpXchg:
3307     SubExprs.push_back(TheCall->getArg(3)); // Order
3308     SubExprs.push_back(TheCall->getArg(1)); // Val1
3309     SubExprs.push_back(TheCall->getArg(4)); // OrderFail
3310     SubExprs.push_back(TheCall->getArg(2)); // Val2
3311     break;
3312   case GNUCmpXchg:
3313     SubExprs.push_back(TheCall->getArg(4)); // Order
3314     SubExprs.push_back(TheCall->getArg(1)); // Val1
3315     SubExprs.push_back(TheCall->getArg(5)); // OrderFail
3316     SubExprs.push_back(TheCall->getArg(2)); // Val2
3317     SubExprs.push_back(TheCall->getArg(3)); // Weak
3318     break;
3319   }
3320 
3321   if (SubExprs.size() >= 2 && Form != Init) {
3322     llvm::APSInt Result(32);
3323     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
3324         !isValidOrderingForOp(Result.getSExtValue(), Op))
3325       Diag(SubExprs[1]->getLocStart(),
3326            diag::warn_atomic_op_has_invalid_memory_order)
3327           << SubExprs[1]->getSourceRange();
3328   }
3329 
3330   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
3331     auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
3332     llvm::APSInt Result(32);
3333     if (Scope->isIntegerConstantExpr(Result, Context) &&
3334         !ScopeModel->isValid(Result.getZExtValue())) {
3335       Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope)
3336           << Scope->getSourceRange();
3337     }
3338     SubExprs.push_back(Scope);
3339   }
3340 
3341   AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
3342                                             SubExprs, ResultType, Op,
3343                                             TheCall->getRParenLoc());
3344 
3345   if ((Op == AtomicExpr::AO__c11_atomic_load ||
3346        Op == AtomicExpr::AO__c11_atomic_store ||
3347        Op == AtomicExpr::AO__opencl_atomic_load ||
3348        Op == AtomicExpr::AO__opencl_atomic_store ) &&
3349       Context.AtomicUsesUnsupportedLibcall(AE))
3350     Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib)
3351         << ((Op == AtomicExpr::AO__c11_atomic_load ||
3352             Op == AtomicExpr::AO__opencl_atomic_load)
3353                 ? 0 : 1);
3354 
3355   return AE;
3356 }
3357 
3358 /// checkBuiltinArgument - Given a call to a builtin function, perform
3359 /// normal type-checking on the given argument, updating the call in
3360 /// place.  This is useful when a builtin function requires custom
3361 /// type-checking for some of its arguments but not necessarily all of
3362 /// them.
3363 ///
3364 /// Returns true on error.
3365 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
3366   FunctionDecl *Fn = E->getDirectCallee();
3367   assert(Fn && "builtin call without direct callee!");
3368 
3369   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
3370   InitializedEntity Entity =
3371     InitializedEntity::InitializeParameter(S.Context, Param);
3372 
3373   ExprResult Arg = E->getArg(0);
3374   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3375   if (Arg.isInvalid())
3376     return true;
3377 
3378   E->setArg(ArgIndex, Arg.get());
3379   return false;
3380 }
3381 
3382 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
3383 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
3384 /// type of its first argument.  The main ActOnCallExpr routines have already
3385 /// promoted the types of arguments because all of these calls are prototyped as
3386 /// void(...).
3387 ///
3388 /// This function goes through and does final semantic checking for these
3389 /// builtins,
3390 ExprResult
3391 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
3392   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3393   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3394   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3395 
3396   // Ensure that we have at least one argument to do type inference from.
3397   if (TheCall->getNumArgs() < 1) {
3398     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3399       << 0 << 1 << TheCall->getNumArgs()
3400       << TheCall->getCallee()->getSourceRange();
3401     return ExprError();
3402   }
3403 
3404   // Inspect the first argument of the atomic builtin.  This should always be
3405   // a pointer type, whose element is an integral scalar or pointer type.
3406   // Because it is a pointer type, we don't have to worry about any implicit
3407   // casts here.
3408   // FIXME: We don't allow floating point scalars as input.
3409   Expr *FirstArg = TheCall->getArg(0);
3410   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3411   if (FirstArgResult.isInvalid())
3412     return ExprError();
3413   FirstArg = FirstArgResult.get();
3414   TheCall->setArg(0, FirstArg);
3415 
3416   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3417   if (!pointerType) {
3418     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3419       << FirstArg->getType() << FirstArg->getSourceRange();
3420     return ExprError();
3421   }
3422 
3423   QualType ValType = pointerType->getPointeeType();
3424   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3425       !ValType->isBlockPointerType()) {
3426     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3427       << FirstArg->getType() << FirstArg->getSourceRange();
3428     return ExprError();
3429   }
3430 
3431   switch (ValType.getObjCLifetime()) {
3432   case Qualifiers::OCL_None:
3433   case Qualifiers::OCL_ExplicitNone:
3434     // okay
3435     break;
3436 
3437   case Qualifiers::OCL_Weak:
3438   case Qualifiers::OCL_Strong:
3439   case Qualifiers::OCL_Autoreleasing:
3440     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3441       << ValType << FirstArg->getSourceRange();
3442     return ExprError();
3443   }
3444 
3445   // Strip any qualifiers off ValType.
3446   ValType = ValType.getUnqualifiedType();
3447 
3448   // The majority of builtins return a value, but a few have special return
3449   // types, so allow them to override appropriately below.
3450   QualType ResultType = ValType;
3451 
3452   // We need to figure out which concrete builtin this maps onto.  For example,
3453   // __sync_fetch_and_add with a 2 byte object turns into
3454   // __sync_fetch_and_add_2.
3455 #define BUILTIN_ROW(x) \
3456   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3457     Builtin::BI##x##_8, Builtin::BI##x##_16 }
3458 
3459   static const unsigned BuiltinIndices[][5] = {
3460     BUILTIN_ROW(__sync_fetch_and_add),
3461     BUILTIN_ROW(__sync_fetch_and_sub),
3462     BUILTIN_ROW(__sync_fetch_and_or),
3463     BUILTIN_ROW(__sync_fetch_and_and),
3464     BUILTIN_ROW(__sync_fetch_and_xor),
3465     BUILTIN_ROW(__sync_fetch_and_nand),
3466 
3467     BUILTIN_ROW(__sync_add_and_fetch),
3468     BUILTIN_ROW(__sync_sub_and_fetch),
3469     BUILTIN_ROW(__sync_and_and_fetch),
3470     BUILTIN_ROW(__sync_or_and_fetch),
3471     BUILTIN_ROW(__sync_xor_and_fetch),
3472     BUILTIN_ROW(__sync_nand_and_fetch),
3473 
3474     BUILTIN_ROW(__sync_val_compare_and_swap),
3475     BUILTIN_ROW(__sync_bool_compare_and_swap),
3476     BUILTIN_ROW(__sync_lock_test_and_set),
3477     BUILTIN_ROW(__sync_lock_release),
3478     BUILTIN_ROW(__sync_swap)
3479   };
3480 #undef BUILTIN_ROW
3481 
3482   // Determine the index of the size.
3483   unsigned SizeIndex;
3484   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
3485   case 1: SizeIndex = 0; break;
3486   case 2: SizeIndex = 1; break;
3487   case 4: SizeIndex = 2; break;
3488   case 8: SizeIndex = 3; break;
3489   case 16: SizeIndex = 4; break;
3490   default:
3491     Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3492       << FirstArg->getType() << FirstArg->getSourceRange();
3493     return ExprError();
3494   }
3495 
3496   // Each of these builtins has one pointer argument, followed by some number of
3497   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3498   // that we ignore.  Find out which row of BuiltinIndices to read from as well
3499   // as the number of fixed args.
3500   unsigned BuiltinID = FDecl->getBuiltinID();
3501   unsigned BuiltinIndex, NumFixed = 1;
3502   bool WarnAboutSemanticsChange = false;
3503   switch (BuiltinID) {
3504   default: llvm_unreachable("Unknown overloaded atomic builtin!");
3505   case Builtin::BI__sync_fetch_and_add:
3506   case Builtin::BI__sync_fetch_and_add_1:
3507   case Builtin::BI__sync_fetch_and_add_2:
3508   case Builtin::BI__sync_fetch_and_add_4:
3509   case Builtin::BI__sync_fetch_and_add_8:
3510   case Builtin::BI__sync_fetch_and_add_16:
3511     BuiltinIndex = 0;
3512     break;
3513 
3514   case Builtin::BI__sync_fetch_and_sub:
3515   case Builtin::BI__sync_fetch_and_sub_1:
3516   case Builtin::BI__sync_fetch_and_sub_2:
3517   case Builtin::BI__sync_fetch_and_sub_4:
3518   case Builtin::BI__sync_fetch_and_sub_8:
3519   case Builtin::BI__sync_fetch_and_sub_16:
3520     BuiltinIndex = 1;
3521     break;
3522 
3523   case Builtin::BI__sync_fetch_and_or:
3524   case Builtin::BI__sync_fetch_and_or_1:
3525   case Builtin::BI__sync_fetch_and_or_2:
3526   case Builtin::BI__sync_fetch_and_or_4:
3527   case Builtin::BI__sync_fetch_and_or_8:
3528   case Builtin::BI__sync_fetch_and_or_16:
3529     BuiltinIndex = 2;
3530     break;
3531 
3532   case Builtin::BI__sync_fetch_and_and:
3533   case Builtin::BI__sync_fetch_and_and_1:
3534   case Builtin::BI__sync_fetch_and_and_2:
3535   case Builtin::BI__sync_fetch_and_and_4:
3536   case Builtin::BI__sync_fetch_and_and_8:
3537   case Builtin::BI__sync_fetch_and_and_16:
3538     BuiltinIndex = 3;
3539     break;
3540 
3541   case Builtin::BI__sync_fetch_and_xor:
3542   case Builtin::BI__sync_fetch_and_xor_1:
3543   case Builtin::BI__sync_fetch_and_xor_2:
3544   case Builtin::BI__sync_fetch_and_xor_4:
3545   case Builtin::BI__sync_fetch_and_xor_8:
3546   case Builtin::BI__sync_fetch_and_xor_16:
3547     BuiltinIndex = 4;
3548     break;
3549 
3550   case Builtin::BI__sync_fetch_and_nand:
3551   case Builtin::BI__sync_fetch_and_nand_1:
3552   case Builtin::BI__sync_fetch_and_nand_2:
3553   case Builtin::BI__sync_fetch_and_nand_4:
3554   case Builtin::BI__sync_fetch_and_nand_8:
3555   case Builtin::BI__sync_fetch_and_nand_16:
3556     BuiltinIndex = 5;
3557     WarnAboutSemanticsChange = true;
3558     break;
3559 
3560   case Builtin::BI__sync_add_and_fetch:
3561   case Builtin::BI__sync_add_and_fetch_1:
3562   case Builtin::BI__sync_add_and_fetch_2:
3563   case Builtin::BI__sync_add_and_fetch_4:
3564   case Builtin::BI__sync_add_and_fetch_8:
3565   case Builtin::BI__sync_add_and_fetch_16:
3566     BuiltinIndex = 6;
3567     break;
3568 
3569   case Builtin::BI__sync_sub_and_fetch:
3570   case Builtin::BI__sync_sub_and_fetch_1:
3571   case Builtin::BI__sync_sub_and_fetch_2:
3572   case Builtin::BI__sync_sub_and_fetch_4:
3573   case Builtin::BI__sync_sub_and_fetch_8:
3574   case Builtin::BI__sync_sub_and_fetch_16:
3575     BuiltinIndex = 7;
3576     break;
3577 
3578   case Builtin::BI__sync_and_and_fetch:
3579   case Builtin::BI__sync_and_and_fetch_1:
3580   case Builtin::BI__sync_and_and_fetch_2:
3581   case Builtin::BI__sync_and_and_fetch_4:
3582   case Builtin::BI__sync_and_and_fetch_8:
3583   case Builtin::BI__sync_and_and_fetch_16:
3584     BuiltinIndex = 8;
3585     break;
3586 
3587   case Builtin::BI__sync_or_and_fetch:
3588   case Builtin::BI__sync_or_and_fetch_1:
3589   case Builtin::BI__sync_or_and_fetch_2:
3590   case Builtin::BI__sync_or_and_fetch_4:
3591   case Builtin::BI__sync_or_and_fetch_8:
3592   case Builtin::BI__sync_or_and_fetch_16:
3593     BuiltinIndex = 9;
3594     break;
3595 
3596   case Builtin::BI__sync_xor_and_fetch:
3597   case Builtin::BI__sync_xor_and_fetch_1:
3598   case Builtin::BI__sync_xor_and_fetch_2:
3599   case Builtin::BI__sync_xor_and_fetch_4:
3600   case Builtin::BI__sync_xor_and_fetch_8:
3601   case Builtin::BI__sync_xor_and_fetch_16:
3602     BuiltinIndex = 10;
3603     break;
3604 
3605   case Builtin::BI__sync_nand_and_fetch:
3606   case Builtin::BI__sync_nand_and_fetch_1:
3607   case Builtin::BI__sync_nand_and_fetch_2:
3608   case Builtin::BI__sync_nand_and_fetch_4:
3609   case Builtin::BI__sync_nand_and_fetch_8:
3610   case Builtin::BI__sync_nand_and_fetch_16:
3611     BuiltinIndex = 11;
3612     WarnAboutSemanticsChange = true;
3613     break;
3614 
3615   case Builtin::BI__sync_val_compare_and_swap:
3616   case Builtin::BI__sync_val_compare_and_swap_1:
3617   case Builtin::BI__sync_val_compare_and_swap_2:
3618   case Builtin::BI__sync_val_compare_and_swap_4:
3619   case Builtin::BI__sync_val_compare_and_swap_8:
3620   case Builtin::BI__sync_val_compare_and_swap_16:
3621     BuiltinIndex = 12;
3622     NumFixed = 2;
3623     break;
3624 
3625   case Builtin::BI__sync_bool_compare_and_swap:
3626   case Builtin::BI__sync_bool_compare_and_swap_1:
3627   case Builtin::BI__sync_bool_compare_and_swap_2:
3628   case Builtin::BI__sync_bool_compare_and_swap_4:
3629   case Builtin::BI__sync_bool_compare_and_swap_8:
3630   case Builtin::BI__sync_bool_compare_and_swap_16:
3631     BuiltinIndex = 13;
3632     NumFixed = 2;
3633     ResultType = Context.BoolTy;
3634     break;
3635 
3636   case Builtin::BI__sync_lock_test_and_set:
3637   case Builtin::BI__sync_lock_test_and_set_1:
3638   case Builtin::BI__sync_lock_test_and_set_2:
3639   case Builtin::BI__sync_lock_test_and_set_4:
3640   case Builtin::BI__sync_lock_test_and_set_8:
3641   case Builtin::BI__sync_lock_test_and_set_16:
3642     BuiltinIndex = 14;
3643     break;
3644 
3645   case Builtin::BI__sync_lock_release:
3646   case Builtin::BI__sync_lock_release_1:
3647   case Builtin::BI__sync_lock_release_2:
3648   case Builtin::BI__sync_lock_release_4:
3649   case Builtin::BI__sync_lock_release_8:
3650   case Builtin::BI__sync_lock_release_16:
3651     BuiltinIndex = 15;
3652     NumFixed = 0;
3653     ResultType = Context.VoidTy;
3654     break;
3655 
3656   case Builtin::BI__sync_swap:
3657   case Builtin::BI__sync_swap_1:
3658   case Builtin::BI__sync_swap_2:
3659   case Builtin::BI__sync_swap_4:
3660   case Builtin::BI__sync_swap_8:
3661   case Builtin::BI__sync_swap_16:
3662     BuiltinIndex = 16;
3663     break;
3664   }
3665 
3666   // Now that we know how many fixed arguments we expect, first check that we
3667   // have at least that many.
3668   if (TheCall->getNumArgs() < 1+NumFixed) {
3669     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3670       << 0 << 1+NumFixed << TheCall->getNumArgs()
3671       << TheCall->getCallee()->getSourceRange();
3672     return ExprError();
3673   }
3674 
3675   if (WarnAboutSemanticsChange) {
3676     Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3677       << TheCall->getCallee()->getSourceRange();
3678   }
3679 
3680   // Get the decl for the concrete builtin from this, we can tell what the
3681   // concrete integer type we should convert to is.
3682   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
3683   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
3684   FunctionDecl *NewBuiltinDecl;
3685   if (NewBuiltinID == BuiltinID)
3686     NewBuiltinDecl = FDecl;
3687   else {
3688     // Perform builtin lookup to avoid redeclaring it.
3689     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3690     LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3691     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3692     assert(Res.getFoundDecl());
3693     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
3694     if (!NewBuiltinDecl)
3695       return ExprError();
3696   }
3697 
3698   // The first argument --- the pointer --- has a fixed type; we
3699   // deduce the types of the rest of the arguments accordingly.  Walk
3700   // the remaining arguments, converting them to the deduced value type.
3701   for (unsigned i = 0; i != NumFixed; ++i) {
3702     ExprResult Arg = TheCall->getArg(i+1);
3703 
3704     // GCC does an implicit conversion to the pointer or integer ValType.  This
3705     // can fail in some cases (1i -> int**), check for this error case now.
3706     // Initialize the argument.
3707     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3708                                                    ValType, /*consume*/ false);
3709     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3710     if (Arg.isInvalid())
3711       return ExprError();
3712 
3713     // Okay, we have something that *can* be converted to the right type.  Check
3714     // to see if there is a potentially weird extension going on here.  This can
3715     // happen when you do an atomic operation on something like an char* and
3716     // pass in 42.  The 42 gets converted to char.  This is even more strange
3717     // for things like 45.123 -> char, etc.
3718     // FIXME: Do this check.
3719     TheCall->setArg(i+1, Arg.get());
3720   }
3721 
3722   ASTContext& Context = this->getASTContext();
3723 
3724   // Create a new DeclRefExpr to refer to the new decl.
3725   DeclRefExpr* NewDRE = DeclRefExpr::Create(
3726       Context,
3727       DRE->getQualifierLoc(),
3728       SourceLocation(),
3729       NewBuiltinDecl,
3730       /*enclosing*/ false,
3731       DRE->getLocation(),
3732       Context.BuiltinFnTy,
3733       DRE->getValueKind());
3734 
3735   // Set the callee in the CallExpr.
3736   // FIXME: This loses syntactic information.
3737   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3738   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3739                                               CK_BuiltinFnToFnPtr);
3740   TheCall->setCallee(PromotedCall.get());
3741 
3742   // Change the result type of the call to match the original value type. This
3743   // is arbitrary, but the codegen for these builtins ins design to handle it
3744   // gracefully.
3745   TheCall->setType(ResultType);
3746 
3747   return TheCallResult;
3748 }
3749 
3750 /// SemaBuiltinNontemporalOverloaded - We have a call to
3751 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3752 /// overloaded function based on the pointer type of its last argument.
3753 ///
3754 /// This function goes through and does final semantic checking for these
3755 /// builtins.
3756 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3757   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3758   DeclRefExpr *DRE =
3759       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3760   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3761   unsigned BuiltinID = FDecl->getBuiltinID();
3762   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3763           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3764          "Unexpected nontemporal load/store builtin!");
3765   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3766   unsigned numArgs = isStore ? 2 : 1;
3767 
3768   // Ensure that we have the proper number of arguments.
3769   if (checkArgCount(*this, TheCall, numArgs))
3770     return ExprError();
3771 
3772   // Inspect the last argument of the nontemporal builtin.  This should always
3773   // be a pointer type, from which we imply the type of the memory access.
3774   // Because it is a pointer type, we don't have to worry about any implicit
3775   // casts here.
3776   Expr *PointerArg = TheCall->getArg(numArgs - 1);
3777   ExprResult PointerArgResult =
3778       DefaultFunctionArrayLvalueConversion(PointerArg);
3779 
3780   if (PointerArgResult.isInvalid())
3781     return ExprError();
3782   PointerArg = PointerArgResult.get();
3783   TheCall->setArg(numArgs - 1, PointerArg);
3784 
3785   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3786   if (!pointerType) {
3787     Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3788         << PointerArg->getType() << PointerArg->getSourceRange();
3789     return ExprError();
3790   }
3791 
3792   QualType ValType = pointerType->getPointeeType();
3793 
3794   // Strip any qualifiers off ValType.
3795   ValType = ValType.getUnqualifiedType();
3796   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3797       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3798       !ValType->isVectorType()) {
3799     Diag(DRE->getLocStart(),
3800          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3801         << PointerArg->getType() << PointerArg->getSourceRange();
3802     return ExprError();
3803   }
3804 
3805   if (!isStore) {
3806     TheCall->setType(ValType);
3807     return TheCallResult;
3808   }
3809 
3810   ExprResult ValArg = TheCall->getArg(0);
3811   InitializedEntity Entity = InitializedEntity::InitializeParameter(
3812       Context, ValType, /*consume*/ false);
3813   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3814   if (ValArg.isInvalid())
3815     return ExprError();
3816 
3817   TheCall->setArg(0, ValArg.get());
3818   TheCall->setType(Context.VoidTy);
3819   return TheCallResult;
3820 }
3821 
3822 /// CheckObjCString - Checks that the argument to the builtin
3823 /// CFString constructor is correct
3824 /// Note: It might also make sense to do the UTF-16 conversion here (would
3825 /// simplify the backend).
3826 bool Sema::CheckObjCString(Expr *Arg) {
3827   Arg = Arg->IgnoreParenCasts();
3828   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3829 
3830   if (!Literal || !Literal->isAscii()) {
3831     Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3832       << Arg->getSourceRange();
3833     return true;
3834   }
3835 
3836   if (Literal->containsNonAsciiOrNull()) {
3837     StringRef String = Literal->getString();
3838     unsigned NumBytes = String.size();
3839     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3840     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3841     llvm::UTF16 *ToPtr = &ToBuf[0];
3842 
3843     llvm::ConversionResult Result =
3844         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3845                                  ToPtr + NumBytes, llvm::strictConversion);
3846     // Check for conversion failure.
3847     if (Result != llvm::conversionOK)
3848       Diag(Arg->getLocStart(),
3849            diag::warn_cfstring_truncated) << Arg->getSourceRange();
3850   }
3851   return false;
3852 }
3853 
3854 /// CheckObjCString - Checks that the format string argument to the os_log()
3855 /// and os_trace() functions is correct, and converts it to const char *.
3856 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3857   Arg = Arg->IgnoreParenCasts();
3858   auto *Literal = dyn_cast<StringLiteral>(Arg);
3859   if (!Literal) {
3860     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3861       Literal = ObjcLiteral->getString();
3862     }
3863   }
3864 
3865   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3866     return ExprError(
3867         Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3868         << Arg->getSourceRange());
3869   }
3870 
3871   ExprResult Result(Literal);
3872   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3873   InitializedEntity Entity =
3874       InitializedEntity::InitializeParameter(Context, ResultTy, false);
3875   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3876   return Result;
3877 }
3878 
3879 /// Check that the user is calling the appropriate va_start builtin for the
3880 /// target and calling convention.
3881 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
3882   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
3883   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
3884   bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
3885   bool IsWindows = TT.isOSWindows();
3886   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
3887   if (IsX64 || IsAArch64) {
3888     CallingConv CC = CC_C;
3889     if (const FunctionDecl *FD = S.getCurFunctionDecl())
3890       CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3891     if (IsMSVAStart) {
3892       // Don't allow this in System V ABI functions.
3893       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
3894         return S.Diag(Fn->getLocStart(),
3895                       diag::err_ms_va_start_used_in_sysv_function);
3896     } else {
3897       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
3898       // On x64 Windows, don't allow this in System V ABI functions.
3899       // (Yes, that means there's no corresponding way to support variadic
3900       // System V ABI functions on Windows.)
3901       if ((IsWindows && CC == CC_X86_64SysV) ||
3902           (!IsWindows && CC == CC_Win64))
3903         return S.Diag(Fn->getLocStart(),
3904                       diag::err_va_start_used_in_wrong_abi_function)
3905                << !IsWindows;
3906     }
3907     return false;
3908   }
3909 
3910   if (IsMSVAStart)
3911     return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only);
3912   return false;
3913 }
3914 
3915 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
3916                                              ParmVarDecl **LastParam = nullptr) {
3917   // Determine whether the current function, block, or obj-c method is variadic
3918   // and get its parameter list.
3919   bool IsVariadic = false;
3920   ArrayRef<ParmVarDecl *> Params;
3921   DeclContext *Caller = S.CurContext;
3922   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
3923     IsVariadic = Block->isVariadic();
3924     Params = Block->parameters();
3925   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
3926     IsVariadic = FD->isVariadic();
3927     Params = FD->parameters();
3928   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
3929     IsVariadic = MD->isVariadic();
3930     // FIXME: This isn't correct for methods (results in bogus warning).
3931     Params = MD->parameters();
3932   } else if (isa<CapturedDecl>(Caller)) {
3933     // We don't support va_start in a CapturedDecl.
3934     S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
3935     return true;
3936   } else {
3937     // This must be some other declcontext that parses exprs.
3938     S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
3939     return true;
3940   }
3941 
3942   if (!IsVariadic) {
3943     S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
3944     return true;
3945   }
3946 
3947   if (LastParam)
3948     *LastParam = Params.empty() ? nullptr : Params.back();
3949 
3950   return false;
3951 }
3952 
3953 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3954 /// for validity.  Emit an error and return true on failure; return false
3955 /// on success.
3956 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
3957   Expr *Fn = TheCall->getCallee();
3958 
3959   if (checkVAStartABI(*this, BuiltinID, Fn))
3960     return true;
3961 
3962   if (TheCall->getNumArgs() > 2) {
3963     Diag(TheCall->getArg(2)->getLocStart(),
3964          diag::err_typecheck_call_too_many_args)
3965       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3966       << Fn->getSourceRange()
3967       << SourceRange(TheCall->getArg(2)->getLocStart(),
3968                      (*(TheCall->arg_end()-1))->getLocEnd());
3969     return true;
3970   }
3971 
3972   if (TheCall->getNumArgs() < 2) {
3973     return Diag(TheCall->getLocEnd(),
3974       diag::err_typecheck_call_too_few_args_at_least)
3975       << 0 /*function call*/ << 2 << TheCall->getNumArgs();
3976   }
3977 
3978   // Type-check the first argument normally.
3979   if (checkBuiltinArgument(*this, TheCall, 0))
3980     return true;
3981 
3982   // Check that the current function is variadic, and get its last parameter.
3983   ParmVarDecl *LastParam;
3984   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
3985     return true;
3986 
3987   // Verify that the second argument to the builtin is the last argument of the
3988   // current function or method.
3989   bool SecondArgIsLastNamedArgument = false;
3990   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
3991 
3992   // These are valid if SecondArgIsLastNamedArgument is false after the next
3993   // block.
3994   QualType Type;
3995   SourceLocation ParamLoc;
3996   bool IsCRegister = false;
3997 
3998   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3999     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
4000       SecondArgIsLastNamedArgument = PV == LastParam;
4001 
4002       Type = PV->getType();
4003       ParamLoc = PV->getLocation();
4004       IsCRegister =
4005           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
4006     }
4007   }
4008 
4009   if (!SecondArgIsLastNamedArgument)
4010     Diag(TheCall->getArg(1)->getLocStart(),
4011          diag::warn_second_arg_of_va_start_not_last_named_param);
4012   else if (IsCRegister || Type->isReferenceType() ||
4013            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
4014              // Promotable integers are UB, but enumerations need a bit of
4015              // extra checking to see what their promotable type actually is.
4016              if (!Type->isPromotableIntegerType())
4017                return false;
4018              if (!Type->isEnumeralType())
4019                return true;
4020              const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
4021              return !(ED &&
4022                       Context.typesAreCompatible(ED->getPromotionType(), Type));
4023            }()) {
4024     unsigned Reason = 0;
4025     if (Type->isReferenceType())  Reason = 1;
4026     else if (IsCRegister)         Reason = 2;
4027     Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
4028     Diag(ParamLoc, diag::note_parameter_type) << Type;
4029   }
4030 
4031   TheCall->setType(Context.VoidTy);
4032   return false;
4033 }
4034 
4035 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
4036   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
4037   //                 const char *named_addr);
4038 
4039   Expr *Func = Call->getCallee();
4040 
4041   if (Call->getNumArgs() < 3)
4042     return Diag(Call->getLocEnd(),
4043                 diag::err_typecheck_call_too_few_args_at_least)
4044            << 0 /*function call*/ << 3 << Call->getNumArgs();
4045 
4046   // Type-check the first argument normally.
4047   if (checkBuiltinArgument(*this, Call, 0))
4048     return true;
4049 
4050   // Check that the current function is variadic.
4051   if (checkVAStartIsInVariadicFunction(*this, Func))
4052     return true;
4053 
4054   // __va_start on Windows does not validate the parameter qualifiers
4055 
4056   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
4057   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
4058 
4059   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
4060   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
4061 
4062   const QualType &ConstCharPtrTy =
4063       Context.getPointerType(Context.CharTy.withConst());
4064   if (!Arg1Ty->isPointerType() ||
4065       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
4066     Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible)
4067         << Arg1->getType() << ConstCharPtrTy
4068         << 1 /* different class */
4069         << 0 /* qualifier difference */
4070         << 3 /* parameter mismatch */
4071         << 2 << Arg1->getType() << ConstCharPtrTy;
4072 
4073   const QualType SizeTy = Context.getSizeType();
4074   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
4075     Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible)
4076         << Arg2->getType() << SizeTy
4077         << 1 /* different class */
4078         << 0 /* qualifier difference */
4079         << 3 /* parameter mismatch */
4080         << 3 << Arg2->getType() << SizeTy;
4081 
4082   return false;
4083 }
4084 
4085 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
4086 /// friends.  This is declared to take (...), so we have to check everything.
4087 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
4088   if (TheCall->getNumArgs() < 2)
4089     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4090       << 0 << 2 << TheCall->getNumArgs()/*function call*/;
4091   if (TheCall->getNumArgs() > 2)
4092     return Diag(TheCall->getArg(2)->getLocStart(),
4093                 diag::err_typecheck_call_too_many_args)
4094       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4095       << SourceRange(TheCall->getArg(2)->getLocStart(),
4096                      (*(TheCall->arg_end()-1))->getLocEnd());
4097 
4098   ExprResult OrigArg0 = TheCall->getArg(0);
4099   ExprResult OrigArg1 = TheCall->getArg(1);
4100 
4101   // Do standard promotions between the two arguments, returning their common
4102   // type.
4103   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
4104   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
4105     return true;
4106 
4107   // Make sure any conversions are pushed back into the call; this is
4108   // type safe since unordered compare builtins are declared as "_Bool
4109   // foo(...)".
4110   TheCall->setArg(0, OrigArg0.get());
4111   TheCall->setArg(1, OrigArg1.get());
4112 
4113   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
4114     return false;
4115 
4116   // If the common type isn't a real floating type, then the arguments were
4117   // invalid for this operation.
4118   if (Res.isNull() || !Res->isRealFloatingType())
4119     return Diag(OrigArg0.get()->getLocStart(),
4120                 diag::err_typecheck_call_invalid_ordered_compare)
4121       << OrigArg0.get()->getType() << OrigArg1.get()->getType()
4122       << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
4123 
4124   return false;
4125 }
4126 
4127 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
4128 /// __builtin_isnan and friends.  This is declared to take (...), so we have
4129 /// to check everything. We expect the last argument to be a floating point
4130 /// value.
4131 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
4132   if (TheCall->getNumArgs() < NumArgs)
4133     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4134       << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
4135   if (TheCall->getNumArgs() > NumArgs)
4136     return Diag(TheCall->getArg(NumArgs)->getLocStart(),
4137                 diag::err_typecheck_call_too_many_args)
4138       << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
4139       << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
4140                      (*(TheCall->arg_end()-1))->getLocEnd());
4141 
4142   Expr *OrigArg = TheCall->getArg(NumArgs-1);
4143 
4144   if (OrigArg->isTypeDependent())
4145     return false;
4146 
4147   // This operation requires a non-_Complex floating-point number.
4148   if (!OrigArg->getType()->isRealFloatingType())
4149     return Diag(OrigArg->getLocStart(),
4150                 diag::err_typecheck_call_invalid_unary_fp)
4151       << OrigArg->getType() << OrigArg->getSourceRange();
4152 
4153   // If this is an implicit conversion from float -> float or double, remove it.
4154   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
4155     // Only remove standard FloatCasts, leaving other casts inplace
4156     if (Cast->getCastKind() == CK_FloatingCast) {
4157       Expr *CastArg = Cast->getSubExpr();
4158       if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
4159           assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
4160                   Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
4161                "promotion from float to either float or double is the only expected cast here");
4162         Cast->setSubExpr(nullptr);
4163         TheCall->setArg(NumArgs-1, CastArg);
4164       }
4165     }
4166   }
4167 
4168   return false;
4169 }
4170 
4171 // Customized Sema Checking for VSX builtins that have the following signature:
4172 // vector [...] builtinName(vector [...], vector [...], const int);
4173 // Which takes the same type of vectors (any legal vector type) for the first
4174 // two arguments and takes compile time constant for the third argument.
4175 // Example builtins are :
4176 // vector double vec_xxpermdi(vector double, vector double, int);
4177 // vector short vec_xxsldwi(vector short, vector short, int);
4178 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
4179   unsigned ExpectedNumArgs = 3;
4180   if (TheCall->getNumArgs() < ExpectedNumArgs)
4181     return Diag(TheCall->getLocEnd(),
4182                 diag::err_typecheck_call_too_few_args_at_least)
4183            << 0 /*function call*/ <<  ExpectedNumArgs << TheCall->getNumArgs()
4184            << TheCall->getSourceRange();
4185 
4186   if (TheCall->getNumArgs() > ExpectedNumArgs)
4187     return Diag(TheCall->getLocEnd(),
4188                 diag::err_typecheck_call_too_many_args_at_most)
4189            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4190            << TheCall->getSourceRange();
4191 
4192   // Check the third argument is a compile time constant
4193   llvm::APSInt Value;
4194   if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
4195     return Diag(TheCall->getLocStart(),
4196                 diag::err_vsx_builtin_nonconstant_argument)
4197            << 3 /* argument index */ << TheCall->getDirectCallee()
4198            << SourceRange(TheCall->getArg(2)->getLocStart(),
4199                           TheCall->getArg(2)->getLocEnd());
4200 
4201   QualType Arg1Ty = TheCall->getArg(0)->getType();
4202   QualType Arg2Ty = TheCall->getArg(1)->getType();
4203 
4204   // Check the type of argument 1 and argument 2 are vectors.
4205   SourceLocation BuiltinLoc = TheCall->getLocStart();
4206   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
4207       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
4208     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
4209            << TheCall->getDirectCallee()
4210            << SourceRange(TheCall->getArg(0)->getLocStart(),
4211                           TheCall->getArg(1)->getLocEnd());
4212   }
4213 
4214   // Check the first two arguments are the same type.
4215   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
4216     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
4217            << TheCall->getDirectCallee()
4218            << SourceRange(TheCall->getArg(0)->getLocStart(),
4219                           TheCall->getArg(1)->getLocEnd());
4220   }
4221 
4222   // When default clang type checking is turned off and the customized type
4223   // checking is used, the returning type of the function must be explicitly
4224   // set. Otherwise it is _Bool by default.
4225   TheCall->setType(Arg1Ty);
4226 
4227   return false;
4228 }
4229 
4230 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
4231 // This is declared to take (...), so we have to check everything.
4232 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
4233   if (TheCall->getNumArgs() < 2)
4234     return ExprError(Diag(TheCall->getLocEnd(),
4235                           diag::err_typecheck_call_too_few_args_at_least)
4236                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4237                      << TheCall->getSourceRange());
4238 
4239   // Determine which of the following types of shufflevector we're checking:
4240   // 1) unary, vector mask: (lhs, mask)
4241   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
4242   QualType resType = TheCall->getArg(0)->getType();
4243   unsigned numElements = 0;
4244 
4245   if (!TheCall->getArg(0)->isTypeDependent() &&
4246       !TheCall->getArg(1)->isTypeDependent()) {
4247     QualType LHSType = TheCall->getArg(0)->getType();
4248     QualType RHSType = TheCall->getArg(1)->getType();
4249 
4250     if (!LHSType->isVectorType() || !RHSType->isVectorType())
4251       return ExprError(Diag(TheCall->getLocStart(),
4252                             diag::err_vec_builtin_non_vector)
4253                        << TheCall->getDirectCallee()
4254                        << SourceRange(TheCall->getArg(0)->getLocStart(),
4255                                       TheCall->getArg(1)->getLocEnd()));
4256 
4257     numElements = LHSType->getAs<VectorType>()->getNumElements();
4258     unsigned numResElements = TheCall->getNumArgs() - 2;
4259 
4260     // Check to see if we have a call with 2 vector arguments, the unary shuffle
4261     // with mask.  If so, verify that RHS is an integer vector type with the
4262     // same number of elts as lhs.
4263     if (TheCall->getNumArgs() == 2) {
4264       if (!RHSType->hasIntegerRepresentation() ||
4265           RHSType->getAs<VectorType>()->getNumElements() != numElements)
4266         return ExprError(Diag(TheCall->getLocStart(),
4267                               diag::err_vec_builtin_incompatible_vector)
4268                          << TheCall->getDirectCallee()
4269                          << SourceRange(TheCall->getArg(1)->getLocStart(),
4270                                         TheCall->getArg(1)->getLocEnd()));
4271     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
4272       return ExprError(Diag(TheCall->getLocStart(),
4273                             diag::err_vec_builtin_incompatible_vector)
4274                        << TheCall->getDirectCallee()
4275                        << SourceRange(TheCall->getArg(0)->getLocStart(),
4276                                       TheCall->getArg(1)->getLocEnd()));
4277     } else if (numElements != numResElements) {
4278       QualType eltType = LHSType->getAs<VectorType>()->getElementType();
4279       resType = Context.getVectorType(eltType, numResElements,
4280                                       VectorType::GenericVector);
4281     }
4282   }
4283 
4284   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
4285     if (TheCall->getArg(i)->isTypeDependent() ||
4286         TheCall->getArg(i)->isValueDependent())
4287       continue;
4288 
4289     llvm::APSInt Result(32);
4290     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
4291       return ExprError(Diag(TheCall->getLocStart(),
4292                             diag::err_shufflevector_nonconstant_argument)
4293                        << TheCall->getArg(i)->getSourceRange());
4294 
4295     // Allow -1 which will be translated to undef in the IR.
4296     if (Result.isSigned() && Result.isAllOnesValue())
4297       continue;
4298 
4299     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
4300       return ExprError(Diag(TheCall->getLocStart(),
4301                             diag::err_shufflevector_argument_too_large)
4302                        << TheCall->getArg(i)->getSourceRange());
4303   }
4304 
4305   SmallVector<Expr*, 32> exprs;
4306 
4307   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
4308     exprs.push_back(TheCall->getArg(i));
4309     TheCall->setArg(i, nullptr);
4310   }
4311 
4312   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
4313                                          TheCall->getCallee()->getLocStart(),
4314                                          TheCall->getRParenLoc());
4315 }
4316 
4317 /// SemaConvertVectorExpr - Handle __builtin_convertvector
4318 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
4319                                        SourceLocation BuiltinLoc,
4320                                        SourceLocation RParenLoc) {
4321   ExprValueKind VK = VK_RValue;
4322   ExprObjectKind OK = OK_Ordinary;
4323   QualType DstTy = TInfo->getType();
4324   QualType SrcTy = E->getType();
4325 
4326   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
4327     return ExprError(Diag(BuiltinLoc,
4328                           diag::err_convertvector_non_vector)
4329                      << E->getSourceRange());
4330   if (!DstTy->isVectorType() && !DstTy->isDependentType())
4331     return ExprError(Diag(BuiltinLoc,
4332                           diag::err_convertvector_non_vector_type));
4333 
4334   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
4335     unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
4336     unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
4337     if (SrcElts != DstElts)
4338       return ExprError(Diag(BuiltinLoc,
4339                             diag::err_convertvector_incompatible_vector)
4340                        << E->getSourceRange());
4341   }
4342 
4343   return new (Context)
4344       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
4345 }
4346 
4347 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
4348 // This is declared to take (const void*, ...) and can take two
4349 // optional constant int args.
4350 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
4351   unsigned NumArgs = TheCall->getNumArgs();
4352 
4353   if (NumArgs > 3)
4354     return Diag(TheCall->getLocEnd(),
4355              diag::err_typecheck_call_too_many_args_at_most)
4356              << 0 /*function call*/ << 3 << NumArgs
4357              << TheCall->getSourceRange();
4358 
4359   // Argument 0 is checked for us and the remaining arguments must be
4360   // constant integers.
4361   for (unsigned i = 1; i != NumArgs; ++i)
4362     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
4363       return true;
4364 
4365   return false;
4366 }
4367 
4368 /// SemaBuiltinAssume - Handle __assume (MS Extension).
4369 // __assume does not evaluate its arguments, and should warn if its argument
4370 // has side effects.
4371 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
4372   Expr *Arg = TheCall->getArg(0);
4373   if (Arg->isInstantiationDependent()) return false;
4374 
4375   if (Arg->HasSideEffects(Context))
4376     Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
4377       << Arg->getSourceRange()
4378       << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
4379 
4380   return false;
4381 }
4382 
4383 /// Handle __builtin_alloca_with_align. This is declared
4384 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
4385 /// than 8.
4386 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
4387   // The alignment must be a constant integer.
4388   Expr *Arg = TheCall->getArg(1);
4389 
4390   // We can't check the value of a dependent argument.
4391   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4392     if (const auto *UE =
4393             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
4394       if (UE->getKind() == UETT_AlignOf)
4395         Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
4396           << Arg->getSourceRange();
4397 
4398     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
4399 
4400     if (!Result.isPowerOf2())
4401       return Diag(TheCall->getLocStart(),
4402                   diag::err_alignment_not_power_of_two)
4403            << Arg->getSourceRange();
4404 
4405     if (Result < Context.getCharWidth())
4406       return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
4407            << (unsigned)Context.getCharWidth()
4408            << Arg->getSourceRange();
4409 
4410     if (Result > std::numeric_limits<int32_t>::max())
4411       return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
4412            << std::numeric_limits<int32_t>::max()
4413            << Arg->getSourceRange();
4414   }
4415 
4416   return false;
4417 }
4418 
4419 /// Handle __builtin_assume_aligned. This is declared
4420 /// as (const void*, size_t, ...) and can take one optional constant int arg.
4421 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
4422   unsigned NumArgs = TheCall->getNumArgs();
4423 
4424   if (NumArgs > 3)
4425     return Diag(TheCall->getLocEnd(),
4426              diag::err_typecheck_call_too_many_args_at_most)
4427              << 0 /*function call*/ << 3 << NumArgs
4428              << TheCall->getSourceRange();
4429 
4430   // The alignment must be a constant integer.
4431   Expr *Arg = TheCall->getArg(1);
4432 
4433   // We can't check the value of a dependent argument.
4434   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4435     llvm::APSInt Result;
4436     if (SemaBuiltinConstantArg(TheCall, 1, Result))
4437       return true;
4438 
4439     if (!Result.isPowerOf2())
4440       return Diag(TheCall->getLocStart(),
4441                   diag::err_alignment_not_power_of_two)
4442            << Arg->getSourceRange();
4443   }
4444 
4445   if (NumArgs > 2) {
4446     ExprResult Arg(TheCall->getArg(2));
4447     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4448       Context.getSizeType(), false);
4449     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4450     if (Arg.isInvalid()) return true;
4451     TheCall->setArg(2, Arg.get());
4452   }
4453 
4454   return false;
4455 }
4456 
4457 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4458   unsigned BuiltinID =
4459       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4460   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4461 
4462   unsigned NumArgs = TheCall->getNumArgs();
4463   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4464   if (NumArgs < NumRequiredArgs) {
4465     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4466            << 0 /* function call */ << NumRequiredArgs << NumArgs
4467            << TheCall->getSourceRange();
4468   }
4469   if (NumArgs >= NumRequiredArgs + 0x100) {
4470     return Diag(TheCall->getLocEnd(),
4471                 diag::err_typecheck_call_too_many_args_at_most)
4472            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4473            << TheCall->getSourceRange();
4474   }
4475   unsigned i = 0;
4476 
4477   // For formatting call, check buffer arg.
4478   if (!IsSizeCall) {
4479     ExprResult Arg(TheCall->getArg(i));
4480     InitializedEntity Entity = InitializedEntity::InitializeParameter(
4481         Context, Context.VoidPtrTy, false);
4482     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4483     if (Arg.isInvalid())
4484       return true;
4485     TheCall->setArg(i, Arg.get());
4486     i++;
4487   }
4488 
4489   // Check string literal arg.
4490   unsigned FormatIdx = i;
4491   {
4492     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4493     if (Arg.isInvalid())
4494       return true;
4495     TheCall->setArg(i, Arg.get());
4496     i++;
4497   }
4498 
4499   // Make sure variadic args are scalar.
4500   unsigned FirstDataArg = i;
4501   while (i < NumArgs) {
4502     ExprResult Arg = DefaultVariadicArgumentPromotion(
4503         TheCall->getArg(i), VariadicFunction, nullptr);
4504     if (Arg.isInvalid())
4505       return true;
4506     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4507     if (ArgSize.getQuantity() >= 0x100) {
4508       return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4509              << i << (int)ArgSize.getQuantity() << 0xff
4510              << TheCall->getSourceRange();
4511     }
4512     TheCall->setArg(i, Arg.get());
4513     i++;
4514   }
4515 
4516   // Check formatting specifiers. NOTE: We're only doing this for the non-size
4517   // call to avoid duplicate diagnostics.
4518   if (!IsSizeCall) {
4519     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4520     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4521     bool Success = CheckFormatArguments(
4522         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4523         VariadicFunction, TheCall->getLocStart(), SourceRange(),
4524         CheckedVarArgs);
4525     if (!Success)
4526       return true;
4527   }
4528 
4529   if (IsSizeCall) {
4530     TheCall->setType(Context.getSizeType());
4531   } else {
4532     TheCall->setType(Context.VoidPtrTy);
4533   }
4534   return false;
4535 }
4536 
4537 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4538 /// TheCall is a constant expression.
4539 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4540                                   llvm::APSInt &Result) {
4541   Expr *Arg = TheCall->getArg(ArgNum);
4542   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4543   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4544 
4545   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4546 
4547   if (!Arg->isIntegerConstantExpr(Result, Context))
4548     return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
4549                 << FDecl->getDeclName() <<  Arg->getSourceRange();
4550 
4551   return false;
4552 }
4553 
4554 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4555 /// TheCall is a constant expression in the range [Low, High].
4556 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4557                                        int Low, int High) {
4558   llvm::APSInt Result;
4559 
4560   // We can't check the value of a dependent argument.
4561   Expr *Arg = TheCall->getArg(ArgNum);
4562   if (Arg->isTypeDependent() || Arg->isValueDependent())
4563     return false;
4564 
4565   // Check constant-ness first.
4566   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4567     return true;
4568 
4569   if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
4570     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
4571       << Low << High << Arg->getSourceRange();
4572 
4573   return false;
4574 }
4575 
4576 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4577 /// TheCall is a constant expression is a multiple of Num..
4578 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4579                                           unsigned Num) {
4580   llvm::APSInt Result;
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 constant-ness first.
4588   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4589     return true;
4590 
4591   if (Result.getSExtValue() % Num != 0)
4592     return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4593       << Num << Arg->getSourceRange();
4594 
4595   return false;
4596 }
4597 
4598 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4599 /// TheCall is an ARM/AArch64 special register string literal.
4600 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4601                                     int ArgNum, unsigned ExpectedFieldNum,
4602                                     bool AllowName) {
4603   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4604                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4605                       BuiltinID == ARM::BI__builtin_arm_rsr ||
4606                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
4607                       BuiltinID == ARM::BI__builtin_arm_wsr ||
4608                       BuiltinID == ARM::BI__builtin_arm_wsrp;
4609   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4610                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4611                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
4612                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4613                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
4614                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
4615   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4616 
4617   // We can't check the value of a dependent argument.
4618   Expr *Arg = TheCall->getArg(ArgNum);
4619   if (Arg->isTypeDependent() || Arg->isValueDependent())
4620     return false;
4621 
4622   // Check if the argument is a string literal.
4623   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4624     return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4625            << Arg->getSourceRange();
4626 
4627   // Check the type of special register given.
4628   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4629   SmallVector<StringRef, 6> Fields;
4630   Reg.split(Fields, ":");
4631 
4632   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4633     return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4634            << Arg->getSourceRange();
4635 
4636   // If the string is the name of a register then we cannot check that it is
4637   // valid here but if the string is of one the forms described in ACLE then we
4638   // can check that the supplied fields are integers and within the valid
4639   // ranges.
4640   if (Fields.size() > 1) {
4641     bool FiveFields = Fields.size() == 5;
4642 
4643     bool ValidString = true;
4644     if (IsARMBuiltin) {
4645       ValidString &= Fields[0].startswith_lower("cp") ||
4646                      Fields[0].startswith_lower("p");
4647       if (ValidString)
4648         Fields[0] =
4649           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4650 
4651       ValidString &= Fields[2].startswith_lower("c");
4652       if (ValidString)
4653         Fields[2] = Fields[2].drop_front(1);
4654 
4655       if (FiveFields) {
4656         ValidString &= Fields[3].startswith_lower("c");
4657         if (ValidString)
4658           Fields[3] = Fields[3].drop_front(1);
4659       }
4660     }
4661 
4662     SmallVector<int, 5> Ranges;
4663     if (FiveFields)
4664       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
4665     else
4666       Ranges.append({15, 7, 15});
4667 
4668     for (unsigned i=0; i<Fields.size(); ++i) {
4669       int IntField;
4670       ValidString &= !Fields[i].getAsInteger(10, IntField);
4671       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4672     }
4673 
4674     if (!ValidString)
4675       return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4676              << Arg->getSourceRange();
4677   } else if (IsAArch64Builtin && Fields.size() == 1) {
4678     // If the register name is one of those that appear in the condition below
4679     // and the special register builtin being used is one of the write builtins,
4680     // then we require that the argument provided for writing to the register
4681     // is an integer constant expression. This is because it will be lowered to
4682     // an MSR (immediate) instruction, so we need to know the immediate at
4683     // compile time.
4684     if (TheCall->getNumArgs() != 2)
4685       return false;
4686 
4687     std::string RegLower = Reg.lower();
4688     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4689         RegLower != "pan" && RegLower != "uao")
4690       return false;
4691 
4692     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4693   }
4694 
4695   return false;
4696 }
4697 
4698 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
4699 /// This checks that the target supports __builtin_longjmp and
4700 /// that val is a constant 1.
4701 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
4702   if (!Context.getTargetInfo().hasSjLjLowering())
4703     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4704              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4705 
4706   Expr *Arg = TheCall->getArg(1);
4707   llvm::APSInt Result;
4708 
4709   // TODO: This is less than ideal. Overload this to take a value.
4710   if (SemaBuiltinConstantArg(TheCall, 1, Result))
4711     return true;
4712 
4713   if (Result != 1)
4714     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4715              << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4716 
4717   return false;
4718 }
4719 
4720 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4721 /// This checks that the target supports __builtin_setjmp.
4722 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4723   if (!Context.getTargetInfo().hasSjLjLowering())
4724     return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4725              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4726   return false;
4727 }
4728 
4729 namespace {
4730 
4731 class UncoveredArgHandler {
4732   enum { Unknown = -1, AllCovered = -2 };
4733 
4734   signed FirstUncoveredArg = Unknown;
4735   SmallVector<const Expr *, 4> DiagnosticExprs;
4736 
4737 public:
4738   UncoveredArgHandler() = default;
4739 
4740   bool hasUncoveredArg() const {
4741     return (FirstUncoveredArg >= 0);
4742   }
4743 
4744   unsigned getUncoveredArg() const {
4745     assert(hasUncoveredArg() && "no uncovered argument");
4746     return FirstUncoveredArg;
4747   }
4748 
4749   void setAllCovered() {
4750     // A string has been found with all arguments covered, so clear out
4751     // the diagnostics.
4752     DiagnosticExprs.clear();
4753     FirstUncoveredArg = AllCovered;
4754   }
4755 
4756   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4757     assert(NewFirstUncoveredArg >= 0 && "Outside range");
4758 
4759     // Don't update if a previous string covers all arguments.
4760     if (FirstUncoveredArg == AllCovered)
4761       return;
4762 
4763     // UncoveredArgHandler tracks the highest uncovered argument index
4764     // and with it all the strings that match this index.
4765     if (NewFirstUncoveredArg == FirstUncoveredArg)
4766       DiagnosticExprs.push_back(StrExpr);
4767     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4768       DiagnosticExprs.clear();
4769       DiagnosticExprs.push_back(StrExpr);
4770       FirstUncoveredArg = NewFirstUncoveredArg;
4771     }
4772   }
4773 
4774   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4775 };
4776 
4777 enum StringLiteralCheckType {
4778   SLCT_NotALiteral,
4779   SLCT_UncheckedLiteral,
4780   SLCT_CheckedLiteral
4781 };
4782 
4783 } // namespace
4784 
4785 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4786                                      BinaryOperatorKind BinOpKind,
4787                                      bool AddendIsRight) {
4788   unsigned BitWidth = Offset.getBitWidth();
4789   unsigned AddendBitWidth = Addend.getBitWidth();
4790   // There might be negative interim results.
4791   if (Addend.isUnsigned()) {
4792     Addend = Addend.zext(++AddendBitWidth);
4793     Addend.setIsSigned(true);
4794   }
4795   // Adjust the bit width of the APSInts.
4796   if (AddendBitWidth > BitWidth) {
4797     Offset = Offset.sext(AddendBitWidth);
4798     BitWidth = AddendBitWidth;
4799   } else if (BitWidth > AddendBitWidth) {
4800     Addend = Addend.sext(BitWidth);
4801   }
4802 
4803   bool Ov = false;
4804   llvm::APSInt ResOffset = Offset;
4805   if (BinOpKind == BO_Add)
4806     ResOffset = Offset.sadd_ov(Addend, Ov);
4807   else {
4808     assert(AddendIsRight && BinOpKind == BO_Sub &&
4809            "operator must be add or sub with addend on the right");
4810     ResOffset = Offset.ssub_ov(Addend, Ov);
4811   }
4812 
4813   // We add an offset to a pointer here so we should support an offset as big as
4814   // possible.
4815   if (Ov) {
4816     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
4817            "index (intermediate) result too big");
4818     Offset = Offset.sext(2 * BitWidth);
4819     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4820     return;
4821   }
4822 
4823   Offset = ResOffset;
4824 }
4825 
4826 namespace {
4827 
4828 // This is a wrapper class around StringLiteral to support offsetted string
4829 // literals as format strings. It takes the offset into account when returning
4830 // the string and its length or the source locations to display notes correctly.
4831 class FormatStringLiteral {
4832   const StringLiteral *FExpr;
4833   int64_t Offset;
4834 
4835  public:
4836   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4837       : FExpr(fexpr), Offset(Offset) {}
4838 
4839   StringRef getString() const {
4840     return FExpr->getString().drop_front(Offset);
4841   }
4842 
4843   unsigned getByteLength() const {
4844     return FExpr->getByteLength() - getCharByteWidth() * Offset;
4845   }
4846 
4847   unsigned getLength() const { return FExpr->getLength() - Offset; }
4848   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4849 
4850   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4851 
4852   QualType getType() const { return FExpr->getType(); }
4853 
4854   bool isAscii() const { return FExpr->isAscii(); }
4855   bool isWide() const { return FExpr->isWide(); }
4856   bool isUTF8() const { return FExpr->isUTF8(); }
4857   bool isUTF16() const { return FExpr->isUTF16(); }
4858   bool isUTF32() const { return FExpr->isUTF32(); }
4859   bool isPascal() const { return FExpr->isPascal(); }
4860 
4861   SourceLocation getLocationOfByte(
4862       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4863       const TargetInfo &Target, unsigned *StartToken = nullptr,
4864       unsigned *StartTokenByteOffset = nullptr) const {
4865     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4866                                     StartToken, StartTokenByteOffset);
4867   }
4868 
4869   SourceLocation getLocStart() const LLVM_READONLY {
4870     return FExpr->getLocStart().getLocWithOffset(Offset);
4871   }
4872 
4873   SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4874 };
4875 
4876 }  // namespace
4877 
4878 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
4879                               const Expr *OrigFormatExpr,
4880                               ArrayRef<const Expr *> Args,
4881                               bool HasVAListArg, unsigned format_idx,
4882                               unsigned firstDataArg,
4883                               Sema::FormatStringType Type,
4884                               bool inFunctionCall,
4885                               Sema::VariadicCallType CallType,
4886                               llvm::SmallBitVector &CheckedVarArgs,
4887                               UncoveredArgHandler &UncoveredArg);
4888 
4889 // Determine if an expression is a string literal or constant string.
4890 // If this function returns false on the arguments to a function expecting a
4891 // format string, we will usually need to emit a warning.
4892 // True string literals are then checked by CheckFormatString.
4893 static StringLiteralCheckType
4894 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4895                       bool HasVAListArg, unsigned format_idx,
4896                       unsigned firstDataArg, Sema::FormatStringType Type,
4897                       Sema::VariadicCallType CallType, bool InFunctionCall,
4898                       llvm::SmallBitVector &CheckedVarArgs,
4899                       UncoveredArgHandler &UncoveredArg,
4900                       llvm::APSInt Offset) {
4901  tryAgain:
4902   assert(Offset.isSigned() && "invalid offset");
4903 
4904   if (E->isTypeDependent() || E->isValueDependent())
4905     return SLCT_NotALiteral;
4906 
4907   E = E->IgnoreParenCasts();
4908 
4909   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
4910     // Technically -Wformat-nonliteral does not warn about this case.
4911     // The behavior of printf and friends in this case is implementation
4912     // dependent.  Ideally if the format string cannot be null then
4913     // it should have a 'nonnull' attribute in the function prototype.
4914     return SLCT_UncheckedLiteral;
4915 
4916   switch (E->getStmtClass()) {
4917   case Stmt::BinaryConditionalOperatorClass:
4918   case Stmt::ConditionalOperatorClass: {
4919     // The expression is a literal if both sub-expressions were, and it was
4920     // completely checked only if both sub-expressions were checked.
4921     const AbstractConditionalOperator *C =
4922         cast<AbstractConditionalOperator>(E);
4923 
4924     // Determine whether it is necessary to check both sub-expressions, for
4925     // example, because the condition expression is a constant that can be
4926     // evaluated at compile time.
4927     bool CheckLeft = true, CheckRight = true;
4928 
4929     bool Cond;
4930     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4931       if (Cond)
4932         CheckRight = false;
4933       else
4934         CheckLeft = false;
4935     }
4936 
4937     // We need to maintain the offsets for the right and the left hand side
4938     // separately to check if every possible indexed expression is a valid
4939     // string literal. They might have different offsets for different string
4940     // literals in the end.
4941     StringLiteralCheckType Left;
4942     if (!CheckLeft)
4943       Left = SLCT_UncheckedLiteral;
4944     else {
4945       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4946                                    HasVAListArg, format_idx, firstDataArg,
4947                                    Type, CallType, InFunctionCall,
4948                                    CheckedVarArgs, UncoveredArg, Offset);
4949       if (Left == SLCT_NotALiteral || !CheckRight) {
4950         return Left;
4951       }
4952     }
4953 
4954     StringLiteralCheckType Right =
4955         checkFormatStringExpr(S, C->getFalseExpr(), Args,
4956                               HasVAListArg, format_idx, firstDataArg,
4957                               Type, CallType, InFunctionCall, CheckedVarArgs,
4958                               UncoveredArg, Offset);
4959 
4960     return (CheckLeft && Left < Right) ? Left : Right;
4961   }
4962 
4963   case Stmt::ImplicitCastExprClass:
4964     E = cast<ImplicitCastExpr>(E)->getSubExpr();
4965     goto tryAgain;
4966 
4967   case Stmt::OpaqueValueExprClass:
4968     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4969       E = src;
4970       goto tryAgain;
4971     }
4972     return SLCT_NotALiteral;
4973 
4974   case Stmt::PredefinedExprClass:
4975     // While __func__, etc., are technically not string literals, they
4976     // cannot contain format specifiers and thus are not a security
4977     // liability.
4978     return SLCT_UncheckedLiteral;
4979 
4980   case Stmt::DeclRefExprClass: {
4981     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
4982 
4983     // As an exception, do not flag errors for variables binding to
4984     // const string literals.
4985     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4986       bool isConstant = false;
4987       QualType T = DR->getType();
4988 
4989       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4990         isConstant = AT->getElementType().isConstant(S.Context);
4991       } else if (const PointerType *PT = T->getAs<PointerType>()) {
4992         isConstant = T.isConstant(S.Context) &&
4993                      PT->getPointeeType().isConstant(S.Context);
4994       } else if (T->isObjCObjectPointerType()) {
4995         // In ObjC, there is usually no "const ObjectPointer" type,
4996         // so don't check if the pointee type is constant.
4997         isConstant = T.isConstant(S.Context);
4998       }
4999 
5000       if (isConstant) {
5001         if (const Expr *Init = VD->getAnyInitializer()) {
5002           // Look through initializers like const char c[] = { "foo" }
5003           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
5004             if (InitList->isStringLiteralInit())
5005               Init = InitList->getInit(0)->IgnoreParenImpCasts();
5006           }
5007           return checkFormatStringExpr(S, Init, Args,
5008                                        HasVAListArg, format_idx,
5009                                        firstDataArg, Type, CallType,
5010                                        /*InFunctionCall*/ false, CheckedVarArgs,
5011                                        UncoveredArg, Offset);
5012         }
5013       }
5014 
5015       // For vprintf* functions (i.e., HasVAListArg==true), we add a
5016       // special check to see if the format string is a function parameter
5017       // of the function calling the printf function.  If the function
5018       // has an attribute indicating it is a printf-like function, then we
5019       // should suppress warnings concerning non-literals being used in a call
5020       // to a vprintf function.  For example:
5021       //
5022       // void
5023       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
5024       //      va_list ap;
5025       //      va_start(ap, fmt);
5026       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
5027       //      ...
5028       // }
5029       if (HasVAListArg) {
5030         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
5031           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
5032             int PVIndex = PV->getFunctionScopeIndex() + 1;
5033             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
5034               // adjust for implicit parameter
5035               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5036                 if (MD->isInstance())
5037                   ++PVIndex;
5038               // We also check if the formats are compatible.
5039               // We can't pass a 'scanf' string to a 'printf' function.
5040               if (PVIndex == PVFormat->getFormatIdx() &&
5041                   Type == S.GetFormatStringType(PVFormat))
5042                 return SLCT_UncheckedLiteral;
5043             }
5044           }
5045         }
5046       }
5047     }
5048 
5049     return SLCT_NotALiteral;
5050   }
5051 
5052   case Stmt::CallExprClass:
5053   case Stmt::CXXMemberCallExprClass: {
5054     const CallExpr *CE = cast<CallExpr>(E);
5055     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
5056       if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
5057         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
5058         return checkFormatStringExpr(S, Arg, Args,
5059                                      HasVAListArg, format_idx, firstDataArg,
5060                                      Type, CallType, InFunctionCall,
5061                                      CheckedVarArgs, UncoveredArg, Offset);
5062       } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5063         unsigned BuiltinID = FD->getBuiltinID();
5064         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
5065             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
5066           const Expr *Arg = CE->getArg(0);
5067           return checkFormatStringExpr(S, Arg, Args,
5068                                        HasVAListArg, format_idx,
5069                                        firstDataArg, Type, CallType,
5070                                        InFunctionCall, CheckedVarArgs,
5071                                        UncoveredArg, Offset);
5072         }
5073       }
5074     }
5075 
5076     return SLCT_NotALiteral;
5077   }
5078   case Stmt::ObjCMessageExprClass: {
5079     const auto *ME = cast<ObjCMessageExpr>(E);
5080     if (const auto *ND = ME->getMethodDecl()) {
5081       if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
5082         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
5083         return checkFormatStringExpr(
5084             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
5085             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
5086       }
5087     }
5088 
5089     return SLCT_NotALiteral;
5090   }
5091   case Stmt::ObjCStringLiteralClass:
5092   case Stmt::StringLiteralClass: {
5093     const StringLiteral *StrE = nullptr;
5094 
5095     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
5096       StrE = ObjCFExpr->getString();
5097     else
5098       StrE = cast<StringLiteral>(E);
5099 
5100     if (StrE) {
5101       if (Offset.isNegative() || Offset > StrE->getLength()) {
5102         // TODO: It would be better to have an explicit warning for out of
5103         // bounds literals.
5104         return SLCT_NotALiteral;
5105       }
5106       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
5107       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
5108                         firstDataArg, Type, InFunctionCall, CallType,
5109                         CheckedVarArgs, UncoveredArg);
5110       return SLCT_CheckedLiteral;
5111     }
5112 
5113     return SLCT_NotALiteral;
5114   }
5115   case Stmt::BinaryOperatorClass: {
5116     llvm::APSInt LResult;
5117     llvm::APSInt RResult;
5118 
5119     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
5120 
5121     // A string literal + an int offset is still a string literal.
5122     if (BinOp->isAdditiveOp()) {
5123       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
5124       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
5125 
5126       if (LIsInt != RIsInt) {
5127         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
5128 
5129         if (LIsInt) {
5130           if (BinOpKind == BO_Add) {
5131             sumOffsets(Offset, LResult, BinOpKind, RIsInt);
5132             E = BinOp->getRHS();
5133             goto tryAgain;
5134           }
5135         } else {
5136           sumOffsets(Offset, RResult, BinOpKind, RIsInt);
5137           E = BinOp->getLHS();
5138           goto tryAgain;
5139         }
5140       }
5141     }
5142 
5143     return SLCT_NotALiteral;
5144   }
5145   case Stmt::UnaryOperatorClass: {
5146     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
5147     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
5148     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
5149       llvm::APSInt IndexResult;
5150       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
5151         sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
5152         E = ASE->getBase();
5153         goto tryAgain;
5154       }
5155     }
5156 
5157     return SLCT_NotALiteral;
5158   }
5159 
5160   default:
5161     return SLCT_NotALiteral;
5162   }
5163 }
5164 
5165 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
5166   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
5167       .Case("scanf", FST_Scanf)
5168       .Cases("printf", "printf0", FST_Printf)
5169       .Cases("NSString", "CFString", FST_NSString)
5170       .Case("strftime", FST_Strftime)
5171       .Case("strfmon", FST_Strfmon)
5172       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
5173       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
5174       .Case("os_trace", FST_OSLog)
5175       .Case("os_log", FST_OSLog)
5176       .Default(FST_Unknown);
5177 }
5178 
5179 /// CheckFormatArguments - Check calls to printf and scanf (and similar
5180 /// functions) for correct use of format strings.
5181 /// Returns true if a format string has been fully checked.
5182 bool Sema::CheckFormatArguments(const FormatAttr *Format,
5183                                 ArrayRef<const Expr *> Args,
5184                                 bool IsCXXMember,
5185                                 VariadicCallType CallType,
5186                                 SourceLocation Loc, SourceRange Range,
5187                                 llvm::SmallBitVector &CheckedVarArgs) {
5188   FormatStringInfo FSI;
5189   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
5190     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
5191                                 FSI.FirstDataArg, GetFormatStringType(Format),
5192                                 CallType, Loc, Range, CheckedVarArgs);
5193   return false;
5194 }
5195 
5196 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
5197                                 bool HasVAListArg, unsigned format_idx,
5198                                 unsigned firstDataArg, FormatStringType Type,
5199                                 VariadicCallType CallType,
5200                                 SourceLocation Loc, SourceRange Range,
5201                                 llvm::SmallBitVector &CheckedVarArgs) {
5202   // CHECK: printf/scanf-like function is called with no format string.
5203   if (format_idx >= Args.size()) {
5204     Diag(Loc, diag::warn_missing_format_string) << Range;
5205     return false;
5206   }
5207 
5208   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
5209 
5210   // CHECK: format string is not a string literal.
5211   //
5212   // Dynamically generated format strings are difficult to
5213   // automatically vet at compile time.  Requiring that format strings
5214   // are string literals: (1) permits the checking of format strings by
5215   // the compiler and thereby (2) can practically remove the source of
5216   // many format string exploits.
5217 
5218   // Format string can be either ObjC string (e.g. @"%d") or
5219   // C string (e.g. "%d")
5220   // ObjC string uses the same format specifiers as C string, so we can use
5221   // the same format string checking logic for both ObjC and C strings.
5222   UncoveredArgHandler UncoveredArg;
5223   StringLiteralCheckType CT =
5224       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
5225                             format_idx, firstDataArg, Type, CallType,
5226                             /*IsFunctionCall*/ true, CheckedVarArgs,
5227                             UncoveredArg,
5228                             /*no string offset*/ llvm::APSInt(64, false) = 0);
5229 
5230   // Generate a diagnostic where an uncovered argument is detected.
5231   if (UncoveredArg.hasUncoveredArg()) {
5232     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
5233     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
5234     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
5235   }
5236 
5237   if (CT != SLCT_NotALiteral)
5238     // Literal format string found, check done!
5239     return CT == SLCT_CheckedLiteral;
5240 
5241   // Strftime is particular as it always uses a single 'time' argument,
5242   // so it is safe to pass a non-literal string.
5243   if (Type == FST_Strftime)
5244     return false;
5245 
5246   // Do not emit diag when the string param is a macro expansion and the
5247   // format is either NSString or CFString. This is a hack to prevent
5248   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
5249   // which are usually used in place of NS and CF string literals.
5250   SourceLocation FormatLoc = Args[format_idx]->getLocStart();
5251   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
5252     return false;
5253 
5254   // If there are no arguments specified, warn with -Wformat-security, otherwise
5255   // warn only with -Wformat-nonliteral.
5256   if (Args.size() == firstDataArg) {
5257     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
5258       << OrigFormatExpr->getSourceRange();
5259     switch (Type) {
5260     default:
5261       break;
5262     case FST_Kprintf:
5263     case FST_FreeBSDKPrintf:
5264     case FST_Printf:
5265       Diag(FormatLoc, diag::note_format_security_fixit)
5266         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
5267       break;
5268     case FST_NSString:
5269       Diag(FormatLoc, diag::note_format_security_fixit)
5270         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
5271       break;
5272     }
5273   } else {
5274     Diag(FormatLoc, diag::warn_format_nonliteral)
5275       << OrigFormatExpr->getSourceRange();
5276   }
5277   return false;
5278 }
5279 
5280 namespace {
5281 
5282 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
5283 protected:
5284   Sema &S;
5285   const FormatStringLiteral *FExpr;
5286   const Expr *OrigFormatExpr;
5287   const Sema::FormatStringType FSType;
5288   const unsigned FirstDataArg;
5289   const unsigned NumDataArgs;
5290   const char *Beg; // Start of format string.
5291   const bool HasVAListArg;
5292   ArrayRef<const Expr *> Args;
5293   unsigned FormatIdx;
5294   llvm::SmallBitVector CoveredArgs;
5295   bool usesPositionalArgs = false;
5296   bool atFirstArg = true;
5297   bool inFunctionCall;
5298   Sema::VariadicCallType CallType;
5299   llvm::SmallBitVector &CheckedVarArgs;
5300   UncoveredArgHandler &UncoveredArg;
5301 
5302 public:
5303   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
5304                      const Expr *origFormatExpr,
5305                      const Sema::FormatStringType type, unsigned firstDataArg,
5306                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
5307                      ArrayRef<const Expr *> Args, unsigned formatIdx,
5308                      bool inFunctionCall, Sema::VariadicCallType callType,
5309                      llvm::SmallBitVector &CheckedVarArgs,
5310                      UncoveredArgHandler &UncoveredArg)
5311       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
5312         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
5313         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
5314         inFunctionCall(inFunctionCall), CallType(callType),
5315         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
5316     CoveredArgs.resize(numDataArgs);
5317     CoveredArgs.reset();
5318   }
5319 
5320   void DoneProcessing();
5321 
5322   void HandleIncompleteSpecifier(const char *startSpecifier,
5323                                  unsigned specifierLen) override;
5324 
5325   void HandleInvalidLengthModifier(
5326                            const analyze_format_string::FormatSpecifier &FS,
5327                            const analyze_format_string::ConversionSpecifier &CS,
5328                            const char *startSpecifier, unsigned specifierLen,
5329                            unsigned DiagID);
5330 
5331   void HandleNonStandardLengthModifier(
5332                     const analyze_format_string::FormatSpecifier &FS,
5333                     const char *startSpecifier, unsigned specifierLen);
5334 
5335   void HandleNonStandardConversionSpecifier(
5336                     const analyze_format_string::ConversionSpecifier &CS,
5337                     const char *startSpecifier, unsigned specifierLen);
5338 
5339   void HandlePosition(const char *startPos, unsigned posLen) override;
5340 
5341   void HandleInvalidPosition(const char *startSpecifier,
5342                              unsigned specifierLen,
5343                              analyze_format_string::PositionContext p) override;
5344 
5345   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
5346 
5347   void HandleNullChar(const char *nullCharacter) override;
5348 
5349   template <typename Range>
5350   static void
5351   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
5352                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
5353                        bool IsStringLocation, Range StringRange,
5354                        ArrayRef<FixItHint> Fixit = None);
5355 
5356 protected:
5357   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
5358                                         const char *startSpec,
5359                                         unsigned specifierLen,
5360                                         const char *csStart, unsigned csLen);
5361 
5362   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
5363                                          const char *startSpec,
5364                                          unsigned specifierLen);
5365 
5366   SourceRange getFormatStringRange();
5367   CharSourceRange getSpecifierRange(const char *startSpecifier,
5368                                     unsigned specifierLen);
5369   SourceLocation getLocationOfByte(const char *x);
5370 
5371   const Expr *getDataArg(unsigned i) const;
5372 
5373   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
5374                     const analyze_format_string::ConversionSpecifier &CS,
5375                     const char *startSpecifier, unsigned specifierLen,
5376                     unsigned argIndex);
5377 
5378   template <typename Range>
5379   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5380                             bool IsStringLocation, Range StringRange,
5381                             ArrayRef<FixItHint> Fixit = None);
5382 };
5383 
5384 } // namespace
5385 
5386 SourceRange CheckFormatHandler::getFormatStringRange() {
5387   return OrigFormatExpr->getSourceRange();
5388 }
5389 
5390 CharSourceRange CheckFormatHandler::
5391 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
5392   SourceLocation Start = getLocationOfByte(startSpecifier);
5393   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
5394 
5395   // Advance the end SourceLocation by one due to half-open ranges.
5396   End = End.getLocWithOffset(1);
5397 
5398   return CharSourceRange::getCharRange(Start, End);
5399 }
5400 
5401 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
5402   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
5403                                   S.getLangOpts(), S.Context.getTargetInfo());
5404 }
5405 
5406 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
5407                                                    unsigned specifierLen){
5408   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
5409                        getLocationOfByte(startSpecifier),
5410                        /*IsStringLocation*/true,
5411                        getSpecifierRange(startSpecifier, specifierLen));
5412 }
5413 
5414 void CheckFormatHandler::HandleInvalidLengthModifier(
5415     const analyze_format_string::FormatSpecifier &FS,
5416     const analyze_format_string::ConversionSpecifier &CS,
5417     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
5418   using namespace analyze_format_string;
5419 
5420   const LengthModifier &LM = FS.getLengthModifier();
5421   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5422 
5423   // See if we know how to fix this length modifier.
5424   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
5425   if (FixedLM) {
5426     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
5427                          getLocationOfByte(LM.getStart()),
5428                          /*IsStringLocation*/true,
5429                          getSpecifierRange(startSpecifier, specifierLen));
5430 
5431     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5432       << FixedLM->toString()
5433       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5434 
5435   } else {
5436     FixItHint Hint;
5437     if (DiagID == diag::warn_format_nonsensical_length)
5438       Hint = FixItHint::CreateRemoval(LMRange);
5439 
5440     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
5441                          getLocationOfByte(LM.getStart()),
5442                          /*IsStringLocation*/true,
5443                          getSpecifierRange(startSpecifier, specifierLen),
5444                          Hint);
5445   }
5446 }
5447 
5448 void CheckFormatHandler::HandleNonStandardLengthModifier(
5449     const analyze_format_string::FormatSpecifier &FS,
5450     const char *startSpecifier, unsigned specifierLen) {
5451   using namespace analyze_format_string;
5452 
5453   const LengthModifier &LM = FS.getLengthModifier();
5454   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5455 
5456   // See if we know how to fix this length modifier.
5457   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
5458   if (FixedLM) {
5459     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5460                            << LM.toString() << 0,
5461                          getLocationOfByte(LM.getStart()),
5462                          /*IsStringLocation*/true,
5463                          getSpecifierRange(startSpecifier, specifierLen));
5464 
5465     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5466       << FixedLM->toString()
5467       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5468 
5469   } else {
5470     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5471                            << LM.toString() << 0,
5472                          getLocationOfByte(LM.getStart()),
5473                          /*IsStringLocation*/true,
5474                          getSpecifierRange(startSpecifier, specifierLen));
5475   }
5476 }
5477 
5478 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5479     const analyze_format_string::ConversionSpecifier &CS,
5480     const char *startSpecifier, unsigned specifierLen) {
5481   using namespace analyze_format_string;
5482 
5483   // See if we know how to fix this conversion specifier.
5484   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
5485   if (FixedCS) {
5486     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5487                           << CS.toString() << /*conversion specifier*/1,
5488                          getLocationOfByte(CS.getStart()),
5489                          /*IsStringLocation*/true,
5490                          getSpecifierRange(startSpecifier, specifierLen));
5491 
5492     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5493     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5494       << FixedCS->toString()
5495       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5496   } else {
5497     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5498                           << CS.toString() << /*conversion specifier*/1,
5499                          getLocationOfByte(CS.getStart()),
5500                          /*IsStringLocation*/true,
5501                          getSpecifierRange(startSpecifier, specifierLen));
5502   }
5503 }
5504 
5505 void CheckFormatHandler::HandlePosition(const char *startPos,
5506                                         unsigned posLen) {
5507   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5508                                getLocationOfByte(startPos),
5509                                /*IsStringLocation*/true,
5510                                getSpecifierRange(startPos, posLen));
5511 }
5512 
5513 void
5514 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5515                                      analyze_format_string::PositionContext p) {
5516   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5517                          << (unsigned) p,
5518                        getLocationOfByte(startPos), /*IsStringLocation*/true,
5519                        getSpecifierRange(startPos, posLen));
5520 }
5521 
5522 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
5523                                             unsigned posLen) {
5524   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5525                                getLocationOfByte(startPos),
5526                                /*IsStringLocation*/true,
5527                                getSpecifierRange(startPos, posLen));
5528 }
5529 
5530 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
5531   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
5532     // The presence of a null character is likely an error.
5533     EmitFormatDiagnostic(
5534       S.PDiag(diag::warn_printf_format_string_contains_null_char),
5535       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5536       getFormatStringRange());
5537   }
5538 }
5539 
5540 // Note that this may return NULL if there was an error parsing or building
5541 // one of the argument expressions.
5542 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
5543   return Args[FirstDataArg + i];
5544 }
5545 
5546 void CheckFormatHandler::DoneProcessing() {
5547   // Does the number of data arguments exceed the number of
5548   // format conversions in the format string?
5549   if (!HasVAListArg) {
5550       // Find any arguments that weren't covered.
5551     CoveredArgs.flip();
5552     signed notCoveredArg = CoveredArgs.find_first();
5553     if (notCoveredArg >= 0) {
5554       assert((unsigned)notCoveredArg < NumDataArgs);
5555       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5556     } else {
5557       UncoveredArg.setAllCovered();
5558     }
5559   }
5560 }
5561 
5562 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5563                                    const Expr *ArgExpr) {
5564   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5565          "Invalid state");
5566 
5567   if (!ArgExpr)
5568     return;
5569 
5570   SourceLocation Loc = ArgExpr->getLocStart();
5571 
5572   if (S.getSourceManager().isInSystemMacro(Loc))
5573     return;
5574 
5575   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5576   for (auto E : DiagnosticExprs)
5577     PDiag << E->getSourceRange();
5578 
5579   CheckFormatHandler::EmitFormatDiagnostic(
5580                                   S, IsFunctionCall, DiagnosticExprs[0],
5581                                   PDiag, Loc, /*IsStringLocation*/false,
5582                                   DiagnosticExprs[0]->getSourceRange());
5583 }
5584 
5585 bool
5586 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5587                                                      SourceLocation Loc,
5588                                                      const char *startSpec,
5589                                                      unsigned specifierLen,
5590                                                      const char *csStart,
5591                                                      unsigned csLen) {
5592   bool keepGoing = true;
5593   if (argIndex < NumDataArgs) {
5594     // Consider the argument coverered, even though the specifier doesn't
5595     // make sense.
5596     CoveredArgs.set(argIndex);
5597   }
5598   else {
5599     // If argIndex exceeds the number of data arguments we
5600     // don't issue a warning because that is just a cascade of warnings (and
5601     // they may have intended '%%' anyway). We don't want to continue processing
5602     // the format string after this point, however, as we will like just get
5603     // gibberish when trying to match arguments.
5604     keepGoing = false;
5605   }
5606 
5607   StringRef Specifier(csStart, csLen);
5608 
5609   // If the specifier in non-printable, it could be the first byte of a UTF-8
5610   // sequence. In that case, print the UTF-8 code point. If not, print the byte
5611   // hex value.
5612   std::string CodePointStr;
5613   if (!llvm::sys::locale::isPrint(*csStart)) {
5614     llvm::UTF32 CodePoint;
5615     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5616     const llvm::UTF8 *E =
5617         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5618     llvm::ConversionResult Result =
5619         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
5620 
5621     if (Result != llvm::conversionOK) {
5622       unsigned char FirstChar = *csStart;
5623       CodePoint = (llvm::UTF32)FirstChar;
5624     }
5625 
5626     llvm::raw_string_ostream OS(CodePointStr);
5627     if (CodePoint < 256)
5628       OS << "\\x" << llvm::format("%02x", CodePoint);
5629     else if (CodePoint <= 0xFFFF)
5630       OS << "\\u" << llvm::format("%04x", CodePoint);
5631     else
5632       OS << "\\U" << llvm::format("%08x", CodePoint);
5633     OS.flush();
5634     Specifier = CodePointStr;
5635   }
5636 
5637   EmitFormatDiagnostic(
5638       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5639       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5640 
5641   return keepGoing;
5642 }
5643 
5644 void
5645 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5646                                                       const char *startSpec,
5647                                                       unsigned specifierLen) {
5648   EmitFormatDiagnostic(
5649     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5650     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5651 }
5652 
5653 bool
5654 CheckFormatHandler::CheckNumArgs(
5655   const analyze_format_string::FormatSpecifier &FS,
5656   const analyze_format_string::ConversionSpecifier &CS,
5657   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5658 
5659   if (argIndex >= NumDataArgs) {
5660     PartialDiagnostic PDiag = FS.usesPositionalArg()
5661       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5662            << (argIndex+1) << NumDataArgs)
5663       : S.PDiag(diag::warn_printf_insufficient_data_args);
5664     EmitFormatDiagnostic(
5665       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5666       getSpecifierRange(startSpecifier, specifierLen));
5667 
5668     // Since more arguments than conversion tokens are given, by extension
5669     // all arguments are covered, so mark this as so.
5670     UncoveredArg.setAllCovered();
5671     return false;
5672   }
5673   return true;
5674 }
5675 
5676 template<typename Range>
5677 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5678                                               SourceLocation Loc,
5679                                               bool IsStringLocation,
5680                                               Range StringRange,
5681                                               ArrayRef<FixItHint> FixIt) {
5682   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
5683                        Loc, IsStringLocation, StringRange, FixIt);
5684 }
5685 
5686 /// \brief If the format string is not within the function call, emit a note
5687 /// so that the function call and string are in diagnostic messages.
5688 ///
5689 /// \param InFunctionCall if true, the format string is within the function
5690 /// call and only one diagnostic message will be produced.  Otherwise, an
5691 /// extra note will be emitted pointing to location of the format string.
5692 ///
5693 /// \param ArgumentExpr the expression that is passed as the format string
5694 /// argument in the function call.  Used for getting locations when two
5695 /// diagnostics are emitted.
5696 ///
5697 /// \param PDiag the callee should already have provided any strings for the
5698 /// diagnostic message.  This function only adds locations and fixits
5699 /// to diagnostics.
5700 ///
5701 /// \param Loc primary location for diagnostic.  If two diagnostics are
5702 /// required, one will be at Loc and a new SourceLocation will be created for
5703 /// the other one.
5704 ///
5705 /// \param IsStringLocation if true, Loc points to the format string should be
5706 /// used for the note.  Otherwise, Loc points to the argument list and will
5707 /// be used with PDiag.
5708 ///
5709 /// \param StringRange some or all of the string to highlight.  This is
5710 /// templated so it can accept either a CharSourceRange or a SourceRange.
5711 ///
5712 /// \param FixIt optional fix it hint for the format string.
5713 template <typename Range>
5714 void CheckFormatHandler::EmitFormatDiagnostic(
5715     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5716     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5717     Range StringRange, ArrayRef<FixItHint> FixIt) {
5718   if (InFunctionCall) {
5719     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5720     D << StringRange;
5721     D << FixIt;
5722   } else {
5723     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5724       << ArgumentExpr->getSourceRange();
5725 
5726     const Sema::SemaDiagnosticBuilder &Note =
5727       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5728              diag::note_format_string_defined);
5729 
5730     Note << StringRange;
5731     Note << FixIt;
5732   }
5733 }
5734 
5735 //===--- CHECK: Printf format string checking ------------------------------===//
5736 
5737 namespace {
5738 
5739 class CheckPrintfHandler : public CheckFormatHandler {
5740 public:
5741   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
5742                      const Expr *origFormatExpr,
5743                      const Sema::FormatStringType type, unsigned firstDataArg,
5744                      unsigned numDataArgs, bool isObjC, const char *beg,
5745                      bool hasVAListArg, ArrayRef<const Expr *> Args,
5746                      unsigned formatIdx, bool inFunctionCall,
5747                      Sema::VariadicCallType CallType,
5748                      llvm::SmallBitVector &CheckedVarArgs,
5749                      UncoveredArgHandler &UncoveredArg)
5750       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5751                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
5752                            inFunctionCall, CallType, CheckedVarArgs,
5753                            UncoveredArg) {}
5754 
5755   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5756 
5757   /// Returns true if '%@' specifiers are allowed in the format string.
5758   bool allowsObjCArg() const {
5759     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5760            FSType == Sema::FST_OSTrace;
5761   }
5762 
5763   bool HandleInvalidPrintfConversionSpecifier(
5764                                       const analyze_printf::PrintfSpecifier &FS,
5765                                       const char *startSpecifier,
5766                                       unsigned specifierLen) override;
5767 
5768   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5769                              const char *startSpecifier,
5770                              unsigned specifierLen) override;
5771   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5772                        const char *StartSpecifier,
5773                        unsigned SpecifierLen,
5774                        const Expr *E);
5775 
5776   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5777                     const char *startSpecifier, unsigned specifierLen);
5778   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5779                            const analyze_printf::OptionalAmount &Amt,
5780                            unsigned type,
5781                            const char *startSpecifier, unsigned specifierLen);
5782   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5783                   const analyze_printf::OptionalFlag &flag,
5784                   const char *startSpecifier, unsigned specifierLen);
5785   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5786                          const analyze_printf::OptionalFlag &ignoredFlag,
5787                          const analyze_printf::OptionalFlag &flag,
5788                          const char *startSpecifier, unsigned specifierLen);
5789   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
5790                            const Expr *E);
5791 
5792   void HandleEmptyObjCModifierFlag(const char *startFlag,
5793                                    unsigned flagLen) override;
5794 
5795   void HandleInvalidObjCModifierFlag(const char *startFlag,
5796                                             unsigned flagLen) override;
5797 
5798   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5799                                            const char *flagsEnd,
5800                                            const char *conversionPosition)
5801                                              override;
5802 };
5803 
5804 } // namespace
5805 
5806 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5807                                       const analyze_printf::PrintfSpecifier &FS,
5808                                       const char *startSpecifier,
5809                                       unsigned specifierLen) {
5810   const analyze_printf::PrintfConversionSpecifier &CS =
5811     FS.getConversionSpecifier();
5812 
5813   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5814                                           getLocationOfByte(CS.getStart()),
5815                                           startSpecifier, specifierLen,
5816                                           CS.getStart(), CS.getLength());
5817 }
5818 
5819 bool CheckPrintfHandler::HandleAmount(
5820                                const analyze_format_string::OptionalAmount &Amt,
5821                                unsigned k, const char *startSpecifier,
5822                                unsigned specifierLen) {
5823   if (Amt.hasDataArgument()) {
5824     if (!HasVAListArg) {
5825       unsigned argIndex = Amt.getArgIndex();
5826       if (argIndex >= NumDataArgs) {
5827         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5828                                << k,
5829                              getLocationOfByte(Amt.getStart()),
5830                              /*IsStringLocation*/true,
5831                              getSpecifierRange(startSpecifier, specifierLen));
5832         // Don't do any more checking.  We will just emit
5833         // spurious errors.
5834         return false;
5835       }
5836 
5837       // Type check the data argument.  It should be an 'int'.
5838       // Although not in conformance with C99, we also allow the argument to be
5839       // an 'unsigned int' as that is a reasonably safe case.  GCC also
5840       // doesn't emit a warning for that case.
5841       CoveredArgs.set(argIndex);
5842       const Expr *Arg = getDataArg(argIndex);
5843       if (!Arg)
5844         return false;
5845 
5846       QualType T = Arg->getType();
5847 
5848       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5849       assert(AT.isValid());
5850 
5851       if (!AT.matchesType(S.Context, T)) {
5852         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
5853                                << k << AT.getRepresentativeTypeName(S.Context)
5854                                << T << Arg->getSourceRange(),
5855                              getLocationOfByte(Amt.getStart()),
5856                              /*IsStringLocation*/true,
5857                              getSpecifierRange(startSpecifier, specifierLen));
5858         // Don't do any more checking.  We will just emit
5859         // spurious errors.
5860         return false;
5861       }
5862     }
5863   }
5864   return true;
5865 }
5866 
5867 void CheckPrintfHandler::HandleInvalidAmount(
5868                                       const analyze_printf::PrintfSpecifier &FS,
5869                                       const analyze_printf::OptionalAmount &Amt,
5870                                       unsigned type,
5871                                       const char *startSpecifier,
5872                                       unsigned specifierLen) {
5873   const analyze_printf::PrintfConversionSpecifier &CS =
5874     FS.getConversionSpecifier();
5875 
5876   FixItHint fixit =
5877     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5878       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5879                                  Amt.getConstantLength()))
5880       : FixItHint();
5881 
5882   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5883                          << type << CS.toString(),
5884                        getLocationOfByte(Amt.getStart()),
5885                        /*IsStringLocation*/true,
5886                        getSpecifierRange(startSpecifier, specifierLen),
5887                        fixit);
5888 }
5889 
5890 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5891                                     const analyze_printf::OptionalFlag &flag,
5892                                     const char *startSpecifier,
5893                                     unsigned specifierLen) {
5894   // Warn about pointless flag with a fixit removal.
5895   const analyze_printf::PrintfConversionSpecifier &CS =
5896     FS.getConversionSpecifier();
5897   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5898                          << flag.toString() << CS.toString(),
5899                        getLocationOfByte(flag.getPosition()),
5900                        /*IsStringLocation*/true,
5901                        getSpecifierRange(startSpecifier, specifierLen),
5902                        FixItHint::CreateRemoval(
5903                          getSpecifierRange(flag.getPosition(), 1)));
5904 }
5905 
5906 void CheckPrintfHandler::HandleIgnoredFlag(
5907                                 const analyze_printf::PrintfSpecifier &FS,
5908                                 const analyze_printf::OptionalFlag &ignoredFlag,
5909                                 const analyze_printf::OptionalFlag &flag,
5910                                 const char *startSpecifier,
5911                                 unsigned specifierLen) {
5912   // Warn about ignored flag with a fixit removal.
5913   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5914                          << ignoredFlag.toString() << flag.toString(),
5915                        getLocationOfByte(ignoredFlag.getPosition()),
5916                        /*IsStringLocation*/true,
5917                        getSpecifierRange(startSpecifier, specifierLen),
5918                        FixItHint::CreateRemoval(
5919                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
5920 }
5921 
5922 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5923                                                      unsigned flagLen) {
5924   // Warn about an empty flag.
5925   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5926                        getLocationOfByte(startFlag),
5927                        /*IsStringLocation*/true,
5928                        getSpecifierRange(startFlag, flagLen));
5929 }
5930 
5931 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5932                                                        unsigned flagLen) {
5933   // Warn about an invalid flag.
5934   auto Range = getSpecifierRange(startFlag, flagLen);
5935   StringRef flag(startFlag, flagLen);
5936   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5937                       getLocationOfByte(startFlag),
5938                       /*IsStringLocation*/true,
5939                       Range, FixItHint::CreateRemoval(Range));
5940 }
5941 
5942 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5943     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5944     // Warn about using '[...]' without a '@' conversion.
5945     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5946     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5947     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5948                          getLocationOfByte(conversionPosition),
5949                          /*IsStringLocation*/true,
5950                          Range, FixItHint::CreateRemoval(Range));
5951 }
5952 
5953 // Determines if the specified is a C++ class or struct containing
5954 // a member with the specified name and kind (e.g. a CXXMethodDecl named
5955 // "c_str()").
5956 template<typename MemberKind>
5957 static llvm::SmallPtrSet<MemberKind*, 1>
5958 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5959   const RecordType *RT = Ty->getAs<RecordType>();
5960   llvm::SmallPtrSet<MemberKind*, 1> Results;
5961 
5962   if (!RT)
5963     return Results;
5964   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
5965   if (!RD || !RD->getDefinition())
5966     return Results;
5967 
5968   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
5969                  Sema::LookupMemberName);
5970   R.suppressDiagnostics();
5971 
5972   // We just need to include all members of the right kind turned up by the
5973   // filter, at this point.
5974   if (S.LookupQualifiedName(R, RT->getDecl()))
5975     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5976       NamedDecl *decl = (*I)->getUnderlyingDecl();
5977       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5978         Results.insert(FK);
5979     }
5980   return Results;
5981 }
5982 
5983 /// Check if we could call '.c_str()' on an object.
5984 ///
5985 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5986 /// allow the call, or if it would be ambiguous).
5987 bool Sema::hasCStrMethod(const Expr *E) {
5988   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
5989 
5990   MethodSet Results =
5991       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5992   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5993        MI != ME; ++MI)
5994     if ((*MI)->getMinRequiredArguments() == 0)
5995       return true;
5996   return false;
5997 }
5998 
5999 // Check if a (w)string was passed when a (w)char* was needed, and offer a
6000 // better diagnostic if so. AT is assumed to be valid.
6001 // Returns true when a c_str() conversion method is found.
6002 bool CheckPrintfHandler::checkForCStrMembers(
6003     const analyze_printf::ArgType &AT, const Expr *E) {
6004   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
6005 
6006   MethodSet Results =
6007       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
6008 
6009   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
6010        MI != ME; ++MI) {
6011     const CXXMethodDecl *Method = *MI;
6012     if (Method->getMinRequiredArguments() == 0 &&
6013         AT.matchesType(S.Context, Method->getReturnType())) {
6014       // FIXME: Suggest parens if the expression needs them.
6015       SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
6016       S.Diag(E->getLocStart(), diag::note_printf_c_str)
6017           << "c_str()"
6018           << FixItHint::CreateInsertion(EndLoc, ".c_str()");
6019       return true;
6020     }
6021   }
6022 
6023   return false;
6024 }
6025 
6026 bool
6027 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
6028                                             &FS,
6029                                           const char *startSpecifier,
6030                                           unsigned specifierLen) {
6031   using namespace analyze_format_string;
6032   using namespace analyze_printf;
6033 
6034   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
6035 
6036   if (FS.consumesDataArgument()) {
6037     if (atFirstArg) {
6038         atFirstArg = false;
6039         usesPositionalArgs = FS.usesPositionalArg();
6040     }
6041     else if (usesPositionalArgs != FS.usesPositionalArg()) {
6042       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6043                                         startSpecifier, specifierLen);
6044       return false;
6045     }
6046   }
6047 
6048   // First check if the field width, precision, and conversion specifier
6049   // have matching data arguments.
6050   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
6051                     startSpecifier, specifierLen)) {
6052     return false;
6053   }
6054 
6055   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
6056                     startSpecifier, specifierLen)) {
6057     return false;
6058   }
6059 
6060   if (!CS.consumesDataArgument()) {
6061     // FIXME: Technically specifying a precision or field width here
6062     // makes no sense.  Worth issuing a warning at some point.
6063     return true;
6064   }
6065 
6066   // Consume the argument.
6067   unsigned argIndex = FS.getArgIndex();
6068   if (argIndex < NumDataArgs) {
6069     // The check to see if the argIndex is valid will come later.
6070     // We set the bit here because we may exit early from this
6071     // function if we encounter some other error.
6072     CoveredArgs.set(argIndex);
6073   }
6074 
6075   // FreeBSD kernel extensions.
6076   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
6077       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
6078     // We need at least two arguments.
6079     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
6080       return false;
6081 
6082     // Claim the second argument.
6083     CoveredArgs.set(argIndex + 1);
6084 
6085     // Type check the first argument (int for %b, pointer for %D)
6086     const Expr *Ex = getDataArg(argIndex);
6087     const analyze_printf::ArgType &AT =
6088       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
6089         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
6090     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
6091       EmitFormatDiagnostic(
6092         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6093         << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
6094         << false << Ex->getSourceRange(),
6095         Ex->getLocStart(), /*IsStringLocation*/false,
6096         getSpecifierRange(startSpecifier, specifierLen));
6097 
6098     // Type check the second argument (char * for both %b and %D)
6099     Ex = getDataArg(argIndex + 1);
6100     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
6101     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
6102       EmitFormatDiagnostic(
6103         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6104         << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
6105         << false << Ex->getSourceRange(),
6106         Ex->getLocStart(), /*IsStringLocation*/false,
6107         getSpecifierRange(startSpecifier, specifierLen));
6108 
6109      return true;
6110   }
6111 
6112   // Check for using an Objective-C specific conversion specifier
6113   // in a non-ObjC literal.
6114   if (!allowsObjCArg() && CS.isObjCArg()) {
6115     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6116                                                   specifierLen);
6117   }
6118 
6119   // %P can only be used with os_log.
6120   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
6121     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6122                                                   specifierLen);
6123   }
6124 
6125   // %n is not allowed with os_log.
6126   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
6127     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
6128                          getLocationOfByte(CS.getStart()),
6129                          /*IsStringLocation*/ false,
6130                          getSpecifierRange(startSpecifier, specifierLen));
6131 
6132     return true;
6133   }
6134 
6135   // Only scalars are allowed for os_trace.
6136   if (FSType == Sema::FST_OSTrace &&
6137       (CS.getKind() == ConversionSpecifier::PArg ||
6138        CS.getKind() == ConversionSpecifier::sArg ||
6139        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
6140     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6141                                                   specifierLen);
6142   }
6143 
6144   // Check for use of public/private annotation outside of os_log().
6145   if (FSType != Sema::FST_OSLog) {
6146     if (FS.isPublic().isSet()) {
6147       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6148                                << "public",
6149                            getLocationOfByte(FS.isPublic().getPosition()),
6150                            /*IsStringLocation*/ false,
6151                            getSpecifierRange(startSpecifier, specifierLen));
6152     }
6153     if (FS.isPrivate().isSet()) {
6154       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6155                                << "private",
6156                            getLocationOfByte(FS.isPrivate().getPosition()),
6157                            /*IsStringLocation*/ false,
6158                            getSpecifierRange(startSpecifier, specifierLen));
6159     }
6160   }
6161 
6162   // Check for invalid use of field width
6163   if (!FS.hasValidFieldWidth()) {
6164     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
6165         startSpecifier, specifierLen);
6166   }
6167 
6168   // Check for invalid use of precision
6169   if (!FS.hasValidPrecision()) {
6170     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
6171         startSpecifier, specifierLen);
6172   }
6173 
6174   // Precision is mandatory for %P specifier.
6175   if (CS.getKind() == ConversionSpecifier::PArg &&
6176       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
6177     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
6178                          getLocationOfByte(startSpecifier),
6179                          /*IsStringLocation*/ false,
6180                          getSpecifierRange(startSpecifier, specifierLen));
6181   }
6182 
6183   // Check each flag does not conflict with any other component.
6184   if (!FS.hasValidThousandsGroupingPrefix())
6185     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
6186   if (!FS.hasValidLeadingZeros())
6187     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
6188   if (!FS.hasValidPlusPrefix())
6189     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
6190   if (!FS.hasValidSpacePrefix())
6191     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
6192   if (!FS.hasValidAlternativeForm())
6193     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
6194   if (!FS.hasValidLeftJustified())
6195     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
6196 
6197   // Check that flags are not ignored by another flag
6198   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
6199     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
6200         startSpecifier, specifierLen);
6201   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
6202     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
6203             startSpecifier, specifierLen);
6204 
6205   // Check the length modifier is valid with the given conversion specifier.
6206   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
6207     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6208                                 diag::warn_format_nonsensical_length);
6209   else if (!FS.hasStandardLengthModifier())
6210     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
6211   else if (!FS.hasStandardLengthConversionCombination())
6212     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6213                                 diag::warn_format_non_standard_conversion_spec);
6214 
6215   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6216     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6217 
6218   // The remaining checks depend on the data arguments.
6219   if (HasVAListArg)
6220     return true;
6221 
6222   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
6223     return false;
6224 
6225   const Expr *Arg = getDataArg(argIndex);
6226   if (!Arg)
6227     return true;
6228 
6229   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
6230 }
6231 
6232 static bool requiresParensToAddCast(const Expr *E) {
6233   // FIXME: We should have a general way to reason about operator
6234   // precedence and whether parens are actually needed here.
6235   // Take care of a few common cases where they aren't.
6236   const Expr *Inside = E->IgnoreImpCasts();
6237   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
6238     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
6239 
6240   switch (Inside->getStmtClass()) {
6241   case Stmt::ArraySubscriptExprClass:
6242   case Stmt::CallExprClass:
6243   case Stmt::CharacterLiteralClass:
6244   case Stmt::CXXBoolLiteralExprClass:
6245   case Stmt::DeclRefExprClass:
6246   case Stmt::FloatingLiteralClass:
6247   case Stmt::IntegerLiteralClass:
6248   case Stmt::MemberExprClass:
6249   case Stmt::ObjCArrayLiteralClass:
6250   case Stmt::ObjCBoolLiteralExprClass:
6251   case Stmt::ObjCBoxedExprClass:
6252   case Stmt::ObjCDictionaryLiteralClass:
6253   case Stmt::ObjCEncodeExprClass:
6254   case Stmt::ObjCIvarRefExprClass:
6255   case Stmt::ObjCMessageExprClass:
6256   case Stmt::ObjCPropertyRefExprClass:
6257   case Stmt::ObjCStringLiteralClass:
6258   case Stmt::ObjCSubscriptRefExprClass:
6259   case Stmt::ParenExprClass:
6260   case Stmt::StringLiteralClass:
6261   case Stmt::UnaryOperatorClass:
6262     return false;
6263   default:
6264     return true;
6265   }
6266 }
6267 
6268 static std::pair<QualType, StringRef>
6269 shouldNotPrintDirectly(const ASTContext &Context,
6270                        QualType IntendedTy,
6271                        const Expr *E) {
6272   // Use a 'while' to peel off layers of typedefs.
6273   QualType TyTy = IntendedTy;
6274   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
6275     StringRef Name = UserTy->getDecl()->getName();
6276     QualType CastTy = llvm::StringSwitch<QualType>(Name)
6277       .Case("CFIndex", Context.getNSIntegerType())
6278       .Case("NSInteger", Context.getNSIntegerType())
6279       .Case("NSUInteger", Context.getNSUIntegerType())
6280       .Case("SInt32", Context.IntTy)
6281       .Case("UInt32", Context.UnsignedIntTy)
6282       .Default(QualType());
6283 
6284     if (!CastTy.isNull())
6285       return std::make_pair(CastTy, Name);
6286 
6287     TyTy = UserTy->desugar();
6288   }
6289 
6290   // Strip parens if necessary.
6291   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
6292     return shouldNotPrintDirectly(Context,
6293                                   PE->getSubExpr()->getType(),
6294                                   PE->getSubExpr());
6295 
6296   // If this is a conditional expression, then its result type is constructed
6297   // via usual arithmetic conversions and thus there might be no necessary
6298   // typedef sugar there.  Recurse to operands to check for NSInteger &
6299   // Co. usage condition.
6300   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6301     QualType TrueTy, FalseTy;
6302     StringRef TrueName, FalseName;
6303 
6304     std::tie(TrueTy, TrueName) =
6305       shouldNotPrintDirectly(Context,
6306                              CO->getTrueExpr()->getType(),
6307                              CO->getTrueExpr());
6308     std::tie(FalseTy, FalseName) =
6309       shouldNotPrintDirectly(Context,
6310                              CO->getFalseExpr()->getType(),
6311                              CO->getFalseExpr());
6312 
6313     if (TrueTy == FalseTy)
6314       return std::make_pair(TrueTy, TrueName);
6315     else if (TrueTy.isNull())
6316       return std::make_pair(FalseTy, FalseName);
6317     else if (FalseTy.isNull())
6318       return std::make_pair(TrueTy, TrueName);
6319   }
6320 
6321   return std::make_pair(QualType(), StringRef());
6322 }
6323 
6324 bool
6325 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6326                                     const char *StartSpecifier,
6327                                     unsigned SpecifierLen,
6328                                     const Expr *E) {
6329   using namespace analyze_format_string;
6330   using namespace analyze_printf;
6331 
6332   // Now type check the data expression that matches the
6333   // format specifier.
6334   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
6335   if (!AT.isValid())
6336     return true;
6337 
6338   QualType ExprTy = E->getType();
6339   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
6340     ExprTy = TET->getUnderlyingExpr()->getType();
6341   }
6342 
6343   analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
6344 
6345   if (match == analyze_printf::ArgType::Match) {
6346     return true;
6347   }
6348 
6349   // Look through argument promotions for our error message's reported type.
6350   // This includes the integral and floating promotions, but excludes array
6351   // and function pointer decay; seeing that an argument intended to be a
6352   // string has type 'char [6]' is probably more confusing than 'char *'.
6353   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6354     if (ICE->getCastKind() == CK_IntegralCast ||
6355         ICE->getCastKind() == CK_FloatingCast) {
6356       E = ICE->getSubExpr();
6357       ExprTy = E->getType();
6358 
6359       // Check if we didn't match because of an implicit cast from a 'char'
6360       // or 'short' to an 'int'.  This is done because printf is a varargs
6361       // function.
6362       if (ICE->getType() == S.Context.IntTy ||
6363           ICE->getType() == S.Context.UnsignedIntTy) {
6364         // All further checking is done on the subexpression.
6365         if (AT.matchesType(S.Context, ExprTy))
6366           return true;
6367       }
6368     }
6369   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
6370     // Special case for 'a', which has type 'int' in C.
6371     // Note, however, that we do /not/ want to treat multibyte constants like
6372     // 'MooV' as characters! This form is deprecated but still exists.
6373     if (ExprTy == S.Context.IntTy)
6374       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6375         ExprTy = S.Context.CharTy;
6376   }
6377 
6378   // Look through enums to their underlying type.
6379   bool IsEnum = false;
6380   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
6381     ExprTy = EnumTy->getDecl()->getIntegerType();
6382     IsEnum = true;
6383   }
6384 
6385   // %C in an Objective-C context prints a unichar, not a wchar_t.
6386   // If the argument is an integer of some kind, believe the %C and suggest
6387   // a cast instead of changing the conversion specifier.
6388   QualType IntendedTy = ExprTy;
6389   if (isObjCContext() &&
6390       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
6391     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6392         !ExprTy->isCharType()) {
6393       // 'unichar' is defined as a typedef of unsigned short, but we should
6394       // prefer using the typedef if it is visible.
6395       IntendedTy = S.Context.UnsignedShortTy;
6396 
6397       // While we are here, check if the value is an IntegerLiteral that happens
6398       // to be within the valid range.
6399       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
6400         const llvm::APInt &V = IL->getValue();
6401         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6402           return true;
6403       }
6404 
6405       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
6406                           Sema::LookupOrdinaryName);
6407       if (S.LookupName(Result, S.getCurScope())) {
6408         NamedDecl *ND = Result.getFoundDecl();
6409         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
6410           if (TD->getUnderlyingType() == IntendedTy)
6411             IntendedTy = S.Context.getTypedefType(TD);
6412       }
6413     }
6414   }
6415 
6416   // Special-case some of Darwin's platform-independence types by suggesting
6417   // casts to primitive types that are known to be large enough.
6418   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
6419   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
6420     QualType CastTy;
6421     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
6422     if (!CastTy.isNull()) {
6423       IntendedTy = CastTy;
6424       ShouldNotPrintDirectly = true;
6425     }
6426   }
6427 
6428   // We may be able to offer a FixItHint if it is a supported type.
6429   PrintfSpecifier fixedFS = FS;
6430   bool success =
6431       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
6432 
6433   if (success) {
6434     // Get the fix string from the fixed format specifier
6435     SmallString<16> buf;
6436     llvm::raw_svector_ostream os(buf);
6437     fixedFS.toString(os);
6438 
6439     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6440 
6441     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
6442       unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6443       if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6444         diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6445       }
6446       // In this case, the specifier is wrong and should be changed to match
6447       // the argument.
6448       EmitFormatDiagnostic(S.PDiag(diag)
6449                                << AT.getRepresentativeTypeName(S.Context)
6450                                << IntendedTy << IsEnum << E->getSourceRange(),
6451                            E->getLocStart(),
6452                            /*IsStringLocation*/ false, SpecRange,
6453                            FixItHint::CreateReplacement(SpecRange, os.str()));
6454     } else {
6455       // The canonical type for formatting this value is different from the
6456       // actual type of the expression. (This occurs, for example, with Darwin's
6457       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6458       // should be printed as 'long' for 64-bit compatibility.)
6459       // Rather than emitting a normal format/argument mismatch, we want to
6460       // add a cast to the recommended type (and correct the format string
6461       // if necessary).
6462       SmallString<16> CastBuf;
6463       llvm::raw_svector_ostream CastFix(CastBuf);
6464       CastFix << "(";
6465       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6466       CastFix << ")";
6467 
6468       SmallVector<FixItHint,4> Hints;
6469       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
6470         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6471 
6472       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6473         // If there's already a cast present, just replace it.
6474         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6475         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6476 
6477       } else if (!requiresParensToAddCast(E)) {
6478         // If the expression has high enough precedence,
6479         // just write the C-style cast.
6480         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6481                                                    CastFix.str()));
6482       } else {
6483         // Otherwise, add parens around the expression as well as the cast.
6484         CastFix << "(";
6485         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6486                                                    CastFix.str()));
6487 
6488         SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
6489         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6490       }
6491 
6492       if (ShouldNotPrintDirectly) {
6493         // The expression has a type that should not be printed directly.
6494         // We extract the name from the typedef because we don't want to show
6495         // the underlying type in the diagnostic.
6496         StringRef Name;
6497         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6498           Name = TypedefTy->getDecl()->getName();
6499         else
6500           Name = CastTyName;
6501         EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
6502                                << Name << IntendedTy << IsEnum
6503                                << E->getSourceRange(),
6504                              E->getLocStart(), /*IsStringLocation=*/false,
6505                              SpecRange, Hints);
6506       } else {
6507         // In this case, the expression could be printed using a different
6508         // specifier, but we've decided that the specifier is probably correct
6509         // and we should cast instead. Just use the normal warning message.
6510         EmitFormatDiagnostic(
6511           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6512             << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
6513             << E->getSourceRange(),
6514           E->getLocStart(), /*IsStringLocation*/false,
6515           SpecRange, Hints);
6516       }
6517     }
6518   } else {
6519     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6520                                                    SpecifierLen);
6521     // Since the warning for passing non-POD types to variadic functions
6522     // was deferred until now, we emit a warning for non-POD
6523     // arguments here.
6524     switch (S.isValidVarArgType(ExprTy)) {
6525     case Sema::VAK_Valid:
6526     case Sema::VAK_ValidInCXX11: {
6527       unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6528       if (match == analyze_printf::ArgType::NoMatchPedantic) {
6529         diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6530       }
6531 
6532       EmitFormatDiagnostic(
6533           S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6534                         << IsEnum << CSR << E->getSourceRange(),
6535           E->getLocStart(), /*IsStringLocation*/ false, CSR);
6536       break;
6537     }
6538     case Sema::VAK_Undefined:
6539     case Sema::VAK_MSVCUndefined:
6540       EmitFormatDiagnostic(
6541         S.PDiag(diag::warn_non_pod_vararg_with_format_string)
6542           << S.getLangOpts().CPlusPlus11
6543           << ExprTy
6544           << CallType
6545           << AT.getRepresentativeTypeName(S.Context)
6546           << CSR
6547           << E->getSourceRange(),
6548         E->getLocStart(), /*IsStringLocation*/false, CSR);
6549       checkForCStrMembers(AT, E);
6550       break;
6551 
6552     case Sema::VAK_Invalid:
6553       if (ExprTy->isObjCObjectType())
6554         EmitFormatDiagnostic(
6555           S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6556             << S.getLangOpts().CPlusPlus11
6557             << ExprTy
6558             << CallType
6559             << AT.getRepresentativeTypeName(S.Context)
6560             << CSR
6561             << E->getSourceRange(),
6562           E->getLocStart(), /*IsStringLocation*/false, CSR);
6563       else
6564         // FIXME: If this is an initializer list, suggest removing the braces
6565         // or inserting a cast to the target type.
6566         S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6567           << isa<InitListExpr>(E) << ExprTy << CallType
6568           << AT.getRepresentativeTypeName(S.Context)
6569           << E->getSourceRange();
6570       break;
6571     }
6572 
6573     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6574            "format string specifier index out of range");
6575     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
6576   }
6577 
6578   return true;
6579 }
6580 
6581 //===--- CHECK: Scanf format string checking ------------------------------===//
6582 
6583 namespace {
6584 
6585 class CheckScanfHandler : public CheckFormatHandler {
6586 public:
6587   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
6588                     const Expr *origFormatExpr, Sema::FormatStringType type,
6589                     unsigned firstDataArg, unsigned numDataArgs,
6590                     const char *beg, bool hasVAListArg,
6591                     ArrayRef<const Expr *> Args, unsigned formatIdx,
6592                     bool inFunctionCall, Sema::VariadicCallType CallType,
6593                     llvm::SmallBitVector &CheckedVarArgs,
6594                     UncoveredArgHandler &UncoveredArg)
6595       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6596                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
6597                            inFunctionCall, CallType, CheckedVarArgs,
6598                            UncoveredArg) {}
6599 
6600   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6601                             const char *startSpecifier,
6602                             unsigned specifierLen) override;
6603 
6604   bool HandleInvalidScanfConversionSpecifier(
6605           const analyze_scanf::ScanfSpecifier &FS,
6606           const char *startSpecifier,
6607           unsigned specifierLen) override;
6608 
6609   void HandleIncompleteScanList(const char *start, const char *end) override;
6610 };
6611 
6612 } // namespace
6613 
6614 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6615                                                  const char *end) {
6616   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6617                        getLocationOfByte(end), /*IsStringLocation*/true,
6618                        getSpecifierRange(start, end - start));
6619 }
6620 
6621 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6622                                         const analyze_scanf::ScanfSpecifier &FS,
6623                                         const char *startSpecifier,
6624                                         unsigned specifierLen) {
6625   const analyze_scanf::ScanfConversionSpecifier &CS =
6626     FS.getConversionSpecifier();
6627 
6628   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6629                                           getLocationOfByte(CS.getStart()),
6630                                           startSpecifier, specifierLen,
6631                                           CS.getStart(), CS.getLength());
6632 }
6633 
6634 bool CheckScanfHandler::HandleScanfSpecifier(
6635                                        const analyze_scanf::ScanfSpecifier &FS,
6636                                        const char *startSpecifier,
6637                                        unsigned specifierLen) {
6638   using namespace analyze_scanf;
6639   using namespace analyze_format_string;
6640 
6641   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
6642 
6643   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
6644   // be used to decide if we are using positional arguments consistently.
6645   if (FS.consumesDataArgument()) {
6646     if (atFirstArg) {
6647       atFirstArg = false;
6648       usesPositionalArgs = FS.usesPositionalArg();
6649     }
6650     else if (usesPositionalArgs != FS.usesPositionalArg()) {
6651       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6652                                         startSpecifier, specifierLen);
6653       return false;
6654     }
6655   }
6656 
6657   // Check if the field with is non-zero.
6658   const OptionalAmount &Amt = FS.getFieldWidth();
6659   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6660     if (Amt.getConstantAmount() == 0) {
6661       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6662                                                    Amt.getConstantLength());
6663       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6664                            getLocationOfByte(Amt.getStart()),
6665                            /*IsStringLocation*/true, R,
6666                            FixItHint::CreateRemoval(R));
6667     }
6668   }
6669 
6670   if (!FS.consumesDataArgument()) {
6671     // FIXME: Technically specifying a precision or field width here
6672     // makes no sense.  Worth issuing a warning at some point.
6673     return true;
6674   }
6675 
6676   // Consume the argument.
6677   unsigned argIndex = FS.getArgIndex();
6678   if (argIndex < NumDataArgs) {
6679       // The check to see if the argIndex is valid will come later.
6680       // We set the bit here because we may exit early from this
6681       // function if we encounter some other error.
6682     CoveredArgs.set(argIndex);
6683   }
6684 
6685   // Check the length modifier is valid with the given conversion specifier.
6686   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
6687     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6688                                 diag::warn_format_nonsensical_length);
6689   else if (!FS.hasStandardLengthModifier())
6690     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
6691   else if (!FS.hasStandardLengthConversionCombination())
6692     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6693                                 diag::warn_format_non_standard_conversion_spec);
6694 
6695   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6696     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6697 
6698   // The remaining checks depend on the data arguments.
6699   if (HasVAListArg)
6700     return true;
6701 
6702   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
6703     return false;
6704 
6705   // Check that the argument type matches the format specifier.
6706   const Expr *Ex = getDataArg(argIndex);
6707   if (!Ex)
6708     return true;
6709 
6710   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
6711 
6712   if (!AT.isValid()) {
6713     return true;
6714   }
6715 
6716   analyze_format_string::ArgType::MatchKind match =
6717       AT.matchesType(S.Context, Ex->getType());
6718   if (match == analyze_format_string::ArgType::Match) {
6719     return true;
6720   }
6721 
6722   ScanfSpecifier fixedFS = FS;
6723   bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6724                                  S.getLangOpts(), S.Context);
6725 
6726   unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6727   if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6728     diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6729   }
6730 
6731   if (success) {
6732     // Get the fix string from the fixed format specifier.
6733     SmallString<128> buf;
6734     llvm::raw_svector_ostream os(buf);
6735     fixedFS.toString(os);
6736 
6737     EmitFormatDiagnostic(
6738         S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6739                       << Ex->getType() << false << Ex->getSourceRange(),
6740         Ex->getLocStart(),
6741         /*IsStringLocation*/ false,
6742         getSpecifierRange(startSpecifier, specifierLen),
6743         FixItHint::CreateReplacement(
6744             getSpecifierRange(startSpecifier, specifierLen), os.str()));
6745   } else {
6746     EmitFormatDiagnostic(S.PDiag(diag)
6747                              << AT.getRepresentativeTypeName(S.Context)
6748                              << Ex->getType() << false << Ex->getSourceRange(),
6749                          Ex->getLocStart(),
6750                          /*IsStringLocation*/ false,
6751                          getSpecifierRange(startSpecifier, specifierLen));
6752   }
6753 
6754   return true;
6755 }
6756 
6757 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6758                               const Expr *OrigFormatExpr,
6759                               ArrayRef<const Expr *> Args,
6760                               bool HasVAListArg, unsigned format_idx,
6761                               unsigned firstDataArg,
6762                               Sema::FormatStringType Type,
6763                               bool inFunctionCall,
6764                               Sema::VariadicCallType CallType,
6765                               llvm::SmallBitVector &CheckedVarArgs,
6766                               UncoveredArgHandler &UncoveredArg) {
6767   // CHECK: is the format string a wide literal?
6768   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
6769     CheckFormatHandler::EmitFormatDiagnostic(
6770       S, inFunctionCall, Args[format_idx],
6771       S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
6772       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
6773     return;
6774   }
6775 
6776   // Str - The format string.  NOTE: this is NOT null-terminated!
6777   StringRef StrRef = FExpr->getString();
6778   const char *Str = StrRef.data();
6779   // Account for cases where the string literal is truncated in a declaration.
6780   const ConstantArrayType *T =
6781     S.Context.getAsConstantArrayType(FExpr->getType());
6782   assert(T && "String literal not of constant array type!");
6783   size_t TypeSize = T->getSize().getZExtValue();
6784   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6785   const unsigned numDataArgs = Args.size() - firstDataArg;
6786 
6787   // Emit a warning if the string literal is truncated and does not contain an
6788   // embedded null character.
6789   if (TypeSize <= StrRef.size() &&
6790       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6791     CheckFormatHandler::EmitFormatDiagnostic(
6792         S, inFunctionCall, Args[format_idx],
6793         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
6794         FExpr->getLocStart(),
6795         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6796     return;
6797   }
6798 
6799   // CHECK: empty format string?
6800   if (StrLen == 0 && numDataArgs > 0) {
6801     CheckFormatHandler::EmitFormatDiagnostic(
6802       S, inFunctionCall, Args[format_idx],
6803       S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
6804       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
6805     return;
6806   }
6807 
6808   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
6809       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6810       Type == Sema::FST_OSTrace) {
6811     CheckPrintfHandler H(
6812         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6813         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6814         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6815         CheckedVarArgs, UncoveredArg);
6816 
6817     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
6818                                                   S.getLangOpts(),
6819                                                   S.Context.getTargetInfo(),
6820                                             Type == Sema::FST_FreeBSDKPrintf))
6821       H.DoneProcessing();
6822   } else if (Type == Sema::FST_Scanf) {
6823     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6824                         numDataArgs, Str, HasVAListArg, Args, format_idx,
6825                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
6826 
6827     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
6828                                                  S.getLangOpts(),
6829                                                  S.Context.getTargetInfo()))
6830       H.DoneProcessing();
6831   } // TODO: handle other formats
6832 }
6833 
6834 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6835   // Str - The format string.  NOTE: this is NOT null-terminated!
6836   StringRef StrRef = FExpr->getString();
6837   const char *Str = StrRef.data();
6838   // Account for cases where the string literal is truncated in a declaration.
6839   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6840   assert(T && "String literal not of constant array type!");
6841   size_t TypeSize = T->getSize().getZExtValue();
6842   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6843   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6844                                                          getLangOpts(),
6845                                                          Context.getTargetInfo());
6846 }
6847 
6848 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6849 
6850 // Returns the related absolute value function that is larger, of 0 if one
6851 // does not exist.
6852 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6853   switch (AbsFunction) {
6854   default:
6855     return 0;
6856 
6857   case Builtin::BI__builtin_abs:
6858     return Builtin::BI__builtin_labs;
6859   case Builtin::BI__builtin_labs:
6860     return Builtin::BI__builtin_llabs;
6861   case Builtin::BI__builtin_llabs:
6862     return 0;
6863 
6864   case Builtin::BI__builtin_fabsf:
6865     return Builtin::BI__builtin_fabs;
6866   case Builtin::BI__builtin_fabs:
6867     return Builtin::BI__builtin_fabsl;
6868   case Builtin::BI__builtin_fabsl:
6869     return 0;
6870 
6871   case Builtin::BI__builtin_cabsf:
6872     return Builtin::BI__builtin_cabs;
6873   case Builtin::BI__builtin_cabs:
6874     return Builtin::BI__builtin_cabsl;
6875   case Builtin::BI__builtin_cabsl:
6876     return 0;
6877 
6878   case Builtin::BIabs:
6879     return Builtin::BIlabs;
6880   case Builtin::BIlabs:
6881     return Builtin::BIllabs;
6882   case Builtin::BIllabs:
6883     return 0;
6884 
6885   case Builtin::BIfabsf:
6886     return Builtin::BIfabs;
6887   case Builtin::BIfabs:
6888     return Builtin::BIfabsl;
6889   case Builtin::BIfabsl:
6890     return 0;
6891 
6892   case Builtin::BIcabsf:
6893    return Builtin::BIcabs;
6894   case Builtin::BIcabs:
6895     return Builtin::BIcabsl;
6896   case Builtin::BIcabsl:
6897     return 0;
6898   }
6899 }
6900 
6901 // Returns the argument type of the absolute value function.
6902 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6903                                              unsigned AbsType) {
6904   if (AbsType == 0)
6905     return QualType();
6906 
6907   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6908   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6909   if (Error != ASTContext::GE_None)
6910     return QualType();
6911 
6912   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6913   if (!FT)
6914     return QualType();
6915 
6916   if (FT->getNumParams() != 1)
6917     return QualType();
6918 
6919   return FT->getParamType(0);
6920 }
6921 
6922 // Returns the best absolute value function, or zero, based on type and
6923 // current absolute value function.
6924 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6925                                    unsigned AbsFunctionKind) {
6926   unsigned BestKind = 0;
6927   uint64_t ArgSize = Context.getTypeSize(ArgType);
6928   for (unsigned Kind = AbsFunctionKind; Kind != 0;
6929        Kind = getLargerAbsoluteValueFunction(Kind)) {
6930     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6931     if (Context.getTypeSize(ParamType) >= ArgSize) {
6932       if (BestKind == 0)
6933         BestKind = Kind;
6934       else if (Context.hasSameType(ParamType, ArgType)) {
6935         BestKind = Kind;
6936         break;
6937       }
6938     }
6939   }
6940   return BestKind;
6941 }
6942 
6943 enum AbsoluteValueKind {
6944   AVK_Integer,
6945   AVK_Floating,
6946   AVK_Complex
6947 };
6948 
6949 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6950   if (T->isIntegralOrEnumerationType())
6951     return AVK_Integer;
6952   if (T->isRealFloatingType())
6953     return AVK_Floating;
6954   if (T->isAnyComplexType())
6955     return AVK_Complex;
6956 
6957   llvm_unreachable("Type not integer, floating, or complex");
6958 }
6959 
6960 // Changes the absolute value function to a different type.  Preserves whether
6961 // the function is a builtin.
6962 static unsigned changeAbsFunction(unsigned AbsKind,
6963                                   AbsoluteValueKind ValueKind) {
6964   switch (ValueKind) {
6965   case AVK_Integer:
6966     switch (AbsKind) {
6967     default:
6968       return 0;
6969     case Builtin::BI__builtin_fabsf:
6970     case Builtin::BI__builtin_fabs:
6971     case Builtin::BI__builtin_fabsl:
6972     case Builtin::BI__builtin_cabsf:
6973     case Builtin::BI__builtin_cabs:
6974     case Builtin::BI__builtin_cabsl:
6975       return Builtin::BI__builtin_abs;
6976     case Builtin::BIfabsf:
6977     case Builtin::BIfabs:
6978     case Builtin::BIfabsl:
6979     case Builtin::BIcabsf:
6980     case Builtin::BIcabs:
6981     case Builtin::BIcabsl:
6982       return Builtin::BIabs;
6983     }
6984   case AVK_Floating:
6985     switch (AbsKind) {
6986     default:
6987       return 0;
6988     case Builtin::BI__builtin_abs:
6989     case Builtin::BI__builtin_labs:
6990     case Builtin::BI__builtin_llabs:
6991     case Builtin::BI__builtin_cabsf:
6992     case Builtin::BI__builtin_cabs:
6993     case Builtin::BI__builtin_cabsl:
6994       return Builtin::BI__builtin_fabsf;
6995     case Builtin::BIabs:
6996     case Builtin::BIlabs:
6997     case Builtin::BIllabs:
6998     case Builtin::BIcabsf:
6999     case Builtin::BIcabs:
7000     case Builtin::BIcabsl:
7001       return Builtin::BIfabsf;
7002     }
7003   case AVK_Complex:
7004     switch (AbsKind) {
7005     default:
7006       return 0;
7007     case Builtin::BI__builtin_abs:
7008     case Builtin::BI__builtin_labs:
7009     case Builtin::BI__builtin_llabs:
7010     case Builtin::BI__builtin_fabsf:
7011     case Builtin::BI__builtin_fabs:
7012     case Builtin::BI__builtin_fabsl:
7013       return Builtin::BI__builtin_cabsf;
7014     case Builtin::BIabs:
7015     case Builtin::BIlabs:
7016     case Builtin::BIllabs:
7017     case Builtin::BIfabsf:
7018     case Builtin::BIfabs:
7019     case Builtin::BIfabsl:
7020       return Builtin::BIcabsf;
7021     }
7022   }
7023   llvm_unreachable("Unable to convert function");
7024 }
7025 
7026 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
7027   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
7028   if (!FnInfo)
7029     return 0;
7030 
7031   switch (FDecl->getBuiltinID()) {
7032   default:
7033     return 0;
7034   case Builtin::BI__builtin_abs:
7035   case Builtin::BI__builtin_fabs:
7036   case Builtin::BI__builtin_fabsf:
7037   case Builtin::BI__builtin_fabsl:
7038   case Builtin::BI__builtin_labs:
7039   case Builtin::BI__builtin_llabs:
7040   case Builtin::BI__builtin_cabs:
7041   case Builtin::BI__builtin_cabsf:
7042   case Builtin::BI__builtin_cabsl:
7043   case Builtin::BIabs:
7044   case Builtin::BIlabs:
7045   case Builtin::BIllabs:
7046   case Builtin::BIfabs:
7047   case Builtin::BIfabsf:
7048   case Builtin::BIfabsl:
7049   case Builtin::BIcabs:
7050   case Builtin::BIcabsf:
7051   case Builtin::BIcabsl:
7052     return FDecl->getBuiltinID();
7053   }
7054   llvm_unreachable("Unknown Builtin type");
7055 }
7056 
7057 // If the replacement is valid, emit a note with replacement function.
7058 // Additionally, suggest including the proper header if not already included.
7059 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
7060                             unsigned AbsKind, QualType ArgType) {
7061   bool EmitHeaderHint = true;
7062   const char *HeaderName = nullptr;
7063   const char *FunctionName = nullptr;
7064   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
7065     FunctionName = "std::abs";
7066     if (ArgType->isIntegralOrEnumerationType()) {
7067       HeaderName = "cstdlib";
7068     } else if (ArgType->isRealFloatingType()) {
7069       HeaderName = "cmath";
7070     } else {
7071       llvm_unreachable("Invalid Type");
7072     }
7073 
7074     // Lookup all std::abs
7075     if (NamespaceDecl *Std = S.getStdNamespace()) {
7076       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
7077       R.suppressDiagnostics();
7078       S.LookupQualifiedName(R, Std);
7079 
7080       for (const auto *I : R) {
7081         const FunctionDecl *FDecl = nullptr;
7082         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
7083           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
7084         } else {
7085           FDecl = dyn_cast<FunctionDecl>(I);
7086         }
7087         if (!FDecl)
7088           continue;
7089 
7090         // Found std::abs(), check that they are the right ones.
7091         if (FDecl->getNumParams() != 1)
7092           continue;
7093 
7094         // Check that the parameter type can handle the argument.
7095         QualType ParamType = FDecl->getParamDecl(0)->getType();
7096         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
7097             S.Context.getTypeSize(ArgType) <=
7098                 S.Context.getTypeSize(ParamType)) {
7099           // Found a function, don't need the header hint.
7100           EmitHeaderHint = false;
7101           break;
7102         }
7103       }
7104     }
7105   } else {
7106     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
7107     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
7108 
7109     if (HeaderName) {
7110       DeclarationName DN(&S.Context.Idents.get(FunctionName));
7111       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
7112       R.suppressDiagnostics();
7113       S.LookupName(R, S.getCurScope());
7114 
7115       if (R.isSingleResult()) {
7116         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
7117         if (FD && FD->getBuiltinID() == AbsKind) {
7118           EmitHeaderHint = false;
7119         } else {
7120           return;
7121         }
7122       } else if (!R.empty()) {
7123         return;
7124       }
7125     }
7126   }
7127 
7128   S.Diag(Loc, diag::note_replace_abs_function)
7129       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
7130 
7131   if (!HeaderName)
7132     return;
7133 
7134   if (!EmitHeaderHint)
7135     return;
7136 
7137   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
7138                                                     << FunctionName;
7139 }
7140 
7141 template <std::size_t StrLen>
7142 static bool IsStdFunction(const FunctionDecl *FDecl,
7143                           const char (&Str)[StrLen]) {
7144   if (!FDecl)
7145     return false;
7146   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
7147     return false;
7148   if (!FDecl->isInStdNamespace())
7149     return false;
7150 
7151   return true;
7152 }
7153 
7154 // Warn when using the wrong abs() function.
7155 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
7156                                       const FunctionDecl *FDecl) {
7157   if (Call->getNumArgs() != 1)
7158     return;
7159 
7160   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
7161   bool IsStdAbs = IsStdFunction(FDecl, "abs");
7162   if (AbsKind == 0 && !IsStdAbs)
7163     return;
7164 
7165   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7166   QualType ParamType = Call->getArg(0)->getType();
7167 
7168   // Unsigned types cannot be negative.  Suggest removing the absolute value
7169   // function call.
7170   if (ArgType->isUnsignedIntegerType()) {
7171     const char *FunctionName =
7172         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
7173     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
7174     Diag(Call->getExprLoc(), diag::note_remove_abs)
7175         << FunctionName
7176         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
7177     return;
7178   }
7179 
7180   // Taking the absolute value of a pointer is very suspicious, they probably
7181   // wanted to index into an array, dereference a pointer, call a function, etc.
7182   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
7183     unsigned DiagType = 0;
7184     if (ArgType->isFunctionType())
7185       DiagType = 1;
7186     else if (ArgType->isArrayType())
7187       DiagType = 2;
7188 
7189     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
7190     return;
7191   }
7192 
7193   // std::abs has overloads which prevent most of the absolute value problems
7194   // from occurring.
7195   if (IsStdAbs)
7196     return;
7197 
7198   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
7199   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
7200 
7201   // The argument and parameter are the same kind.  Check if they are the right
7202   // size.
7203   if (ArgValueKind == ParamValueKind) {
7204     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
7205       return;
7206 
7207     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
7208     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
7209         << FDecl << ArgType << ParamType;
7210 
7211     if (NewAbsKind == 0)
7212       return;
7213 
7214     emitReplacement(*this, Call->getExprLoc(),
7215                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
7216     return;
7217   }
7218 
7219   // ArgValueKind != ParamValueKind
7220   // The wrong type of absolute value function was used.  Attempt to find the
7221   // proper one.
7222   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
7223   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
7224   if (NewAbsKind == 0)
7225     return;
7226 
7227   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
7228       << FDecl << ParamValueKind << ArgValueKind;
7229 
7230   emitReplacement(*this, Call->getExprLoc(),
7231                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
7232 }
7233 
7234 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
7235 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
7236                                 const FunctionDecl *FDecl) {
7237   if (!Call || !FDecl) return;
7238 
7239   // Ignore template specializations and macros.
7240   if (inTemplateInstantiation()) return;
7241   if (Call->getExprLoc().isMacroID()) return;
7242 
7243   // Only care about the one template argument, two function parameter std::max
7244   if (Call->getNumArgs() != 2) return;
7245   if (!IsStdFunction(FDecl, "max")) return;
7246   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
7247   if (!ArgList) return;
7248   if (ArgList->size() != 1) return;
7249 
7250   // Check that template type argument is unsigned integer.
7251   const auto& TA = ArgList->get(0);
7252   if (TA.getKind() != TemplateArgument::Type) return;
7253   QualType ArgType = TA.getAsType();
7254   if (!ArgType->isUnsignedIntegerType()) return;
7255 
7256   // See if either argument is a literal zero.
7257   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
7258     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
7259     if (!MTE) return false;
7260     const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
7261     if (!Num) return false;
7262     if (Num->getValue() != 0) return false;
7263     return true;
7264   };
7265 
7266   const Expr *FirstArg = Call->getArg(0);
7267   const Expr *SecondArg = Call->getArg(1);
7268   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
7269   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
7270 
7271   // Only warn when exactly one argument is zero.
7272   if (IsFirstArgZero == IsSecondArgZero) return;
7273 
7274   SourceRange FirstRange = FirstArg->getSourceRange();
7275   SourceRange SecondRange = SecondArg->getSourceRange();
7276 
7277   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
7278 
7279   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
7280       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
7281 
7282   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
7283   SourceRange RemovalRange;
7284   if (IsFirstArgZero) {
7285     RemovalRange = SourceRange(FirstRange.getBegin(),
7286                                SecondRange.getBegin().getLocWithOffset(-1));
7287   } else {
7288     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
7289                                SecondRange.getEnd());
7290   }
7291 
7292   Diag(Call->getExprLoc(), diag::note_remove_max_call)
7293         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
7294         << FixItHint::CreateRemoval(RemovalRange);
7295 }
7296 
7297 //===--- CHECK: Standard memory functions ---------------------------------===//
7298 
7299 /// \brief Takes the expression passed to the size_t parameter of functions
7300 /// such as memcmp, strncat, etc and warns if it's a comparison.
7301 ///
7302 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
7303 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
7304                                            IdentifierInfo *FnName,
7305                                            SourceLocation FnLoc,
7306                                            SourceLocation RParenLoc) {
7307   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
7308   if (!Size)
7309     return false;
7310 
7311   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
7312   if (!Size->isComparisonOp() && !Size->isLogicalOp())
7313     return false;
7314 
7315   SourceRange SizeRange = Size->getSourceRange();
7316   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
7317       << SizeRange << FnName;
7318   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
7319       << FnName << FixItHint::CreateInsertion(
7320                        S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
7321       << FixItHint::CreateRemoval(RParenLoc);
7322   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
7323       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
7324       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
7325                                     ")");
7326 
7327   return true;
7328 }
7329 
7330 /// \brief Determine whether the given type is or contains a dynamic class type
7331 /// (e.g., whether it has a vtable).
7332 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
7333                                                      bool &IsContained) {
7334   // Look through array types while ignoring qualifiers.
7335   const Type *Ty = T->getBaseElementTypeUnsafe();
7336   IsContained = false;
7337 
7338   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
7339   RD = RD ? RD->getDefinition() : nullptr;
7340   if (!RD || RD->isInvalidDecl())
7341     return nullptr;
7342 
7343   if (RD->isDynamicClass())
7344     return RD;
7345 
7346   // Check all the fields.  If any bases were dynamic, the class is dynamic.
7347   // It's impossible for a class to transitively contain itself by value, so
7348   // infinite recursion is impossible.
7349   for (auto *FD : RD->fields()) {
7350     bool SubContained;
7351     if (const CXXRecordDecl *ContainedRD =
7352             getContainedDynamicClass(FD->getType(), SubContained)) {
7353       IsContained = true;
7354       return ContainedRD;
7355     }
7356   }
7357 
7358   return nullptr;
7359 }
7360 
7361 /// \brief If E is a sizeof expression, returns its argument expression,
7362 /// otherwise returns NULL.
7363 static const Expr *getSizeOfExprArg(const Expr *E) {
7364   if (const UnaryExprOrTypeTraitExpr *SizeOf =
7365       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7366     if (SizeOf->getKind() == UETT_SizeOf && !SizeOf->isArgumentType())
7367       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
7368 
7369   return nullptr;
7370 }
7371 
7372 /// \brief If E is a sizeof expression, returns its argument type.
7373 static QualType getSizeOfArgType(const Expr *E) {
7374   if (const UnaryExprOrTypeTraitExpr *SizeOf =
7375       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7376     if (SizeOf->getKind() == UETT_SizeOf)
7377       return SizeOf->getTypeOfArgument();
7378 
7379   return QualType();
7380 }
7381 
7382 namespace {
7383 
7384 struct SearchNonTrivialToInitializeField
7385     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
7386   using Super =
7387       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
7388 
7389   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
7390 
7391   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
7392                      SourceLocation SL) {
7393     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
7394       asDerived().visitArray(PDIK, AT, SL);
7395       return;
7396     }
7397 
7398     Super::visitWithKind(PDIK, FT, SL);
7399   }
7400 
7401   void visitARCStrong(QualType FT, SourceLocation SL) {
7402     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
7403   }
7404   void visitARCWeak(QualType FT, SourceLocation SL) {
7405     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
7406   }
7407   void visitStruct(QualType FT, SourceLocation SL) {
7408     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
7409       visit(FD->getType(), FD->getLocation());
7410   }
7411   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
7412                   const ArrayType *AT, SourceLocation SL) {
7413     visit(getContext().getBaseElementType(AT), SL);
7414   }
7415   void visitTrivial(QualType FT, SourceLocation SL) {}
7416 
7417   static void diag(QualType RT, const Expr *E, Sema &S) {
7418     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
7419   }
7420 
7421   ASTContext &getContext() { return S.getASTContext(); }
7422 
7423   const Expr *E;
7424   Sema &S;
7425 };
7426 
7427 struct SearchNonTrivialToCopyField
7428     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
7429   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
7430 
7431   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
7432 
7433   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
7434                      SourceLocation SL) {
7435     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
7436       asDerived().visitArray(PCK, AT, SL);
7437       return;
7438     }
7439 
7440     Super::visitWithKind(PCK, FT, SL);
7441   }
7442 
7443   void visitARCStrong(QualType FT, SourceLocation SL) {
7444     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
7445   }
7446   void visitARCWeak(QualType FT, SourceLocation SL) {
7447     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
7448   }
7449   void visitStruct(QualType FT, SourceLocation SL) {
7450     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
7451       visit(FD->getType(), FD->getLocation());
7452   }
7453   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
7454                   SourceLocation SL) {
7455     visit(getContext().getBaseElementType(AT), SL);
7456   }
7457   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
7458                 SourceLocation SL) {}
7459   void visitTrivial(QualType FT, SourceLocation SL) {}
7460   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
7461 
7462   static void diag(QualType RT, const Expr *E, Sema &S) {
7463     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
7464   }
7465 
7466   ASTContext &getContext() { return S.getASTContext(); }
7467 
7468   const Expr *E;
7469   Sema &S;
7470 };
7471 
7472 }
7473 
7474 /// \brief Check for dangerous or invalid arguments to memset().
7475 ///
7476 /// This issues warnings on known problematic, dangerous or unspecified
7477 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
7478 /// function calls.
7479 ///
7480 /// \param Call The call expression to diagnose.
7481 void Sema::CheckMemaccessArguments(const CallExpr *Call,
7482                                    unsigned BId,
7483                                    IdentifierInfo *FnName) {
7484   assert(BId != 0);
7485 
7486   // It is possible to have a non-standard definition of memset.  Validate
7487   // we have enough arguments, and if not, abort further checking.
7488   unsigned ExpectedNumArgs =
7489       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
7490   if (Call->getNumArgs() < ExpectedNumArgs)
7491     return;
7492 
7493   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
7494                       BId == Builtin::BIstrndup ? 1 : 2);
7495   unsigned LenArg =
7496       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
7497   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
7498 
7499   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
7500                                      Call->getLocStart(), Call->getRParenLoc()))
7501     return;
7502 
7503   // We have special checking when the length is a sizeof expression.
7504   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
7505   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
7506   llvm::FoldingSetNodeID SizeOfArgID;
7507 
7508   // Although widely used, 'bzero' is not a standard function. Be more strict
7509   // with the argument types before allowing diagnostics and only allow the
7510   // form bzero(ptr, sizeof(...)).
7511   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7512   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
7513     return;
7514 
7515   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7516     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
7517     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
7518 
7519     QualType DestTy = Dest->getType();
7520     QualType PointeeTy;
7521     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
7522       PointeeTy = DestPtrTy->getPointeeType();
7523 
7524       // Never warn about void type pointers. This can be used to suppress
7525       // false positives.
7526       if (PointeeTy->isVoidType())
7527         continue;
7528 
7529       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
7530       // actually comparing the expressions for equality. Because computing the
7531       // expression IDs can be expensive, we only do this if the diagnostic is
7532       // enabled.
7533       if (SizeOfArg &&
7534           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
7535                            SizeOfArg->getExprLoc())) {
7536         // We only compute IDs for expressions if the warning is enabled, and
7537         // cache the sizeof arg's ID.
7538         if (SizeOfArgID == llvm::FoldingSetNodeID())
7539           SizeOfArg->Profile(SizeOfArgID, Context, true);
7540         llvm::FoldingSetNodeID DestID;
7541         Dest->Profile(DestID, Context, true);
7542         if (DestID == SizeOfArgID) {
7543           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
7544           //       over sizeof(src) as well.
7545           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
7546           StringRef ReadableName = FnName->getName();
7547 
7548           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
7549             if (UnaryOp->getOpcode() == UO_AddrOf)
7550               ActionIdx = 1; // If its an address-of operator, just remove it.
7551           if (!PointeeTy->isIncompleteType() &&
7552               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
7553             ActionIdx = 2; // If the pointee's size is sizeof(char),
7554                            // suggest an explicit length.
7555 
7556           // If the function is defined as a builtin macro, do not show macro
7557           // expansion.
7558           SourceLocation SL = SizeOfArg->getExprLoc();
7559           SourceRange DSR = Dest->getSourceRange();
7560           SourceRange SSR = SizeOfArg->getSourceRange();
7561           SourceManager &SM = getSourceManager();
7562 
7563           if (SM.isMacroArgExpansion(SL)) {
7564             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7565             SL = SM.getSpellingLoc(SL);
7566             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7567                              SM.getSpellingLoc(DSR.getEnd()));
7568             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7569                              SM.getSpellingLoc(SSR.getEnd()));
7570           }
7571 
7572           DiagRuntimeBehavior(SL, SizeOfArg,
7573                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
7574                                 << ReadableName
7575                                 << PointeeTy
7576                                 << DestTy
7577                                 << DSR
7578                                 << SSR);
7579           DiagRuntimeBehavior(SL, SizeOfArg,
7580                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7581                                 << ActionIdx
7582                                 << SSR);
7583 
7584           break;
7585         }
7586       }
7587 
7588       // Also check for cases where the sizeof argument is the exact same
7589       // type as the memory argument, and where it points to a user-defined
7590       // record type.
7591       if (SizeOfArgTy != QualType()) {
7592         if (PointeeTy->isRecordType() &&
7593             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7594           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7595                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
7596                                 << FnName << SizeOfArgTy << ArgIdx
7597                                 << PointeeTy << Dest->getSourceRange()
7598                                 << LenExpr->getSourceRange());
7599           break;
7600         }
7601       }
7602     } else if (DestTy->isArrayType()) {
7603       PointeeTy = DestTy;
7604     }
7605 
7606     if (PointeeTy == QualType())
7607       continue;
7608 
7609     // Always complain about dynamic classes.
7610     bool IsContained;
7611     if (const CXXRecordDecl *ContainedRD =
7612             getContainedDynamicClass(PointeeTy, IsContained)) {
7613 
7614       unsigned OperationType = 0;
7615       // "overwritten" if we're warning about the destination for any call
7616       // but memcmp; otherwise a verb appropriate to the call.
7617       if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7618         if (BId == Builtin::BImemcpy)
7619           OperationType = 1;
7620         else if(BId == Builtin::BImemmove)
7621           OperationType = 2;
7622         else if (BId == Builtin::BImemcmp)
7623           OperationType = 3;
7624       }
7625 
7626       DiagRuntimeBehavior(
7627         Dest->getExprLoc(), Dest,
7628         PDiag(diag::warn_dyn_class_memaccess)
7629           << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7630           << FnName << IsContained << ContainedRD << OperationType
7631           << Call->getCallee()->getSourceRange());
7632     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7633              BId != Builtin::BImemset)
7634       DiagRuntimeBehavior(
7635         Dest->getExprLoc(), Dest,
7636         PDiag(diag::warn_arc_object_memaccess)
7637           << ArgIdx << FnName << PointeeTy
7638           << Call->getCallee()->getSourceRange());
7639     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
7640       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
7641           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
7642         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
7643                             PDiag(diag::warn_cstruct_memaccess)
7644                                 << ArgIdx << FnName << PointeeTy << 0);
7645         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
7646       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
7647                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
7648         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
7649                             PDiag(diag::warn_cstruct_memaccess)
7650                                 << ArgIdx << FnName << PointeeTy << 1);
7651         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
7652       } else {
7653         continue;
7654       }
7655     } else
7656       continue;
7657 
7658     DiagRuntimeBehavior(
7659       Dest->getExprLoc(), Dest,
7660       PDiag(diag::note_bad_memaccess_silence)
7661         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7662     break;
7663   }
7664 }
7665 
7666 // A little helper routine: ignore addition and subtraction of integer literals.
7667 // This intentionally does not ignore all integer constant expressions because
7668 // we don't want to remove sizeof().
7669 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7670   Ex = Ex->IgnoreParenCasts();
7671 
7672   while (true) {
7673     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7674     if (!BO || !BO->isAdditiveOp())
7675       break;
7676 
7677     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7678     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7679 
7680     if (isa<IntegerLiteral>(RHS))
7681       Ex = LHS;
7682     else if (isa<IntegerLiteral>(LHS))
7683       Ex = RHS;
7684     else
7685       break;
7686   }
7687 
7688   return Ex;
7689 }
7690 
7691 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7692                                                       ASTContext &Context) {
7693   // Only handle constant-sized or VLAs, but not flexible members.
7694   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7695     // Only issue the FIXIT for arrays of size > 1.
7696     if (CAT->getSize().getSExtValue() <= 1)
7697       return false;
7698   } else if (!Ty->isVariableArrayType()) {
7699     return false;
7700   }
7701   return true;
7702 }
7703 
7704 // Warn if the user has made the 'size' argument to strlcpy or strlcat
7705 // be the size of the source, instead of the destination.
7706 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7707                                     IdentifierInfo *FnName) {
7708 
7709   // Don't crash if the user has the wrong number of arguments
7710   unsigned NumArgs = Call->getNumArgs();
7711   if ((NumArgs != 3) && (NumArgs != 4))
7712     return;
7713 
7714   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7715   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
7716   const Expr *CompareWithSrc = nullptr;
7717 
7718   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7719                                      Call->getLocStart(), Call->getRParenLoc()))
7720     return;
7721 
7722   // Look for 'strlcpy(dst, x, sizeof(x))'
7723   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7724     CompareWithSrc = Ex;
7725   else {
7726     // Look for 'strlcpy(dst, x, strlen(x))'
7727     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
7728       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7729           SizeCall->getNumArgs() == 1)
7730         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7731     }
7732   }
7733 
7734   if (!CompareWithSrc)
7735     return;
7736 
7737   // Determine if the argument to sizeof/strlen is equal to the source
7738   // argument.  In principle there's all kinds of things you could do
7739   // here, for instance creating an == expression and evaluating it with
7740   // EvaluateAsBooleanCondition, but this uses a more direct technique:
7741   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7742   if (!SrcArgDRE)
7743     return;
7744 
7745   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7746   if (!CompareWithSrcDRE ||
7747       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7748     return;
7749 
7750   const Expr *OriginalSizeArg = Call->getArg(2);
7751   Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7752     << OriginalSizeArg->getSourceRange() << FnName;
7753 
7754   // Output a FIXIT hint if the destination is an array (rather than a
7755   // pointer to an array).  This could be enhanced to handle some
7756   // pointers if we know the actual size, like if DstArg is 'array+2'
7757   // we could say 'sizeof(array)-2'.
7758   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
7759   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
7760     return;
7761 
7762   SmallString<128> sizeString;
7763   llvm::raw_svector_ostream OS(sizeString);
7764   OS << "sizeof(";
7765   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7766   OS << ")";
7767 
7768   Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7769     << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7770                                     OS.str());
7771 }
7772 
7773 /// Check if two expressions refer to the same declaration.
7774 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7775   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7776     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7777       return D1->getDecl() == D2->getDecl();
7778   return false;
7779 }
7780 
7781 static const Expr *getStrlenExprArg(const Expr *E) {
7782   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7783     const FunctionDecl *FD = CE->getDirectCallee();
7784     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
7785       return nullptr;
7786     return CE->getArg(0)->IgnoreParenCasts();
7787   }
7788   return nullptr;
7789 }
7790 
7791 // Warn on anti-patterns as the 'size' argument to strncat.
7792 // The correct size argument should look like following:
7793 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7794 void Sema::CheckStrncatArguments(const CallExpr *CE,
7795                                  IdentifierInfo *FnName) {
7796   // Don't crash if the user has the wrong number of arguments.
7797   if (CE->getNumArgs() < 3)
7798     return;
7799   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7800   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7801   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7802 
7803   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7804                                      CE->getRParenLoc()))
7805     return;
7806 
7807   // Identify common expressions, which are wrongly used as the size argument
7808   // to strncat and may lead to buffer overflows.
7809   unsigned PatternType = 0;
7810   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7811     // - sizeof(dst)
7812     if (referToTheSameDecl(SizeOfArg, DstArg))
7813       PatternType = 1;
7814     // - sizeof(src)
7815     else if (referToTheSameDecl(SizeOfArg, SrcArg))
7816       PatternType = 2;
7817   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7818     if (BE->getOpcode() == BO_Sub) {
7819       const Expr *L = BE->getLHS()->IgnoreParenCasts();
7820       const Expr *R = BE->getRHS()->IgnoreParenCasts();
7821       // - sizeof(dst) - strlen(dst)
7822       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7823           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7824         PatternType = 1;
7825       // - sizeof(src) - (anything)
7826       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7827         PatternType = 2;
7828     }
7829   }
7830 
7831   if (PatternType == 0)
7832     return;
7833 
7834   // Generate the diagnostic.
7835   SourceLocation SL = LenArg->getLocStart();
7836   SourceRange SR = LenArg->getSourceRange();
7837   SourceManager &SM = getSourceManager();
7838 
7839   // If the function is defined as a builtin macro, do not show macro expansion.
7840   if (SM.isMacroArgExpansion(SL)) {
7841     SL = SM.getSpellingLoc(SL);
7842     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7843                      SM.getSpellingLoc(SR.getEnd()));
7844   }
7845 
7846   // Check if the destination is an array (rather than a pointer to an array).
7847   QualType DstTy = DstArg->getType();
7848   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7849                                                                     Context);
7850   if (!isKnownSizeArray) {
7851     if (PatternType == 1)
7852       Diag(SL, diag::warn_strncat_wrong_size) << SR;
7853     else
7854       Diag(SL, diag::warn_strncat_src_size) << SR;
7855     return;
7856   }
7857 
7858   if (PatternType == 1)
7859     Diag(SL, diag::warn_strncat_large_size) << SR;
7860   else
7861     Diag(SL, diag::warn_strncat_src_size) << SR;
7862 
7863   SmallString<128> sizeString;
7864   llvm::raw_svector_ostream OS(sizeString);
7865   OS << "sizeof(";
7866   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7867   OS << ") - ";
7868   OS << "strlen(";
7869   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7870   OS << ") - 1";
7871 
7872   Diag(SL, diag::note_strncat_wrong_size)
7873     << FixItHint::CreateReplacement(SR, OS.str());
7874 }
7875 
7876 //===--- CHECK: Return Address of Stack Variable --------------------------===//
7877 
7878 static const Expr *EvalVal(const Expr *E,
7879                            SmallVectorImpl<const DeclRefExpr *> &refVars,
7880                            const Decl *ParentDecl);
7881 static const Expr *EvalAddr(const Expr *E,
7882                             SmallVectorImpl<const DeclRefExpr *> &refVars,
7883                             const Decl *ParentDecl);
7884 
7885 /// CheckReturnStackAddr - Check if a return statement returns the address
7886 ///   of a stack variable.
7887 static void
7888 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7889                      SourceLocation ReturnLoc) {
7890   const Expr *stackE = nullptr;
7891   SmallVector<const DeclRefExpr *, 8> refVars;
7892 
7893   // Perform checking for returned stack addresses, local blocks,
7894   // label addresses or references to temporaries.
7895   if (lhsType->isPointerType() ||
7896       (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
7897     stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
7898   } else if (lhsType->isReferenceType()) {
7899     stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
7900   }
7901 
7902   if (!stackE)
7903     return; // Nothing suspicious was found.
7904 
7905   // Parameters are initialized in the calling scope, so taking the address
7906   // of a parameter reference doesn't need a warning.
7907   for (auto *DRE : refVars)
7908     if (isa<ParmVarDecl>(DRE->getDecl()))
7909       return;
7910 
7911   SourceLocation diagLoc;
7912   SourceRange diagRange;
7913   if (refVars.empty()) {
7914     diagLoc = stackE->getLocStart();
7915     diagRange = stackE->getSourceRange();
7916   } else {
7917     // We followed through a reference variable. 'stackE' contains the
7918     // problematic expression but we will warn at the return statement pointing
7919     // at the reference variable. We will later display the "trail" of
7920     // reference variables using notes.
7921     diagLoc = refVars[0]->getLocStart();
7922     diagRange = refVars[0]->getSourceRange();
7923   }
7924 
7925   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7926     // address of local var
7927     S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
7928      << DR->getDecl()->getDeclName() << diagRange;
7929   } else if (isa<BlockExpr>(stackE)) { // local block.
7930     S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
7931   } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
7932     S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
7933   } else { // local temporary.
7934     // If there is an LValue->RValue conversion, then the value of the
7935     // reference type is used, not the reference.
7936     if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7937       if (ICE->getCastKind() == CK_LValueToRValue) {
7938         return;
7939       }
7940     }
7941     S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7942      << lhsType->isReferenceType() << diagRange;
7943   }
7944 
7945   // Display the "trail" of reference variables that we followed until we
7946   // found the problematic expression using notes.
7947   for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
7948     const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
7949     // If this var binds to another reference var, show the range of the next
7950     // var, otherwise the var binds to the problematic expression, in which case
7951     // show the range of the expression.
7952     SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7953                                     : stackE->getSourceRange();
7954     S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7955         << VD->getDeclName() << range;
7956   }
7957 }
7958 
7959 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7960 ///  check if the expression in a return statement evaluates to an address
7961 ///  to a location on the stack, a local block, an address of a label, or a
7962 ///  reference to local temporary. The recursion is used to traverse the
7963 ///  AST of the return expression, with recursion backtracking when we
7964 ///  encounter a subexpression that (1) clearly does not lead to one of the
7965 ///  above problematic expressions (2) is something we cannot determine leads to
7966 ///  a problematic expression based on such local checking.
7967 ///
7968 ///  Both EvalAddr and EvalVal follow through reference variables to evaluate
7969 ///  the expression that they point to. Such variables are added to the
7970 ///  'refVars' vector so that we know what the reference variable "trail" was.
7971 ///
7972 ///  EvalAddr processes expressions that are pointers that are used as
7973 ///  references (and not L-values).  EvalVal handles all other values.
7974 ///  At the base case of the recursion is a check for the above problematic
7975 ///  expressions.
7976 ///
7977 ///  This implementation handles:
7978 ///
7979 ///   * pointer-to-pointer casts
7980 ///   * implicit conversions from array references to pointers
7981 ///   * taking the address of fields
7982 ///   * arbitrary interplay between "&" and "*" operators
7983 ///   * pointer arithmetic from an address of a stack variable
7984 ///   * taking the address of an array element where the array is on the stack
7985 static const Expr *EvalAddr(const Expr *E,
7986                             SmallVectorImpl<const DeclRefExpr *> &refVars,
7987                             const Decl *ParentDecl) {
7988   if (E->isTypeDependent())
7989     return nullptr;
7990 
7991   // We should only be called for evaluating pointer expressions.
7992   assert((E->getType()->isAnyPointerType() ||
7993           E->getType()->isBlockPointerType() ||
7994           E->getType()->isObjCQualifiedIdType()) &&
7995          "EvalAddr only works on pointers");
7996 
7997   E = E->IgnoreParens();
7998 
7999   // Our "symbolic interpreter" is just a dispatch off the currently
8000   // viewed AST node.  We then recursively traverse the AST by calling
8001   // EvalAddr and EvalVal appropriately.
8002   switch (E->getStmtClass()) {
8003   case Stmt::DeclRefExprClass: {
8004     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
8005 
8006     // If we leave the immediate function, the lifetime isn't about to end.
8007     if (DR->refersToEnclosingVariableOrCapture())
8008       return nullptr;
8009 
8010     if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
8011       // If this is a reference variable, follow through to the expression that
8012       // it points to.
8013       if (V->hasLocalStorage() &&
8014           V->getType()->isReferenceType() && V->hasInit()) {
8015         // Add the reference variable to the "trail".
8016         refVars.push_back(DR);
8017         return EvalAddr(V->getInit(), refVars, ParentDecl);
8018       }
8019 
8020     return nullptr;
8021   }
8022 
8023   case Stmt::UnaryOperatorClass: {
8024     // The only unary operator that make sense to handle here
8025     // is AddrOf.  All others don't make sense as pointers.
8026     const UnaryOperator *U = cast<UnaryOperator>(E);
8027 
8028     if (U->getOpcode() == UO_AddrOf)
8029       return EvalVal(U->getSubExpr(), refVars, ParentDecl);
8030     return nullptr;
8031   }
8032 
8033   case Stmt::BinaryOperatorClass: {
8034     // Handle pointer arithmetic.  All other binary operators are not valid
8035     // in this context.
8036     const BinaryOperator *B = cast<BinaryOperator>(E);
8037     BinaryOperatorKind op = B->getOpcode();
8038 
8039     if (op != BO_Add && op != BO_Sub)
8040       return nullptr;
8041 
8042     const Expr *Base = B->getLHS();
8043 
8044     // Determine which argument is the real pointer base.  It could be
8045     // the RHS argument instead of the LHS.
8046     if (!Base->getType()->isPointerType())
8047       Base = B->getRHS();
8048 
8049     assert(Base->getType()->isPointerType());
8050     return EvalAddr(Base, refVars, ParentDecl);
8051   }
8052 
8053   // For conditional operators we need to see if either the LHS or RHS are
8054   // valid DeclRefExpr*s.  If one of them is valid, we return it.
8055   case Stmt::ConditionalOperatorClass: {
8056     const ConditionalOperator *C = cast<ConditionalOperator>(E);
8057 
8058     // Handle the GNU extension for missing LHS.
8059     // FIXME: That isn't a ConditionalOperator, so doesn't get here.
8060     if (const Expr *LHSExpr = C->getLHS()) {
8061       // In C++, we can have a throw-expression, which has 'void' type.
8062       if (!LHSExpr->getType()->isVoidType())
8063         if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
8064           return LHS;
8065     }
8066 
8067     // In C++, we can have a throw-expression, which has 'void' type.
8068     if (C->getRHS()->getType()->isVoidType())
8069       return nullptr;
8070 
8071     return EvalAddr(C->getRHS(), refVars, ParentDecl);
8072   }
8073 
8074   case Stmt::BlockExprClass:
8075     if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
8076       return E; // local block.
8077     return nullptr;
8078 
8079   case Stmt::AddrLabelExprClass:
8080     return E; // address of label.
8081 
8082   case Stmt::ExprWithCleanupsClass:
8083     return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
8084                     ParentDecl);
8085 
8086   // For casts, we need to handle conversions from arrays to
8087   // pointer values, and pointer-to-pointer conversions.
8088   case Stmt::ImplicitCastExprClass:
8089   case Stmt::CStyleCastExprClass:
8090   case Stmt::CXXFunctionalCastExprClass:
8091   case Stmt::ObjCBridgedCastExprClass:
8092   case Stmt::CXXStaticCastExprClass:
8093   case Stmt::CXXDynamicCastExprClass:
8094   case Stmt::CXXConstCastExprClass:
8095   case Stmt::CXXReinterpretCastExprClass: {
8096     const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
8097     switch (cast<CastExpr>(E)->getCastKind()) {
8098     case CK_LValueToRValue:
8099     case CK_NoOp:
8100     case CK_BaseToDerived:
8101     case CK_DerivedToBase:
8102     case CK_UncheckedDerivedToBase:
8103     case CK_Dynamic:
8104     case CK_CPointerToObjCPointerCast:
8105     case CK_BlockPointerToObjCPointerCast:
8106     case CK_AnyPointerToBlockPointerCast:
8107       return EvalAddr(SubExpr, refVars, ParentDecl);
8108 
8109     case CK_ArrayToPointerDecay:
8110       return EvalVal(SubExpr, refVars, ParentDecl);
8111 
8112     case CK_BitCast:
8113       if (SubExpr->getType()->isAnyPointerType() ||
8114           SubExpr->getType()->isBlockPointerType() ||
8115           SubExpr->getType()->isObjCQualifiedIdType())
8116         return EvalAddr(SubExpr, refVars, ParentDecl);
8117       else
8118         return nullptr;
8119 
8120     default:
8121       return nullptr;
8122     }
8123   }
8124 
8125   case Stmt::MaterializeTemporaryExprClass:
8126     if (const Expr *Result =
8127             EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8128                      refVars, ParentDecl))
8129       return Result;
8130     return E;
8131 
8132   // Everything else: we simply don't reason about them.
8133   default:
8134     return nullptr;
8135   }
8136 }
8137 
8138 ///  EvalVal - This function is complements EvalAddr in the mutual recursion.
8139 ///   See the comments for EvalAddr for more details.
8140 static const Expr *EvalVal(const Expr *E,
8141                            SmallVectorImpl<const DeclRefExpr *> &refVars,
8142                            const Decl *ParentDecl) {
8143   do {
8144     // We should only be called for evaluating non-pointer expressions, or
8145     // expressions with a pointer type that are not used as references but
8146     // instead
8147     // are l-values (e.g., DeclRefExpr with a pointer type).
8148 
8149     // Our "symbolic interpreter" is just a dispatch off the currently
8150     // viewed AST node.  We then recursively traverse the AST by calling
8151     // EvalAddr and EvalVal appropriately.
8152 
8153     E = E->IgnoreParens();
8154     switch (E->getStmtClass()) {
8155     case Stmt::ImplicitCastExprClass: {
8156       const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
8157       if (IE->getValueKind() == VK_LValue) {
8158         E = IE->getSubExpr();
8159         continue;
8160       }
8161       return nullptr;
8162     }
8163 
8164     case Stmt::ExprWithCleanupsClass:
8165       return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
8166                      ParentDecl);
8167 
8168     case Stmt::DeclRefExprClass: {
8169       // When we hit a DeclRefExpr we are looking at code that refers to a
8170       // variable's name. If it's not a reference variable we check if it has
8171       // local storage within the function, and if so, return the expression.
8172       const DeclRefExpr *DR = cast<DeclRefExpr>(E);
8173 
8174       // If we leave the immediate function, the lifetime isn't about to end.
8175       if (DR->refersToEnclosingVariableOrCapture())
8176         return nullptr;
8177 
8178       if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
8179         // Check if it refers to itself, e.g. "int& i = i;".
8180         if (V == ParentDecl)
8181           return DR;
8182 
8183         if (V->hasLocalStorage()) {
8184           if (!V->getType()->isReferenceType())
8185             return DR;
8186 
8187           // Reference variable, follow through to the expression that
8188           // it points to.
8189           if (V->hasInit()) {
8190             // Add the reference variable to the "trail".
8191             refVars.push_back(DR);
8192             return EvalVal(V->getInit(), refVars, V);
8193           }
8194         }
8195       }
8196 
8197       return nullptr;
8198     }
8199 
8200     case Stmt::UnaryOperatorClass: {
8201       // The only unary operator that make sense to handle here
8202       // is Deref.  All others don't resolve to a "name."  This includes
8203       // handling all sorts of rvalues passed to a unary operator.
8204       const UnaryOperator *U = cast<UnaryOperator>(E);
8205 
8206       if (U->getOpcode() == UO_Deref)
8207         return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
8208 
8209       return nullptr;
8210     }
8211 
8212     case Stmt::ArraySubscriptExprClass: {
8213       // Array subscripts are potential references to data on the stack.  We
8214       // retrieve the DeclRefExpr* for the array variable if it indeed
8215       // has local storage.
8216       const auto *ASE = cast<ArraySubscriptExpr>(E);
8217       if (ASE->isTypeDependent())
8218         return nullptr;
8219       return EvalAddr(ASE->getBase(), refVars, ParentDecl);
8220     }
8221 
8222     case Stmt::OMPArraySectionExprClass: {
8223       return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
8224                       ParentDecl);
8225     }
8226 
8227     case Stmt::ConditionalOperatorClass: {
8228       // For conditional operators we need to see if either the LHS or RHS are
8229       // non-NULL Expr's.  If one is non-NULL, we return it.
8230       const ConditionalOperator *C = cast<ConditionalOperator>(E);
8231 
8232       // Handle the GNU extension for missing LHS.
8233       if (const Expr *LHSExpr = C->getLHS()) {
8234         // In C++, we can have a throw-expression, which has 'void' type.
8235         if (!LHSExpr->getType()->isVoidType())
8236           if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
8237             return LHS;
8238       }
8239 
8240       // In C++, we can have a throw-expression, which has 'void' type.
8241       if (C->getRHS()->getType()->isVoidType())
8242         return nullptr;
8243 
8244       return EvalVal(C->getRHS(), refVars, ParentDecl);
8245     }
8246 
8247     // Accesses to members are potential references to data on the stack.
8248     case Stmt::MemberExprClass: {
8249       const MemberExpr *M = cast<MemberExpr>(E);
8250 
8251       // Check for indirect access.  We only want direct field accesses.
8252       if (M->isArrow())
8253         return nullptr;
8254 
8255       // Check whether the member type is itself a reference, in which case
8256       // we're not going to refer to the member, but to what the member refers
8257       // to.
8258       if (M->getMemberDecl()->getType()->isReferenceType())
8259         return nullptr;
8260 
8261       return EvalVal(M->getBase(), refVars, ParentDecl);
8262     }
8263 
8264     case Stmt::MaterializeTemporaryExprClass:
8265       if (const Expr *Result =
8266               EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8267                       refVars, ParentDecl))
8268         return Result;
8269       return E;
8270 
8271     default:
8272       // Check that we don't return or take the address of a reference to a
8273       // temporary. This is only useful in C++.
8274       if (!E->isTypeDependent() && E->isRValue())
8275         return E;
8276 
8277       // Everything else: we simply don't reason about them.
8278       return nullptr;
8279     }
8280   } while (true);
8281 }
8282 
8283 void
8284 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
8285                          SourceLocation ReturnLoc,
8286                          bool isObjCMethod,
8287                          const AttrVec *Attrs,
8288                          const FunctionDecl *FD) {
8289   CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
8290 
8291   // Check if the return value is null but should not be.
8292   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
8293        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
8294       CheckNonNullExpr(*this, RetValExp))
8295     Diag(ReturnLoc, diag::warn_null_ret)
8296       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
8297 
8298   // C++11 [basic.stc.dynamic.allocation]p4:
8299   //   If an allocation function declared with a non-throwing
8300   //   exception-specification fails to allocate storage, it shall return
8301   //   a null pointer. Any other allocation function that fails to allocate
8302   //   storage shall indicate failure only by throwing an exception [...]
8303   if (FD) {
8304     OverloadedOperatorKind Op = FD->getOverloadedOperator();
8305     if (Op == OO_New || Op == OO_Array_New) {
8306       const FunctionProtoType *Proto
8307         = FD->getType()->castAs<FunctionProtoType>();
8308       if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
8309           CheckNonNullExpr(*this, RetValExp))
8310         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
8311           << FD << getLangOpts().CPlusPlus11;
8312     }
8313   }
8314 }
8315 
8316 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
8317 
8318 /// Check for comparisons of floating point operands using != and ==.
8319 /// Issue a warning if these are no self-comparisons, as they are not likely
8320 /// to do what the programmer intended.
8321 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
8322   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
8323   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
8324 
8325   // Special case: check for x == x (which is OK).
8326   // Do not emit warnings for such cases.
8327   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
8328     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
8329       if (DRL->getDecl() == DRR->getDecl())
8330         return;
8331 
8332   // Special case: check for comparisons against literals that can be exactly
8333   //  represented by APFloat.  In such cases, do not emit a warning.  This
8334   //  is a heuristic: often comparison against such literals are used to
8335   //  detect if a value in a variable has not changed.  This clearly can
8336   //  lead to false negatives.
8337   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
8338     if (FLL->isExact())
8339       return;
8340   } else
8341     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
8342       if (FLR->isExact())
8343         return;
8344 
8345   // Check for comparisons with builtin types.
8346   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
8347     if (CL->getBuiltinCallee())
8348       return;
8349 
8350   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
8351     if (CR->getBuiltinCallee())
8352       return;
8353 
8354   // Emit the diagnostic.
8355   Diag(Loc, diag::warn_floatingpoint_eq)
8356     << LHS->getSourceRange() << RHS->getSourceRange();
8357 }
8358 
8359 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
8360 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
8361 
8362 namespace {
8363 
8364 /// Structure recording the 'active' range of an integer-valued
8365 /// expression.
8366 struct IntRange {
8367   /// The number of bits active in the int.
8368   unsigned Width;
8369 
8370   /// True if the int is known not to have negative values.
8371   bool NonNegative;
8372 
8373   IntRange(unsigned Width, bool NonNegative)
8374       : Width(Width), NonNegative(NonNegative) {}
8375 
8376   /// Returns the range of the bool type.
8377   static IntRange forBoolType() {
8378     return IntRange(1, true);
8379   }
8380 
8381   /// Returns the range of an opaque value of the given integral type.
8382   static IntRange forValueOfType(ASTContext &C, QualType T) {
8383     return forValueOfCanonicalType(C,
8384                           T->getCanonicalTypeInternal().getTypePtr());
8385   }
8386 
8387   /// Returns the range of an opaque value of a canonical integral type.
8388   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
8389     assert(T->isCanonicalUnqualified());
8390 
8391     if (const VectorType *VT = dyn_cast<VectorType>(T))
8392       T = VT->getElementType().getTypePtr();
8393     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8394       T = CT->getElementType().getTypePtr();
8395     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8396       T = AT->getValueType().getTypePtr();
8397 
8398     if (!C.getLangOpts().CPlusPlus) {
8399       // For enum types in C code, use the underlying datatype.
8400       if (const EnumType *ET = dyn_cast<EnumType>(T))
8401         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
8402     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
8403       // For enum types in C++, use the known bit width of the enumerators.
8404       EnumDecl *Enum = ET->getDecl();
8405       // In C++11, enums can have a fixed underlying type. Use this type to
8406       // compute the range.
8407       if (Enum->isFixed()) {
8408         return IntRange(C.getIntWidth(QualType(T, 0)),
8409                         !ET->isSignedIntegerOrEnumerationType());
8410       }
8411 
8412       unsigned NumPositive = Enum->getNumPositiveBits();
8413       unsigned NumNegative = Enum->getNumNegativeBits();
8414 
8415       if (NumNegative == 0)
8416         return IntRange(NumPositive, true/*NonNegative*/);
8417       else
8418         return IntRange(std::max(NumPositive + 1, NumNegative),
8419                         false/*NonNegative*/);
8420     }
8421 
8422     const BuiltinType *BT = cast<BuiltinType>(T);
8423     assert(BT->isInteger());
8424 
8425     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8426   }
8427 
8428   /// Returns the "target" range of a canonical integral type, i.e.
8429   /// the range of values expressible in the type.
8430   ///
8431   /// This matches forValueOfCanonicalType except that enums have the
8432   /// full range of their type, not the range of their enumerators.
8433   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
8434     assert(T->isCanonicalUnqualified());
8435 
8436     if (const VectorType *VT = dyn_cast<VectorType>(T))
8437       T = VT->getElementType().getTypePtr();
8438     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8439       T = CT->getElementType().getTypePtr();
8440     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8441       T = AT->getValueType().getTypePtr();
8442     if (const EnumType *ET = dyn_cast<EnumType>(T))
8443       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
8444 
8445     const BuiltinType *BT = cast<BuiltinType>(T);
8446     assert(BT->isInteger());
8447 
8448     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8449   }
8450 
8451   /// Returns the supremum of two ranges: i.e. their conservative merge.
8452   static IntRange join(IntRange L, IntRange R) {
8453     return IntRange(std::max(L.Width, R.Width),
8454                     L.NonNegative && R.NonNegative);
8455   }
8456 
8457   /// Returns the infinum of two ranges: i.e. their aggressive merge.
8458   static IntRange meet(IntRange L, IntRange R) {
8459     return IntRange(std::min(L.Width, R.Width),
8460                     L.NonNegative || R.NonNegative);
8461   }
8462 };
8463 
8464 } // namespace
8465 
8466 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
8467                               unsigned MaxWidth) {
8468   if (value.isSigned() && value.isNegative())
8469     return IntRange(value.getMinSignedBits(), false);
8470 
8471   if (value.getBitWidth() > MaxWidth)
8472     value = value.trunc(MaxWidth);
8473 
8474   // isNonNegative() just checks the sign bit without considering
8475   // signedness.
8476   return IntRange(value.getActiveBits(), true);
8477 }
8478 
8479 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
8480                               unsigned MaxWidth) {
8481   if (result.isInt())
8482     return GetValueRange(C, result.getInt(), MaxWidth);
8483 
8484   if (result.isVector()) {
8485     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
8486     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
8487       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
8488       R = IntRange::join(R, El);
8489     }
8490     return R;
8491   }
8492 
8493   if (result.isComplexInt()) {
8494     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
8495     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
8496     return IntRange::join(R, I);
8497   }
8498 
8499   // This can happen with lossless casts to intptr_t of "based" lvalues.
8500   // Assume it might use arbitrary bits.
8501   // FIXME: The only reason we need to pass the type in here is to get
8502   // the sign right on this one case.  It would be nice if APValue
8503   // preserved this.
8504   assert(result.isLValue() || result.isAddrLabelDiff());
8505   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
8506 }
8507 
8508 static QualType GetExprType(const Expr *E) {
8509   QualType Ty = E->getType();
8510   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
8511     Ty = AtomicRHS->getValueType();
8512   return Ty;
8513 }
8514 
8515 /// Pseudo-evaluate the given integer expression, estimating the
8516 /// range of values it might take.
8517 ///
8518 /// \param MaxWidth - the width to which the value will be truncated
8519 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
8520   E = E->IgnoreParens();
8521 
8522   // Try a full evaluation first.
8523   Expr::EvalResult result;
8524   if (E->EvaluateAsRValue(result, C))
8525     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
8526 
8527   // I think we only want to look through implicit casts here; if the
8528   // user has an explicit widening cast, we should treat the value as
8529   // being of the new, wider type.
8530   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
8531     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
8532       return GetExprRange(C, CE->getSubExpr(), MaxWidth);
8533 
8534     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
8535 
8536     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
8537                          CE->getCastKind() == CK_BooleanToSignedIntegral;
8538 
8539     // Assume that non-integer casts can span the full range of the type.
8540     if (!isIntegerCast)
8541       return OutputTypeRange;
8542 
8543     IntRange SubRange
8544       = GetExprRange(C, CE->getSubExpr(),
8545                      std::min(MaxWidth, OutputTypeRange.Width));
8546 
8547     // Bail out if the subexpr's range is as wide as the cast type.
8548     if (SubRange.Width >= OutputTypeRange.Width)
8549       return OutputTypeRange;
8550 
8551     // Otherwise, we take the smaller width, and we're non-negative if
8552     // either the output type or the subexpr is.
8553     return IntRange(SubRange.Width,
8554                     SubRange.NonNegative || OutputTypeRange.NonNegative);
8555   }
8556 
8557   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
8558     // If we can fold the condition, just take that operand.
8559     bool CondResult;
8560     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
8561       return GetExprRange(C, CondResult ? CO->getTrueExpr()
8562                                         : CO->getFalseExpr(),
8563                           MaxWidth);
8564 
8565     // Otherwise, conservatively merge.
8566     IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
8567     IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
8568     return IntRange::join(L, R);
8569   }
8570 
8571   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
8572     switch (BO->getOpcode()) {
8573     case BO_Cmp:
8574       llvm_unreachable("builtin <=> should have class type");
8575 
8576     // Boolean-valued operations are single-bit and positive.
8577     case BO_LAnd:
8578     case BO_LOr:
8579     case BO_LT:
8580     case BO_GT:
8581     case BO_LE:
8582     case BO_GE:
8583     case BO_EQ:
8584     case BO_NE:
8585       return IntRange::forBoolType();
8586 
8587     // The type of the assignments is the type of the LHS, so the RHS
8588     // is not necessarily the same type.
8589     case BO_MulAssign:
8590     case BO_DivAssign:
8591     case BO_RemAssign:
8592     case BO_AddAssign:
8593     case BO_SubAssign:
8594     case BO_XorAssign:
8595     case BO_OrAssign:
8596       // TODO: bitfields?
8597       return IntRange::forValueOfType(C, GetExprType(E));
8598 
8599     // Simple assignments just pass through the RHS, which will have
8600     // been coerced to the LHS type.
8601     case BO_Assign:
8602       // TODO: bitfields?
8603       return GetExprRange(C, BO->getRHS(), MaxWidth);
8604 
8605     // Operations with opaque sources are black-listed.
8606     case BO_PtrMemD:
8607     case BO_PtrMemI:
8608       return IntRange::forValueOfType(C, GetExprType(E));
8609 
8610     // Bitwise-and uses the *infinum* of the two source ranges.
8611     case BO_And:
8612     case BO_AndAssign:
8613       return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8614                             GetExprRange(C, BO->getRHS(), MaxWidth));
8615 
8616     // Left shift gets black-listed based on a judgement call.
8617     case BO_Shl:
8618       // ...except that we want to treat '1 << (blah)' as logically
8619       // positive.  It's an important idiom.
8620       if (IntegerLiteral *I
8621             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8622         if (I->getValue() == 1) {
8623           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
8624           return IntRange(R.Width, /*NonNegative*/ true);
8625         }
8626       }
8627       LLVM_FALLTHROUGH;
8628 
8629     case BO_ShlAssign:
8630       return IntRange::forValueOfType(C, GetExprType(E));
8631 
8632     // Right shift by a constant can narrow its left argument.
8633     case BO_Shr:
8634     case BO_ShrAssign: {
8635       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8636 
8637       // If the shift amount is a positive constant, drop the width by
8638       // that much.
8639       llvm::APSInt shift;
8640       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8641           shift.isNonNegative()) {
8642         unsigned zext = shift.getZExtValue();
8643         if (zext >= L.Width)
8644           L.Width = (L.NonNegative ? 0 : 1);
8645         else
8646           L.Width -= zext;
8647       }
8648 
8649       return L;
8650     }
8651 
8652     // Comma acts as its right operand.
8653     case BO_Comma:
8654       return GetExprRange(C, BO->getRHS(), MaxWidth);
8655 
8656     // Black-list pointer subtractions.
8657     case BO_Sub:
8658       if (BO->getLHS()->getType()->isPointerType())
8659         return IntRange::forValueOfType(C, GetExprType(E));
8660       break;
8661 
8662     // The width of a division result is mostly determined by the size
8663     // of the LHS.
8664     case BO_Div: {
8665       // Don't 'pre-truncate' the operands.
8666       unsigned opWidth = C.getIntWidth(GetExprType(E));
8667       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8668 
8669       // If the divisor is constant, use that.
8670       llvm::APSInt divisor;
8671       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8672         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8673         if (log2 >= L.Width)
8674           L.Width = (L.NonNegative ? 0 : 1);
8675         else
8676           L.Width = std::min(L.Width - log2, MaxWidth);
8677         return L;
8678       }
8679 
8680       // Otherwise, just use the LHS's width.
8681       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8682       return IntRange(L.Width, L.NonNegative && R.NonNegative);
8683     }
8684 
8685     // The result of a remainder can't be larger than the result of
8686     // either side.
8687     case BO_Rem: {
8688       // Don't 'pre-truncate' the operands.
8689       unsigned opWidth = C.getIntWidth(GetExprType(E));
8690       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8691       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8692 
8693       IntRange meet = IntRange::meet(L, R);
8694       meet.Width = std::min(meet.Width, MaxWidth);
8695       return meet;
8696     }
8697 
8698     // The default behavior is okay for these.
8699     case BO_Mul:
8700     case BO_Add:
8701     case BO_Xor:
8702     case BO_Or:
8703       break;
8704     }
8705 
8706     // The default case is to treat the operation as if it were closed
8707     // on the narrowest type that encompasses both operands.
8708     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8709     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8710     return IntRange::join(L, R);
8711   }
8712 
8713   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
8714     switch (UO->getOpcode()) {
8715     // Boolean-valued operations are white-listed.
8716     case UO_LNot:
8717       return IntRange::forBoolType();
8718 
8719     // Operations with opaque sources are black-listed.
8720     case UO_Deref:
8721     case UO_AddrOf: // should be impossible
8722       return IntRange::forValueOfType(C, GetExprType(E));
8723 
8724     default:
8725       return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8726     }
8727   }
8728 
8729   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
8730     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8731 
8732   if (const auto *BitField = E->getSourceBitField())
8733     return IntRange(BitField->getBitWidthValue(C),
8734                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
8735 
8736   return IntRange::forValueOfType(C, GetExprType(E));
8737 }
8738 
8739 static IntRange GetExprRange(ASTContext &C, const Expr *E) {
8740   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
8741 }
8742 
8743 /// Checks whether the given value, which currently has the given
8744 /// source semantics, has the same value when coerced through the
8745 /// target semantics.
8746 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
8747                                  const llvm::fltSemantics &Src,
8748                                  const llvm::fltSemantics &Tgt) {
8749   llvm::APFloat truncated = value;
8750 
8751   bool ignored;
8752   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8753   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8754 
8755   return truncated.bitwiseIsEqual(value);
8756 }
8757 
8758 /// Checks whether the given value, which currently has the given
8759 /// source semantics, has the same value when coerced through the
8760 /// target semantics.
8761 ///
8762 /// The value might be a vector of floats (or a complex number).
8763 static bool IsSameFloatAfterCast(const APValue &value,
8764                                  const llvm::fltSemantics &Src,
8765                                  const llvm::fltSemantics &Tgt) {
8766   if (value.isFloat())
8767     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8768 
8769   if (value.isVector()) {
8770     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8771       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8772         return false;
8773     return true;
8774   }
8775 
8776   assert(value.isComplexFloat());
8777   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8778           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8779 }
8780 
8781 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
8782 
8783 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
8784   // Suppress cases where we are comparing against an enum constant.
8785   if (const DeclRefExpr *DR =
8786       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8787     if (isa<EnumConstantDecl>(DR->getDecl()))
8788       return true;
8789 
8790   // Suppress cases where the '0' value is expanded from a macro.
8791   if (E->getLocStart().isMacroID())
8792     return true;
8793 
8794   return false;
8795 }
8796 
8797 static bool isKnownToHaveUnsignedValue(Expr *E) {
8798   return E->getType()->isIntegerType() &&
8799          (!E->getType()->isSignedIntegerType() ||
8800           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
8801 }
8802 
8803 namespace {
8804 /// The promoted range of values of a type. In general this has the
8805 /// following structure:
8806 ///
8807 ///     |-----------| . . . |-----------|
8808 ///     ^           ^       ^           ^
8809 ///    Min       HoleMin  HoleMax      Max
8810 ///
8811 /// ... where there is only a hole if a signed type is promoted to unsigned
8812 /// (in which case Min and Max are the smallest and largest representable
8813 /// values).
8814 struct PromotedRange {
8815   // Min, or HoleMax if there is a hole.
8816   llvm::APSInt PromotedMin;
8817   // Max, or HoleMin if there is a hole.
8818   llvm::APSInt PromotedMax;
8819 
8820   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
8821     if (R.Width == 0)
8822       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
8823     else if (R.Width >= BitWidth && !Unsigned) {
8824       // Promotion made the type *narrower*. This happens when promoting
8825       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
8826       // Treat all values of 'signed int' as being in range for now.
8827       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
8828       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
8829     } else {
8830       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
8831                         .extOrTrunc(BitWidth);
8832       PromotedMin.setIsUnsigned(Unsigned);
8833 
8834       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
8835                         .extOrTrunc(BitWidth);
8836       PromotedMax.setIsUnsigned(Unsigned);
8837     }
8838   }
8839 
8840   // Determine whether this range is contiguous (has no hole).
8841   bool isContiguous() const { return PromotedMin <= PromotedMax; }
8842 
8843   // Where a constant value is within the range.
8844   enum ComparisonResult {
8845     LT = 0x1,
8846     LE = 0x2,
8847     GT = 0x4,
8848     GE = 0x8,
8849     EQ = 0x10,
8850     NE = 0x20,
8851     InRangeFlag = 0x40,
8852 
8853     Less = LE | LT | NE,
8854     Min = LE | InRangeFlag,
8855     InRange = InRangeFlag,
8856     Max = GE | InRangeFlag,
8857     Greater = GE | GT | NE,
8858 
8859     OnlyValue = LE | GE | EQ | InRangeFlag,
8860     InHole = NE
8861   };
8862 
8863   ComparisonResult compare(const llvm::APSInt &Value) const {
8864     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
8865            Value.isUnsigned() == PromotedMin.isUnsigned());
8866     if (!isContiguous()) {
8867       assert(Value.isUnsigned() && "discontiguous range for signed compare");
8868       if (Value.isMinValue()) return Min;
8869       if (Value.isMaxValue()) return Max;
8870       if (Value >= PromotedMin) return InRange;
8871       if (Value <= PromotedMax) return InRange;
8872       return InHole;
8873     }
8874 
8875     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
8876     case -1: return Less;
8877     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
8878     case 1:
8879       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
8880       case -1: return InRange;
8881       case 0: return Max;
8882       case 1: return Greater;
8883       }
8884     }
8885 
8886     llvm_unreachable("impossible compare result");
8887   }
8888 
8889   static llvm::Optional<StringRef>
8890   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
8891     if (Op == BO_Cmp) {
8892       ComparisonResult LTFlag = LT, GTFlag = GT;
8893       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
8894 
8895       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
8896       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
8897       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
8898       return llvm::None;
8899     }
8900 
8901     ComparisonResult TrueFlag, FalseFlag;
8902     if (Op == BO_EQ) {
8903       TrueFlag = EQ;
8904       FalseFlag = NE;
8905     } else if (Op == BO_NE) {
8906       TrueFlag = NE;
8907       FalseFlag = EQ;
8908     } else {
8909       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
8910         TrueFlag = LT;
8911         FalseFlag = GE;
8912       } else {
8913         TrueFlag = GT;
8914         FalseFlag = LE;
8915       }
8916       if (Op == BO_GE || Op == BO_LE)
8917         std::swap(TrueFlag, FalseFlag);
8918     }
8919     if (R & TrueFlag)
8920       return StringRef("true");
8921     if (R & FalseFlag)
8922       return StringRef("false");
8923     return llvm::None;
8924   }
8925 };
8926 }
8927 
8928 static bool HasEnumType(Expr *E) {
8929   // Strip off implicit integral promotions.
8930   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8931     if (ICE->getCastKind() != CK_IntegralCast &&
8932         ICE->getCastKind() != CK_NoOp)
8933       break;
8934     E = ICE->getSubExpr();
8935   }
8936 
8937   return E->getType()->isEnumeralType();
8938 }
8939 
8940 static int classifyConstantValue(Expr *Constant) {
8941   // The values of this enumeration are used in the diagnostics
8942   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
8943   enum ConstantValueKind {
8944     Miscellaneous = 0,
8945     LiteralTrue,
8946     LiteralFalse
8947   };
8948   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
8949     return BL->getValue() ? ConstantValueKind::LiteralTrue
8950                           : ConstantValueKind::LiteralFalse;
8951   return ConstantValueKind::Miscellaneous;
8952 }
8953 
8954 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
8955                                         Expr *Constant, Expr *Other,
8956                                         const llvm::APSInt &Value,
8957                                         bool RhsConstant) {
8958   if (S.inTemplateInstantiation())
8959     return false;
8960 
8961   Expr *OriginalOther = Other;
8962 
8963   Constant = Constant->IgnoreParenImpCasts();
8964   Other = Other->IgnoreParenImpCasts();
8965 
8966   // Suppress warnings on tautological comparisons between values of the same
8967   // enumeration type. There are only two ways we could warn on this:
8968   //  - If the constant is outside the range of representable values of
8969   //    the enumeration. In such a case, we should warn about the cast
8970   //    to enumeration type, not about the comparison.
8971   //  - If the constant is the maximum / minimum in-range value. For an
8972   //    enumeratin type, such comparisons can be meaningful and useful.
8973   if (Constant->getType()->isEnumeralType() &&
8974       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
8975     return false;
8976 
8977   // TODO: Investigate using GetExprRange() to get tighter bounds
8978   // on the bit ranges.
8979   QualType OtherT = Other->getType();
8980   if (const auto *AT = OtherT->getAs<AtomicType>())
8981     OtherT = AT->getValueType();
8982   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8983 
8984   // Whether we're treating Other as being a bool because of the form of
8985   // expression despite it having another type (typically 'int' in C).
8986   bool OtherIsBooleanDespiteType =
8987       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
8988   if (OtherIsBooleanDespiteType)
8989     OtherRange = IntRange::forBoolType();
8990 
8991   // Determine the promoted range of the other type and see if a comparison of
8992   // the constant against that range is tautological.
8993   PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
8994                                    Value.isUnsigned());
8995   auto Cmp = OtherPromotedRange.compare(Value);
8996   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
8997   if (!Result)
8998     return false;
8999 
9000   // Suppress the diagnostic for an in-range comparison if the constant comes
9001   // from a macro or enumerator. We don't want to diagnose
9002   //
9003   //   some_long_value <= INT_MAX
9004   //
9005   // when sizeof(int) == sizeof(long).
9006   bool InRange = Cmp & PromotedRange::InRangeFlag;
9007   if (InRange && IsEnumConstOrFromMacro(S, Constant))
9008     return false;
9009 
9010   // If this is a comparison to an enum constant, include that
9011   // constant in the diagnostic.
9012   const EnumConstantDecl *ED = nullptr;
9013   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
9014     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
9015 
9016   // Should be enough for uint128 (39 decimal digits)
9017   SmallString<64> PrettySourceValue;
9018   llvm::raw_svector_ostream OS(PrettySourceValue);
9019   if (ED)
9020     OS << '\'' << *ED << "' (" << Value << ")";
9021   else
9022     OS << Value;
9023 
9024   // FIXME: We use a somewhat different formatting for the in-range cases and
9025   // cases involving boolean values for historical reasons. We should pick a
9026   // consistent way of presenting these diagnostics.
9027   if (!InRange || Other->isKnownToHaveBooleanValue()) {
9028     S.DiagRuntimeBehavior(
9029       E->getOperatorLoc(), E,
9030       S.PDiag(!InRange ? diag::warn_out_of_range_compare
9031                        : diag::warn_tautological_bool_compare)
9032           << OS.str() << classifyConstantValue(Constant)
9033           << OtherT << OtherIsBooleanDespiteType << *Result
9034           << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
9035   } else {
9036     unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
9037                         ? (HasEnumType(OriginalOther)
9038                                ? diag::warn_unsigned_enum_always_true_comparison
9039                                : diag::warn_unsigned_always_true_comparison)
9040                         : diag::warn_tautological_constant_compare;
9041 
9042     S.Diag(E->getOperatorLoc(), Diag)
9043         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
9044         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
9045   }
9046 
9047   return true;
9048 }
9049 
9050 /// Analyze the operands of the given comparison.  Implements the
9051 /// fallback case from AnalyzeComparison.
9052 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
9053   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9054   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9055 }
9056 
9057 /// \brief Implements -Wsign-compare.
9058 ///
9059 /// \param E the binary operator to check for warnings
9060 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
9061   // The type the comparison is being performed in.
9062   QualType T = E->getLHS()->getType();
9063 
9064   // Only analyze comparison operators where both sides have been converted to
9065   // the same type.
9066   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
9067     return AnalyzeImpConvsInComparison(S, E);
9068 
9069   // Don't analyze value-dependent comparisons directly.
9070   if (E->isValueDependent())
9071     return AnalyzeImpConvsInComparison(S, E);
9072 
9073   Expr *LHS = E->getLHS();
9074   Expr *RHS = E->getRHS();
9075 
9076   if (T->isIntegralType(S.Context)) {
9077     llvm::APSInt RHSValue;
9078     llvm::APSInt LHSValue;
9079 
9080     bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
9081     bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
9082 
9083     // We don't care about expressions whose result is a constant.
9084     if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
9085       return AnalyzeImpConvsInComparison(S, E);
9086 
9087     // We only care about expressions where just one side is literal
9088     if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
9089       // Is the constant on the RHS or LHS?
9090       const bool RhsConstant = IsRHSIntegralLiteral;
9091       Expr *Const = RhsConstant ? RHS : LHS;
9092       Expr *Other = RhsConstant ? LHS : RHS;
9093       const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
9094 
9095       // Check whether an integer constant comparison results in a value
9096       // of 'true' or 'false'.
9097       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
9098         return AnalyzeImpConvsInComparison(S, E);
9099     }
9100   }
9101 
9102   if (!T->hasUnsignedIntegerRepresentation()) {
9103     // We don't do anything special if this isn't an unsigned integral
9104     // comparison:  we're only interested in integral comparisons, and
9105     // signed comparisons only happen in cases we don't care to warn about.
9106     return AnalyzeImpConvsInComparison(S, E);
9107   }
9108 
9109   LHS = LHS->IgnoreParenImpCasts();
9110   RHS = RHS->IgnoreParenImpCasts();
9111 
9112   if (!S.getLangOpts().CPlusPlus) {
9113     // Avoid warning about comparison of integers with different signs when
9114     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
9115     // the type of `E`.
9116     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
9117       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
9118     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
9119       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
9120   }
9121 
9122   // Check to see if one of the (unmodified) operands is of different
9123   // signedness.
9124   Expr *signedOperand, *unsignedOperand;
9125   if (LHS->getType()->hasSignedIntegerRepresentation()) {
9126     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
9127            "unsigned comparison between two signed integer expressions?");
9128     signedOperand = LHS;
9129     unsignedOperand = RHS;
9130   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
9131     signedOperand = RHS;
9132     unsignedOperand = LHS;
9133   } else {
9134     return AnalyzeImpConvsInComparison(S, E);
9135   }
9136 
9137   // Otherwise, calculate the effective range of the signed operand.
9138   IntRange signedRange = GetExprRange(S.Context, signedOperand);
9139 
9140   // Go ahead and analyze implicit conversions in the operands.  Note
9141   // that we skip the implicit conversions on both sides.
9142   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
9143   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
9144 
9145   // If the signed range is non-negative, -Wsign-compare won't fire.
9146   if (signedRange.NonNegative)
9147     return;
9148 
9149   // For (in)equality comparisons, if the unsigned operand is a
9150   // constant which cannot collide with a overflowed signed operand,
9151   // then reinterpreting the signed operand as unsigned will not
9152   // change the result of the comparison.
9153   if (E->isEqualityOp()) {
9154     unsigned comparisonWidth = S.Context.getIntWidth(T);
9155     IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
9156 
9157     // We should never be unable to prove that the unsigned operand is
9158     // non-negative.
9159     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
9160 
9161     if (unsignedRange.Width < comparisonWidth)
9162       return;
9163   }
9164 
9165   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
9166     S.PDiag(diag::warn_mixed_sign_comparison)
9167       << LHS->getType() << RHS->getType()
9168       << LHS->getSourceRange() << RHS->getSourceRange());
9169 }
9170 
9171 /// Analyzes an attempt to assign the given value to a bitfield.
9172 ///
9173 /// Returns true if there was something fishy about the attempt.
9174 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
9175                                       SourceLocation InitLoc) {
9176   assert(Bitfield->isBitField());
9177   if (Bitfield->isInvalidDecl())
9178     return false;
9179 
9180   // White-list bool bitfields.
9181   QualType BitfieldType = Bitfield->getType();
9182   if (BitfieldType->isBooleanType())
9183      return false;
9184 
9185   if (BitfieldType->isEnumeralType()) {
9186     EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
9187     // If the underlying enum type was not explicitly specified as an unsigned
9188     // type and the enum contain only positive values, MSVC++ will cause an
9189     // inconsistency by storing this as a signed type.
9190     if (S.getLangOpts().CPlusPlus11 &&
9191         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
9192         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
9193         BitfieldEnumDecl->getNumNegativeBits() == 0) {
9194       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
9195         << BitfieldEnumDecl->getNameAsString();
9196     }
9197   }
9198 
9199   if (Bitfield->getType()->isBooleanType())
9200     return false;
9201 
9202   // Ignore value- or type-dependent expressions.
9203   if (Bitfield->getBitWidth()->isValueDependent() ||
9204       Bitfield->getBitWidth()->isTypeDependent() ||
9205       Init->isValueDependent() ||
9206       Init->isTypeDependent())
9207     return false;
9208 
9209   Expr *OriginalInit = Init->IgnoreParenImpCasts();
9210   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
9211 
9212   llvm::APSInt Value;
9213   if (!OriginalInit->EvaluateAsInt(Value, S.Context,
9214                                    Expr::SE_AllowSideEffects)) {
9215     // The RHS is not constant.  If the RHS has an enum type, make sure the
9216     // bitfield is wide enough to hold all the values of the enum without
9217     // truncation.
9218     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
9219       EnumDecl *ED = EnumTy->getDecl();
9220       bool SignedBitfield = BitfieldType->isSignedIntegerType();
9221 
9222       // Enum types are implicitly signed on Windows, so check if there are any
9223       // negative enumerators to see if the enum was intended to be signed or
9224       // not.
9225       bool SignedEnum = ED->getNumNegativeBits() > 0;
9226 
9227       // Check for surprising sign changes when assigning enum values to a
9228       // bitfield of different signedness.  If the bitfield is signed and we
9229       // have exactly the right number of bits to store this unsigned enum,
9230       // suggest changing the enum to an unsigned type. This typically happens
9231       // on Windows where unfixed enums always use an underlying type of 'int'.
9232       unsigned DiagID = 0;
9233       if (SignedEnum && !SignedBitfield) {
9234         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
9235       } else if (SignedBitfield && !SignedEnum &&
9236                  ED->getNumPositiveBits() == FieldWidth) {
9237         DiagID = diag::warn_signed_bitfield_enum_conversion;
9238       }
9239 
9240       if (DiagID) {
9241         S.Diag(InitLoc, DiagID) << Bitfield << ED;
9242         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
9243         SourceRange TypeRange =
9244             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
9245         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
9246             << SignedEnum << TypeRange;
9247       }
9248 
9249       // Compute the required bitwidth. If the enum has negative values, we need
9250       // one more bit than the normal number of positive bits to represent the
9251       // sign bit.
9252       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
9253                                                   ED->getNumNegativeBits())
9254                                        : ED->getNumPositiveBits();
9255 
9256       // Check the bitwidth.
9257       if (BitsNeeded > FieldWidth) {
9258         Expr *WidthExpr = Bitfield->getBitWidth();
9259         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
9260             << Bitfield << ED;
9261         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
9262             << BitsNeeded << ED << WidthExpr->getSourceRange();
9263       }
9264     }
9265 
9266     return false;
9267   }
9268 
9269   unsigned OriginalWidth = Value.getBitWidth();
9270 
9271   if (!Value.isSigned() || Value.isNegative())
9272     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
9273       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
9274         OriginalWidth = Value.getMinSignedBits();
9275 
9276   if (OriginalWidth <= FieldWidth)
9277     return false;
9278 
9279   // Compute the value which the bitfield will contain.
9280   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
9281   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
9282 
9283   // Check whether the stored value is equal to the original value.
9284   TruncatedValue = TruncatedValue.extend(OriginalWidth);
9285   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
9286     return false;
9287 
9288   // Special-case bitfields of width 1: booleans are naturally 0/1, and
9289   // therefore don't strictly fit into a signed bitfield of width 1.
9290   if (FieldWidth == 1 && Value == 1)
9291     return false;
9292 
9293   std::string PrettyValue = Value.toString(10);
9294   std::string PrettyTrunc = TruncatedValue.toString(10);
9295 
9296   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
9297     << PrettyValue << PrettyTrunc << OriginalInit->getType()
9298     << Init->getSourceRange();
9299 
9300   return true;
9301 }
9302 
9303 /// Analyze the given simple or compound assignment for warning-worthy
9304 /// operations.
9305 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
9306   // Just recurse on the LHS.
9307   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9308 
9309   // We want to recurse on the RHS as normal unless we're assigning to
9310   // a bitfield.
9311   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
9312     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
9313                                   E->getOperatorLoc())) {
9314       // Recurse, ignoring any implicit conversions on the RHS.
9315       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
9316                                         E->getOperatorLoc());
9317     }
9318   }
9319 
9320   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9321 }
9322 
9323 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
9324 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
9325                             SourceLocation CContext, unsigned diag,
9326                             bool pruneControlFlow = false) {
9327   if (pruneControlFlow) {
9328     S.DiagRuntimeBehavior(E->getExprLoc(), E,
9329                           S.PDiag(diag)
9330                             << SourceType << T << E->getSourceRange()
9331                             << SourceRange(CContext));
9332     return;
9333   }
9334   S.Diag(E->getExprLoc(), diag)
9335     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
9336 }
9337 
9338 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
9339 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
9340                             SourceLocation CContext,
9341                             unsigned diag, bool pruneControlFlow = false) {
9342   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
9343 }
9344 
9345 /// Analyze the given compound assignment for the possible losing of
9346 /// floating-point precision.
9347 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
9348   assert(isa<CompoundAssignOperator>(E) &&
9349          "Must be compound assignment operation");
9350   // Recurse on the LHS and RHS in here
9351   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9352   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9353 
9354   // Now check the outermost expression
9355   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
9356   const auto *RBT = cast<CompoundAssignOperator>(E)
9357                         ->getComputationResultType()
9358                         ->getAs<BuiltinType>();
9359 
9360   // If both source and target are floating points.
9361   if (ResultBT && ResultBT->isFloatingPoint() && RBT && RBT->isFloatingPoint())
9362     // Builtin FP kinds are ordered by increasing FP rank.
9363     if (ResultBT->getKind() < RBT->getKind())
9364       // We don't want to warn for system macro.
9365       if (!S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
9366         // warn about dropping FP rank.
9367         DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(),
9368                         E->getOperatorLoc(),
9369                         diag::warn_impcast_float_result_precision);
9370 }
9371 
9372 /// Diagnose an implicit cast from a floating point value to an integer value.
9373 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
9374                                     SourceLocation CContext) {
9375   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
9376   const bool PruneWarnings = S.inTemplateInstantiation();
9377 
9378   Expr *InnerE = E->IgnoreParenImpCasts();
9379   // We also want to warn on, e.g., "int i = -1.234"
9380   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
9381     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
9382       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
9383 
9384   const bool IsLiteral =
9385       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
9386 
9387   llvm::APFloat Value(0.0);
9388   bool IsConstant =
9389     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
9390   if (!IsConstant) {
9391     return DiagnoseImpCast(S, E, T, CContext,
9392                            diag::warn_impcast_float_integer, PruneWarnings);
9393   }
9394 
9395   bool isExact = false;
9396 
9397   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
9398                             T->hasUnsignedIntegerRepresentation());
9399   if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
9400                              &isExact) == llvm::APFloat::opOK &&
9401       isExact) {
9402     if (IsLiteral) return;
9403     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
9404                            PruneWarnings);
9405   }
9406 
9407   unsigned DiagID = 0;
9408   if (IsLiteral) {
9409     // Warn on floating point literal to integer.
9410     DiagID = diag::warn_impcast_literal_float_to_integer;
9411   } else if (IntegerValue == 0) {
9412     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
9413       return DiagnoseImpCast(S, E, T, CContext,
9414                              diag::warn_impcast_float_integer, PruneWarnings);
9415     }
9416     // Warn on non-zero to zero conversion.
9417     DiagID = diag::warn_impcast_float_to_integer_zero;
9418   } else {
9419     if (IntegerValue.isUnsigned()) {
9420       if (!IntegerValue.isMaxValue()) {
9421         return DiagnoseImpCast(S, E, T, CContext,
9422                                diag::warn_impcast_float_integer, PruneWarnings);
9423       }
9424     } else {  // IntegerValue.isSigned()
9425       if (!IntegerValue.isMaxSignedValue() &&
9426           !IntegerValue.isMinSignedValue()) {
9427         return DiagnoseImpCast(S, E, T, CContext,
9428                                diag::warn_impcast_float_integer, PruneWarnings);
9429       }
9430     }
9431     // Warn on evaluatable floating point expression to integer conversion.
9432     DiagID = diag::warn_impcast_float_to_integer;
9433   }
9434 
9435   // FIXME: Force the precision of the source value down so we don't print
9436   // digits which are usually useless (we don't really care here if we
9437   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
9438   // would automatically print the shortest representation, but it's a bit
9439   // tricky to implement.
9440   SmallString<16> PrettySourceValue;
9441   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
9442   precision = (precision * 59 + 195) / 196;
9443   Value.toString(PrettySourceValue, precision);
9444 
9445   SmallString<16> PrettyTargetValue;
9446   if (IsBool)
9447     PrettyTargetValue = Value.isZero() ? "false" : "true";
9448   else
9449     IntegerValue.toString(PrettyTargetValue);
9450 
9451   if (PruneWarnings) {
9452     S.DiagRuntimeBehavior(E->getExprLoc(), E,
9453                           S.PDiag(DiagID)
9454                               << E->getType() << T.getUnqualifiedType()
9455                               << PrettySourceValue << PrettyTargetValue
9456                               << E->getSourceRange() << SourceRange(CContext));
9457   } else {
9458     S.Diag(E->getExprLoc(), DiagID)
9459         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
9460         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
9461   }
9462 }
9463 
9464 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
9465                                       IntRange Range) {
9466   if (!Range.Width) return "0";
9467 
9468   llvm::APSInt ValueInRange = Value;
9469   ValueInRange.setIsSigned(!Range.NonNegative);
9470   ValueInRange = ValueInRange.trunc(Range.Width);
9471   return ValueInRange.toString(10);
9472 }
9473 
9474 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
9475   if (!isa<ImplicitCastExpr>(Ex))
9476     return false;
9477 
9478   Expr *InnerE = Ex->IgnoreParenImpCasts();
9479   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
9480   const Type *Source =
9481     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
9482   if (Target->isDependentType())
9483     return false;
9484 
9485   const BuiltinType *FloatCandidateBT =
9486     dyn_cast<BuiltinType>(ToBool ? Source : Target);
9487   const Type *BoolCandidateType = ToBool ? Target : Source;
9488 
9489   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
9490           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
9491 }
9492 
9493 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
9494                                              SourceLocation CC) {
9495   unsigned NumArgs = TheCall->getNumArgs();
9496   for (unsigned i = 0; i < NumArgs; ++i) {
9497     Expr *CurrA = TheCall->getArg(i);
9498     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
9499       continue;
9500 
9501     bool IsSwapped = ((i > 0) &&
9502         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
9503     IsSwapped |= ((i < (NumArgs - 1)) &&
9504         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
9505     if (IsSwapped) {
9506       // Warn on this floating-point to bool conversion.
9507       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
9508                       CurrA->getType(), CC,
9509                       diag::warn_impcast_floating_point_to_bool);
9510     }
9511   }
9512 }
9513 
9514 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
9515                                    SourceLocation CC) {
9516   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
9517                         E->getExprLoc()))
9518     return;
9519 
9520   // Don't warn on functions which have return type nullptr_t.
9521   if (isa<CallExpr>(E))
9522     return;
9523 
9524   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
9525   const Expr::NullPointerConstantKind NullKind =
9526       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
9527   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
9528     return;
9529 
9530   // Return if target type is a safe conversion.
9531   if (T->isAnyPointerType() || T->isBlockPointerType() ||
9532       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
9533     return;
9534 
9535   SourceLocation Loc = E->getSourceRange().getBegin();
9536 
9537   // Venture through the macro stacks to get to the source of macro arguments.
9538   // The new location is a better location than the complete location that was
9539   // passed in.
9540   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
9541   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
9542 
9543   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
9544   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
9545     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
9546         Loc, S.SourceMgr, S.getLangOpts());
9547     if (MacroName == "NULL")
9548       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
9549   }
9550 
9551   // Only warn if the null and context location are in the same macro expansion.
9552   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
9553     return;
9554 
9555   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
9556       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
9557       << FixItHint::CreateReplacement(Loc,
9558                                       S.getFixItZeroLiteralForType(T, Loc));
9559 }
9560 
9561 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9562                                   ObjCArrayLiteral *ArrayLiteral);
9563 
9564 static void
9565 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9566                            ObjCDictionaryLiteral *DictionaryLiteral);
9567 
9568 /// Check a single element within a collection literal against the
9569 /// target element type.
9570 static void checkObjCCollectionLiteralElement(Sema &S,
9571                                               QualType TargetElementType,
9572                                               Expr *Element,
9573                                               unsigned ElementKind) {
9574   // Skip a bitcast to 'id' or qualified 'id'.
9575   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
9576     if (ICE->getCastKind() == CK_BitCast &&
9577         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
9578       Element = ICE->getSubExpr();
9579   }
9580 
9581   QualType ElementType = Element->getType();
9582   ExprResult ElementResult(Element);
9583   if (ElementType->getAs<ObjCObjectPointerType>() &&
9584       S.CheckSingleAssignmentConstraints(TargetElementType,
9585                                          ElementResult,
9586                                          false, false)
9587         != Sema::Compatible) {
9588     S.Diag(Element->getLocStart(),
9589            diag::warn_objc_collection_literal_element)
9590       << ElementType << ElementKind << TargetElementType
9591       << Element->getSourceRange();
9592   }
9593 
9594   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
9595     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
9596   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
9597     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
9598 }
9599 
9600 /// Check an Objective-C array literal being converted to the given
9601 /// target type.
9602 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9603                                   ObjCArrayLiteral *ArrayLiteral) {
9604   if (!S.NSArrayDecl)
9605     return;
9606 
9607   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9608   if (!TargetObjCPtr)
9609     return;
9610 
9611   if (TargetObjCPtr->isUnspecialized() ||
9612       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9613         != S.NSArrayDecl->getCanonicalDecl())
9614     return;
9615 
9616   auto TypeArgs = TargetObjCPtr->getTypeArgs();
9617   if (TypeArgs.size() != 1)
9618     return;
9619 
9620   QualType TargetElementType = TypeArgs[0];
9621   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
9622     checkObjCCollectionLiteralElement(S, TargetElementType,
9623                                       ArrayLiteral->getElement(I),
9624                                       0);
9625   }
9626 }
9627 
9628 /// Check an Objective-C dictionary literal being converted to the given
9629 /// target type.
9630 static void
9631 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9632                            ObjCDictionaryLiteral *DictionaryLiteral) {
9633   if (!S.NSDictionaryDecl)
9634     return;
9635 
9636   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9637   if (!TargetObjCPtr)
9638     return;
9639 
9640   if (TargetObjCPtr->isUnspecialized() ||
9641       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9642         != S.NSDictionaryDecl->getCanonicalDecl())
9643     return;
9644 
9645   auto TypeArgs = TargetObjCPtr->getTypeArgs();
9646   if (TypeArgs.size() != 2)
9647     return;
9648 
9649   QualType TargetKeyType = TypeArgs[0];
9650   QualType TargetObjectType = TypeArgs[1];
9651   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
9652     auto Element = DictionaryLiteral->getKeyValueElement(I);
9653     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
9654     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
9655   }
9656 }
9657 
9658 // Helper function to filter out cases for constant width constant conversion.
9659 // Don't warn on char array initialization or for non-decimal values.
9660 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
9661                                           SourceLocation CC) {
9662   // If initializing from a constant, and the constant starts with '0',
9663   // then it is a binary, octal, or hexadecimal.  Allow these constants
9664   // to fill all the bits, even if there is a sign change.
9665   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
9666     const char FirstLiteralCharacter =
9667         S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
9668     if (FirstLiteralCharacter == '0')
9669       return false;
9670   }
9671 
9672   // If the CC location points to a '{', and the type is char, then assume
9673   // assume it is an array initialization.
9674   if (CC.isValid() && T->isCharType()) {
9675     const char FirstContextCharacter =
9676         S.getSourceManager().getCharacterData(CC)[0];
9677     if (FirstContextCharacter == '{')
9678       return false;
9679   }
9680 
9681   return true;
9682 }
9683 
9684 static void
9685 CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
9686                         bool *ICContext = nullptr) {
9687   if (E->isTypeDependent() || E->isValueDependent()) return;
9688 
9689   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
9690   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
9691   if (Source == Target) return;
9692   if (Target->isDependentType()) return;
9693 
9694   // If the conversion context location is invalid don't complain. We also
9695   // don't want to emit a warning if the issue occurs from the expansion of
9696   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
9697   // delay this check as long as possible. Once we detect we are in that
9698   // scenario, we just return.
9699   if (CC.isInvalid())
9700     return;
9701 
9702   // Diagnose implicit casts to bool.
9703   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
9704     if (isa<StringLiteral>(E))
9705       // Warn on string literal to bool.  Checks for string literals in logical
9706       // and expressions, for instance, assert(0 && "error here"), are
9707       // prevented by a check in AnalyzeImplicitConversions().
9708       return DiagnoseImpCast(S, E, T, CC,
9709                              diag::warn_impcast_string_literal_to_bool);
9710     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
9711         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
9712       // This covers the literal expressions that evaluate to Objective-C
9713       // objects.
9714       return DiagnoseImpCast(S, E, T, CC,
9715                              diag::warn_impcast_objective_c_literal_to_bool);
9716     }
9717     if (Source->isPointerType() || Source->canDecayToPointerType()) {
9718       // Warn on pointer to bool conversion that is always true.
9719       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
9720                                      SourceRange(CC));
9721     }
9722   }
9723 
9724   // Check implicit casts from Objective-C collection literals to specialized
9725   // collection types, e.g., NSArray<NSString *> *.
9726   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
9727     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
9728   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
9729     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
9730 
9731   // Strip vector types.
9732   if (isa<VectorType>(Source)) {
9733     if (!isa<VectorType>(Target)) {
9734       if (S.SourceMgr.isInSystemMacro(CC))
9735         return;
9736       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
9737     }
9738 
9739     // If the vector cast is cast between two vectors of the same size, it is
9740     // a bitcast, not a conversion.
9741     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
9742       return;
9743 
9744     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
9745     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
9746   }
9747   if (auto VecTy = dyn_cast<VectorType>(Target))
9748     Target = VecTy->getElementType().getTypePtr();
9749 
9750   // Strip complex types.
9751   if (isa<ComplexType>(Source)) {
9752     if (!isa<ComplexType>(Target)) {
9753       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
9754         return;
9755 
9756       return DiagnoseImpCast(S, E, T, CC,
9757                              S.getLangOpts().CPlusPlus
9758                                  ? diag::err_impcast_complex_scalar
9759                                  : diag::warn_impcast_complex_scalar);
9760     }
9761 
9762     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
9763     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
9764   }
9765 
9766   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
9767   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
9768 
9769   // If the source is floating point...
9770   if (SourceBT && SourceBT->isFloatingPoint()) {
9771     // ...and the target is floating point...
9772     if (TargetBT && TargetBT->isFloatingPoint()) {
9773       // ...then warn if we're dropping FP rank.
9774 
9775       // Builtin FP kinds are ordered by increasing FP rank.
9776       if (SourceBT->getKind() > TargetBT->getKind()) {
9777         // Don't warn about float constants that are precisely
9778         // representable in the target type.
9779         Expr::EvalResult result;
9780         if (E->EvaluateAsRValue(result, S.Context)) {
9781           // Value might be a float, a float vector, or a float complex.
9782           if (IsSameFloatAfterCast(result.Val,
9783                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9784                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
9785             return;
9786         }
9787 
9788         if (S.SourceMgr.isInSystemMacro(CC))
9789           return;
9790 
9791         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
9792       }
9793       // ... or possibly if we're increasing rank, too
9794       else if (TargetBT->getKind() > SourceBT->getKind()) {
9795         if (S.SourceMgr.isInSystemMacro(CC))
9796           return;
9797 
9798         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
9799       }
9800       return;
9801     }
9802 
9803     // If the target is integral, always warn.
9804     if (TargetBT && TargetBT->isInteger()) {
9805       if (S.SourceMgr.isInSystemMacro(CC))
9806         return;
9807 
9808       DiagnoseFloatingImpCast(S, E, T, CC);
9809     }
9810 
9811     // Detect the case where a call result is converted from floating-point to
9812     // to bool, and the final argument to the call is converted from bool, to
9813     // discover this typo:
9814     //
9815     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
9816     //
9817     // FIXME: This is an incredibly special case; is there some more general
9818     // way to detect this class of misplaced-parentheses bug?
9819     if (Target->isBooleanType() && isa<CallExpr>(E)) {
9820       // Check last argument of function call to see if it is an
9821       // implicit cast from a type matching the type the result
9822       // is being cast to.
9823       CallExpr *CEx = cast<CallExpr>(E);
9824       if (unsigned NumArgs = CEx->getNumArgs()) {
9825         Expr *LastA = CEx->getArg(NumArgs - 1);
9826         Expr *InnerE = LastA->IgnoreParenImpCasts();
9827         if (isa<ImplicitCastExpr>(LastA) &&
9828             InnerE->getType()->isBooleanType()) {
9829           // Warn on this floating-point to bool conversion
9830           DiagnoseImpCast(S, E, T, CC,
9831                           diag::warn_impcast_floating_point_to_bool);
9832         }
9833       }
9834     }
9835     return;
9836   }
9837 
9838   DiagnoseNullConversion(S, E, T, CC);
9839 
9840   S.DiscardMisalignedMemberAddress(Target, E);
9841 
9842   if (!Source->isIntegerType() || !Target->isIntegerType())
9843     return;
9844 
9845   // TODO: remove this early return once the false positives for constant->bool
9846   // in templates, macros, etc, are reduced or removed.
9847   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9848     return;
9849 
9850   IntRange SourceRange = GetExprRange(S.Context, E);
9851   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
9852 
9853   if (SourceRange.Width > TargetRange.Width) {
9854     // If the source is a constant, use a default-on diagnostic.
9855     // TODO: this should happen for bitfield stores, too.
9856     llvm::APSInt Value(32);
9857     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
9858       if (S.SourceMgr.isInSystemMacro(CC))
9859         return;
9860 
9861       std::string PrettySourceValue = Value.toString(10);
9862       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
9863 
9864       S.DiagRuntimeBehavior(E->getExprLoc(), E,
9865         S.PDiag(diag::warn_impcast_integer_precision_constant)
9866             << PrettySourceValue << PrettyTargetValue
9867             << E->getType() << T << E->getSourceRange()
9868             << clang::SourceRange(CC));
9869       return;
9870     }
9871 
9872     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9873     if (S.SourceMgr.isInSystemMacro(CC))
9874       return;
9875 
9876     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
9877       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9878                              /* pruneControlFlow */ true);
9879     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
9880   }
9881 
9882   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9883       SourceRange.NonNegative && Source->isSignedIntegerType()) {
9884     // Warn when doing a signed to signed conversion, warn if the positive
9885     // source value is exactly the width of the target type, which will
9886     // cause a negative value to be stored.
9887 
9888     llvm::APSInt Value;
9889     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9890         !S.SourceMgr.isInSystemMacro(CC)) {
9891       if (isSameWidthConstantConversion(S, E, T, CC)) {
9892         std::string PrettySourceValue = Value.toString(10);
9893         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
9894 
9895         S.DiagRuntimeBehavior(
9896             E->getExprLoc(), E,
9897             S.PDiag(diag::warn_impcast_integer_precision_constant)
9898                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
9899                 << E->getSourceRange() << clang::SourceRange(CC));
9900         return;
9901       }
9902     }
9903 
9904     // Fall through for non-constants to give a sign conversion warning.
9905   }
9906 
9907   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9908       (!TargetRange.NonNegative && SourceRange.NonNegative &&
9909        SourceRange.Width == TargetRange.Width)) {
9910     if (S.SourceMgr.isInSystemMacro(CC))
9911       return;
9912 
9913     unsigned DiagID = diag::warn_impcast_integer_sign;
9914 
9915     // Traditionally, gcc has warned about this under -Wsign-compare.
9916     // We also want to warn about it in -Wconversion.
9917     // So if -Wconversion is off, use a completely identical diagnostic
9918     // in the sign-compare group.
9919     // The conditional-checking code will
9920     if (ICContext) {
9921       DiagID = diag::warn_impcast_integer_sign_conditional;
9922       *ICContext = true;
9923     }
9924 
9925     return DiagnoseImpCast(S, E, T, CC, DiagID);
9926   }
9927 
9928   // Diagnose conversions between different enumeration types.
9929   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9930   // type, to give us better diagnostics.
9931   QualType SourceType = E->getType();
9932   if (!S.getLangOpts().CPlusPlus) {
9933     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9934       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9935         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9936         SourceType = S.Context.getTypeDeclType(Enum);
9937         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9938       }
9939   }
9940 
9941   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9942     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
9943       if (SourceEnum->getDecl()->hasNameForLinkage() &&
9944           TargetEnum->getDecl()->hasNameForLinkage() &&
9945           SourceEnum != TargetEnum) {
9946         if (S.SourceMgr.isInSystemMacro(CC))
9947           return;
9948 
9949         return DiagnoseImpCast(S, E, SourceType, T, CC,
9950                                diag::warn_impcast_different_enum_types);
9951       }
9952 }
9953 
9954 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9955                                      SourceLocation CC, QualType T);
9956 
9957 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
9958                                     SourceLocation CC, bool &ICContext) {
9959   E = E->IgnoreParenImpCasts();
9960 
9961   if (isa<ConditionalOperator>(E))
9962     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
9963 
9964   AnalyzeImplicitConversions(S, E, CC);
9965   if (E->getType() != T)
9966     return CheckImplicitConversion(S, E, T, CC, &ICContext);
9967 }
9968 
9969 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9970                                      SourceLocation CC, QualType T) {
9971   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
9972 
9973   bool Suspicious = false;
9974   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9975   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
9976 
9977   // If -Wconversion would have warned about either of the candidates
9978   // for a signedness conversion to the context type...
9979   if (!Suspicious) return;
9980 
9981   // ...but it's currently ignored...
9982   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
9983     return;
9984 
9985   // ...then check whether it would have warned about either of the
9986   // candidates for a signedness conversion to the condition type.
9987   if (E->getType() == T) return;
9988 
9989   Suspicious = false;
9990   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
9991                           E->getType(), CC, &Suspicious);
9992   if (!Suspicious)
9993     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
9994                             E->getType(), CC, &Suspicious);
9995 }
9996 
9997 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9998 /// Input argument E is a logical expression.
9999 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
10000   if (S.getLangOpts().Bool)
10001     return;
10002   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
10003 }
10004 
10005 /// AnalyzeImplicitConversions - Find and report any interesting
10006 /// implicit conversions in the given expression.  There are a couple
10007 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
10008 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
10009                                        SourceLocation CC) {
10010   QualType T = OrigE->getType();
10011   Expr *E = OrigE->IgnoreParenImpCasts();
10012 
10013   if (E->isTypeDependent() || E->isValueDependent())
10014     return;
10015 
10016   // For conditional operators, we analyze the arguments as if they
10017   // were being fed directly into the output.
10018   if (isa<ConditionalOperator>(E)) {
10019     ConditionalOperator *CO = cast<ConditionalOperator>(E);
10020     CheckConditionalOperator(S, CO, CC, T);
10021     return;
10022   }
10023 
10024   // Check implicit argument conversions for function calls.
10025   if (CallExpr *Call = dyn_cast<CallExpr>(E))
10026     CheckImplicitArgumentConversions(S, Call, CC);
10027 
10028   // Go ahead and check any implicit conversions we might have skipped.
10029   // The non-canonical typecheck is just an optimization;
10030   // CheckImplicitConversion will filter out dead implicit conversions.
10031   if (E->getType() != T)
10032     CheckImplicitConversion(S, E, T, CC);
10033 
10034   // Now continue drilling into this expression.
10035 
10036   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
10037     // The bound subexpressions in a PseudoObjectExpr are not reachable
10038     // as transitive children.
10039     // FIXME: Use a more uniform representation for this.
10040     for (auto *SE : POE->semantics())
10041       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
10042         AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
10043   }
10044 
10045   // Skip past explicit casts.
10046   if (isa<ExplicitCastExpr>(E)) {
10047     E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
10048     return AnalyzeImplicitConversions(S, E, CC);
10049   }
10050 
10051   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10052     // Do a somewhat different check with comparison operators.
10053     if (BO->isComparisonOp())
10054       return AnalyzeComparison(S, BO);
10055 
10056     // And with simple assignments.
10057     if (BO->getOpcode() == BO_Assign)
10058       return AnalyzeAssignment(S, BO);
10059     // And with compound assignments.
10060     if (BO->isAssignmentOp())
10061       return AnalyzeCompoundAssignment(S, BO);
10062   }
10063 
10064   // These break the otherwise-useful invariant below.  Fortunately,
10065   // we don't really need to recurse into them, because any internal
10066   // expressions should have been analyzed already when they were
10067   // built into statements.
10068   if (isa<StmtExpr>(E)) return;
10069 
10070   // Don't descend into unevaluated contexts.
10071   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
10072 
10073   // Now just recurse over the expression's children.
10074   CC = E->getExprLoc();
10075   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
10076   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
10077   for (Stmt *SubStmt : E->children()) {
10078     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
10079     if (!ChildExpr)
10080       continue;
10081 
10082     if (IsLogicalAndOperator &&
10083         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
10084       // Ignore checking string literals that are in logical and operators.
10085       // This is a common pattern for asserts.
10086       continue;
10087     AnalyzeImplicitConversions(S, ChildExpr, CC);
10088   }
10089 
10090   if (BO && BO->isLogicalOp()) {
10091     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
10092     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
10093       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
10094 
10095     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
10096     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
10097       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
10098   }
10099 
10100   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
10101     if (U->getOpcode() == UO_LNot)
10102       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
10103 }
10104 
10105 /// Diagnose integer type and any valid implicit conversion to it.
10106 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
10107   // Taking into account implicit conversions,
10108   // allow any integer.
10109   if (!E->getType()->isIntegerType()) {
10110     S.Diag(E->getLocStart(),
10111            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
10112     return true;
10113   }
10114   // Potentially emit standard warnings for implicit conversions if enabled
10115   // using -Wconversion.
10116   CheckImplicitConversion(S, E, IntT, E->getLocStart());
10117   return false;
10118 }
10119 
10120 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
10121 // Returns true when emitting a warning about taking the address of a reference.
10122 static bool CheckForReference(Sema &SemaRef, const Expr *E,
10123                               const PartialDiagnostic &PD) {
10124   E = E->IgnoreParenImpCasts();
10125 
10126   const FunctionDecl *FD = nullptr;
10127 
10128   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10129     if (!DRE->getDecl()->getType()->isReferenceType())
10130       return false;
10131   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10132     if (!M->getMemberDecl()->getType()->isReferenceType())
10133       return false;
10134   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
10135     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
10136       return false;
10137     FD = Call->getDirectCallee();
10138   } else {
10139     return false;
10140   }
10141 
10142   SemaRef.Diag(E->getExprLoc(), PD);
10143 
10144   // If possible, point to location of function.
10145   if (FD) {
10146     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
10147   }
10148 
10149   return true;
10150 }
10151 
10152 // Returns true if the SourceLocation is expanded from any macro body.
10153 // Returns false if the SourceLocation is invalid, is from not in a macro
10154 // expansion, or is from expanded from a top-level macro argument.
10155 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
10156   if (Loc.isInvalid())
10157     return false;
10158 
10159   while (Loc.isMacroID()) {
10160     if (SM.isMacroBodyExpansion(Loc))
10161       return true;
10162     Loc = SM.getImmediateMacroCallerLoc(Loc);
10163   }
10164 
10165   return false;
10166 }
10167 
10168 /// \brief Diagnose pointers that are always non-null.
10169 /// \param E the expression containing the pointer
10170 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
10171 /// compared to a null pointer
10172 /// \param IsEqual True when the comparison is equal to a null pointer
10173 /// \param Range Extra SourceRange to highlight in the diagnostic
10174 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
10175                                         Expr::NullPointerConstantKind NullKind,
10176                                         bool IsEqual, SourceRange Range) {
10177   if (!E)
10178     return;
10179 
10180   // Don't warn inside macros.
10181   if (E->getExprLoc().isMacroID()) {
10182     const SourceManager &SM = getSourceManager();
10183     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
10184         IsInAnyMacroBody(SM, Range.getBegin()))
10185       return;
10186   }
10187   E = E->IgnoreImpCasts();
10188 
10189   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
10190 
10191   if (isa<CXXThisExpr>(E)) {
10192     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
10193                                 : diag::warn_this_bool_conversion;
10194     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
10195     return;
10196   }
10197 
10198   bool IsAddressOf = false;
10199 
10200   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10201     if (UO->getOpcode() != UO_AddrOf)
10202       return;
10203     IsAddressOf = true;
10204     E = UO->getSubExpr();
10205   }
10206 
10207   if (IsAddressOf) {
10208     unsigned DiagID = IsCompare
10209                           ? diag::warn_address_of_reference_null_compare
10210                           : diag::warn_address_of_reference_bool_conversion;
10211     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
10212                                          << IsEqual;
10213     if (CheckForReference(*this, E, PD)) {
10214       return;
10215     }
10216   }
10217 
10218   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
10219     bool IsParam = isa<NonNullAttr>(NonnullAttr);
10220     std::string Str;
10221     llvm::raw_string_ostream S(Str);
10222     E->printPretty(S, nullptr, getPrintingPolicy());
10223     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
10224                                 : diag::warn_cast_nonnull_to_bool;
10225     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
10226       << E->getSourceRange() << Range << IsEqual;
10227     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
10228   };
10229 
10230   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
10231   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
10232     if (auto *Callee = Call->getDirectCallee()) {
10233       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
10234         ComplainAboutNonnullParamOrCall(A);
10235         return;
10236       }
10237     }
10238   }
10239 
10240   // Expect to find a single Decl.  Skip anything more complicated.
10241   ValueDecl *D = nullptr;
10242   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
10243     D = R->getDecl();
10244   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10245     D = M->getMemberDecl();
10246   }
10247 
10248   // Weak Decls can be null.
10249   if (!D || D->isWeak())
10250     return;
10251 
10252   // Check for parameter decl with nonnull attribute
10253   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
10254     if (getCurFunction() &&
10255         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
10256       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
10257         ComplainAboutNonnullParamOrCall(A);
10258         return;
10259       }
10260 
10261       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
10262         auto ParamIter = llvm::find(FD->parameters(), PV);
10263         assert(ParamIter != FD->param_end());
10264         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
10265 
10266         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
10267           if (!NonNull->args_size()) {
10268               ComplainAboutNonnullParamOrCall(NonNull);
10269               return;
10270           }
10271 
10272           for (const ParamIdx &ArgNo : NonNull->args()) {
10273             if (ArgNo.getASTIndex() == ParamNo) {
10274               ComplainAboutNonnullParamOrCall(NonNull);
10275               return;
10276             }
10277           }
10278         }
10279       }
10280     }
10281   }
10282 
10283   QualType T = D->getType();
10284   const bool IsArray = T->isArrayType();
10285   const bool IsFunction = T->isFunctionType();
10286 
10287   // Address of function is used to silence the function warning.
10288   if (IsAddressOf && IsFunction) {
10289     return;
10290   }
10291 
10292   // Found nothing.
10293   if (!IsAddressOf && !IsFunction && !IsArray)
10294     return;
10295 
10296   // Pretty print the expression for the diagnostic.
10297   std::string Str;
10298   llvm::raw_string_ostream S(Str);
10299   E->printPretty(S, nullptr, getPrintingPolicy());
10300 
10301   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
10302                               : diag::warn_impcast_pointer_to_bool;
10303   enum {
10304     AddressOf,
10305     FunctionPointer,
10306     ArrayPointer
10307   } DiagType;
10308   if (IsAddressOf)
10309     DiagType = AddressOf;
10310   else if (IsFunction)
10311     DiagType = FunctionPointer;
10312   else if (IsArray)
10313     DiagType = ArrayPointer;
10314   else
10315     llvm_unreachable("Could not determine diagnostic.");
10316   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
10317                                 << Range << IsEqual;
10318 
10319   if (!IsFunction)
10320     return;
10321 
10322   // Suggest '&' to silence the function warning.
10323   Diag(E->getExprLoc(), diag::note_function_warning_silence)
10324       << FixItHint::CreateInsertion(E->getLocStart(), "&");
10325 
10326   // Check to see if '()' fixit should be emitted.
10327   QualType ReturnType;
10328   UnresolvedSet<4> NonTemplateOverloads;
10329   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
10330   if (ReturnType.isNull())
10331     return;
10332 
10333   if (IsCompare) {
10334     // There are two cases here.  If there is null constant, the only suggest
10335     // for a pointer return type.  If the null is 0, then suggest if the return
10336     // type is a pointer or an integer type.
10337     if (!ReturnType->isPointerType()) {
10338       if (NullKind == Expr::NPCK_ZeroExpression ||
10339           NullKind == Expr::NPCK_ZeroLiteral) {
10340         if (!ReturnType->isIntegerType())
10341           return;
10342       } else {
10343         return;
10344       }
10345     }
10346   } else { // !IsCompare
10347     // For function to bool, only suggest if the function pointer has bool
10348     // return type.
10349     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
10350       return;
10351   }
10352   Diag(E->getExprLoc(), diag::note_function_to_function_call)
10353       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
10354 }
10355 
10356 /// Diagnoses "dangerous" implicit conversions within the given
10357 /// expression (which is a full expression).  Implements -Wconversion
10358 /// and -Wsign-compare.
10359 ///
10360 /// \param CC the "context" location of the implicit conversion, i.e.
10361 ///   the most location of the syntactic entity requiring the implicit
10362 ///   conversion
10363 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
10364   // Don't diagnose in unevaluated contexts.
10365   if (isUnevaluatedContext())
10366     return;
10367 
10368   // Don't diagnose for value- or type-dependent expressions.
10369   if (E->isTypeDependent() || E->isValueDependent())
10370     return;
10371 
10372   // Check for array bounds violations in cases where the check isn't triggered
10373   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
10374   // ArraySubscriptExpr is on the RHS of a variable initialization.
10375   CheckArrayAccess(E);
10376 
10377   // This is not the right CC for (e.g.) a variable initialization.
10378   AnalyzeImplicitConversions(*this, E, CC);
10379 }
10380 
10381 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10382 /// Input argument E is a logical expression.
10383 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
10384   ::CheckBoolLikeConversion(*this, E, CC);
10385 }
10386 
10387 /// Diagnose when expression is an integer constant expression and its evaluation
10388 /// results in integer overflow
10389 void Sema::CheckForIntOverflow (Expr *E) {
10390   // Use a work list to deal with nested struct initializers.
10391   SmallVector<Expr *, 2> Exprs(1, E);
10392 
10393   do {
10394     Expr *OriginalE = Exprs.pop_back_val();
10395     Expr *E = OriginalE->IgnoreParenCasts();
10396 
10397     if (isa<BinaryOperator>(E)) {
10398       E->EvaluateForOverflow(Context);
10399       continue;
10400     }
10401 
10402     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
10403       Exprs.append(InitList->inits().begin(), InitList->inits().end());
10404     else if (isa<ObjCBoxedExpr>(OriginalE))
10405       E->EvaluateForOverflow(Context);
10406     else if (auto Call = dyn_cast<CallExpr>(E))
10407       Exprs.append(Call->arg_begin(), Call->arg_end());
10408     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
10409       Exprs.append(Message->arg_begin(), Message->arg_end());
10410   } while (!Exprs.empty());
10411 }
10412 
10413 namespace {
10414 
10415 /// \brief Visitor for expressions which looks for unsequenced operations on the
10416 /// same object.
10417 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
10418   using Base = EvaluatedExprVisitor<SequenceChecker>;
10419 
10420   /// \brief A tree of sequenced regions within an expression. Two regions are
10421   /// unsequenced if one is an ancestor or a descendent of the other. When we
10422   /// finish processing an expression with sequencing, such as a comma
10423   /// expression, we fold its tree nodes into its parent, since they are
10424   /// unsequenced with respect to nodes we will visit later.
10425   class SequenceTree {
10426     struct Value {
10427       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
10428       unsigned Parent : 31;
10429       unsigned Merged : 1;
10430     };
10431     SmallVector<Value, 8> Values;
10432 
10433   public:
10434     /// \brief A region within an expression which may be sequenced with respect
10435     /// to some other region.
10436     class Seq {
10437       friend class SequenceTree;
10438 
10439       unsigned Index = 0;
10440 
10441       explicit Seq(unsigned N) : Index(N) {}
10442 
10443     public:
10444       Seq() = default;
10445     };
10446 
10447     SequenceTree() { Values.push_back(Value(0)); }
10448     Seq root() const { return Seq(0); }
10449 
10450     /// \brief Create a new sequence of operations, which is an unsequenced
10451     /// subset of \p Parent. This sequence of operations is sequenced with
10452     /// respect to other children of \p Parent.
10453     Seq allocate(Seq Parent) {
10454       Values.push_back(Value(Parent.Index));
10455       return Seq(Values.size() - 1);
10456     }
10457 
10458     /// \brief Merge a sequence of operations into its parent.
10459     void merge(Seq S) {
10460       Values[S.Index].Merged = true;
10461     }
10462 
10463     /// \brief Determine whether two operations are unsequenced. This operation
10464     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
10465     /// should have been merged into its parent as appropriate.
10466     bool isUnsequenced(Seq Cur, Seq Old) {
10467       unsigned C = representative(Cur.Index);
10468       unsigned Target = representative(Old.Index);
10469       while (C >= Target) {
10470         if (C == Target)
10471           return true;
10472         C = Values[C].Parent;
10473       }
10474       return false;
10475     }
10476 
10477   private:
10478     /// \brief Pick a representative for a sequence.
10479     unsigned representative(unsigned K) {
10480       if (Values[K].Merged)
10481         // Perform path compression as we go.
10482         return Values[K].Parent = representative(Values[K].Parent);
10483       return K;
10484     }
10485   };
10486 
10487   /// An object for which we can track unsequenced uses.
10488   using Object = NamedDecl *;
10489 
10490   /// Different flavors of object usage which we track. We only track the
10491   /// least-sequenced usage of each kind.
10492   enum UsageKind {
10493     /// A read of an object. Multiple unsequenced reads are OK.
10494     UK_Use,
10495 
10496     /// A modification of an object which is sequenced before the value
10497     /// computation of the expression, such as ++n in C++.
10498     UK_ModAsValue,
10499 
10500     /// A modification of an object which is not sequenced before the value
10501     /// computation of the expression, such as n++.
10502     UK_ModAsSideEffect,
10503 
10504     UK_Count = UK_ModAsSideEffect + 1
10505   };
10506 
10507   struct Usage {
10508     Expr *Use = nullptr;
10509     SequenceTree::Seq Seq;
10510 
10511     Usage() = default;
10512   };
10513 
10514   struct UsageInfo {
10515     Usage Uses[UK_Count];
10516 
10517     /// Have we issued a diagnostic for this variable already?
10518     bool Diagnosed = false;
10519 
10520     UsageInfo() = default;
10521   };
10522   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
10523 
10524   Sema &SemaRef;
10525 
10526   /// Sequenced regions within the expression.
10527   SequenceTree Tree;
10528 
10529   /// Declaration modifications and references which we have seen.
10530   UsageInfoMap UsageMap;
10531 
10532   /// The region we are currently within.
10533   SequenceTree::Seq Region;
10534 
10535   /// Filled in with declarations which were modified as a side-effect
10536   /// (that is, post-increment operations).
10537   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
10538 
10539   /// Expressions to check later. We defer checking these to reduce
10540   /// stack usage.
10541   SmallVectorImpl<Expr *> &WorkList;
10542 
10543   /// RAII object wrapping the visitation of a sequenced subexpression of an
10544   /// expression. At the end of this process, the side-effects of the evaluation
10545   /// become sequenced with respect to the value computation of the result, so
10546   /// we downgrade any UK_ModAsSideEffect within the evaluation to
10547   /// UK_ModAsValue.
10548   struct SequencedSubexpression {
10549     SequencedSubexpression(SequenceChecker &Self)
10550       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
10551       Self.ModAsSideEffect = &ModAsSideEffect;
10552     }
10553 
10554     ~SequencedSubexpression() {
10555       for (auto &M : llvm::reverse(ModAsSideEffect)) {
10556         UsageInfo &U = Self.UsageMap[M.first];
10557         auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
10558         Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
10559         SideEffectUsage = M.second;
10560       }
10561       Self.ModAsSideEffect = OldModAsSideEffect;
10562     }
10563 
10564     SequenceChecker &Self;
10565     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
10566     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
10567   };
10568 
10569   /// RAII object wrapping the visitation of a subexpression which we might
10570   /// choose to evaluate as a constant. If any subexpression is evaluated and
10571   /// found to be non-constant, this allows us to suppress the evaluation of
10572   /// the outer expression.
10573   class EvaluationTracker {
10574   public:
10575     EvaluationTracker(SequenceChecker &Self)
10576         : Self(Self), Prev(Self.EvalTracker) {
10577       Self.EvalTracker = this;
10578     }
10579 
10580     ~EvaluationTracker() {
10581       Self.EvalTracker = Prev;
10582       if (Prev)
10583         Prev->EvalOK &= EvalOK;
10584     }
10585 
10586     bool evaluate(const Expr *E, bool &Result) {
10587       if (!EvalOK || E->isValueDependent())
10588         return false;
10589       EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
10590       return EvalOK;
10591     }
10592 
10593   private:
10594     SequenceChecker &Self;
10595     EvaluationTracker *Prev;
10596     bool EvalOK = true;
10597   } *EvalTracker = nullptr;
10598 
10599   /// \brief Find the object which is produced by the specified expression,
10600   /// if any.
10601   Object getObject(Expr *E, bool Mod) const {
10602     E = E->IgnoreParenCasts();
10603     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10604       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
10605         return getObject(UO->getSubExpr(), Mod);
10606     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10607       if (BO->getOpcode() == BO_Comma)
10608         return getObject(BO->getRHS(), Mod);
10609       if (Mod && BO->isAssignmentOp())
10610         return getObject(BO->getLHS(), Mod);
10611     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10612       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
10613       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
10614         return ME->getMemberDecl();
10615     } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10616       // FIXME: If this is a reference, map through to its value.
10617       return DRE->getDecl();
10618     return nullptr;
10619   }
10620 
10621   /// \brief Note that an object was modified or used by an expression.
10622   void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
10623     Usage &U = UI.Uses[UK];
10624     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
10625       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
10626         ModAsSideEffect->push_back(std::make_pair(O, U));
10627       U.Use = Ref;
10628       U.Seq = Region;
10629     }
10630   }
10631 
10632   /// \brief Check whether a modification or use conflicts with a prior usage.
10633   void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
10634                   bool IsModMod) {
10635     if (UI.Diagnosed)
10636       return;
10637 
10638     const Usage &U = UI.Uses[OtherKind];
10639     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
10640       return;
10641 
10642     Expr *Mod = U.Use;
10643     Expr *ModOrUse = Ref;
10644     if (OtherKind == UK_Use)
10645       std::swap(Mod, ModOrUse);
10646 
10647     SemaRef.Diag(Mod->getExprLoc(),
10648                  IsModMod ? diag::warn_unsequenced_mod_mod
10649                           : diag::warn_unsequenced_mod_use)
10650       << O << SourceRange(ModOrUse->getExprLoc());
10651     UI.Diagnosed = true;
10652   }
10653 
10654   void notePreUse(Object O, Expr *Use) {
10655     UsageInfo &U = UsageMap[O];
10656     // Uses conflict with other modifications.
10657     checkUsage(O, U, Use, UK_ModAsValue, false);
10658   }
10659 
10660   void notePostUse(Object O, Expr *Use) {
10661     UsageInfo &U = UsageMap[O];
10662     checkUsage(O, U, Use, UK_ModAsSideEffect, false);
10663     addUsage(U, O, Use, UK_Use);
10664   }
10665 
10666   void notePreMod(Object O, Expr *Mod) {
10667     UsageInfo &U = UsageMap[O];
10668     // Modifications conflict with other modifications and with uses.
10669     checkUsage(O, U, Mod, UK_ModAsValue, true);
10670     checkUsage(O, U, Mod, UK_Use, false);
10671   }
10672 
10673   void notePostMod(Object O, Expr *Use, UsageKind UK) {
10674     UsageInfo &U = UsageMap[O];
10675     checkUsage(O, U, Use, UK_ModAsSideEffect, true);
10676     addUsage(U, O, Use, UK);
10677   }
10678 
10679 public:
10680   SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
10681       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
10682     Visit(E);
10683   }
10684 
10685   void VisitStmt(Stmt *S) {
10686     // Skip all statements which aren't expressions for now.
10687   }
10688 
10689   void VisitExpr(Expr *E) {
10690     // By default, just recurse to evaluated subexpressions.
10691     Base::VisitStmt(E);
10692   }
10693 
10694   void VisitCastExpr(CastExpr *E) {
10695     Object O = Object();
10696     if (E->getCastKind() == CK_LValueToRValue)
10697       O = getObject(E->getSubExpr(), false);
10698 
10699     if (O)
10700       notePreUse(O, E);
10701     VisitExpr(E);
10702     if (O)
10703       notePostUse(O, E);
10704   }
10705 
10706   void VisitBinComma(BinaryOperator *BO) {
10707     // C++11 [expr.comma]p1:
10708     //   Every value computation and side effect associated with the left
10709     //   expression is sequenced before every value computation and side
10710     //   effect associated with the right expression.
10711     SequenceTree::Seq LHS = Tree.allocate(Region);
10712     SequenceTree::Seq RHS = Tree.allocate(Region);
10713     SequenceTree::Seq OldRegion = Region;
10714 
10715     {
10716       SequencedSubexpression SeqLHS(*this);
10717       Region = LHS;
10718       Visit(BO->getLHS());
10719     }
10720 
10721     Region = RHS;
10722     Visit(BO->getRHS());
10723 
10724     Region = OldRegion;
10725 
10726     // Forget that LHS and RHS are sequenced. They are both unsequenced
10727     // with respect to other stuff.
10728     Tree.merge(LHS);
10729     Tree.merge(RHS);
10730   }
10731 
10732   void VisitBinAssign(BinaryOperator *BO) {
10733     // The modification is sequenced after the value computation of the LHS
10734     // and RHS, so check it before inspecting the operands and update the
10735     // map afterwards.
10736     Object O = getObject(BO->getLHS(), true);
10737     if (!O)
10738       return VisitExpr(BO);
10739 
10740     notePreMod(O, BO);
10741 
10742     // C++11 [expr.ass]p7:
10743     //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
10744     //   only once.
10745     //
10746     // Therefore, for a compound assignment operator, O is considered used
10747     // everywhere except within the evaluation of E1 itself.
10748     if (isa<CompoundAssignOperator>(BO))
10749       notePreUse(O, BO);
10750 
10751     Visit(BO->getLHS());
10752 
10753     if (isa<CompoundAssignOperator>(BO))
10754       notePostUse(O, BO);
10755 
10756     Visit(BO->getRHS());
10757 
10758     // C++11 [expr.ass]p1:
10759     //   the assignment is sequenced [...] before the value computation of the
10760     //   assignment expression.
10761     // C11 6.5.16/3 has no such rule.
10762     notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10763                                                        : UK_ModAsSideEffect);
10764   }
10765 
10766   void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
10767     VisitBinAssign(CAO);
10768   }
10769 
10770   void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10771   void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10772   void VisitUnaryPreIncDec(UnaryOperator *UO) {
10773     Object O = getObject(UO->getSubExpr(), true);
10774     if (!O)
10775       return VisitExpr(UO);
10776 
10777     notePreMod(O, UO);
10778     Visit(UO->getSubExpr());
10779     // C++11 [expr.pre.incr]p1:
10780     //   the expression ++x is equivalent to x+=1
10781     notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10782                                                        : UK_ModAsSideEffect);
10783   }
10784 
10785   void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10786   void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10787   void VisitUnaryPostIncDec(UnaryOperator *UO) {
10788     Object O = getObject(UO->getSubExpr(), true);
10789     if (!O)
10790       return VisitExpr(UO);
10791 
10792     notePreMod(O, UO);
10793     Visit(UO->getSubExpr());
10794     notePostMod(O, UO, UK_ModAsSideEffect);
10795   }
10796 
10797   /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
10798   void VisitBinLOr(BinaryOperator *BO) {
10799     // The side-effects of the LHS of an '&&' are sequenced before the
10800     // value computation of the RHS, and hence before the value computation
10801     // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10802     // as if they were unconditionally sequenced.
10803     EvaluationTracker Eval(*this);
10804     {
10805       SequencedSubexpression Sequenced(*this);
10806       Visit(BO->getLHS());
10807     }
10808 
10809     bool Result;
10810     if (Eval.evaluate(BO->getLHS(), Result)) {
10811       if (!Result)
10812         Visit(BO->getRHS());
10813     } else {
10814       // Check for unsequenced operations in the RHS, treating it as an
10815       // entirely separate evaluation.
10816       //
10817       // FIXME: If there are operations in the RHS which are unsequenced
10818       // with respect to operations outside the RHS, and those operations
10819       // are unconditionally evaluated, diagnose them.
10820       WorkList.push_back(BO->getRHS());
10821     }
10822   }
10823   void VisitBinLAnd(BinaryOperator *BO) {
10824     EvaluationTracker Eval(*this);
10825     {
10826       SequencedSubexpression Sequenced(*this);
10827       Visit(BO->getLHS());
10828     }
10829 
10830     bool Result;
10831     if (Eval.evaluate(BO->getLHS(), Result)) {
10832       if (Result)
10833         Visit(BO->getRHS());
10834     } else {
10835       WorkList.push_back(BO->getRHS());
10836     }
10837   }
10838 
10839   // Only visit the condition, unless we can be sure which subexpression will
10840   // be chosen.
10841   void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
10842     EvaluationTracker Eval(*this);
10843     {
10844       SequencedSubexpression Sequenced(*this);
10845       Visit(CO->getCond());
10846     }
10847 
10848     bool Result;
10849     if (Eval.evaluate(CO->getCond(), Result))
10850       Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
10851     else {
10852       WorkList.push_back(CO->getTrueExpr());
10853       WorkList.push_back(CO->getFalseExpr());
10854     }
10855   }
10856 
10857   void VisitCallExpr(CallExpr *CE) {
10858     // C++11 [intro.execution]p15:
10859     //   When calling a function [...], every value computation and side effect
10860     //   associated with any argument expression, or with the postfix expression
10861     //   designating the called function, is sequenced before execution of every
10862     //   expression or statement in the body of the function [and thus before
10863     //   the value computation of its result].
10864     SequencedSubexpression Sequenced(*this);
10865     Base::VisitCallExpr(CE);
10866 
10867     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10868   }
10869 
10870   void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
10871     // This is a call, so all subexpressions are sequenced before the result.
10872     SequencedSubexpression Sequenced(*this);
10873 
10874     if (!CCE->isListInitialization())
10875       return VisitExpr(CCE);
10876 
10877     // In C++11, list initializations are sequenced.
10878     SmallVector<SequenceTree::Seq, 32> Elts;
10879     SequenceTree::Seq Parent = Region;
10880     for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10881                                         E = CCE->arg_end();
10882          I != E; ++I) {
10883       Region = Tree.allocate(Parent);
10884       Elts.push_back(Region);
10885       Visit(*I);
10886     }
10887 
10888     // Forget that the initializers are sequenced.
10889     Region = Parent;
10890     for (unsigned I = 0; I < Elts.size(); ++I)
10891       Tree.merge(Elts[I]);
10892   }
10893 
10894   void VisitInitListExpr(InitListExpr *ILE) {
10895     if (!SemaRef.getLangOpts().CPlusPlus11)
10896       return VisitExpr(ILE);
10897 
10898     // In C++11, list initializations are sequenced.
10899     SmallVector<SequenceTree::Seq, 32> Elts;
10900     SequenceTree::Seq Parent = Region;
10901     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10902       Expr *E = ILE->getInit(I);
10903       if (!E) continue;
10904       Region = Tree.allocate(Parent);
10905       Elts.push_back(Region);
10906       Visit(E);
10907     }
10908 
10909     // Forget that the initializers are sequenced.
10910     Region = Parent;
10911     for (unsigned I = 0; I < Elts.size(); ++I)
10912       Tree.merge(Elts[I]);
10913   }
10914 };
10915 
10916 } // namespace
10917 
10918 void Sema::CheckUnsequencedOperations(Expr *E) {
10919   SmallVector<Expr *, 8> WorkList;
10920   WorkList.push_back(E);
10921   while (!WorkList.empty()) {
10922     Expr *Item = WorkList.pop_back_val();
10923     SequenceChecker(*this, Item, WorkList);
10924   }
10925 }
10926 
10927 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10928                               bool IsConstexpr) {
10929   CheckImplicitConversions(E, CheckLoc);
10930   if (!E->isInstantiationDependent())
10931     CheckUnsequencedOperations(E);
10932   if (!IsConstexpr && !E->isValueDependent())
10933     CheckForIntOverflow(E);
10934   DiagnoseMisalignedMembers();
10935 }
10936 
10937 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10938                                        FieldDecl *BitField,
10939                                        Expr *Init) {
10940   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10941 }
10942 
10943 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
10944                                          SourceLocation Loc) {
10945   if (!PType->isVariablyModifiedType())
10946     return;
10947   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10948     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10949     return;
10950   }
10951   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10952     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10953     return;
10954   }
10955   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10956     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10957     return;
10958   }
10959 
10960   const ArrayType *AT = S.Context.getAsArrayType(PType);
10961   if (!AT)
10962     return;
10963 
10964   if (AT->getSizeModifier() != ArrayType::Star) {
10965     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
10966     return;
10967   }
10968 
10969   S.Diag(Loc, diag::err_array_star_in_function_definition);
10970 }
10971 
10972 /// CheckParmsForFunctionDef - Check that the parameters of the given
10973 /// function are appropriate for the definition of a function. This
10974 /// takes care of any checks that cannot be performed on the
10975 /// declaration itself, e.g., that the types of each of the function
10976 /// parameters are complete.
10977 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
10978                                     bool CheckParameterNames) {
10979   bool HasInvalidParm = false;
10980   for (ParmVarDecl *Param : Parameters) {
10981     // C99 6.7.5.3p4: the parameters in a parameter type list in a
10982     // function declarator that is part of a function definition of
10983     // that function shall not have incomplete type.
10984     //
10985     // This is also C++ [dcl.fct]p6.
10986     if (!Param->isInvalidDecl() &&
10987         RequireCompleteType(Param->getLocation(), Param->getType(),
10988                             diag::err_typecheck_decl_incomplete_type)) {
10989       Param->setInvalidDecl();
10990       HasInvalidParm = true;
10991     }
10992 
10993     // C99 6.9.1p5: If the declarator includes a parameter type list, the
10994     // declaration of each parameter shall include an identifier.
10995     if (CheckParameterNames &&
10996         Param->getIdentifier() == nullptr &&
10997         !Param->isImplicit() &&
10998         !getLangOpts().CPlusPlus)
10999       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
11000 
11001     // C99 6.7.5.3p12:
11002     //   If the function declarator is not part of a definition of that
11003     //   function, parameters may have incomplete type and may use the [*]
11004     //   notation in their sequences of declarator specifiers to specify
11005     //   variable length array types.
11006     QualType PType = Param->getOriginalType();
11007     // FIXME: This diagnostic should point the '[*]' if source-location
11008     // information is added for it.
11009     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
11010 
11011     // If the parameter is a c++ class type and it has to be destructed in the
11012     // callee function, declare the destructor so that it can be called by the
11013     // callee function. Do not perform any direct access check on the dtor here.
11014     if (!Param->isInvalidDecl()) {
11015       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
11016         if (!ClassDecl->isInvalidDecl() &&
11017             !ClassDecl->hasIrrelevantDestructor() &&
11018             !ClassDecl->isDependentContext() &&
11019             Context.isParamDestroyedInCallee(Param->getType())) {
11020           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
11021           MarkFunctionReferenced(Param->getLocation(), Destructor);
11022           DiagnoseUseOfDecl(Destructor, Param->getLocation());
11023         }
11024       }
11025     }
11026 
11027     // Parameters with the pass_object_size attribute only need to be marked
11028     // constant at function definitions. Because we lack information about
11029     // whether we're on a declaration or definition when we're instantiating the
11030     // attribute, we need to check for constness here.
11031     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
11032       if (!Param->getType().isConstQualified())
11033         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
11034             << Attr->getSpelling() << 1;
11035   }
11036 
11037   return HasInvalidParm;
11038 }
11039 
11040 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
11041 /// or MemberExpr.
11042 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
11043                               ASTContext &Context) {
11044   if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
11045     return Context.getDeclAlign(DRE->getDecl());
11046 
11047   if (const auto *ME = dyn_cast<MemberExpr>(E))
11048     return Context.getDeclAlign(ME->getMemberDecl());
11049 
11050   return TypeAlign;
11051 }
11052 
11053 /// CheckCastAlign - Implements -Wcast-align, which warns when a
11054 /// pointer cast increases the alignment requirements.
11055 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
11056   // This is actually a lot of work to potentially be doing on every
11057   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
11058   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
11059     return;
11060 
11061   // Ignore dependent types.
11062   if (T->isDependentType() || Op->getType()->isDependentType())
11063     return;
11064 
11065   // Require that the destination be a pointer type.
11066   const PointerType *DestPtr = T->getAs<PointerType>();
11067   if (!DestPtr) return;
11068 
11069   // If the destination has alignment 1, we're done.
11070   QualType DestPointee = DestPtr->getPointeeType();
11071   if (DestPointee->isIncompleteType()) return;
11072   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
11073   if (DestAlign.isOne()) return;
11074 
11075   // Require that the source be a pointer type.
11076   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
11077   if (!SrcPtr) return;
11078   QualType SrcPointee = SrcPtr->getPointeeType();
11079 
11080   // Whitelist casts from cv void*.  We already implicitly
11081   // whitelisted casts to cv void*, since they have alignment 1.
11082   // Also whitelist casts involving incomplete types, which implicitly
11083   // includes 'void'.
11084   if (SrcPointee->isIncompleteType()) return;
11085 
11086   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
11087 
11088   if (auto *CE = dyn_cast<CastExpr>(Op)) {
11089     if (CE->getCastKind() == CK_ArrayToPointerDecay)
11090       SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
11091   } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
11092     if (UO->getOpcode() == UO_AddrOf)
11093       SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
11094   }
11095 
11096   if (SrcAlign >= DestAlign) return;
11097 
11098   Diag(TRange.getBegin(), diag::warn_cast_align)
11099     << Op->getType() << T
11100     << static_cast<unsigned>(SrcAlign.getQuantity())
11101     << static_cast<unsigned>(DestAlign.getQuantity())
11102     << TRange << Op->getSourceRange();
11103 }
11104 
11105 /// \brief Check whether this array fits the idiom of a size-one tail padded
11106 /// array member of a struct.
11107 ///
11108 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
11109 /// commonly used to emulate flexible arrays in C89 code.
11110 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
11111                                     const NamedDecl *ND) {
11112   if (Size != 1 || !ND) return false;
11113 
11114   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
11115   if (!FD) return false;
11116 
11117   // Don't consider sizes resulting from macro expansions or template argument
11118   // substitution to form C89 tail-padded arrays.
11119 
11120   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
11121   while (TInfo) {
11122     TypeLoc TL = TInfo->getTypeLoc();
11123     // Look through typedefs.
11124     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
11125       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
11126       TInfo = TDL->getTypeSourceInfo();
11127       continue;
11128     }
11129     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
11130       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
11131       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
11132         return false;
11133     }
11134     break;
11135   }
11136 
11137   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
11138   if (!RD) return false;
11139   if (RD->isUnion()) return false;
11140   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
11141     if (!CRD->isStandardLayout()) return false;
11142   }
11143 
11144   // See if this is the last field decl in the record.
11145   const Decl *D = FD;
11146   while ((D = D->getNextDeclInContext()))
11147     if (isa<FieldDecl>(D))
11148       return false;
11149   return true;
11150 }
11151 
11152 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
11153                             const ArraySubscriptExpr *ASE,
11154                             bool AllowOnePastEnd, bool IndexNegated) {
11155   IndexExpr = IndexExpr->IgnoreParenImpCasts();
11156   if (IndexExpr->isValueDependent())
11157     return;
11158 
11159   const Type *EffectiveType =
11160       BaseExpr->getType()->getPointeeOrArrayElementType();
11161   BaseExpr = BaseExpr->IgnoreParenCasts();
11162   const ConstantArrayType *ArrayTy =
11163     Context.getAsConstantArrayType(BaseExpr->getType());
11164   if (!ArrayTy)
11165     return;
11166 
11167   llvm::APSInt index;
11168   if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
11169     return;
11170   if (IndexNegated)
11171     index = -index;
11172 
11173   const NamedDecl *ND = nullptr;
11174   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
11175     ND = DRE->getDecl();
11176   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
11177     ND = ME->getMemberDecl();
11178 
11179   if (index.isUnsigned() || !index.isNegative()) {
11180     llvm::APInt size = ArrayTy->getSize();
11181     if (!size.isStrictlyPositive())
11182       return;
11183 
11184     const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
11185     if (BaseType != EffectiveType) {
11186       // Make sure we're comparing apples to apples when comparing index to size
11187       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
11188       uint64_t array_typesize = Context.getTypeSize(BaseType);
11189       // Handle ptrarith_typesize being zero, such as when casting to void*
11190       if (!ptrarith_typesize) ptrarith_typesize = 1;
11191       if (ptrarith_typesize != array_typesize) {
11192         // There's a cast to a different size type involved
11193         uint64_t ratio = array_typesize / ptrarith_typesize;
11194         // TODO: Be smarter about handling cases where array_typesize is not a
11195         // multiple of ptrarith_typesize
11196         if (ptrarith_typesize * ratio == array_typesize)
11197           size *= llvm::APInt(size.getBitWidth(), ratio);
11198       }
11199     }
11200 
11201     if (size.getBitWidth() > index.getBitWidth())
11202       index = index.zext(size.getBitWidth());
11203     else if (size.getBitWidth() < index.getBitWidth())
11204       size = size.zext(index.getBitWidth());
11205 
11206     // For array subscripting the index must be less than size, but for pointer
11207     // arithmetic also allow the index (offset) to be equal to size since
11208     // computing the next address after the end of the array is legal and
11209     // commonly done e.g. in C++ iterators and range-based for loops.
11210     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
11211       return;
11212 
11213     // Also don't warn for arrays of size 1 which are members of some
11214     // structure. These are often used to approximate flexible arrays in C89
11215     // code.
11216     if (IsTailPaddedMemberArray(*this, size, ND))
11217       return;
11218 
11219     // Suppress the warning if the subscript expression (as identified by the
11220     // ']' location) and the index expression are both from macro expansions
11221     // within a system header.
11222     if (ASE) {
11223       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
11224           ASE->getRBracketLoc());
11225       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
11226         SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
11227             IndexExpr->getLocStart());
11228         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
11229           return;
11230       }
11231     }
11232 
11233     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
11234     if (ASE)
11235       DiagID = diag::warn_array_index_exceeds_bounds;
11236 
11237     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11238                         PDiag(DiagID) << index.toString(10, true)
11239                           << size.toString(10, true)
11240                           << (unsigned)size.getLimitedValue(~0U)
11241                           << IndexExpr->getSourceRange());
11242   } else {
11243     unsigned DiagID = diag::warn_array_index_precedes_bounds;
11244     if (!ASE) {
11245       DiagID = diag::warn_ptr_arith_precedes_bounds;
11246       if (index.isNegative()) index = -index;
11247     }
11248 
11249     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11250                         PDiag(DiagID) << index.toString(10, true)
11251                           << IndexExpr->getSourceRange());
11252   }
11253 
11254   if (!ND) {
11255     // Try harder to find a NamedDecl to point at in the note.
11256     while (const ArraySubscriptExpr *ASE =
11257            dyn_cast<ArraySubscriptExpr>(BaseExpr))
11258       BaseExpr = ASE->getBase()->IgnoreParenCasts();
11259     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
11260       ND = DRE->getDecl();
11261     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
11262       ND = ME->getMemberDecl();
11263   }
11264 
11265   if (ND)
11266     DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
11267                         PDiag(diag::note_array_index_out_of_bounds)
11268                           << ND->getDeclName());
11269 }
11270 
11271 void Sema::CheckArrayAccess(const Expr *expr) {
11272   int AllowOnePastEnd = 0;
11273   while (expr) {
11274     expr = expr->IgnoreParenImpCasts();
11275     switch (expr->getStmtClass()) {
11276       case Stmt::ArraySubscriptExprClass: {
11277         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
11278         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
11279                          AllowOnePastEnd > 0);
11280         return;
11281       }
11282       case Stmt::OMPArraySectionExprClass: {
11283         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
11284         if (ASE->getLowerBound())
11285           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
11286                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
11287         return;
11288       }
11289       case Stmt::UnaryOperatorClass: {
11290         // Only unwrap the * and & unary operators
11291         const UnaryOperator *UO = cast<UnaryOperator>(expr);
11292         expr = UO->getSubExpr();
11293         switch (UO->getOpcode()) {
11294           case UO_AddrOf:
11295             AllowOnePastEnd++;
11296             break;
11297           case UO_Deref:
11298             AllowOnePastEnd--;
11299             break;
11300           default:
11301             return;
11302         }
11303         break;
11304       }
11305       case Stmt::ConditionalOperatorClass: {
11306         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
11307         if (const Expr *lhs = cond->getLHS())
11308           CheckArrayAccess(lhs);
11309         if (const Expr *rhs = cond->getRHS())
11310           CheckArrayAccess(rhs);
11311         return;
11312       }
11313       case Stmt::CXXOperatorCallExprClass: {
11314         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
11315         for (const auto *Arg : OCE->arguments())
11316           CheckArrayAccess(Arg);
11317         return;
11318       }
11319       default:
11320         return;
11321     }
11322   }
11323 }
11324 
11325 //===--- CHECK: Objective-C retain cycles ----------------------------------//
11326 
11327 namespace {
11328 
11329 struct RetainCycleOwner {
11330   VarDecl *Variable = nullptr;
11331   SourceRange Range;
11332   SourceLocation Loc;
11333   bool Indirect = false;
11334 
11335   RetainCycleOwner() = default;
11336 
11337   void setLocsFrom(Expr *e) {
11338     Loc = e->getExprLoc();
11339     Range = e->getSourceRange();
11340   }
11341 };
11342 
11343 } // namespace
11344 
11345 /// Consider whether capturing the given variable can possibly lead to
11346 /// a retain cycle.
11347 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
11348   // In ARC, it's captured strongly iff the variable has __strong
11349   // lifetime.  In MRR, it's captured strongly if the variable is
11350   // __block and has an appropriate type.
11351   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11352     return false;
11353 
11354   owner.Variable = var;
11355   if (ref)
11356     owner.setLocsFrom(ref);
11357   return true;
11358 }
11359 
11360 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
11361   while (true) {
11362     e = e->IgnoreParens();
11363     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
11364       switch (cast->getCastKind()) {
11365       case CK_BitCast:
11366       case CK_LValueBitCast:
11367       case CK_LValueToRValue:
11368       case CK_ARCReclaimReturnedObject:
11369         e = cast->getSubExpr();
11370         continue;
11371 
11372       default:
11373         return false;
11374       }
11375     }
11376 
11377     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
11378       ObjCIvarDecl *ivar = ref->getDecl();
11379       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11380         return false;
11381 
11382       // Try to find a retain cycle in the base.
11383       if (!findRetainCycleOwner(S, ref->getBase(), owner))
11384         return false;
11385 
11386       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
11387       owner.Indirect = true;
11388       return true;
11389     }
11390 
11391     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
11392       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
11393       if (!var) return false;
11394       return considerVariable(var, ref, owner);
11395     }
11396 
11397     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
11398       if (member->isArrow()) return false;
11399 
11400       // Don't count this as an indirect ownership.
11401       e = member->getBase();
11402       continue;
11403     }
11404 
11405     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
11406       // Only pay attention to pseudo-objects on property references.
11407       ObjCPropertyRefExpr *pre
11408         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
11409                                               ->IgnoreParens());
11410       if (!pre) return false;
11411       if (pre->isImplicitProperty()) return false;
11412       ObjCPropertyDecl *property = pre->getExplicitProperty();
11413       if (!property->isRetaining() &&
11414           !(property->getPropertyIvarDecl() &&
11415             property->getPropertyIvarDecl()->getType()
11416               .getObjCLifetime() == Qualifiers::OCL_Strong))
11417           return false;
11418 
11419       owner.Indirect = true;
11420       if (pre->isSuperReceiver()) {
11421         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
11422         if (!owner.Variable)
11423           return false;
11424         owner.Loc = pre->getLocation();
11425         owner.Range = pre->getSourceRange();
11426         return true;
11427       }
11428       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
11429                               ->getSourceExpr());
11430       continue;
11431     }
11432 
11433     // Array ivars?
11434 
11435     return false;
11436   }
11437 }
11438 
11439 namespace {
11440 
11441   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
11442     ASTContext &Context;
11443     VarDecl *Variable;
11444     Expr *Capturer = nullptr;
11445     bool VarWillBeReased = false;
11446 
11447     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
11448         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
11449           Context(Context), Variable(variable) {}
11450 
11451     void VisitDeclRefExpr(DeclRefExpr *ref) {
11452       if (ref->getDecl() == Variable && !Capturer)
11453         Capturer = ref;
11454     }
11455 
11456     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
11457       if (Capturer) return;
11458       Visit(ref->getBase());
11459       if (Capturer && ref->isFreeIvar())
11460         Capturer = ref;
11461     }
11462 
11463     void VisitBlockExpr(BlockExpr *block) {
11464       // Look inside nested blocks
11465       if (block->getBlockDecl()->capturesVariable(Variable))
11466         Visit(block->getBlockDecl()->getBody());
11467     }
11468 
11469     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
11470       if (Capturer) return;
11471       if (OVE->getSourceExpr())
11472         Visit(OVE->getSourceExpr());
11473     }
11474 
11475     void VisitBinaryOperator(BinaryOperator *BinOp) {
11476       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
11477         return;
11478       Expr *LHS = BinOp->getLHS();
11479       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
11480         if (DRE->getDecl() != Variable)
11481           return;
11482         if (Expr *RHS = BinOp->getRHS()) {
11483           RHS = RHS->IgnoreParenCasts();
11484           llvm::APSInt Value;
11485           VarWillBeReased =
11486             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
11487         }
11488       }
11489     }
11490   };
11491 
11492 } // namespace
11493 
11494 /// Check whether the given argument is a block which captures a
11495 /// variable.
11496 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
11497   assert(owner.Variable && owner.Loc.isValid());
11498 
11499   e = e->IgnoreParenCasts();
11500 
11501   // Look through [^{...} copy] and Block_copy(^{...}).
11502   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
11503     Selector Cmd = ME->getSelector();
11504     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
11505       e = ME->getInstanceReceiver();
11506       if (!e)
11507         return nullptr;
11508       e = e->IgnoreParenCasts();
11509     }
11510   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
11511     if (CE->getNumArgs() == 1) {
11512       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
11513       if (Fn) {
11514         const IdentifierInfo *FnI = Fn->getIdentifier();
11515         if (FnI && FnI->isStr("_Block_copy")) {
11516           e = CE->getArg(0)->IgnoreParenCasts();
11517         }
11518       }
11519     }
11520   }
11521 
11522   BlockExpr *block = dyn_cast<BlockExpr>(e);
11523   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
11524     return nullptr;
11525 
11526   FindCaptureVisitor visitor(S.Context, owner.Variable);
11527   visitor.Visit(block->getBlockDecl()->getBody());
11528   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
11529 }
11530 
11531 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
11532                                 RetainCycleOwner &owner) {
11533   assert(capturer);
11534   assert(owner.Variable && owner.Loc.isValid());
11535 
11536   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
11537     << owner.Variable << capturer->getSourceRange();
11538   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
11539     << owner.Indirect << owner.Range;
11540 }
11541 
11542 /// Check for a keyword selector that starts with the word 'add' or
11543 /// 'set'.
11544 static bool isSetterLikeSelector(Selector sel) {
11545   if (sel.isUnarySelector()) return false;
11546 
11547   StringRef str = sel.getNameForSlot(0);
11548   while (!str.empty() && str.front() == '_') str = str.substr(1);
11549   if (str.startswith("set"))
11550     str = str.substr(3);
11551   else if (str.startswith("add")) {
11552     // Specially whitelist 'addOperationWithBlock:'.
11553     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
11554       return false;
11555     str = str.substr(3);
11556   }
11557   else
11558     return false;
11559 
11560   if (str.empty()) return true;
11561   return !isLowercase(str.front());
11562 }
11563 
11564 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
11565                                                     ObjCMessageExpr *Message) {
11566   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
11567                                                 Message->getReceiverInterface(),
11568                                                 NSAPI::ClassId_NSMutableArray);
11569   if (!IsMutableArray) {
11570     return None;
11571   }
11572 
11573   Selector Sel = Message->getSelector();
11574 
11575   Optional<NSAPI::NSArrayMethodKind> MKOpt =
11576     S.NSAPIObj->getNSArrayMethodKind(Sel);
11577   if (!MKOpt) {
11578     return None;
11579   }
11580 
11581   NSAPI::NSArrayMethodKind MK = *MKOpt;
11582 
11583   switch (MK) {
11584     case NSAPI::NSMutableArr_addObject:
11585     case NSAPI::NSMutableArr_insertObjectAtIndex:
11586     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
11587       return 0;
11588     case NSAPI::NSMutableArr_replaceObjectAtIndex:
11589       return 1;
11590 
11591     default:
11592       return None;
11593   }
11594 
11595   return None;
11596 }
11597 
11598 static
11599 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
11600                                                   ObjCMessageExpr *Message) {
11601   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
11602                                             Message->getReceiverInterface(),
11603                                             NSAPI::ClassId_NSMutableDictionary);
11604   if (!IsMutableDictionary) {
11605     return None;
11606   }
11607 
11608   Selector Sel = Message->getSelector();
11609 
11610   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
11611     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
11612   if (!MKOpt) {
11613     return None;
11614   }
11615 
11616   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
11617 
11618   switch (MK) {
11619     case NSAPI::NSMutableDict_setObjectForKey:
11620     case NSAPI::NSMutableDict_setValueForKey:
11621     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
11622       return 0;
11623 
11624     default:
11625       return None;
11626   }
11627 
11628   return None;
11629 }
11630 
11631 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
11632   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
11633                                                 Message->getReceiverInterface(),
11634                                                 NSAPI::ClassId_NSMutableSet);
11635 
11636   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
11637                                             Message->getReceiverInterface(),
11638                                             NSAPI::ClassId_NSMutableOrderedSet);
11639   if (!IsMutableSet && !IsMutableOrderedSet) {
11640     return None;
11641   }
11642 
11643   Selector Sel = Message->getSelector();
11644 
11645   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
11646   if (!MKOpt) {
11647     return None;
11648   }
11649 
11650   NSAPI::NSSetMethodKind MK = *MKOpt;
11651 
11652   switch (MK) {
11653     case NSAPI::NSMutableSet_addObject:
11654     case NSAPI::NSOrderedSet_setObjectAtIndex:
11655     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
11656     case NSAPI::NSOrderedSet_insertObjectAtIndex:
11657       return 0;
11658     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
11659       return 1;
11660   }
11661 
11662   return None;
11663 }
11664 
11665 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
11666   if (!Message->isInstanceMessage()) {
11667     return;
11668   }
11669 
11670   Optional<int> ArgOpt;
11671 
11672   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
11673       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
11674       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
11675     return;
11676   }
11677 
11678   int ArgIndex = *ArgOpt;
11679 
11680   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
11681   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
11682     Arg = OE->getSourceExpr()->IgnoreImpCasts();
11683   }
11684 
11685   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
11686     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11687       if (ArgRE->isObjCSelfExpr()) {
11688         Diag(Message->getSourceRange().getBegin(),
11689              diag::warn_objc_circular_container)
11690           << ArgRE->getDecl() << StringRef("'super'");
11691       }
11692     }
11693   } else {
11694     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
11695 
11696     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
11697       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
11698     }
11699 
11700     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
11701       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11702         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
11703           ValueDecl *Decl = ReceiverRE->getDecl();
11704           Diag(Message->getSourceRange().getBegin(),
11705                diag::warn_objc_circular_container)
11706             << Decl << Decl;
11707           if (!ArgRE->isObjCSelfExpr()) {
11708             Diag(Decl->getLocation(),
11709                  diag::note_objc_circular_container_declared_here)
11710               << Decl;
11711           }
11712         }
11713       }
11714     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
11715       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
11716         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
11717           ObjCIvarDecl *Decl = IvarRE->getDecl();
11718           Diag(Message->getSourceRange().getBegin(),
11719                diag::warn_objc_circular_container)
11720             << Decl << Decl;
11721           Diag(Decl->getLocation(),
11722                diag::note_objc_circular_container_declared_here)
11723             << Decl;
11724         }
11725       }
11726     }
11727   }
11728 }
11729 
11730 /// Check a message send to see if it's likely to cause a retain cycle.
11731 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
11732   // Only check instance methods whose selector looks like a setter.
11733   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
11734     return;
11735 
11736   // Try to find a variable that the receiver is strongly owned by.
11737   RetainCycleOwner owner;
11738   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
11739     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
11740       return;
11741   } else {
11742     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
11743     owner.Variable = getCurMethodDecl()->getSelfDecl();
11744     owner.Loc = msg->getSuperLoc();
11745     owner.Range = msg->getSuperLoc();
11746   }
11747 
11748   // Check whether the receiver is captured by any of the arguments.
11749   const ObjCMethodDecl *MD = msg->getMethodDecl();
11750   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
11751     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
11752       // noescape blocks should not be retained by the method.
11753       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
11754         continue;
11755       return diagnoseRetainCycle(*this, capturer, owner);
11756     }
11757   }
11758 }
11759 
11760 /// Check a property assign to see if it's likely to cause a retain cycle.
11761 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
11762   RetainCycleOwner owner;
11763   if (!findRetainCycleOwner(*this, receiver, owner))
11764     return;
11765 
11766   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
11767     diagnoseRetainCycle(*this, capturer, owner);
11768 }
11769 
11770 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
11771   RetainCycleOwner Owner;
11772   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
11773     return;
11774 
11775   // Because we don't have an expression for the variable, we have to set the
11776   // location explicitly here.
11777   Owner.Loc = Var->getLocation();
11778   Owner.Range = Var->getSourceRange();
11779 
11780   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
11781     diagnoseRetainCycle(*this, Capturer, Owner);
11782 }
11783 
11784 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
11785                                      Expr *RHS, bool isProperty) {
11786   // Check if RHS is an Objective-C object literal, which also can get
11787   // immediately zapped in a weak reference.  Note that we explicitly
11788   // allow ObjCStringLiterals, since those are designed to never really die.
11789   RHS = RHS->IgnoreParenImpCasts();
11790 
11791   // This enum needs to match with the 'select' in
11792   // warn_objc_arc_literal_assign (off-by-1).
11793   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
11794   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
11795     return false;
11796 
11797   S.Diag(Loc, diag::warn_arc_literal_assign)
11798     << (unsigned) Kind
11799     << (isProperty ? 0 : 1)
11800     << RHS->getSourceRange();
11801 
11802   return true;
11803 }
11804 
11805 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
11806                                     Qualifiers::ObjCLifetime LT,
11807                                     Expr *RHS, bool isProperty) {
11808   // Strip off any implicit cast added to get to the one ARC-specific.
11809   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11810     if (cast->getCastKind() == CK_ARCConsumeObject) {
11811       S.Diag(Loc, diag::warn_arc_retained_assign)
11812         << (LT == Qualifiers::OCL_ExplicitNone)
11813         << (isProperty ? 0 : 1)
11814         << RHS->getSourceRange();
11815       return true;
11816     }
11817     RHS = cast->getSubExpr();
11818   }
11819 
11820   if (LT == Qualifiers::OCL_Weak &&
11821       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
11822     return true;
11823 
11824   return false;
11825 }
11826 
11827 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
11828                               QualType LHS, Expr *RHS) {
11829   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
11830 
11831   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
11832     return false;
11833 
11834   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
11835     return true;
11836 
11837   return false;
11838 }
11839 
11840 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
11841                               Expr *LHS, Expr *RHS) {
11842   QualType LHSType;
11843   // PropertyRef on LHS type need be directly obtained from
11844   // its declaration as it has a PseudoType.
11845   ObjCPropertyRefExpr *PRE
11846     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11847   if (PRE && !PRE->isImplicitProperty()) {
11848     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11849     if (PD)
11850       LHSType = PD->getType();
11851   }
11852 
11853   if (LHSType.isNull())
11854     LHSType = LHS->getType();
11855 
11856   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
11857 
11858   if (LT == Qualifiers::OCL_Weak) {
11859     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
11860       getCurFunction()->markSafeWeakUse(LHS);
11861   }
11862 
11863   if (checkUnsafeAssigns(Loc, LHSType, RHS))
11864     return;
11865 
11866   // FIXME. Check for other life times.
11867   if (LT != Qualifiers::OCL_None)
11868     return;
11869 
11870   if (PRE) {
11871     if (PRE->isImplicitProperty())
11872       return;
11873     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11874     if (!PD)
11875       return;
11876 
11877     unsigned Attributes = PD->getPropertyAttributes();
11878     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
11879       // when 'assign' attribute was not explicitly specified
11880       // by user, ignore it and rely on property type itself
11881       // for lifetime info.
11882       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11883       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11884           LHSType->isObjCRetainableType())
11885         return;
11886 
11887       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11888         if (cast->getCastKind() == CK_ARCConsumeObject) {
11889           Diag(Loc, diag::warn_arc_retained_property_assign)
11890           << RHS->getSourceRange();
11891           return;
11892         }
11893         RHS = cast->getSubExpr();
11894       }
11895     }
11896     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
11897       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11898         return;
11899     }
11900   }
11901 }
11902 
11903 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11904 
11905 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11906                                         SourceLocation StmtLoc,
11907                                         const NullStmt *Body) {
11908   // Do not warn if the body is a macro that expands to nothing, e.g:
11909   //
11910   // #define CALL(x)
11911   // if (condition)
11912   //   CALL(0);
11913   if (Body->hasLeadingEmptyMacro())
11914     return false;
11915 
11916   // Get line numbers of statement and body.
11917   bool StmtLineInvalid;
11918   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
11919                                                       &StmtLineInvalid);
11920   if (StmtLineInvalid)
11921     return false;
11922 
11923   bool BodyLineInvalid;
11924   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11925                                                       &BodyLineInvalid);
11926   if (BodyLineInvalid)
11927     return false;
11928 
11929   // Warn if null statement and body are on the same line.
11930   if (StmtLine != BodyLine)
11931     return false;
11932 
11933   return true;
11934 }
11935 
11936 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
11937                                  const Stmt *Body,
11938                                  unsigned DiagID) {
11939   // Since this is a syntactic check, don't emit diagnostic for template
11940   // instantiations, this just adds noise.
11941   if (CurrentInstantiationScope)
11942     return;
11943 
11944   // The body should be a null statement.
11945   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11946   if (!NBody)
11947     return;
11948 
11949   // Do the usual checks.
11950   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11951     return;
11952 
11953   Diag(NBody->getSemiLoc(), DiagID);
11954   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11955 }
11956 
11957 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
11958                                  const Stmt *PossibleBody) {
11959   assert(!CurrentInstantiationScope); // Ensured by caller
11960 
11961   SourceLocation StmtLoc;
11962   const Stmt *Body;
11963   unsigned DiagID;
11964   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11965     StmtLoc = FS->getRParenLoc();
11966     Body = FS->getBody();
11967     DiagID = diag::warn_empty_for_body;
11968   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11969     StmtLoc = WS->getCond()->getSourceRange().getEnd();
11970     Body = WS->getBody();
11971     DiagID = diag::warn_empty_while_body;
11972   } else
11973     return; // Neither `for' nor `while'.
11974 
11975   // The body should be a null statement.
11976   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11977   if (!NBody)
11978     return;
11979 
11980   // Skip expensive checks if diagnostic is disabled.
11981   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
11982     return;
11983 
11984   // Do the usual checks.
11985   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11986     return;
11987 
11988   // `for(...);' and `while(...);' are popular idioms, so in order to keep
11989   // noise level low, emit diagnostics only if for/while is followed by a
11990   // CompoundStmt, e.g.:
11991   //    for (int i = 0; i < n; i++);
11992   //    {
11993   //      a(i);
11994   //    }
11995   // or if for/while is followed by a statement with more indentation
11996   // than for/while itself:
11997   //    for (int i = 0; i < n; i++);
11998   //      a(i);
11999   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
12000   if (!ProbableTypo) {
12001     bool BodyColInvalid;
12002     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
12003                              PossibleBody->getLocStart(),
12004                              &BodyColInvalid);
12005     if (BodyColInvalid)
12006       return;
12007 
12008     bool StmtColInvalid;
12009     unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
12010                              S->getLocStart(),
12011                              &StmtColInvalid);
12012     if (StmtColInvalid)
12013       return;
12014 
12015     if (BodyCol > StmtCol)
12016       ProbableTypo = true;
12017   }
12018 
12019   if (ProbableTypo) {
12020     Diag(NBody->getSemiLoc(), DiagID);
12021     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
12022   }
12023 }
12024 
12025 //===--- CHECK: Warn on self move with std::move. -------------------------===//
12026 
12027 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
12028 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
12029                              SourceLocation OpLoc) {
12030   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
12031     return;
12032 
12033   if (inTemplateInstantiation())
12034     return;
12035 
12036   // Strip parens and casts away.
12037   LHSExpr = LHSExpr->IgnoreParenImpCasts();
12038   RHSExpr = RHSExpr->IgnoreParenImpCasts();
12039 
12040   // Check for a call expression
12041   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
12042   if (!CE || CE->getNumArgs() != 1)
12043     return;
12044 
12045   // Check for a call to std::move
12046   if (!CE->isCallToStdMove())
12047     return;
12048 
12049   // Get argument from std::move
12050   RHSExpr = CE->getArg(0);
12051 
12052   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
12053   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
12054 
12055   // Two DeclRefExpr's, check that the decls are the same.
12056   if (LHSDeclRef && RHSDeclRef) {
12057     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
12058       return;
12059     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
12060         RHSDeclRef->getDecl()->getCanonicalDecl())
12061       return;
12062 
12063     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12064                                         << LHSExpr->getSourceRange()
12065                                         << RHSExpr->getSourceRange();
12066     return;
12067   }
12068 
12069   // Member variables require a different approach to check for self moves.
12070   // MemberExpr's are the same if every nested MemberExpr refers to the same
12071   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
12072   // the base Expr's are CXXThisExpr's.
12073   const Expr *LHSBase = LHSExpr;
12074   const Expr *RHSBase = RHSExpr;
12075   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
12076   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
12077   if (!LHSME || !RHSME)
12078     return;
12079 
12080   while (LHSME && RHSME) {
12081     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
12082         RHSME->getMemberDecl()->getCanonicalDecl())
12083       return;
12084 
12085     LHSBase = LHSME->getBase();
12086     RHSBase = RHSME->getBase();
12087     LHSME = dyn_cast<MemberExpr>(LHSBase);
12088     RHSME = dyn_cast<MemberExpr>(RHSBase);
12089   }
12090 
12091   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
12092   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
12093   if (LHSDeclRef && RHSDeclRef) {
12094     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
12095       return;
12096     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
12097         RHSDeclRef->getDecl()->getCanonicalDecl())
12098       return;
12099 
12100     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12101                                         << LHSExpr->getSourceRange()
12102                                         << RHSExpr->getSourceRange();
12103     return;
12104   }
12105 
12106   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
12107     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12108                                         << LHSExpr->getSourceRange()
12109                                         << RHSExpr->getSourceRange();
12110 }
12111 
12112 //===--- Layout compatibility ----------------------------------------------//
12113 
12114 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
12115 
12116 /// \brief Check if two enumeration types are layout-compatible.
12117 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
12118   // C++11 [dcl.enum] p8:
12119   // Two enumeration types are layout-compatible if they have the same
12120   // underlying type.
12121   return ED1->isComplete() && ED2->isComplete() &&
12122          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
12123 }
12124 
12125 /// \brief Check if two fields are layout-compatible.
12126 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
12127                                FieldDecl *Field2) {
12128   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
12129     return false;
12130 
12131   if (Field1->isBitField() != Field2->isBitField())
12132     return false;
12133 
12134   if (Field1->isBitField()) {
12135     // Make sure that the bit-fields are the same length.
12136     unsigned Bits1 = Field1->getBitWidthValue(C);
12137     unsigned Bits2 = Field2->getBitWidthValue(C);
12138 
12139     if (Bits1 != Bits2)
12140       return false;
12141   }
12142 
12143   return true;
12144 }
12145 
12146 /// \brief Check if two standard-layout structs are layout-compatible.
12147 /// (C++11 [class.mem] p17)
12148 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
12149                                      RecordDecl *RD2) {
12150   // If both records are C++ classes, check that base classes match.
12151   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
12152     // If one of records is a CXXRecordDecl we are in C++ mode,
12153     // thus the other one is a CXXRecordDecl, too.
12154     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
12155     // Check number of base classes.
12156     if (D1CXX->getNumBases() != D2CXX->getNumBases())
12157       return false;
12158 
12159     // Check the base classes.
12160     for (CXXRecordDecl::base_class_const_iterator
12161                Base1 = D1CXX->bases_begin(),
12162            BaseEnd1 = D1CXX->bases_end(),
12163               Base2 = D2CXX->bases_begin();
12164          Base1 != BaseEnd1;
12165          ++Base1, ++Base2) {
12166       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
12167         return false;
12168     }
12169   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
12170     // If only RD2 is a C++ class, it should have zero base classes.
12171     if (D2CXX->getNumBases() > 0)
12172       return false;
12173   }
12174 
12175   // Check the fields.
12176   RecordDecl::field_iterator Field2 = RD2->field_begin(),
12177                              Field2End = RD2->field_end(),
12178                              Field1 = RD1->field_begin(),
12179                              Field1End = RD1->field_end();
12180   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
12181     if (!isLayoutCompatible(C, *Field1, *Field2))
12182       return false;
12183   }
12184   if (Field1 != Field1End || Field2 != Field2End)
12185     return false;
12186 
12187   return true;
12188 }
12189 
12190 /// \brief Check if two standard-layout unions are layout-compatible.
12191 /// (C++11 [class.mem] p18)
12192 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
12193                                     RecordDecl *RD2) {
12194   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
12195   for (auto *Field2 : RD2->fields())
12196     UnmatchedFields.insert(Field2);
12197 
12198   for (auto *Field1 : RD1->fields()) {
12199     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
12200         I = UnmatchedFields.begin(),
12201         E = UnmatchedFields.end();
12202 
12203     for ( ; I != E; ++I) {
12204       if (isLayoutCompatible(C, Field1, *I)) {
12205         bool Result = UnmatchedFields.erase(*I);
12206         (void) Result;
12207         assert(Result);
12208         break;
12209       }
12210     }
12211     if (I == E)
12212       return false;
12213   }
12214 
12215   return UnmatchedFields.empty();
12216 }
12217 
12218 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
12219                                RecordDecl *RD2) {
12220   if (RD1->isUnion() != RD2->isUnion())
12221     return false;
12222 
12223   if (RD1->isUnion())
12224     return isLayoutCompatibleUnion(C, RD1, RD2);
12225   else
12226     return isLayoutCompatibleStruct(C, RD1, RD2);
12227 }
12228 
12229 /// \brief Check if two types are layout-compatible in C++11 sense.
12230 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
12231   if (T1.isNull() || T2.isNull())
12232     return false;
12233 
12234   // C++11 [basic.types] p11:
12235   // If two types T1 and T2 are the same type, then T1 and T2 are
12236   // layout-compatible types.
12237   if (C.hasSameType(T1, T2))
12238     return true;
12239 
12240   T1 = T1.getCanonicalType().getUnqualifiedType();
12241   T2 = T2.getCanonicalType().getUnqualifiedType();
12242 
12243   const Type::TypeClass TC1 = T1->getTypeClass();
12244   const Type::TypeClass TC2 = T2->getTypeClass();
12245 
12246   if (TC1 != TC2)
12247     return false;
12248 
12249   if (TC1 == Type::Enum) {
12250     return isLayoutCompatible(C,
12251                               cast<EnumType>(T1)->getDecl(),
12252                               cast<EnumType>(T2)->getDecl());
12253   } else if (TC1 == Type::Record) {
12254     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
12255       return false;
12256 
12257     return isLayoutCompatible(C,
12258                               cast<RecordType>(T1)->getDecl(),
12259                               cast<RecordType>(T2)->getDecl());
12260   }
12261 
12262   return false;
12263 }
12264 
12265 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
12266 
12267 /// \brief Given a type tag expression find the type tag itself.
12268 ///
12269 /// \param TypeExpr Type tag expression, as it appears in user's code.
12270 ///
12271 /// \param VD Declaration of an identifier that appears in a type tag.
12272 ///
12273 /// \param MagicValue Type tag magic value.
12274 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
12275                             const ValueDecl **VD, uint64_t *MagicValue) {
12276   while(true) {
12277     if (!TypeExpr)
12278       return false;
12279 
12280     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
12281 
12282     switch (TypeExpr->getStmtClass()) {
12283     case Stmt::UnaryOperatorClass: {
12284       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
12285       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
12286         TypeExpr = UO->getSubExpr();
12287         continue;
12288       }
12289       return false;
12290     }
12291 
12292     case Stmt::DeclRefExprClass: {
12293       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
12294       *VD = DRE->getDecl();
12295       return true;
12296     }
12297 
12298     case Stmt::IntegerLiteralClass: {
12299       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
12300       llvm::APInt MagicValueAPInt = IL->getValue();
12301       if (MagicValueAPInt.getActiveBits() <= 64) {
12302         *MagicValue = MagicValueAPInt.getZExtValue();
12303         return true;
12304       } else
12305         return false;
12306     }
12307 
12308     case Stmt::BinaryConditionalOperatorClass:
12309     case Stmt::ConditionalOperatorClass: {
12310       const AbstractConditionalOperator *ACO =
12311           cast<AbstractConditionalOperator>(TypeExpr);
12312       bool Result;
12313       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
12314         if (Result)
12315           TypeExpr = ACO->getTrueExpr();
12316         else
12317           TypeExpr = ACO->getFalseExpr();
12318         continue;
12319       }
12320       return false;
12321     }
12322 
12323     case Stmt::BinaryOperatorClass: {
12324       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
12325       if (BO->getOpcode() == BO_Comma) {
12326         TypeExpr = BO->getRHS();
12327         continue;
12328       }
12329       return false;
12330     }
12331 
12332     default:
12333       return false;
12334     }
12335   }
12336 }
12337 
12338 /// \brief Retrieve the C type corresponding to type tag TypeExpr.
12339 ///
12340 /// \param TypeExpr Expression that specifies a type tag.
12341 ///
12342 /// \param MagicValues Registered magic values.
12343 ///
12344 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
12345 ///        kind.
12346 ///
12347 /// \param TypeInfo Information about the corresponding C type.
12348 ///
12349 /// \returns true if the corresponding C type was found.
12350 static bool GetMatchingCType(
12351         const IdentifierInfo *ArgumentKind,
12352         const Expr *TypeExpr, const ASTContext &Ctx,
12353         const llvm::DenseMap<Sema::TypeTagMagicValue,
12354                              Sema::TypeTagData> *MagicValues,
12355         bool &FoundWrongKind,
12356         Sema::TypeTagData &TypeInfo) {
12357   FoundWrongKind = false;
12358 
12359   // Variable declaration that has type_tag_for_datatype attribute.
12360   const ValueDecl *VD = nullptr;
12361 
12362   uint64_t MagicValue;
12363 
12364   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
12365     return false;
12366 
12367   if (VD) {
12368     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
12369       if (I->getArgumentKind() != ArgumentKind) {
12370         FoundWrongKind = true;
12371         return false;
12372       }
12373       TypeInfo.Type = I->getMatchingCType();
12374       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
12375       TypeInfo.MustBeNull = I->getMustBeNull();
12376       return true;
12377     }
12378     return false;
12379   }
12380 
12381   if (!MagicValues)
12382     return false;
12383 
12384   llvm::DenseMap<Sema::TypeTagMagicValue,
12385                  Sema::TypeTagData>::const_iterator I =
12386       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
12387   if (I == MagicValues->end())
12388     return false;
12389 
12390   TypeInfo = I->second;
12391   return true;
12392 }
12393 
12394 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
12395                                       uint64_t MagicValue, QualType Type,
12396                                       bool LayoutCompatible,
12397                                       bool MustBeNull) {
12398   if (!TypeTagForDatatypeMagicValues)
12399     TypeTagForDatatypeMagicValues.reset(
12400         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
12401 
12402   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
12403   (*TypeTagForDatatypeMagicValues)[Magic] =
12404       TypeTagData(Type, LayoutCompatible, MustBeNull);
12405 }
12406 
12407 static bool IsSameCharType(QualType T1, QualType T2) {
12408   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
12409   if (!BT1)
12410     return false;
12411 
12412   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
12413   if (!BT2)
12414     return false;
12415 
12416   BuiltinType::Kind T1Kind = BT1->getKind();
12417   BuiltinType::Kind T2Kind = BT2->getKind();
12418 
12419   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
12420          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
12421          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
12422          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
12423 }
12424 
12425 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
12426                                     const ArrayRef<const Expr *> ExprArgs,
12427                                     SourceLocation CallSiteLoc) {
12428   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
12429   bool IsPointerAttr = Attr->getIsPointer();
12430 
12431   // Retrieve the argument representing the 'type_tag'.
12432   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
12433   if (TypeTagIdxAST >= ExprArgs.size()) {
12434     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
12435         << 0 << Attr->getTypeTagIdx().getSourceIndex();
12436     return;
12437   }
12438   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
12439   bool FoundWrongKind;
12440   TypeTagData TypeInfo;
12441   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
12442                         TypeTagForDatatypeMagicValues.get(),
12443                         FoundWrongKind, TypeInfo)) {
12444     if (FoundWrongKind)
12445       Diag(TypeTagExpr->getExprLoc(),
12446            diag::warn_type_tag_for_datatype_wrong_kind)
12447         << TypeTagExpr->getSourceRange();
12448     return;
12449   }
12450 
12451   // Retrieve the argument representing the 'arg_idx'.
12452   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
12453   if (ArgumentIdxAST >= ExprArgs.size()) {
12454     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
12455         << 1 << Attr->getArgumentIdx().getSourceIndex();
12456     return;
12457   }
12458   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
12459   if (IsPointerAttr) {
12460     // Skip implicit cast of pointer to `void *' (as a function argument).
12461     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
12462       if (ICE->getType()->isVoidPointerType() &&
12463           ICE->getCastKind() == CK_BitCast)
12464         ArgumentExpr = ICE->getSubExpr();
12465   }
12466   QualType ArgumentType = ArgumentExpr->getType();
12467 
12468   // Passing a `void*' pointer shouldn't trigger a warning.
12469   if (IsPointerAttr && ArgumentType->isVoidPointerType())
12470     return;
12471 
12472   if (TypeInfo.MustBeNull) {
12473     // Type tag with matching void type requires a null pointer.
12474     if (!ArgumentExpr->isNullPointerConstant(Context,
12475                                              Expr::NPC_ValueDependentIsNotNull)) {
12476       Diag(ArgumentExpr->getExprLoc(),
12477            diag::warn_type_safety_null_pointer_required)
12478           << ArgumentKind->getName()
12479           << ArgumentExpr->getSourceRange()
12480           << TypeTagExpr->getSourceRange();
12481     }
12482     return;
12483   }
12484 
12485   QualType RequiredType = TypeInfo.Type;
12486   if (IsPointerAttr)
12487     RequiredType = Context.getPointerType(RequiredType);
12488 
12489   bool mismatch = false;
12490   if (!TypeInfo.LayoutCompatible) {
12491     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
12492 
12493     // C++11 [basic.fundamental] p1:
12494     // Plain char, signed char, and unsigned char are three distinct types.
12495     //
12496     // But we treat plain `char' as equivalent to `signed char' or `unsigned
12497     // char' depending on the current char signedness mode.
12498     if (mismatch)
12499       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
12500                                            RequiredType->getPointeeType())) ||
12501           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
12502         mismatch = false;
12503   } else
12504     if (IsPointerAttr)
12505       mismatch = !isLayoutCompatible(Context,
12506                                      ArgumentType->getPointeeType(),
12507                                      RequiredType->getPointeeType());
12508     else
12509       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
12510 
12511   if (mismatch)
12512     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
12513         << ArgumentType << ArgumentKind
12514         << TypeInfo.LayoutCompatible << RequiredType
12515         << ArgumentExpr->getSourceRange()
12516         << TypeTagExpr->getSourceRange();
12517 }
12518 
12519 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
12520                                          CharUnits Alignment) {
12521   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
12522 }
12523 
12524 void Sema::DiagnoseMisalignedMembers() {
12525   for (MisalignedMember &m : MisalignedMembers) {
12526     const NamedDecl *ND = m.RD;
12527     if (ND->getName().empty()) {
12528       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
12529         ND = TD;
12530     }
12531     Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
12532         << m.MD << ND << m.E->getSourceRange();
12533   }
12534   MisalignedMembers.clear();
12535 }
12536 
12537 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
12538   E = E->IgnoreParens();
12539   if (!T->isPointerType() && !T->isIntegerType())
12540     return;
12541   if (isa<UnaryOperator>(E) &&
12542       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
12543     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12544     if (isa<MemberExpr>(Op)) {
12545       auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
12546                           MisalignedMember(Op));
12547       if (MA != MisalignedMembers.end() &&
12548           (T->isIntegerType() ||
12549            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
12550                                    Context.getTypeAlignInChars(
12551                                        T->getPointeeType()) <= MA->Alignment))))
12552         MisalignedMembers.erase(MA);
12553     }
12554   }
12555 }
12556 
12557 void Sema::RefersToMemberWithReducedAlignment(
12558     Expr *E,
12559     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
12560         Action) {
12561   const auto *ME = dyn_cast<MemberExpr>(E);
12562   if (!ME)
12563     return;
12564 
12565   // No need to check expressions with an __unaligned-qualified type.
12566   if (E->getType().getQualifiers().hasUnaligned())
12567     return;
12568 
12569   // For a chain of MemberExpr like "a.b.c.d" this list
12570   // will keep FieldDecl's like [d, c, b].
12571   SmallVector<FieldDecl *, 4> ReverseMemberChain;
12572   const MemberExpr *TopME = nullptr;
12573   bool AnyIsPacked = false;
12574   do {
12575     QualType BaseType = ME->getBase()->getType();
12576     if (ME->isArrow())
12577       BaseType = BaseType->getPointeeType();
12578     RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
12579     if (RD->isInvalidDecl())
12580       return;
12581 
12582     ValueDecl *MD = ME->getMemberDecl();
12583     auto *FD = dyn_cast<FieldDecl>(MD);
12584     // We do not care about non-data members.
12585     if (!FD || FD->isInvalidDecl())
12586       return;
12587 
12588     AnyIsPacked =
12589         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
12590     ReverseMemberChain.push_back(FD);
12591 
12592     TopME = ME;
12593     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
12594   } while (ME);
12595   assert(TopME && "We did not compute a topmost MemberExpr!");
12596 
12597   // Not the scope of this diagnostic.
12598   if (!AnyIsPacked)
12599     return;
12600 
12601   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
12602   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
12603   // TODO: The innermost base of the member expression may be too complicated.
12604   // For now, just disregard these cases. This is left for future
12605   // improvement.
12606   if (!DRE && !isa<CXXThisExpr>(TopBase))
12607       return;
12608 
12609   // Alignment expected by the whole expression.
12610   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
12611 
12612   // No need to do anything else with this case.
12613   if (ExpectedAlignment.isOne())
12614     return;
12615 
12616   // Synthesize offset of the whole access.
12617   CharUnits Offset;
12618   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
12619        I++) {
12620     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
12621   }
12622 
12623   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
12624   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
12625       ReverseMemberChain.back()->getParent()->getTypeForDecl());
12626 
12627   // The base expression of the innermost MemberExpr may give
12628   // stronger guarantees than the class containing the member.
12629   if (DRE && !TopME->isArrow()) {
12630     const ValueDecl *VD = DRE->getDecl();
12631     if (!VD->getType()->isReferenceType())
12632       CompleteObjectAlignment =
12633           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
12634   }
12635 
12636   // Check if the synthesized offset fulfills the alignment.
12637   if (Offset % ExpectedAlignment != 0 ||
12638       // It may fulfill the offset it but the effective alignment may still be
12639       // lower than the expected expression alignment.
12640       CompleteObjectAlignment < ExpectedAlignment) {
12641     // If this happens, we want to determine a sensible culprit of this.
12642     // Intuitively, watching the chain of member expressions from right to
12643     // left, we start with the required alignment (as required by the field
12644     // type) but some packed attribute in that chain has reduced the alignment.
12645     // It may happen that another packed structure increases it again. But if
12646     // we are here such increase has not been enough. So pointing the first
12647     // FieldDecl that either is packed or else its RecordDecl is,
12648     // seems reasonable.
12649     FieldDecl *FD = nullptr;
12650     CharUnits Alignment;
12651     for (FieldDecl *FDI : ReverseMemberChain) {
12652       if (FDI->hasAttr<PackedAttr>() ||
12653           FDI->getParent()->hasAttr<PackedAttr>()) {
12654         FD = FDI;
12655         Alignment = std::min(
12656             Context.getTypeAlignInChars(FD->getType()),
12657             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
12658         break;
12659       }
12660     }
12661     assert(FD && "We did not find a packed FieldDecl!");
12662     Action(E, FD->getParent(), FD, Alignment);
12663   }
12664 }
12665 
12666 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
12667   using namespace std::placeholders;
12668 
12669   RefersToMemberWithReducedAlignment(
12670       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
12671                      _2, _3, _4));
12672 }
12673