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 static bool isX86_32Builtin(unsigned BuiltinID) {
2313   // These builtins only work on x86-32 targets.
2314   switch (BuiltinID) {
2315   case X86::BI__builtin_ia32_readeflags_u32:
2316   case X86::BI__builtin_ia32_writeeflags_u32:
2317     return true;
2318   }
2319 
2320   return false;
2321 }
2322 
2323 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2324   if (BuiltinID == X86::BI__builtin_cpu_supports)
2325     return SemaBuiltinCpuSupports(*this, TheCall);
2326 
2327   if (BuiltinID == X86::BI__builtin_cpu_is)
2328     return SemaBuiltinCpuIs(*this, TheCall);
2329 
2330   // Check for 32-bit only builtins on a 64-bit target.
2331   const llvm::Triple &TT = Context.getTargetInfo().getTriple();
2332   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
2333     return Diag(TheCall->getCallee()->getLocStart(),
2334                 diag::err_32_bit_builtin_64_bit_tgt);
2335 
2336   // If the intrinsic has rounding or SAE make sure its valid.
2337   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2338     return true;
2339 
2340   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
2341   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
2342     return true;
2343 
2344   // For intrinsics which take an immediate value as part of the instruction,
2345   // range check them here.
2346   int i = 0, l = 0, u = 0;
2347   switch (BuiltinID) {
2348   default:
2349     return false;
2350   case X86::BI_mm_prefetch:
2351     i = 1; l = 0; u = 7;
2352     break;
2353   case X86::BI__builtin_ia32_sha1rnds4:
2354   case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2355   case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2356   case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2357   case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
2358     i = 2; l = 0; u = 3;
2359     break;
2360   case X86::BI__builtin_ia32_vpermil2pd:
2361   case X86::BI__builtin_ia32_vpermil2pd256:
2362   case X86::BI__builtin_ia32_vpermil2ps:
2363   case X86::BI__builtin_ia32_vpermil2ps256:
2364     i = 3; l = 0; u = 3;
2365     break;
2366   case X86::BI__builtin_ia32_cmpb128_mask:
2367   case X86::BI__builtin_ia32_cmpw128_mask:
2368   case X86::BI__builtin_ia32_cmpd128_mask:
2369   case X86::BI__builtin_ia32_cmpq128_mask:
2370   case X86::BI__builtin_ia32_cmpb256_mask:
2371   case X86::BI__builtin_ia32_cmpw256_mask:
2372   case X86::BI__builtin_ia32_cmpd256_mask:
2373   case X86::BI__builtin_ia32_cmpq256_mask:
2374   case X86::BI__builtin_ia32_cmpb512_mask:
2375   case X86::BI__builtin_ia32_cmpw512_mask:
2376   case X86::BI__builtin_ia32_cmpd512_mask:
2377   case X86::BI__builtin_ia32_cmpq512_mask:
2378   case X86::BI__builtin_ia32_ucmpb128_mask:
2379   case X86::BI__builtin_ia32_ucmpw128_mask:
2380   case X86::BI__builtin_ia32_ucmpd128_mask:
2381   case X86::BI__builtin_ia32_ucmpq128_mask:
2382   case X86::BI__builtin_ia32_ucmpb256_mask:
2383   case X86::BI__builtin_ia32_ucmpw256_mask:
2384   case X86::BI__builtin_ia32_ucmpd256_mask:
2385   case X86::BI__builtin_ia32_ucmpq256_mask:
2386   case X86::BI__builtin_ia32_ucmpb512_mask:
2387   case X86::BI__builtin_ia32_ucmpw512_mask:
2388   case X86::BI__builtin_ia32_ucmpd512_mask:
2389   case X86::BI__builtin_ia32_ucmpq512_mask:
2390   case X86::BI__builtin_ia32_vpcomub:
2391   case X86::BI__builtin_ia32_vpcomuw:
2392   case X86::BI__builtin_ia32_vpcomud:
2393   case X86::BI__builtin_ia32_vpcomuq:
2394   case X86::BI__builtin_ia32_vpcomb:
2395   case X86::BI__builtin_ia32_vpcomw:
2396   case X86::BI__builtin_ia32_vpcomd:
2397   case X86::BI__builtin_ia32_vpcomq:
2398     i = 2; l = 0; u = 7;
2399     break;
2400   case X86::BI__builtin_ia32_roundps:
2401   case X86::BI__builtin_ia32_roundpd:
2402   case X86::BI__builtin_ia32_roundps256:
2403   case X86::BI__builtin_ia32_roundpd256:
2404     i = 1; l = 0; u = 15;
2405     break;
2406   case X86::BI__builtin_ia32_roundss:
2407   case X86::BI__builtin_ia32_roundsd:
2408   case X86::BI__builtin_ia32_rangepd128_mask:
2409   case X86::BI__builtin_ia32_rangepd256_mask:
2410   case X86::BI__builtin_ia32_rangepd512_mask:
2411   case X86::BI__builtin_ia32_rangeps128_mask:
2412   case X86::BI__builtin_ia32_rangeps256_mask:
2413   case X86::BI__builtin_ia32_rangeps512_mask:
2414   case X86::BI__builtin_ia32_getmantsd_round_mask:
2415   case X86::BI__builtin_ia32_getmantss_round_mask:
2416     i = 2; l = 0; u = 15;
2417     break;
2418   case X86::BI__builtin_ia32_cmpps:
2419   case X86::BI__builtin_ia32_cmpss:
2420   case X86::BI__builtin_ia32_cmppd:
2421   case X86::BI__builtin_ia32_cmpsd:
2422   case X86::BI__builtin_ia32_cmpps256:
2423   case X86::BI__builtin_ia32_cmppd256:
2424   case X86::BI__builtin_ia32_cmpps128_mask:
2425   case X86::BI__builtin_ia32_cmppd128_mask:
2426   case X86::BI__builtin_ia32_cmpps256_mask:
2427   case X86::BI__builtin_ia32_cmppd256_mask:
2428   case X86::BI__builtin_ia32_cmpps512_mask:
2429   case X86::BI__builtin_ia32_cmppd512_mask:
2430   case X86::BI__builtin_ia32_cmpsd_mask:
2431   case X86::BI__builtin_ia32_cmpss_mask:
2432     i = 2; l = 0; u = 31;
2433     break;
2434   case X86::BI__builtin_ia32_vcvtps2ph:
2435   case X86::BI__builtin_ia32_vcvtps2ph_mask:
2436   case X86::BI__builtin_ia32_vcvtps2ph256:
2437   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
2438   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
2439   case X86::BI__builtin_ia32_rndscaleps_128_mask:
2440   case X86::BI__builtin_ia32_rndscalepd_128_mask:
2441   case X86::BI__builtin_ia32_rndscaleps_256_mask:
2442   case X86::BI__builtin_ia32_rndscalepd_256_mask:
2443   case X86::BI__builtin_ia32_rndscaleps_mask:
2444   case X86::BI__builtin_ia32_rndscalepd_mask:
2445   case X86::BI__builtin_ia32_reducepd128_mask:
2446   case X86::BI__builtin_ia32_reducepd256_mask:
2447   case X86::BI__builtin_ia32_reducepd512_mask:
2448   case X86::BI__builtin_ia32_reduceps128_mask:
2449   case X86::BI__builtin_ia32_reduceps256_mask:
2450   case X86::BI__builtin_ia32_reduceps512_mask:
2451   case X86::BI__builtin_ia32_prold512_mask:
2452   case X86::BI__builtin_ia32_prolq512_mask:
2453   case X86::BI__builtin_ia32_prold128_mask:
2454   case X86::BI__builtin_ia32_prold256_mask:
2455   case X86::BI__builtin_ia32_prolq128_mask:
2456   case X86::BI__builtin_ia32_prolq256_mask:
2457   case X86::BI__builtin_ia32_prord128_mask:
2458   case X86::BI__builtin_ia32_prord256_mask:
2459   case X86::BI__builtin_ia32_prorq128_mask:
2460   case X86::BI__builtin_ia32_prorq256_mask:
2461   case X86::BI__builtin_ia32_fpclasspd128_mask:
2462   case X86::BI__builtin_ia32_fpclasspd256_mask:
2463   case X86::BI__builtin_ia32_fpclassps128_mask:
2464   case X86::BI__builtin_ia32_fpclassps256_mask:
2465   case X86::BI__builtin_ia32_fpclassps512_mask:
2466   case X86::BI__builtin_ia32_fpclasspd512_mask:
2467   case X86::BI__builtin_ia32_fpclasssd_mask:
2468   case X86::BI__builtin_ia32_fpclassss_mask:
2469     i = 1; l = 0; u = 255;
2470     break;
2471   case X86::BI__builtin_ia32_palignr128:
2472   case X86::BI__builtin_ia32_palignr256:
2473   case X86::BI__builtin_ia32_palignr512_mask:
2474   case X86::BI__builtin_ia32_vcomisd:
2475   case X86::BI__builtin_ia32_vcomiss:
2476   case X86::BI__builtin_ia32_shuf_f32x4_mask:
2477   case X86::BI__builtin_ia32_shuf_f64x2_mask:
2478   case X86::BI__builtin_ia32_shuf_i32x4_mask:
2479   case X86::BI__builtin_ia32_shuf_i64x2_mask:
2480   case X86::BI__builtin_ia32_dbpsadbw128_mask:
2481   case X86::BI__builtin_ia32_dbpsadbw256_mask:
2482   case X86::BI__builtin_ia32_dbpsadbw512_mask:
2483   case X86::BI__builtin_ia32_vpshldd128_mask:
2484   case X86::BI__builtin_ia32_vpshldd256_mask:
2485   case X86::BI__builtin_ia32_vpshldd512_mask:
2486   case X86::BI__builtin_ia32_vpshldq128_mask:
2487   case X86::BI__builtin_ia32_vpshldq256_mask:
2488   case X86::BI__builtin_ia32_vpshldq512_mask:
2489   case X86::BI__builtin_ia32_vpshldw128_mask:
2490   case X86::BI__builtin_ia32_vpshldw256_mask:
2491   case X86::BI__builtin_ia32_vpshldw512_mask:
2492   case X86::BI__builtin_ia32_vpshrdd128_mask:
2493   case X86::BI__builtin_ia32_vpshrdd256_mask:
2494   case X86::BI__builtin_ia32_vpshrdd512_mask:
2495   case X86::BI__builtin_ia32_vpshrdq128_mask:
2496   case X86::BI__builtin_ia32_vpshrdq256_mask:
2497   case X86::BI__builtin_ia32_vpshrdq512_mask:
2498   case X86::BI__builtin_ia32_vpshrdw128_mask:
2499   case X86::BI__builtin_ia32_vpshrdw256_mask:
2500   case X86::BI__builtin_ia32_vpshrdw512_mask:
2501     i = 2; l = 0; u = 255;
2502     break;
2503   case X86::BI__builtin_ia32_fixupimmpd512_mask:
2504   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2505   case X86::BI__builtin_ia32_fixupimmps512_mask:
2506   case X86::BI__builtin_ia32_fixupimmps512_maskz:
2507   case X86::BI__builtin_ia32_fixupimmsd_mask:
2508   case X86::BI__builtin_ia32_fixupimmsd_maskz:
2509   case X86::BI__builtin_ia32_fixupimmss_mask:
2510   case X86::BI__builtin_ia32_fixupimmss_maskz:
2511   case X86::BI__builtin_ia32_fixupimmpd128_mask:
2512   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2513   case X86::BI__builtin_ia32_fixupimmpd256_mask:
2514   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2515   case X86::BI__builtin_ia32_fixupimmps128_mask:
2516   case X86::BI__builtin_ia32_fixupimmps128_maskz:
2517   case X86::BI__builtin_ia32_fixupimmps256_mask:
2518   case X86::BI__builtin_ia32_fixupimmps256_maskz:
2519   case X86::BI__builtin_ia32_pternlogd512_mask:
2520   case X86::BI__builtin_ia32_pternlogd512_maskz:
2521   case X86::BI__builtin_ia32_pternlogq512_mask:
2522   case X86::BI__builtin_ia32_pternlogq512_maskz:
2523   case X86::BI__builtin_ia32_pternlogd128_mask:
2524   case X86::BI__builtin_ia32_pternlogd128_maskz:
2525   case X86::BI__builtin_ia32_pternlogd256_mask:
2526   case X86::BI__builtin_ia32_pternlogd256_maskz:
2527   case X86::BI__builtin_ia32_pternlogq128_mask:
2528   case X86::BI__builtin_ia32_pternlogq128_maskz:
2529   case X86::BI__builtin_ia32_pternlogq256_mask:
2530   case X86::BI__builtin_ia32_pternlogq256_maskz:
2531     i = 3; l = 0; u = 255;
2532     break;
2533   case X86::BI__builtin_ia32_gatherpfdpd:
2534   case X86::BI__builtin_ia32_gatherpfdps:
2535   case X86::BI__builtin_ia32_gatherpfqpd:
2536   case X86::BI__builtin_ia32_gatherpfqps:
2537   case X86::BI__builtin_ia32_scatterpfdpd:
2538   case X86::BI__builtin_ia32_scatterpfdps:
2539   case X86::BI__builtin_ia32_scatterpfqpd:
2540   case X86::BI__builtin_ia32_scatterpfqps:
2541     i = 4; l = 2; u = 3;
2542     break;
2543   case X86::BI__builtin_ia32_rndscalesd_round_mask:
2544   case X86::BI__builtin_ia32_rndscaless_round_mask:
2545     i = 4; l = 0; u = 255;
2546     break;
2547   }
2548   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2549 }
2550 
2551 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2552 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
2553 /// Returns true when the format fits the function and the FormatStringInfo has
2554 /// been populated.
2555 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2556                                FormatStringInfo *FSI) {
2557   FSI->HasVAListArg = Format->getFirstArg() == 0;
2558   FSI->FormatIdx = Format->getFormatIdx() - 1;
2559   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
2560 
2561   // The way the format attribute works in GCC, the implicit this argument
2562   // of member functions is counted. However, it doesn't appear in our own
2563   // lists, so decrement format_idx in that case.
2564   if (IsCXXMember) {
2565     if(FSI->FormatIdx == 0)
2566       return false;
2567     --FSI->FormatIdx;
2568     if (FSI->FirstDataArg != 0)
2569       --FSI->FirstDataArg;
2570   }
2571   return true;
2572 }
2573 
2574 /// Checks if a the given expression evaluates to null.
2575 ///
2576 /// \brief Returns true if the value evaluates to null.
2577 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
2578   // If the expression has non-null type, it doesn't evaluate to null.
2579   if (auto nullability
2580         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2581     if (*nullability == NullabilityKind::NonNull)
2582       return false;
2583   }
2584 
2585   // As a special case, transparent unions initialized with zero are
2586   // considered null for the purposes of the nonnull attribute.
2587   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
2588     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2589       if (const CompoundLiteralExpr *CLE =
2590           dyn_cast<CompoundLiteralExpr>(Expr))
2591         if (const InitListExpr *ILE =
2592             dyn_cast<InitListExpr>(CLE->getInitializer()))
2593           Expr = ILE->getInit(0);
2594   }
2595 
2596   bool Result;
2597   return (!Expr->isValueDependent() &&
2598           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2599           !Result);
2600 }
2601 
2602 static void CheckNonNullArgument(Sema &S,
2603                                  const Expr *ArgExpr,
2604                                  SourceLocation CallSiteLoc) {
2605   if (CheckNonNullExpr(S, ArgExpr))
2606     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2607            S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
2608 }
2609 
2610 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2611   FormatStringInfo FSI;
2612   if ((GetFormatStringType(Format) == FST_NSString) &&
2613       getFormatStringInfo(Format, false, &FSI)) {
2614     Idx = FSI.FormatIdx;
2615     return true;
2616   }
2617   return false;
2618 }
2619 
2620 /// \brief Diagnose use of %s directive in an NSString which is being passed
2621 /// as formatting string to formatting method.
2622 static void
2623 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2624                                         const NamedDecl *FDecl,
2625                                         Expr **Args,
2626                                         unsigned NumArgs) {
2627   unsigned Idx = 0;
2628   bool Format = false;
2629   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2630   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
2631     Idx = 2;
2632     Format = true;
2633   }
2634   else
2635     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2636       if (S.GetFormatNSStringIdx(I, Idx)) {
2637         Format = true;
2638         break;
2639       }
2640     }
2641   if (!Format || NumArgs <= Idx)
2642     return;
2643   const Expr *FormatExpr = Args[Idx];
2644   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2645     FormatExpr = CSCE->getSubExpr();
2646   const StringLiteral *FormatString;
2647   if (const ObjCStringLiteral *OSL =
2648       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2649     FormatString = OSL->getString();
2650   else
2651     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2652   if (!FormatString)
2653     return;
2654   if (S.FormatStringHasSArg(FormatString)) {
2655     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2656       << "%s" << 1 << 1;
2657     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2658       << FDecl->getDeclName();
2659   }
2660 }
2661 
2662 /// Determine whether the given type has a non-null nullability annotation.
2663 static bool isNonNullType(ASTContext &ctx, QualType type) {
2664   if (auto nullability = type->getNullability(ctx))
2665     return *nullability == NullabilityKind::NonNull;
2666 
2667   return false;
2668 }
2669 
2670 static void CheckNonNullArguments(Sema &S,
2671                                   const NamedDecl *FDecl,
2672                                   const FunctionProtoType *Proto,
2673                                   ArrayRef<const Expr *> Args,
2674                                   SourceLocation CallSiteLoc) {
2675   assert((FDecl || Proto) && "Need a function declaration or prototype");
2676 
2677   // Check the attributes attached to the method/function itself.
2678   llvm::SmallBitVector NonNullArgs;
2679   if (FDecl) {
2680     // Handle the nonnull attribute on the function/method declaration itself.
2681     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2682       if (!NonNull->args_size()) {
2683         // Easy case: all pointer arguments are nonnull.
2684         for (const auto *Arg : Args)
2685           if (S.isValidPointerAttrType(Arg->getType()))
2686             CheckNonNullArgument(S, Arg, CallSiteLoc);
2687         return;
2688       }
2689 
2690       for (const ParamIdx &Idx : NonNull->args()) {
2691         unsigned IdxAST = Idx.getASTIndex();
2692         if (IdxAST >= Args.size())
2693           continue;
2694         if (NonNullArgs.empty())
2695           NonNullArgs.resize(Args.size());
2696         NonNullArgs.set(IdxAST);
2697       }
2698     }
2699   }
2700 
2701   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2702     // Handle the nonnull attribute on the parameters of the
2703     // function/method.
2704     ArrayRef<ParmVarDecl*> parms;
2705     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2706       parms = FD->parameters();
2707     else
2708       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2709 
2710     unsigned ParamIndex = 0;
2711     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2712          I != E; ++I, ++ParamIndex) {
2713       const ParmVarDecl *PVD = *I;
2714       if (PVD->hasAttr<NonNullAttr>() ||
2715           isNonNullType(S.Context, PVD->getType())) {
2716         if (NonNullArgs.empty())
2717           NonNullArgs.resize(Args.size());
2718 
2719         NonNullArgs.set(ParamIndex);
2720       }
2721     }
2722   } else {
2723     // If we have a non-function, non-method declaration but no
2724     // function prototype, try to dig out the function prototype.
2725     if (!Proto) {
2726       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2727         QualType type = VD->getType().getNonReferenceType();
2728         if (auto pointerType = type->getAs<PointerType>())
2729           type = pointerType->getPointeeType();
2730         else if (auto blockType = type->getAs<BlockPointerType>())
2731           type = blockType->getPointeeType();
2732         // FIXME: data member pointers?
2733 
2734         // Dig out the function prototype, if there is one.
2735         Proto = type->getAs<FunctionProtoType>();
2736       }
2737     }
2738 
2739     // Fill in non-null argument information from the nullability
2740     // information on the parameter types (if we have them).
2741     if (Proto) {
2742       unsigned Index = 0;
2743       for (auto paramType : Proto->getParamTypes()) {
2744         if (isNonNullType(S.Context, paramType)) {
2745           if (NonNullArgs.empty())
2746             NonNullArgs.resize(Args.size());
2747 
2748           NonNullArgs.set(Index);
2749         }
2750 
2751         ++Index;
2752       }
2753     }
2754   }
2755 
2756   // Check for non-null arguments.
2757   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2758        ArgIndex != ArgIndexEnd; ++ArgIndex) {
2759     if (NonNullArgs[ArgIndex])
2760       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
2761   }
2762 }
2763 
2764 /// Handles the checks for format strings, non-POD arguments to vararg
2765 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
2766 /// attributes.
2767 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2768                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
2769                      bool IsMemberFunction, SourceLocation Loc,
2770                      SourceRange Range, VariadicCallType CallType) {
2771   // FIXME: We should check as much as we can in the template definition.
2772   if (CurContext->isDependentContext())
2773     return;
2774 
2775   // Printf and scanf checking.
2776   llvm::SmallBitVector CheckedVarArgs;
2777   if (FDecl) {
2778     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2779       // Only create vector if there are format attributes.
2780       CheckedVarArgs.resize(Args.size());
2781 
2782       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
2783                            CheckedVarArgs);
2784     }
2785   }
2786 
2787   // Refuse POD arguments that weren't caught by the format string
2788   // checks above.
2789   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
2790   if (CallType != VariadicDoesNotApply &&
2791       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
2792     unsigned NumParams = Proto ? Proto->getNumParams()
2793                        : FDecl && isa<FunctionDecl>(FDecl)
2794                            ? cast<FunctionDecl>(FDecl)->getNumParams()
2795                        : FDecl && isa<ObjCMethodDecl>(FDecl)
2796                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
2797                        : 0;
2798 
2799     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
2800       // Args[ArgIdx] can be null in malformed code.
2801       if (const Expr *Arg = Args[ArgIdx]) {
2802         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2803           checkVariadicArgument(Arg, CallType);
2804       }
2805     }
2806   }
2807 
2808   if (FDecl || Proto) {
2809     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
2810 
2811     // Type safety checking.
2812     if (FDecl) {
2813       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2814         CheckArgumentWithTypeTag(I, Args, Loc);
2815     }
2816   }
2817 
2818   if (FD)
2819     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
2820 }
2821 
2822 /// CheckConstructorCall - Check a constructor call for correctness and safety
2823 /// properties not enforced by the C type system.
2824 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2825                                 ArrayRef<const Expr *> Args,
2826                                 const FunctionProtoType *Proto,
2827                                 SourceLocation Loc) {
2828   VariadicCallType CallType =
2829     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
2830   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
2831             Loc, SourceRange(), CallType);
2832 }
2833 
2834 /// CheckFunctionCall - Check a direct function call for various correctness
2835 /// and safety properties not strictly enforced by the C type system.
2836 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2837                              const FunctionProtoType *Proto) {
2838   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2839                               isa<CXXMethodDecl>(FDecl);
2840   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2841                           IsMemberOperatorCall;
2842   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2843                                                   TheCall->getCallee());
2844   Expr** Args = TheCall->getArgs();
2845   unsigned NumArgs = TheCall->getNumArgs();
2846 
2847   Expr *ImplicitThis = nullptr;
2848   if (IsMemberOperatorCall) {
2849     // If this is a call to a member operator, hide the first argument
2850     // from checkCall.
2851     // FIXME: Our choice of AST representation here is less than ideal.
2852     ImplicitThis = Args[0];
2853     ++Args;
2854     --NumArgs;
2855   } else if (IsMemberFunction)
2856     ImplicitThis =
2857         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
2858 
2859   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
2860             IsMemberFunction, TheCall->getRParenLoc(),
2861             TheCall->getCallee()->getSourceRange(), CallType);
2862 
2863   IdentifierInfo *FnInfo = FDecl->getIdentifier();
2864   // None of the checks below are needed for functions that don't have
2865   // simple names (e.g., C++ conversion functions).
2866   if (!FnInfo)
2867     return false;
2868 
2869   CheckAbsoluteValueFunction(TheCall, FDecl);
2870   CheckMaxUnsignedZero(TheCall, FDecl);
2871 
2872   if (getLangOpts().ObjC1)
2873     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
2874 
2875   unsigned CMId = FDecl->getMemoryFunctionKind();
2876   if (CMId == 0)
2877     return false;
2878 
2879   // Handle memory setting and copying functions.
2880   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
2881     CheckStrlcpycatArguments(TheCall, FnInfo);
2882   else if (CMId == Builtin::BIstrncat)
2883     CheckStrncatArguments(TheCall, FnInfo);
2884   else
2885     CheckMemaccessArguments(TheCall, CMId, FnInfo);
2886 
2887   return false;
2888 }
2889 
2890 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
2891                                ArrayRef<const Expr *> Args) {
2892   VariadicCallType CallType =
2893       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
2894 
2895   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
2896             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
2897             CallType);
2898 
2899   return false;
2900 }
2901 
2902 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2903                             const FunctionProtoType *Proto) {
2904   QualType Ty;
2905   if (const auto *V = dyn_cast<VarDecl>(NDecl))
2906     Ty = V->getType().getNonReferenceType();
2907   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
2908     Ty = F->getType().getNonReferenceType();
2909   else
2910     return false;
2911 
2912   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2913       !Ty->isFunctionProtoType())
2914     return false;
2915 
2916   VariadicCallType CallType;
2917   if (!Proto || !Proto->isVariadic()) {
2918     CallType = VariadicDoesNotApply;
2919   } else if (Ty->isBlockPointerType()) {
2920     CallType = VariadicBlock;
2921   } else { // Ty->isFunctionPointerType()
2922     CallType = VariadicFunction;
2923   }
2924 
2925   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
2926             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2927             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2928             TheCall->getCallee()->getSourceRange(), CallType);
2929 
2930   return false;
2931 }
2932 
2933 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2934 /// such as function pointers returned from functions.
2935 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
2936   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
2937                                                   TheCall->getCallee());
2938   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
2939             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2940             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2941             TheCall->getCallee()->getSourceRange(), CallType);
2942 
2943   return false;
2944 }
2945 
2946 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
2947   if (!llvm::isValidAtomicOrderingCABI(Ordering))
2948     return false;
2949 
2950   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
2951   switch (Op) {
2952   case AtomicExpr::AO__c11_atomic_init:
2953   case AtomicExpr::AO__opencl_atomic_init:
2954     llvm_unreachable("There is no ordering argument for an init");
2955 
2956   case AtomicExpr::AO__c11_atomic_load:
2957   case AtomicExpr::AO__opencl_atomic_load:
2958   case AtomicExpr::AO__atomic_load_n:
2959   case AtomicExpr::AO__atomic_load:
2960     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2961            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2962 
2963   case AtomicExpr::AO__c11_atomic_store:
2964   case AtomicExpr::AO__opencl_atomic_store:
2965   case AtomicExpr::AO__atomic_store:
2966   case AtomicExpr::AO__atomic_store_n:
2967     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2968            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2969            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2970 
2971   default:
2972     return true;
2973   }
2974 }
2975 
2976 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2977                                          AtomicExpr::AtomicOp Op) {
2978   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2979   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2980 
2981   // All the non-OpenCL operations take one of the following forms.
2982   // The OpenCL operations take the __c11 forms with one extra argument for
2983   // synchronization scope.
2984   enum {
2985     // C    __c11_atomic_init(A *, C)
2986     Init,
2987 
2988     // C    __c11_atomic_load(A *, int)
2989     Load,
2990 
2991     // void __atomic_load(A *, CP, int)
2992     LoadCopy,
2993 
2994     // void __atomic_store(A *, CP, int)
2995     Copy,
2996 
2997     // C    __c11_atomic_add(A *, M, int)
2998     Arithmetic,
2999 
3000     // C    __atomic_exchange_n(A *, CP, int)
3001     Xchg,
3002 
3003     // void __atomic_exchange(A *, C *, CP, int)
3004     GNUXchg,
3005 
3006     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
3007     C11CmpXchg,
3008 
3009     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
3010     GNUCmpXchg
3011   } Form = Init;
3012 
3013   const unsigned NumForm = GNUCmpXchg + 1;
3014   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
3015   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
3016   // where:
3017   //   C is an appropriate type,
3018   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
3019   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
3020   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
3021   //   the int parameters are for orderings.
3022 
3023   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
3024       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
3025       "need to update code for modified forms");
3026   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
3027                     AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
3028                         AtomicExpr::AO__atomic_load,
3029                 "need to update code for modified C11 atomics");
3030   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
3031                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
3032   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
3033                Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
3034                IsOpenCL;
3035   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
3036              Op == AtomicExpr::AO__atomic_store_n ||
3037              Op == AtomicExpr::AO__atomic_exchange_n ||
3038              Op == AtomicExpr::AO__atomic_compare_exchange_n;
3039   bool IsAddSub = false;
3040 
3041   switch (Op) {
3042   case AtomicExpr::AO__c11_atomic_init:
3043   case AtomicExpr::AO__opencl_atomic_init:
3044     Form = Init;
3045     break;
3046 
3047   case AtomicExpr::AO__c11_atomic_load:
3048   case AtomicExpr::AO__opencl_atomic_load:
3049   case AtomicExpr::AO__atomic_load_n:
3050     Form = Load;
3051     break;
3052 
3053   case AtomicExpr::AO__atomic_load:
3054     Form = LoadCopy;
3055     break;
3056 
3057   case AtomicExpr::AO__c11_atomic_store:
3058   case AtomicExpr::AO__opencl_atomic_store:
3059   case AtomicExpr::AO__atomic_store:
3060   case AtomicExpr::AO__atomic_store_n:
3061     Form = Copy;
3062     break;
3063 
3064   case AtomicExpr::AO__c11_atomic_fetch_add:
3065   case AtomicExpr::AO__c11_atomic_fetch_sub:
3066   case AtomicExpr::AO__opencl_atomic_fetch_add:
3067   case AtomicExpr::AO__opencl_atomic_fetch_sub:
3068   case AtomicExpr::AO__opencl_atomic_fetch_min:
3069   case AtomicExpr::AO__opencl_atomic_fetch_max:
3070   case AtomicExpr::AO__atomic_fetch_add:
3071   case AtomicExpr::AO__atomic_fetch_sub:
3072   case AtomicExpr::AO__atomic_add_fetch:
3073   case AtomicExpr::AO__atomic_sub_fetch:
3074     IsAddSub = true;
3075     LLVM_FALLTHROUGH;
3076   case AtomicExpr::AO__c11_atomic_fetch_and:
3077   case AtomicExpr::AO__c11_atomic_fetch_or:
3078   case AtomicExpr::AO__c11_atomic_fetch_xor:
3079   case AtomicExpr::AO__opencl_atomic_fetch_and:
3080   case AtomicExpr::AO__opencl_atomic_fetch_or:
3081   case AtomicExpr::AO__opencl_atomic_fetch_xor:
3082   case AtomicExpr::AO__atomic_fetch_and:
3083   case AtomicExpr::AO__atomic_fetch_or:
3084   case AtomicExpr::AO__atomic_fetch_xor:
3085   case AtomicExpr::AO__atomic_fetch_nand:
3086   case AtomicExpr::AO__atomic_and_fetch:
3087   case AtomicExpr::AO__atomic_or_fetch:
3088   case AtomicExpr::AO__atomic_xor_fetch:
3089   case AtomicExpr::AO__atomic_nand_fetch:
3090     Form = Arithmetic;
3091     break;
3092 
3093   case AtomicExpr::AO__c11_atomic_exchange:
3094   case AtomicExpr::AO__opencl_atomic_exchange:
3095   case AtomicExpr::AO__atomic_exchange_n:
3096     Form = Xchg;
3097     break;
3098 
3099   case AtomicExpr::AO__atomic_exchange:
3100     Form = GNUXchg;
3101     break;
3102 
3103   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3104   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
3105   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
3106   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
3107     Form = C11CmpXchg;
3108     break;
3109 
3110   case AtomicExpr::AO__atomic_compare_exchange:
3111   case AtomicExpr::AO__atomic_compare_exchange_n:
3112     Form = GNUCmpXchg;
3113     break;
3114   }
3115 
3116   unsigned AdjustedNumArgs = NumArgs[Form];
3117   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
3118     ++AdjustedNumArgs;
3119   // Check we have the right number of arguments.
3120   if (TheCall->getNumArgs() < AdjustedNumArgs) {
3121     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3122       << 0 << AdjustedNumArgs << TheCall->getNumArgs()
3123       << TheCall->getCallee()->getSourceRange();
3124     return ExprError();
3125   } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
3126     Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(),
3127          diag::err_typecheck_call_too_many_args)
3128       << 0 << AdjustedNumArgs << TheCall->getNumArgs()
3129       << TheCall->getCallee()->getSourceRange();
3130     return ExprError();
3131   }
3132 
3133   // Inspect the first argument of the atomic operation.
3134   Expr *Ptr = TheCall->getArg(0);
3135   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
3136   if (ConvertedPtr.isInvalid())
3137     return ExprError();
3138 
3139   Ptr = ConvertedPtr.get();
3140   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
3141   if (!pointerType) {
3142     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3143       << Ptr->getType() << Ptr->getSourceRange();
3144     return ExprError();
3145   }
3146 
3147   // For a __c11 builtin, this should be a pointer to an _Atomic type.
3148   QualType AtomTy = pointerType->getPointeeType(); // 'A'
3149   QualType ValType = AtomTy; // 'C'
3150   if (IsC11) {
3151     if (!AtomTy->isAtomicType()) {
3152       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
3153         << Ptr->getType() << Ptr->getSourceRange();
3154       return ExprError();
3155     }
3156     if (AtomTy.isConstQualified() ||
3157         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
3158       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
3159           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
3160           << Ptr->getSourceRange();
3161       return ExprError();
3162     }
3163     ValType = AtomTy->getAs<AtomicType>()->getValueType();
3164   } else if (Form != Load && Form != LoadCopy) {
3165     if (ValType.isConstQualified()) {
3166       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
3167         << Ptr->getType() << Ptr->getSourceRange();
3168       return ExprError();
3169     }
3170   }
3171 
3172   // For an arithmetic operation, the implied arithmetic must be well-formed.
3173   if (Form == Arithmetic) {
3174     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
3175     if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
3176       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3177         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3178       return ExprError();
3179     }
3180     if (!IsAddSub && !ValType->isIntegerType()) {
3181       Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
3182         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3183       return ExprError();
3184     }
3185     if (IsC11 && ValType->isPointerType() &&
3186         RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
3187                             diag::err_incomplete_type)) {
3188       return ExprError();
3189     }
3190   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
3191     // For __atomic_*_n operations, the value type must be a scalar integral or
3192     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
3193     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3194       << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3195     return ExprError();
3196   }
3197 
3198   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
3199       !AtomTy->isScalarType()) {
3200     // For GNU atomics, require a trivially-copyable type. This is not part of
3201     // the GNU atomics specification, but we enforce it for sanity.
3202     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
3203       << Ptr->getType() << Ptr->getSourceRange();
3204     return ExprError();
3205   }
3206 
3207   switch (ValType.getObjCLifetime()) {
3208   case Qualifiers::OCL_None:
3209   case Qualifiers::OCL_ExplicitNone:
3210     // okay
3211     break;
3212 
3213   case Qualifiers::OCL_Weak:
3214   case Qualifiers::OCL_Strong:
3215   case Qualifiers::OCL_Autoreleasing:
3216     // FIXME: Can this happen? By this point, ValType should be known
3217     // to be trivially copyable.
3218     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3219       << ValType << Ptr->getSourceRange();
3220     return ExprError();
3221   }
3222 
3223   // atomic_fetch_or takes a pointer to a volatile 'A'.  We shouldn't let the
3224   // volatile-ness of the pointee-type inject itself into the result or the
3225   // other operands. Similarly atomic_load can take a pointer to a const 'A'.
3226   ValType.removeLocalVolatile();
3227   ValType.removeLocalConst();
3228   QualType ResultType = ValType;
3229   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
3230       Form == Init)
3231     ResultType = Context.VoidTy;
3232   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
3233     ResultType = Context.BoolTy;
3234 
3235   // The type of a parameter passed 'by value'. In the GNU atomics, such
3236   // arguments are actually passed as pointers.
3237   QualType ByValType = ValType; // 'CP'
3238   if (!IsC11 && !IsN)
3239     ByValType = Ptr->getType();
3240 
3241   // The first argument --- the pointer --- has a fixed type; we
3242   // deduce the types of the rest of the arguments accordingly.  Walk
3243   // the remaining arguments, converting them to the deduced value type.
3244   for (unsigned i = 1; i != TheCall->getNumArgs(); ++i) {
3245     QualType Ty;
3246     if (i < NumVals[Form] + 1) {
3247       switch (i) {
3248       case 1:
3249         // The second argument is the non-atomic operand. For arithmetic, this
3250         // is always passed by value, and for a compare_exchange it is always
3251         // passed by address. For the rest, GNU uses by-address and C11 uses
3252         // by-value.
3253         assert(Form != Load);
3254         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
3255           Ty = ValType;
3256         else if (Form == Copy || Form == Xchg)
3257           Ty = ByValType;
3258         else if (Form == Arithmetic)
3259           Ty = Context.getPointerDiffType();
3260         else {
3261           Expr *ValArg = TheCall->getArg(i);
3262           // Treat this argument as _Nonnull as we want to show a warning if
3263           // NULL is passed into it.
3264           CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
3265           LangAS AS = LangAS::Default;
3266           // Keep address space of non-atomic pointer type.
3267           if (const PointerType *PtrTy =
3268                   ValArg->getType()->getAs<PointerType>()) {
3269             AS = PtrTy->getPointeeType().getAddressSpace();
3270           }
3271           Ty = Context.getPointerType(
3272               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
3273         }
3274         break;
3275       case 2:
3276         // The third argument to compare_exchange / GNU exchange is a
3277         // (pointer to a) desired value.
3278         Ty = ByValType;
3279         break;
3280       case 3:
3281         // The fourth argument to GNU compare_exchange is a 'weak' flag.
3282         Ty = Context.BoolTy;
3283         break;
3284       }
3285     } else {
3286       // The order(s) and scope are always converted to int.
3287       Ty = Context.IntTy;
3288     }
3289 
3290     InitializedEntity Entity =
3291         InitializedEntity::InitializeParameter(Context, Ty, false);
3292     ExprResult Arg = TheCall->getArg(i);
3293     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3294     if (Arg.isInvalid())
3295       return true;
3296     TheCall->setArg(i, Arg.get());
3297   }
3298 
3299   // Permute the arguments into a 'consistent' order.
3300   SmallVector<Expr*, 5> SubExprs;
3301   SubExprs.push_back(Ptr);
3302   switch (Form) {
3303   case Init:
3304     // Note, AtomicExpr::getVal1() has a special case for this atomic.
3305     SubExprs.push_back(TheCall->getArg(1)); // Val1
3306     break;
3307   case Load:
3308     SubExprs.push_back(TheCall->getArg(1)); // Order
3309     break;
3310   case LoadCopy:
3311   case Copy:
3312   case Arithmetic:
3313   case Xchg:
3314     SubExprs.push_back(TheCall->getArg(2)); // Order
3315     SubExprs.push_back(TheCall->getArg(1)); // Val1
3316     break;
3317   case GNUXchg:
3318     // Note, AtomicExpr::getVal2() has a special case for this atomic.
3319     SubExprs.push_back(TheCall->getArg(3)); // Order
3320     SubExprs.push_back(TheCall->getArg(1)); // Val1
3321     SubExprs.push_back(TheCall->getArg(2)); // Val2
3322     break;
3323   case C11CmpXchg:
3324     SubExprs.push_back(TheCall->getArg(3)); // Order
3325     SubExprs.push_back(TheCall->getArg(1)); // Val1
3326     SubExprs.push_back(TheCall->getArg(4)); // OrderFail
3327     SubExprs.push_back(TheCall->getArg(2)); // Val2
3328     break;
3329   case GNUCmpXchg:
3330     SubExprs.push_back(TheCall->getArg(4)); // Order
3331     SubExprs.push_back(TheCall->getArg(1)); // Val1
3332     SubExprs.push_back(TheCall->getArg(5)); // OrderFail
3333     SubExprs.push_back(TheCall->getArg(2)); // Val2
3334     SubExprs.push_back(TheCall->getArg(3)); // Weak
3335     break;
3336   }
3337 
3338   if (SubExprs.size() >= 2 && Form != Init) {
3339     llvm::APSInt Result(32);
3340     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
3341         !isValidOrderingForOp(Result.getSExtValue(), Op))
3342       Diag(SubExprs[1]->getLocStart(),
3343            diag::warn_atomic_op_has_invalid_memory_order)
3344           << SubExprs[1]->getSourceRange();
3345   }
3346 
3347   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
3348     auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
3349     llvm::APSInt Result(32);
3350     if (Scope->isIntegerConstantExpr(Result, Context) &&
3351         !ScopeModel->isValid(Result.getZExtValue())) {
3352       Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope)
3353           << Scope->getSourceRange();
3354     }
3355     SubExprs.push_back(Scope);
3356   }
3357 
3358   AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
3359                                             SubExprs, ResultType, Op,
3360                                             TheCall->getRParenLoc());
3361 
3362   if ((Op == AtomicExpr::AO__c11_atomic_load ||
3363        Op == AtomicExpr::AO__c11_atomic_store ||
3364        Op == AtomicExpr::AO__opencl_atomic_load ||
3365        Op == AtomicExpr::AO__opencl_atomic_store ) &&
3366       Context.AtomicUsesUnsupportedLibcall(AE))
3367     Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib)
3368         << ((Op == AtomicExpr::AO__c11_atomic_load ||
3369             Op == AtomicExpr::AO__opencl_atomic_load)
3370                 ? 0 : 1);
3371 
3372   return AE;
3373 }
3374 
3375 /// checkBuiltinArgument - Given a call to a builtin function, perform
3376 /// normal type-checking on the given argument, updating the call in
3377 /// place.  This is useful when a builtin function requires custom
3378 /// type-checking for some of its arguments but not necessarily all of
3379 /// them.
3380 ///
3381 /// Returns true on error.
3382 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
3383   FunctionDecl *Fn = E->getDirectCallee();
3384   assert(Fn && "builtin call without direct callee!");
3385 
3386   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
3387   InitializedEntity Entity =
3388     InitializedEntity::InitializeParameter(S.Context, Param);
3389 
3390   ExprResult Arg = E->getArg(0);
3391   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3392   if (Arg.isInvalid())
3393     return true;
3394 
3395   E->setArg(ArgIndex, Arg.get());
3396   return false;
3397 }
3398 
3399 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
3400 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
3401 /// type of its first argument.  The main ActOnCallExpr routines have already
3402 /// promoted the types of arguments because all of these calls are prototyped as
3403 /// void(...).
3404 ///
3405 /// This function goes through and does final semantic checking for these
3406 /// builtins,
3407 ExprResult
3408 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
3409   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3410   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3411   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3412 
3413   // Ensure that we have at least one argument to do type inference from.
3414   if (TheCall->getNumArgs() < 1) {
3415     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3416       << 0 << 1 << TheCall->getNumArgs()
3417       << TheCall->getCallee()->getSourceRange();
3418     return ExprError();
3419   }
3420 
3421   // Inspect the first argument of the atomic builtin.  This should always be
3422   // a pointer type, whose element is an integral scalar or pointer type.
3423   // Because it is a pointer type, we don't have to worry about any implicit
3424   // casts here.
3425   // FIXME: We don't allow floating point scalars as input.
3426   Expr *FirstArg = TheCall->getArg(0);
3427   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3428   if (FirstArgResult.isInvalid())
3429     return ExprError();
3430   FirstArg = FirstArgResult.get();
3431   TheCall->setArg(0, FirstArg);
3432 
3433   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3434   if (!pointerType) {
3435     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3436       << FirstArg->getType() << FirstArg->getSourceRange();
3437     return ExprError();
3438   }
3439 
3440   QualType ValType = pointerType->getPointeeType();
3441   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3442       !ValType->isBlockPointerType()) {
3443     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3444       << FirstArg->getType() << FirstArg->getSourceRange();
3445     return ExprError();
3446   }
3447 
3448   switch (ValType.getObjCLifetime()) {
3449   case Qualifiers::OCL_None:
3450   case Qualifiers::OCL_ExplicitNone:
3451     // okay
3452     break;
3453 
3454   case Qualifiers::OCL_Weak:
3455   case Qualifiers::OCL_Strong:
3456   case Qualifiers::OCL_Autoreleasing:
3457     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3458       << ValType << FirstArg->getSourceRange();
3459     return ExprError();
3460   }
3461 
3462   // Strip any qualifiers off ValType.
3463   ValType = ValType.getUnqualifiedType();
3464 
3465   // The majority of builtins return a value, but a few have special return
3466   // types, so allow them to override appropriately below.
3467   QualType ResultType = ValType;
3468 
3469   // We need to figure out which concrete builtin this maps onto.  For example,
3470   // __sync_fetch_and_add with a 2 byte object turns into
3471   // __sync_fetch_and_add_2.
3472 #define BUILTIN_ROW(x) \
3473   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3474     Builtin::BI##x##_8, Builtin::BI##x##_16 }
3475 
3476   static const unsigned BuiltinIndices[][5] = {
3477     BUILTIN_ROW(__sync_fetch_and_add),
3478     BUILTIN_ROW(__sync_fetch_and_sub),
3479     BUILTIN_ROW(__sync_fetch_and_or),
3480     BUILTIN_ROW(__sync_fetch_and_and),
3481     BUILTIN_ROW(__sync_fetch_and_xor),
3482     BUILTIN_ROW(__sync_fetch_and_nand),
3483 
3484     BUILTIN_ROW(__sync_add_and_fetch),
3485     BUILTIN_ROW(__sync_sub_and_fetch),
3486     BUILTIN_ROW(__sync_and_and_fetch),
3487     BUILTIN_ROW(__sync_or_and_fetch),
3488     BUILTIN_ROW(__sync_xor_and_fetch),
3489     BUILTIN_ROW(__sync_nand_and_fetch),
3490 
3491     BUILTIN_ROW(__sync_val_compare_and_swap),
3492     BUILTIN_ROW(__sync_bool_compare_and_swap),
3493     BUILTIN_ROW(__sync_lock_test_and_set),
3494     BUILTIN_ROW(__sync_lock_release),
3495     BUILTIN_ROW(__sync_swap)
3496   };
3497 #undef BUILTIN_ROW
3498 
3499   // Determine the index of the size.
3500   unsigned SizeIndex;
3501   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
3502   case 1: SizeIndex = 0; break;
3503   case 2: SizeIndex = 1; break;
3504   case 4: SizeIndex = 2; break;
3505   case 8: SizeIndex = 3; break;
3506   case 16: SizeIndex = 4; break;
3507   default:
3508     Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3509       << FirstArg->getType() << FirstArg->getSourceRange();
3510     return ExprError();
3511   }
3512 
3513   // Each of these builtins has one pointer argument, followed by some number of
3514   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3515   // that we ignore.  Find out which row of BuiltinIndices to read from as well
3516   // as the number of fixed args.
3517   unsigned BuiltinID = FDecl->getBuiltinID();
3518   unsigned BuiltinIndex, NumFixed = 1;
3519   bool WarnAboutSemanticsChange = false;
3520   switch (BuiltinID) {
3521   default: llvm_unreachable("Unknown overloaded atomic builtin!");
3522   case Builtin::BI__sync_fetch_and_add:
3523   case Builtin::BI__sync_fetch_and_add_1:
3524   case Builtin::BI__sync_fetch_and_add_2:
3525   case Builtin::BI__sync_fetch_and_add_4:
3526   case Builtin::BI__sync_fetch_and_add_8:
3527   case Builtin::BI__sync_fetch_and_add_16:
3528     BuiltinIndex = 0;
3529     break;
3530 
3531   case Builtin::BI__sync_fetch_and_sub:
3532   case Builtin::BI__sync_fetch_and_sub_1:
3533   case Builtin::BI__sync_fetch_and_sub_2:
3534   case Builtin::BI__sync_fetch_and_sub_4:
3535   case Builtin::BI__sync_fetch_and_sub_8:
3536   case Builtin::BI__sync_fetch_and_sub_16:
3537     BuiltinIndex = 1;
3538     break;
3539 
3540   case Builtin::BI__sync_fetch_and_or:
3541   case Builtin::BI__sync_fetch_and_or_1:
3542   case Builtin::BI__sync_fetch_and_or_2:
3543   case Builtin::BI__sync_fetch_and_or_4:
3544   case Builtin::BI__sync_fetch_and_or_8:
3545   case Builtin::BI__sync_fetch_and_or_16:
3546     BuiltinIndex = 2;
3547     break;
3548 
3549   case Builtin::BI__sync_fetch_and_and:
3550   case Builtin::BI__sync_fetch_and_and_1:
3551   case Builtin::BI__sync_fetch_and_and_2:
3552   case Builtin::BI__sync_fetch_and_and_4:
3553   case Builtin::BI__sync_fetch_and_and_8:
3554   case Builtin::BI__sync_fetch_and_and_16:
3555     BuiltinIndex = 3;
3556     break;
3557 
3558   case Builtin::BI__sync_fetch_and_xor:
3559   case Builtin::BI__sync_fetch_and_xor_1:
3560   case Builtin::BI__sync_fetch_and_xor_2:
3561   case Builtin::BI__sync_fetch_and_xor_4:
3562   case Builtin::BI__sync_fetch_and_xor_8:
3563   case Builtin::BI__sync_fetch_and_xor_16:
3564     BuiltinIndex = 4;
3565     break;
3566 
3567   case Builtin::BI__sync_fetch_and_nand:
3568   case Builtin::BI__sync_fetch_and_nand_1:
3569   case Builtin::BI__sync_fetch_and_nand_2:
3570   case Builtin::BI__sync_fetch_and_nand_4:
3571   case Builtin::BI__sync_fetch_and_nand_8:
3572   case Builtin::BI__sync_fetch_and_nand_16:
3573     BuiltinIndex = 5;
3574     WarnAboutSemanticsChange = true;
3575     break;
3576 
3577   case Builtin::BI__sync_add_and_fetch:
3578   case Builtin::BI__sync_add_and_fetch_1:
3579   case Builtin::BI__sync_add_and_fetch_2:
3580   case Builtin::BI__sync_add_and_fetch_4:
3581   case Builtin::BI__sync_add_and_fetch_8:
3582   case Builtin::BI__sync_add_and_fetch_16:
3583     BuiltinIndex = 6;
3584     break;
3585 
3586   case Builtin::BI__sync_sub_and_fetch:
3587   case Builtin::BI__sync_sub_and_fetch_1:
3588   case Builtin::BI__sync_sub_and_fetch_2:
3589   case Builtin::BI__sync_sub_and_fetch_4:
3590   case Builtin::BI__sync_sub_and_fetch_8:
3591   case Builtin::BI__sync_sub_and_fetch_16:
3592     BuiltinIndex = 7;
3593     break;
3594 
3595   case Builtin::BI__sync_and_and_fetch:
3596   case Builtin::BI__sync_and_and_fetch_1:
3597   case Builtin::BI__sync_and_and_fetch_2:
3598   case Builtin::BI__sync_and_and_fetch_4:
3599   case Builtin::BI__sync_and_and_fetch_8:
3600   case Builtin::BI__sync_and_and_fetch_16:
3601     BuiltinIndex = 8;
3602     break;
3603 
3604   case Builtin::BI__sync_or_and_fetch:
3605   case Builtin::BI__sync_or_and_fetch_1:
3606   case Builtin::BI__sync_or_and_fetch_2:
3607   case Builtin::BI__sync_or_and_fetch_4:
3608   case Builtin::BI__sync_or_and_fetch_8:
3609   case Builtin::BI__sync_or_and_fetch_16:
3610     BuiltinIndex = 9;
3611     break;
3612 
3613   case Builtin::BI__sync_xor_and_fetch:
3614   case Builtin::BI__sync_xor_and_fetch_1:
3615   case Builtin::BI__sync_xor_and_fetch_2:
3616   case Builtin::BI__sync_xor_and_fetch_4:
3617   case Builtin::BI__sync_xor_and_fetch_8:
3618   case Builtin::BI__sync_xor_and_fetch_16:
3619     BuiltinIndex = 10;
3620     break;
3621 
3622   case Builtin::BI__sync_nand_and_fetch:
3623   case Builtin::BI__sync_nand_and_fetch_1:
3624   case Builtin::BI__sync_nand_and_fetch_2:
3625   case Builtin::BI__sync_nand_and_fetch_4:
3626   case Builtin::BI__sync_nand_and_fetch_8:
3627   case Builtin::BI__sync_nand_and_fetch_16:
3628     BuiltinIndex = 11;
3629     WarnAboutSemanticsChange = true;
3630     break;
3631 
3632   case Builtin::BI__sync_val_compare_and_swap:
3633   case Builtin::BI__sync_val_compare_and_swap_1:
3634   case Builtin::BI__sync_val_compare_and_swap_2:
3635   case Builtin::BI__sync_val_compare_and_swap_4:
3636   case Builtin::BI__sync_val_compare_and_swap_8:
3637   case Builtin::BI__sync_val_compare_and_swap_16:
3638     BuiltinIndex = 12;
3639     NumFixed = 2;
3640     break;
3641 
3642   case Builtin::BI__sync_bool_compare_and_swap:
3643   case Builtin::BI__sync_bool_compare_and_swap_1:
3644   case Builtin::BI__sync_bool_compare_and_swap_2:
3645   case Builtin::BI__sync_bool_compare_and_swap_4:
3646   case Builtin::BI__sync_bool_compare_and_swap_8:
3647   case Builtin::BI__sync_bool_compare_and_swap_16:
3648     BuiltinIndex = 13;
3649     NumFixed = 2;
3650     ResultType = Context.BoolTy;
3651     break;
3652 
3653   case Builtin::BI__sync_lock_test_and_set:
3654   case Builtin::BI__sync_lock_test_and_set_1:
3655   case Builtin::BI__sync_lock_test_and_set_2:
3656   case Builtin::BI__sync_lock_test_and_set_4:
3657   case Builtin::BI__sync_lock_test_and_set_8:
3658   case Builtin::BI__sync_lock_test_and_set_16:
3659     BuiltinIndex = 14;
3660     break;
3661 
3662   case Builtin::BI__sync_lock_release:
3663   case Builtin::BI__sync_lock_release_1:
3664   case Builtin::BI__sync_lock_release_2:
3665   case Builtin::BI__sync_lock_release_4:
3666   case Builtin::BI__sync_lock_release_8:
3667   case Builtin::BI__sync_lock_release_16:
3668     BuiltinIndex = 15;
3669     NumFixed = 0;
3670     ResultType = Context.VoidTy;
3671     break;
3672 
3673   case Builtin::BI__sync_swap:
3674   case Builtin::BI__sync_swap_1:
3675   case Builtin::BI__sync_swap_2:
3676   case Builtin::BI__sync_swap_4:
3677   case Builtin::BI__sync_swap_8:
3678   case Builtin::BI__sync_swap_16:
3679     BuiltinIndex = 16;
3680     break;
3681   }
3682 
3683   // Now that we know how many fixed arguments we expect, first check that we
3684   // have at least that many.
3685   if (TheCall->getNumArgs() < 1+NumFixed) {
3686     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3687       << 0 << 1+NumFixed << TheCall->getNumArgs()
3688       << TheCall->getCallee()->getSourceRange();
3689     return ExprError();
3690   }
3691 
3692   if (WarnAboutSemanticsChange) {
3693     Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3694       << TheCall->getCallee()->getSourceRange();
3695   }
3696 
3697   // Get the decl for the concrete builtin from this, we can tell what the
3698   // concrete integer type we should convert to is.
3699   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
3700   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
3701   FunctionDecl *NewBuiltinDecl;
3702   if (NewBuiltinID == BuiltinID)
3703     NewBuiltinDecl = FDecl;
3704   else {
3705     // Perform builtin lookup to avoid redeclaring it.
3706     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3707     LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3708     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3709     assert(Res.getFoundDecl());
3710     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
3711     if (!NewBuiltinDecl)
3712       return ExprError();
3713   }
3714 
3715   // The first argument --- the pointer --- has a fixed type; we
3716   // deduce the types of the rest of the arguments accordingly.  Walk
3717   // the remaining arguments, converting them to the deduced value type.
3718   for (unsigned i = 0; i != NumFixed; ++i) {
3719     ExprResult Arg = TheCall->getArg(i+1);
3720 
3721     // GCC does an implicit conversion to the pointer or integer ValType.  This
3722     // can fail in some cases (1i -> int**), check for this error case now.
3723     // Initialize the argument.
3724     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3725                                                    ValType, /*consume*/ false);
3726     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3727     if (Arg.isInvalid())
3728       return ExprError();
3729 
3730     // Okay, we have something that *can* be converted to the right type.  Check
3731     // to see if there is a potentially weird extension going on here.  This can
3732     // happen when you do an atomic operation on something like an char* and
3733     // pass in 42.  The 42 gets converted to char.  This is even more strange
3734     // for things like 45.123 -> char, etc.
3735     // FIXME: Do this check.
3736     TheCall->setArg(i+1, Arg.get());
3737   }
3738 
3739   ASTContext& Context = this->getASTContext();
3740 
3741   // Create a new DeclRefExpr to refer to the new decl.
3742   DeclRefExpr* NewDRE = DeclRefExpr::Create(
3743       Context,
3744       DRE->getQualifierLoc(),
3745       SourceLocation(),
3746       NewBuiltinDecl,
3747       /*enclosing*/ false,
3748       DRE->getLocation(),
3749       Context.BuiltinFnTy,
3750       DRE->getValueKind());
3751 
3752   // Set the callee in the CallExpr.
3753   // FIXME: This loses syntactic information.
3754   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3755   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3756                                               CK_BuiltinFnToFnPtr);
3757   TheCall->setCallee(PromotedCall.get());
3758 
3759   // Change the result type of the call to match the original value type. This
3760   // is arbitrary, but the codegen for these builtins ins design to handle it
3761   // gracefully.
3762   TheCall->setType(ResultType);
3763 
3764   return TheCallResult;
3765 }
3766 
3767 /// SemaBuiltinNontemporalOverloaded - We have a call to
3768 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3769 /// overloaded function based on the pointer type of its last argument.
3770 ///
3771 /// This function goes through and does final semantic checking for these
3772 /// builtins.
3773 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3774   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3775   DeclRefExpr *DRE =
3776       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3777   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3778   unsigned BuiltinID = FDecl->getBuiltinID();
3779   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3780           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3781          "Unexpected nontemporal load/store builtin!");
3782   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3783   unsigned numArgs = isStore ? 2 : 1;
3784 
3785   // Ensure that we have the proper number of arguments.
3786   if (checkArgCount(*this, TheCall, numArgs))
3787     return ExprError();
3788 
3789   // Inspect the last argument of the nontemporal builtin.  This should always
3790   // be a pointer type, from which we imply the type of the memory access.
3791   // Because it is a pointer type, we don't have to worry about any implicit
3792   // casts here.
3793   Expr *PointerArg = TheCall->getArg(numArgs - 1);
3794   ExprResult PointerArgResult =
3795       DefaultFunctionArrayLvalueConversion(PointerArg);
3796 
3797   if (PointerArgResult.isInvalid())
3798     return ExprError();
3799   PointerArg = PointerArgResult.get();
3800   TheCall->setArg(numArgs - 1, PointerArg);
3801 
3802   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3803   if (!pointerType) {
3804     Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3805         << PointerArg->getType() << PointerArg->getSourceRange();
3806     return ExprError();
3807   }
3808 
3809   QualType ValType = pointerType->getPointeeType();
3810 
3811   // Strip any qualifiers off ValType.
3812   ValType = ValType.getUnqualifiedType();
3813   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3814       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3815       !ValType->isVectorType()) {
3816     Diag(DRE->getLocStart(),
3817          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3818         << PointerArg->getType() << PointerArg->getSourceRange();
3819     return ExprError();
3820   }
3821 
3822   if (!isStore) {
3823     TheCall->setType(ValType);
3824     return TheCallResult;
3825   }
3826 
3827   ExprResult ValArg = TheCall->getArg(0);
3828   InitializedEntity Entity = InitializedEntity::InitializeParameter(
3829       Context, ValType, /*consume*/ false);
3830   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3831   if (ValArg.isInvalid())
3832     return ExprError();
3833 
3834   TheCall->setArg(0, ValArg.get());
3835   TheCall->setType(Context.VoidTy);
3836   return TheCallResult;
3837 }
3838 
3839 /// CheckObjCString - Checks that the argument to the builtin
3840 /// CFString constructor is correct
3841 /// Note: It might also make sense to do the UTF-16 conversion here (would
3842 /// simplify the backend).
3843 bool Sema::CheckObjCString(Expr *Arg) {
3844   Arg = Arg->IgnoreParenCasts();
3845   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3846 
3847   if (!Literal || !Literal->isAscii()) {
3848     Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3849       << Arg->getSourceRange();
3850     return true;
3851   }
3852 
3853   if (Literal->containsNonAsciiOrNull()) {
3854     StringRef String = Literal->getString();
3855     unsigned NumBytes = String.size();
3856     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3857     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3858     llvm::UTF16 *ToPtr = &ToBuf[0];
3859 
3860     llvm::ConversionResult Result =
3861         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3862                                  ToPtr + NumBytes, llvm::strictConversion);
3863     // Check for conversion failure.
3864     if (Result != llvm::conversionOK)
3865       Diag(Arg->getLocStart(),
3866            diag::warn_cfstring_truncated) << Arg->getSourceRange();
3867   }
3868   return false;
3869 }
3870 
3871 /// CheckObjCString - Checks that the format string argument to the os_log()
3872 /// and os_trace() functions is correct, and converts it to const char *.
3873 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3874   Arg = Arg->IgnoreParenCasts();
3875   auto *Literal = dyn_cast<StringLiteral>(Arg);
3876   if (!Literal) {
3877     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3878       Literal = ObjcLiteral->getString();
3879     }
3880   }
3881 
3882   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3883     return ExprError(
3884         Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3885         << Arg->getSourceRange());
3886   }
3887 
3888   ExprResult Result(Literal);
3889   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3890   InitializedEntity Entity =
3891       InitializedEntity::InitializeParameter(Context, ResultTy, false);
3892   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3893   return Result;
3894 }
3895 
3896 /// Check that the user is calling the appropriate va_start builtin for the
3897 /// target and calling convention.
3898 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
3899   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
3900   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
3901   bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
3902   bool IsWindows = TT.isOSWindows();
3903   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
3904   if (IsX64 || IsAArch64) {
3905     CallingConv CC = CC_C;
3906     if (const FunctionDecl *FD = S.getCurFunctionDecl())
3907       CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3908     if (IsMSVAStart) {
3909       // Don't allow this in System V ABI functions.
3910       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
3911         return S.Diag(Fn->getLocStart(),
3912                       diag::err_ms_va_start_used_in_sysv_function);
3913     } else {
3914       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
3915       // On x64 Windows, don't allow this in System V ABI functions.
3916       // (Yes, that means there's no corresponding way to support variadic
3917       // System V ABI functions on Windows.)
3918       if ((IsWindows && CC == CC_X86_64SysV) ||
3919           (!IsWindows && CC == CC_Win64))
3920         return S.Diag(Fn->getLocStart(),
3921                       diag::err_va_start_used_in_wrong_abi_function)
3922                << !IsWindows;
3923     }
3924     return false;
3925   }
3926 
3927   if (IsMSVAStart)
3928     return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only);
3929   return false;
3930 }
3931 
3932 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
3933                                              ParmVarDecl **LastParam = nullptr) {
3934   // Determine whether the current function, block, or obj-c method is variadic
3935   // and get its parameter list.
3936   bool IsVariadic = false;
3937   ArrayRef<ParmVarDecl *> Params;
3938   DeclContext *Caller = S.CurContext;
3939   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
3940     IsVariadic = Block->isVariadic();
3941     Params = Block->parameters();
3942   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
3943     IsVariadic = FD->isVariadic();
3944     Params = FD->parameters();
3945   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
3946     IsVariadic = MD->isVariadic();
3947     // FIXME: This isn't correct for methods (results in bogus warning).
3948     Params = MD->parameters();
3949   } else if (isa<CapturedDecl>(Caller)) {
3950     // We don't support va_start in a CapturedDecl.
3951     S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
3952     return true;
3953   } else {
3954     // This must be some other declcontext that parses exprs.
3955     S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
3956     return true;
3957   }
3958 
3959   if (!IsVariadic) {
3960     S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
3961     return true;
3962   }
3963 
3964   if (LastParam)
3965     *LastParam = Params.empty() ? nullptr : Params.back();
3966 
3967   return false;
3968 }
3969 
3970 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3971 /// for validity.  Emit an error and return true on failure; return false
3972 /// on success.
3973 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
3974   Expr *Fn = TheCall->getCallee();
3975 
3976   if (checkVAStartABI(*this, BuiltinID, Fn))
3977     return true;
3978 
3979   if (TheCall->getNumArgs() > 2) {
3980     Diag(TheCall->getArg(2)->getLocStart(),
3981          diag::err_typecheck_call_too_many_args)
3982       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3983       << Fn->getSourceRange()
3984       << SourceRange(TheCall->getArg(2)->getLocStart(),
3985                      (*(TheCall->arg_end()-1))->getLocEnd());
3986     return true;
3987   }
3988 
3989   if (TheCall->getNumArgs() < 2) {
3990     return Diag(TheCall->getLocEnd(),
3991       diag::err_typecheck_call_too_few_args_at_least)
3992       << 0 /*function call*/ << 2 << TheCall->getNumArgs();
3993   }
3994 
3995   // Type-check the first argument normally.
3996   if (checkBuiltinArgument(*this, TheCall, 0))
3997     return true;
3998 
3999   // Check that the current function is variadic, and get its last parameter.
4000   ParmVarDecl *LastParam;
4001   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
4002     return true;
4003 
4004   // Verify that the second argument to the builtin is the last argument of the
4005   // current function or method.
4006   bool SecondArgIsLastNamedArgument = false;
4007   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
4008 
4009   // These are valid if SecondArgIsLastNamedArgument is false after the next
4010   // block.
4011   QualType Type;
4012   SourceLocation ParamLoc;
4013   bool IsCRegister = false;
4014 
4015   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
4016     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
4017       SecondArgIsLastNamedArgument = PV == LastParam;
4018 
4019       Type = PV->getType();
4020       ParamLoc = PV->getLocation();
4021       IsCRegister =
4022           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
4023     }
4024   }
4025 
4026   if (!SecondArgIsLastNamedArgument)
4027     Diag(TheCall->getArg(1)->getLocStart(),
4028          diag::warn_second_arg_of_va_start_not_last_named_param);
4029   else if (IsCRegister || Type->isReferenceType() ||
4030            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
4031              // Promotable integers are UB, but enumerations need a bit of
4032              // extra checking to see what their promotable type actually is.
4033              if (!Type->isPromotableIntegerType())
4034                return false;
4035              if (!Type->isEnumeralType())
4036                return true;
4037              const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
4038              return !(ED &&
4039                       Context.typesAreCompatible(ED->getPromotionType(), Type));
4040            }()) {
4041     unsigned Reason = 0;
4042     if (Type->isReferenceType())  Reason = 1;
4043     else if (IsCRegister)         Reason = 2;
4044     Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
4045     Diag(ParamLoc, diag::note_parameter_type) << Type;
4046   }
4047 
4048   TheCall->setType(Context.VoidTy);
4049   return false;
4050 }
4051 
4052 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
4053   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
4054   //                 const char *named_addr);
4055 
4056   Expr *Func = Call->getCallee();
4057 
4058   if (Call->getNumArgs() < 3)
4059     return Diag(Call->getLocEnd(),
4060                 diag::err_typecheck_call_too_few_args_at_least)
4061            << 0 /*function call*/ << 3 << Call->getNumArgs();
4062 
4063   // Type-check the first argument normally.
4064   if (checkBuiltinArgument(*this, Call, 0))
4065     return true;
4066 
4067   // Check that the current function is variadic.
4068   if (checkVAStartIsInVariadicFunction(*this, Func))
4069     return true;
4070 
4071   // __va_start on Windows does not validate the parameter qualifiers
4072 
4073   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
4074   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
4075 
4076   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
4077   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
4078 
4079   const QualType &ConstCharPtrTy =
4080       Context.getPointerType(Context.CharTy.withConst());
4081   if (!Arg1Ty->isPointerType() ||
4082       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
4083     Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible)
4084         << Arg1->getType() << ConstCharPtrTy
4085         << 1 /* different class */
4086         << 0 /* qualifier difference */
4087         << 3 /* parameter mismatch */
4088         << 2 << Arg1->getType() << ConstCharPtrTy;
4089 
4090   const QualType SizeTy = Context.getSizeType();
4091   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
4092     Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible)
4093         << Arg2->getType() << SizeTy
4094         << 1 /* different class */
4095         << 0 /* qualifier difference */
4096         << 3 /* parameter mismatch */
4097         << 3 << Arg2->getType() << SizeTy;
4098 
4099   return false;
4100 }
4101 
4102 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
4103 /// friends.  This is declared to take (...), so we have to check everything.
4104 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
4105   if (TheCall->getNumArgs() < 2)
4106     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4107       << 0 << 2 << TheCall->getNumArgs()/*function call*/;
4108   if (TheCall->getNumArgs() > 2)
4109     return Diag(TheCall->getArg(2)->getLocStart(),
4110                 diag::err_typecheck_call_too_many_args)
4111       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4112       << SourceRange(TheCall->getArg(2)->getLocStart(),
4113                      (*(TheCall->arg_end()-1))->getLocEnd());
4114 
4115   ExprResult OrigArg0 = TheCall->getArg(0);
4116   ExprResult OrigArg1 = TheCall->getArg(1);
4117 
4118   // Do standard promotions between the two arguments, returning their common
4119   // type.
4120   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
4121   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
4122     return true;
4123 
4124   // Make sure any conversions are pushed back into the call; this is
4125   // type safe since unordered compare builtins are declared as "_Bool
4126   // foo(...)".
4127   TheCall->setArg(0, OrigArg0.get());
4128   TheCall->setArg(1, OrigArg1.get());
4129 
4130   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
4131     return false;
4132 
4133   // If the common type isn't a real floating type, then the arguments were
4134   // invalid for this operation.
4135   if (Res.isNull() || !Res->isRealFloatingType())
4136     return Diag(OrigArg0.get()->getLocStart(),
4137                 diag::err_typecheck_call_invalid_ordered_compare)
4138       << OrigArg0.get()->getType() << OrigArg1.get()->getType()
4139       << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
4140 
4141   return false;
4142 }
4143 
4144 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
4145 /// __builtin_isnan and friends.  This is declared to take (...), so we have
4146 /// to check everything. We expect the last argument to be a floating point
4147 /// value.
4148 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
4149   if (TheCall->getNumArgs() < NumArgs)
4150     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4151       << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
4152   if (TheCall->getNumArgs() > NumArgs)
4153     return Diag(TheCall->getArg(NumArgs)->getLocStart(),
4154                 diag::err_typecheck_call_too_many_args)
4155       << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
4156       << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
4157                      (*(TheCall->arg_end()-1))->getLocEnd());
4158 
4159   Expr *OrigArg = TheCall->getArg(NumArgs-1);
4160 
4161   if (OrigArg->isTypeDependent())
4162     return false;
4163 
4164   // This operation requires a non-_Complex floating-point number.
4165   if (!OrigArg->getType()->isRealFloatingType())
4166     return Diag(OrigArg->getLocStart(),
4167                 diag::err_typecheck_call_invalid_unary_fp)
4168       << OrigArg->getType() << OrigArg->getSourceRange();
4169 
4170   // If this is an implicit conversion from float -> float or double, remove it.
4171   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
4172     // Only remove standard FloatCasts, leaving other casts inplace
4173     if (Cast->getCastKind() == CK_FloatingCast) {
4174       Expr *CastArg = Cast->getSubExpr();
4175       if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
4176           assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
4177                   Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
4178                "promotion from float to either float or double is the only expected cast here");
4179         Cast->setSubExpr(nullptr);
4180         TheCall->setArg(NumArgs-1, CastArg);
4181       }
4182     }
4183   }
4184 
4185   return false;
4186 }
4187 
4188 // Customized Sema Checking for VSX builtins that have the following signature:
4189 // vector [...] builtinName(vector [...], vector [...], const int);
4190 // Which takes the same type of vectors (any legal vector type) for the first
4191 // two arguments and takes compile time constant for the third argument.
4192 // Example builtins are :
4193 // vector double vec_xxpermdi(vector double, vector double, int);
4194 // vector short vec_xxsldwi(vector short, vector short, int);
4195 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
4196   unsigned ExpectedNumArgs = 3;
4197   if (TheCall->getNumArgs() < ExpectedNumArgs)
4198     return Diag(TheCall->getLocEnd(),
4199                 diag::err_typecheck_call_too_few_args_at_least)
4200            << 0 /*function call*/ <<  ExpectedNumArgs << TheCall->getNumArgs()
4201            << TheCall->getSourceRange();
4202 
4203   if (TheCall->getNumArgs() > ExpectedNumArgs)
4204     return Diag(TheCall->getLocEnd(),
4205                 diag::err_typecheck_call_too_many_args_at_most)
4206            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4207            << TheCall->getSourceRange();
4208 
4209   // Check the third argument is a compile time constant
4210   llvm::APSInt Value;
4211   if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
4212     return Diag(TheCall->getLocStart(),
4213                 diag::err_vsx_builtin_nonconstant_argument)
4214            << 3 /* argument index */ << TheCall->getDirectCallee()
4215            << SourceRange(TheCall->getArg(2)->getLocStart(),
4216                           TheCall->getArg(2)->getLocEnd());
4217 
4218   QualType Arg1Ty = TheCall->getArg(0)->getType();
4219   QualType Arg2Ty = TheCall->getArg(1)->getType();
4220 
4221   // Check the type of argument 1 and argument 2 are vectors.
4222   SourceLocation BuiltinLoc = TheCall->getLocStart();
4223   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
4224       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
4225     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
4226            << TheCall->getDirectCallee()
4227            << SourceRange(TheCall->getArg(0)->getLocStart(),
4228                           TheCall->getArg(1)->getLocEnd());
4229   }
4230 
4231   // Check the first two arguments are the same type.
4232   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
4233     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
4234            << TheCall->getDirectCallee()
4235            << SourceRange(TheCall->getArg(0)->getLocStart(),
4236                           TheCall->getArg(1)->getLocEnd());
4237   }
4238 
4239   // When default clang type checking is turned off and the customized type
4240   // checking is used, the returning type of the function must be explicitly
4241   // set. Otherwise it is _Bool by default.
4242   TheCall->setType(Arg1Ty);
4243 
4244   return false;
4245 }
4246 
4247 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
4248 // This is declared to take (...), so we have to check everything.
4249 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
4250   if (TheCall->getNumArgs() < 2)
4251     return ExprError(Diag(TheCall->getLocEnd(),
4252                           diag::err_typecheck_call_too_few_args_at_least)
4253                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4254                      << TheCall->getSourceRange());
4255 
4256   // Determine which of the following types of shufflevector we're checking:
4257   // 1) unary, vector mask: (lhs, mask)
4258   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
4259   QualType resType = TheCall->getArg(0)->getType();
4260   unsigned numElements = 0;
4261 
4262   if (!TheCall->getArg(0)->isTypeDependent() &&
4263       !TheCall->getArg(1)->isTypeDependent()) {
4264     QualType LHSType = TheCall->getArg(0)->getType();
4265     QualType RHSType = TheCall->getArg(1)->getType();
4266 
4267     if (!LHSType->isVectorType() || !RHSType->isVectorType())
4268       return ExprError(Diag(TheCall->getLocStart(),
4269                             diag::err_vec_builtin_non_vector)
4270                        << TheCall->getDirectCallee()
4271                        << SourceRange(TheCall->getArg(0)->getLocStart(),
4272                                       TheCall->getArg(1)->getLocEnd()));
4273 
4274     numElements = LHSType->getAs<VectorType>()->getNumElements();
4275     unsigned numResElements = TheCall->getNumArgs() - 2;
4276 
4277     // Check to see if we have a call with 2 vector arguments, the unary shuffle
4278     // with mask.  If so, verify that RHS is an integer vector type with the
4279     // same number of elts as lhs.
4280     if (TheCall->getNumArgs() == 2) {
4281       if (!RHSType->hasIntegerRepresentation() ||
4282           RHSType->getAs<VectorType>()->getNumElements() != numElements)
4283         return ExprError(Diag(TheCall->getLocStart(),
4284                               diag::err_vec_builtin_incompatible_vector)
4285                          << TheCall->getDirectCallee()
4286                          << SourceRange(TheCall->getArg(1)->getLocStart(),
4287                                         TheCall->getArg(1)->getLocEnd()));
4288     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
4289       return ExprError(Diag(TheCall->getLocStart(),
4290                             diag::err_vec_builtin_incompatible_vector)
4291                        << TheCall->getDirectCallee()
4292                        << SourceRange(TheCall->getArg(0)->getLocStart(),
4293                                       TheCall->getArg(1)->getLocEnd()));
4294     } else if (numElements != numResElements) {
4295       QualType eltType = LHSType->getAs<VectorType>()->getElementType();
4296       resType = Context.getVectorType(eltType, numResElements,
4297                                       VectorType::GenericVector);
4298     }
4299   }
4300 
4301   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
4302     if (TheCall->getArg(i)->isTypeDependent() ||
4303         TheCall->getArg(i)->isValueDependent())
4304       continue;
4305 
4306     llvm::APSInt Result(32);
4307     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
4308       return ExprError(Diag(TheCall->getLocStart(),
4309                             diag::err_shufflevector_nonconstant_argument)
4310                        << TheCall->getArg(i)->getSourceRange());
4311 
4312     // Allow -1 which will be translated to undef in the IR.
4313     if (Result.isSigned() && Result.isAllOnesValue())
4314       continue;
4315 
4316     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
4317       return ExprError(Diag(TheCall->getLocStart(),
4318                             diag::err_shufflevector_argument_too_large)
4319                        << TheCall->getArg(i)->getSourceRange());
4320   }
4321 
4322   SmallVector<Expr*, 32> exprs;
4323 
4324   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
4325     exprs.push_back(TheCall->getArg(i));
4326     TheCall->setArg(i, nullptr);
4327   }
4328 
4329   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
4330                                          TheCall->getCallee()->getLocStart(),
4331                                          TheCall->getRParenLoc());
4332 }
4333 
4334 /// SemaConvertVectorExpr - Handle __builtin_convertvector
4335 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
4336                                        SourceLocation BuiltinLoc,
4337                                        SourceLocation RParenLoc) {
4338   ExprValueKind VK = VK_RValue;
4339   ExprObjectKind OK = OK_Ordinary;
4340   QualType DstTy = TInfo->getType();
4341   QualType SrcTy = E->getType();
4342 
4343   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
4344     return ExprError(Diag(BuiltinLoc,
4345                           diag::err_convertvector_non_vector)
4346                      << E->getSourceRange());
4347   if (!DstTy->isVectorType() && !DstTy->isDependentType())
4348     return ExprError(Diag(BuiltinLoc,
4349                           diag::err_convertvector_non_vector_type));
4350 
4351   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
4352     unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
4353     unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
4354     if (SrcElts != DstElts)
4355       return ExprError(Diag(BuiltinLoc,
4356                             diag::err_convertvector_incompatible_vector)
4357                        << E->getSourceRange());
4358   }
4359 
4360   return new (Context)
4361       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
4362 }
4363 
4364 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
4365 // This is declared to take (const void*, ...) and can take two
4366 // optional constant int args.
4367 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
4368   unsigned NumArgs = TheCall->getNumArgs();
4369 
4370   if (NumArgs > 3)
4371     return Diag(TheCall->getLocEnd(),
4372              diag::err_typecheck_call_too_many_args_at_most)
4373              << 0 /*function call*/ << 3 << NumArgs
4374              << TheCall->getSourceRange();
4375 
4376   // Argument 0 is checked for us and the remaining arguments must be
4377   // constant integers.
4378   for (unsigned i = 1; i != NumArgs; ++i)
4379     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
4380       return true;
4381 
4382   return false;
4383 }
4384 
4385 /// SemaBuiltinAssume - Handle __assume (MS Extension).
4386 // __assume does not evaluate its arguments, and should warn if its argument
4387 // has side effects.
4388 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
4389   Expr *Arg = TheCall->getArg(0);
4390   if (Arg->isInstantiationDependent()) return false;
4391 
4392   if (Arg->HasSideEffects(Context))
4393     Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
4394       << Arg->getSourceRange()
4395       << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
4396 
4397   return false;
4398 }
4399 
4400 /// Handle __builtin_alloca_with_align. This is declared
4401 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
4402 /// than 8.
4403 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
4404   // The alignment must be a constant integer.
4405   Expr *Arg = TheCall->getArg(1);
4406 
4407   // We can't check the value of a dependent argument.
4408   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4409     if (const auto *UE =
4410             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
4411       if (UE->getKind() == UETT_AlignOf)
4412         Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
4413           << Arg->getSourceRange();
4414 
4415     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
4416 
4417     if (!Result.isPowerOf2())
4418       return Diag(TheCall->getLocStart(),
4419                   diag::err_alignment_not_power_of_two)
4420            << Arg->getSourceRange();
4421 
4422     if (Result < Context.getCharWidth())
4423       return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
4424            << (unsigned)Context.getCharWidth()
4425            << Arg->getSourceRange();
4426 
4427     if (Result > std::numeric_limits<int32_t>::max())
4428       return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
4429            << std::numeric_limits<int32_t>::max()
4430            << Arg->getSourceRange();
4431   }
4432 
4433   return false;
4434 }
4435 
4436 /// Handle __builtin_assume_aligned. This is declared
4437 /// as (const void*, size_t, ...) and can take one optional constant int arg.
4438 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
4439   unsigned NumArgs = TheCall->getNumArgs();
4440 
4441   if (NumArgs > 3)
4442     return Diag(TheCall->getLocEnd(),
4443              diag::err_typecheck_call_too_many_args_at_most)
4444              << 0 /*function call*/ << 3 << NumArgs
4445              << TheCall->getSourceRange();
4446 
4447   // The alignment must be a constant integer.
4448   Expr *Arg = TheCall->getArg(1);
4449 
4450   // We can't check the value of a dependent argument.
4451   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4452     llvm::APSInt Result;
4453     if (SemaBuiltinConstantArg(TheCall, 1, Result))
4454       return true;
4455 
4456     if (!Result.isPowerOf2())
4457       return Diag(TheCall->getLocStart(),
4458                   diag::err_alignment_not_power_of_two)
4459            << Arg->getSourceRange();
4460   }
4461 
4462   if (NumArgs > 2) {
4463     ExprResult Arg(TheCall->getArg(2));
4464     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4465       Context.getSizeType(), false);
4466     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4467     if (Arg.isInvalid()) return true;
4468     TheCall->setArg(2, Arg.get());
4469   }
4470 
4471   return false;
4472 }
4473 
4474 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4475   unsigned BuiltinID =
4476       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4477   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4478 
4479   unsigned NumArgs = TheCall->getNumArgs();
4480   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4481   if (NumArgs < NumRequiredArgs) {
4482     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4483            << 0 /* function call */ << NumRequiredArgs << NumArgs
4484            << TheCall->getSourceRange();
4485   }
4486   if (NumArgs >= NumRequiredArgs + 0x100) {
4487     return Diag(TheCall->getLocEnd(),
4488                 diag::err_typecheck_call_too_many_args_at_most)
4489            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4490            << TheCall->getSourceRange();
4491   }
4492   unsigned i = 0;
4493 
4494   // For formatting call, check buffer arg.
4495   if (!IsSizeCall) {
4496     ExprResult Arg(TheCall->getArg(i));
4497     InitializedEntity Entity = InitializedEntity::InitializeParameter(
4498         Context, Context.VoidPtrTy, false);
4499     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4500     if (Arg.isInvalid())
4501       return true;
4502     TheCall->setArg(i, Arg.get());
4503     i++;
4504   }
4505 
4506   // Check string literal arg.
4507   unsigned FormatIdx = i;
4508   {
4509     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4510     if (Arg.isInvalid())
4511       return true;
4512     TheCall->setArg(i, Arg.get());
4513     i++;
4514   }
4515 
4516   // Make sure variadic args are scalar.
4517   unsigned FirstDataArg = i;
4518   while (i < NumArgs) {
4519     ExprResult Arg = DefaultVariadicArgumentPromotion(
4520         TheCall->getArg(i), VariadicFunction, nullptr);
4521     if (Arg.isInvalid())
4522       return true;
4523     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4524     if (ArgSize.getQuantity() >= 0x100) {
4525       return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4526              << i << (int)ArgSize.getQuantity() << 0xff
4527              << TheCall->getSourceRange();
4528     }
4529     TheCall->setArg(i, Arg.get());
4530     i++;
4531   }
4532 
4533   // Check formatting specifiers. NOTE: We're only doing this for the non-size
4534   // call to avoid duplicate diagnostics.
4535   if (!IsSizeCall) {
4536     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4537     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4538     bool Success = CheckFormatArguments(
4539         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4540         VariadicFunction, TheCall->getLocStart(), SourceRange(),
4541         CheckedVarArgs);
4542     if (!Success)
4543       return true;
4544   }
4545 
4546   if (IsSizeCall) {
4547     TheCall->setType(Context.getSizeType());
4548   } else {
4549     TheCall->setType(Context.VoidPtrTy);
4550   }
4551   return false;
4552 }
4553 
4554 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4555 /// TheCall is a constant expression.
4556 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4557                                   llvm::APSInt &Result) {
4558   Expr *Arg = TheCall->getArg(ArgNum);
4559   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4560   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4561 
4562   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4563 
4564   if (!Arg->isIntegerConstantExpr(Result, Context))
4565     return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
4566                 << FDecl->getDeclName() <<  Arg->getSourceRange();
4567 
4568   return false;
4569 }
4570 
4571 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4572 /// TheCall is a constant expression in the range [Low, High].
4573 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4574                                        int Low, int High) {
4575   llvm::APSInt Result;
4576 
4577   // We can't check the value of a dependent argument.
4578   Expr *Arg = TheCall->getArg(ArgNum);
4579   if (Arg->isTypeDependent() || Arg->isValueDependent())
4580     return false;
4581 
4582   // Check constant-ness first.
4583   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4584     return true;
4585 
4586   if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
4587     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
4588       << Low << High << Arg->getSourceRange();
4589 
4590   return false;
4591 }
4592 
4593 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4594 /// TheCall is a constant expression is a multiple of Num..
4595 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4596                                           unsigned Num) {
4597   llvm::APSInt Result;
4598 
4599   // We can't check the value of a dependent argument.
4600   Expr *Arg = TheCall->getArg(ArgNum);
4601   if (Arg->isTypeDependent() || Arg->isValueDependent())
4602     return false;
4603 
4604   // Check constant-ness first.
4605   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4606     return true;
4607 
4608   if (Result.getSExtValue() % Num != 0)
4609     return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4610       << Num << Arg->getSourceRange();
4611 
4612   return false;
4613 }
4614 
4615 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4616 /// TheCall is an ARM/AArch64 special register string literal.
4617 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4618                                     int ArgNum, unsigned ExpectedFieldNum,
4619                                     bool AllowName) {
4620   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4621                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4622                       BuiltinID == ARM::BI__builtin_arm_rsr ||
4623                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
4624                       BuiltinID == ARM::BI__builtin_arm_wsr ||
4625                       BuiltinID == ARM::BI__builtin_arm_wsrp;
4626   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4627                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4628                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
4629                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4630                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
4631                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
4632   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4633 
4634   // We can't check the value of a dependent argument.
4635   Expr *Arg = TheCall->getArg(ArgNum);
4636   if (Arg->isTypeDependent() || Arg->isValueDependent())
4637     return false;
4638 
4639   // Check if the argument is a string literal.
4640   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4641     return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4642            << Arg->getSourceRange();
4643 
4644   // Check the type of special register given.
4645   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4646   SmallVector<StringRef, 6> Fields;
4647   Reg.split(Fields, ":");
4648 
4649   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4650     return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4651            << Arg->getSourceRange();
4652 
4653   // If the string is the name of a register then we cannot check that it is
4654   // valid here but if the string is of one the forms described in ACLE then we
4655   // can check that the supplied fields are integers and within the valid
4656   // ranges.
4657   if (Fields.size() > 1) {
4658     bool FiveFields = Fields.size() == 5;
4659 
4660     bool ValidString = true;
4661     if (IsARMBuiltin) {
4662       ValidString &= Fields[0].startswith_lower("cp") ||
4663                      Fields[0].startswith_lower("p");
4664       if (ValidString)
4665         Fields[0] =
4666           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4667 
4668       ValidString &= Fields[2].startswith_lower("c");
4669       if (ValidString)
4670         Fields[2] = Fields[2].drop_front(1);
4671 
4672       if (FiveFields) {
4673         ValidString &= Fields[3].startswith_lower("c");
4674         if (ValidString)
4675           Fields[3] = Fields[3].drop_front(1);
4676       }
4677     }
4678 
4679     SmallVector<int, 5> Ranges;
4680     if (FiveFields)
4681       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
4682     else
4683       Ranges.append({15, 7, 15});
4684 
4685     for (unsigned i=0; i<Fields.size(); ++i) {
4686       int IntField;
4687       ValidString &= !Fields[i].getAsInteger(10, IntField);
4688       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4689     }
4690 
4691     if (!ValidString)
4692       return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4693              << Arg->getSourceRange();
4694   } else if (IsAArch64Builtin && Fields.size() == 1) {
4695     // If the register name is one of those that appear in the condition below
4696     // and the special register builtin being used is one of the write builtins,
4697     // then we require that the argument provided for writing to the register
4698     // is an integer constant expression. This is because it will be lowered to
4699     // an MSR (immediate) instruction, so we need to know the immediate at
4700     // compile time.
4701     if (TheCall->getNumArgs() != 2)
4702       return false;
4703 
4704     std::string RegLower = Reg.lower();
4705     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4706         RegLower != "pan" && RegLower != "uao")
4707       return false;
4708 
4709     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4710   }
4711 
4712   return false;
4713 }
4714 
4715 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
4716 /// This checks that the target supports __builtin_longjmp and
4717 /// that val is a constant 1.
4718 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
4719   if (!Context.getTargetInfo().hasSjLjLowering())
4720     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4721              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4722 
4723   Expr *Arg = TheCall->getArg(1);
4724   llvm::APSInt Result;
4725 
4726   // TODO: This is less than ideal. Overload this to take a value.
4727   if (SemaBuiltinConstantArg(TheCall, 1, Result))
4728     return true;
4729 
4730   if (Result != 1)
4731     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4732              << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4733 
4734   return false;
4735 }
4736 
4737 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4738 /// This checks that the target supports __builtin_setjmp.
4739 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4740   if (!Context.getTargetInfo().hasSjLjLowering())
4741     return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4742              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4743   return false;
4744 }
4745 
4746 namespace {
4747 
4748 class UncoveredArgHandler {
4749   enum { Unknown = -1, AllCovered = -2 };
4750 
4751   signed FirstUncoveredArg = Unknown;
4752   SmallVector<const Expr *, 4> DiagnosticExprs;
4753 
4754 public:
4755   UncoveredArgHandler() = default;
4756 
4757   bool hasUncoveredArg() const {
4758     return (FirstUncoveredArg >= 0);
4759   }
4760 
4761   unsigned getUncoveredArg() const {
4762     assert(hasUncoveredArg() && "no uncovered argument");
4763     return FirstUncoveredArg;
4764   }
4765 
4766   void setAllCovered() {
4767     // A string has been found with all arguments covered, so clear out
4768     // the diagnostics.
4769     DiagnosticExprs.clear();
4770     FirstUncoveredArg = AllCovered;
4771   }
4772 
4773   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4774     assert(NewFirstUncoveredArg >= 0 && "Outside range");
4775 
4776     // Don't update if a previous string covers all arguments.
4777     if (FirstUncoveredArg == AllCovered)
4778       return;
4779 
4780     // UncoveredArgHandler tracks the highest uncovered argument index
4781     // and with it all the strings that match this index.
4782     if (NewFirstUncoveredArg == FirstUncoveredArg)
4783       DiagnosticExprs.push_back(StrExpr);
4784     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4785       DiagnosticExprs.clear();
4786       DiagnosticExprs.push_back(StrExpr);
4787       FirstUncoveredArg = NewFirstUncoveredArg;
4788     }
4789   }
4790 
4791   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4792 };
4793 
4794 enum StringLiteralCheckType {
4795   SLCT_NotALiteral,
4796   SLCT_UncheckedLiteral,
4797   SLCT_CheckedLiteral
4798 };
4799 
4800 } // namespace
4801 
4802 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4803                                      BinaryOperatorKind BinOpKind,
4804                                      bool AddendIsRight) {
4805   unsigned BitWidth = Offset.getBitWidth();
4806   unsigned AddendBitWidth = Addend.getBitWidth();
4807   // There might be negative interim results.
4808   if (Addend.isUnsigned()) {
4809     Addend = Addend.zext(++AddendBitWidth);
4810     Addend.setIsSigned(true);
4811   }
4812   // Adjust the bit width of the APSInts.
4813   if (AddendBitWidth > BitWidth) {
4814     Offset = Offset.sext(AddendBitWidth);
4815     BitWidth = AddendBitWidth;
4816   } else if (BitWidth > AddendBitWidth) {
4817     Addend = Addend.sext(BitWidth);
4818   }
4819 
4820   bool Ov = false;
4821   llvm::APSInt ResOffset = Offset;
4822   if (BinOpKind == BO_Add)
4823     ResOffset = Offset.sadd_ov(Addend, Ov);
4824   else {
4825     assert(AddendIsRight && BinOpKind == BO_Sub &&
4826            "operator must be add or sub with addend on the right");
4827     ResOffset = Offset.ssub_ov(Addend, Ov);
4828   }
4829 
4830   // We add an offset to a pointer here so we should support an offset as big as
4831   // possible.
4832   if (Ov) {
4833     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
4834            "index (intermediate) result too big");
4835     Offset = Offset.sext(2 * BitWidth);
4836     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4837     return;
4838   }
4839 
4840   Offset = ResOffset;
4841 }
4842 
4843 namespace {
4844 
4845 // This is a wrapper class around StringLiteral to support offsetted string
4846 // literals as format strings. It takes the offset into account when returning
4847 // the string and its length or the source locations to display notes correctly.
4848 class FormatStringLiteral {
4849   const StringLiteral *FExpr;
4850   int64_t Offset;
4851 
4852  public:
4853   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4854       : FExpr(fexpr), Offset(Offset) {}
4855 
4856   StringRef getString() const {
4857     return FExpr->getString().drop_front(Offset);
4858   }
4859 
4860   unsigned getByteLength() const {
4861     return FExpr->getByteLength() - getCharByteWidth() * Offset;
4862   }
4863 
4864   unsigned getLength() const { return FExpr->getLength() - Offset; }
4865   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4866 
4867   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4868 
4869   QualType getType() const { return FExpr->getType(); }
4870 
4871   bool isAscii() const { return FExpr->isAscii(); }
4872   bool isWide() const { return FExpr->isWide(); }
4873   bool isUTF8() const { return FExpr->isUTF8(); }
4874   bool isUTF16() const { return FExpr->isUTF16(); }
4875   bool isUTF32() const { return FExpr->isUTF32(); }
4876   bool isPascal() const { return FExpr->isPascal(); }
4877 
4878   SourceLocation getLocationOfByte(
4879       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4880       const TargetInfo &Target, unsigned *StartToken = nullptr,
4881       unsigned *StartTokenByteOffset = nullptr) const {
4882     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4883                                     StartToken, StartTokenByteOffset);
4884   }
4885 
4886   SourceLocation getLocStart() const LLVM_READONLY {
4887     return FExpr->getLocStart().getLocWithOffset(Offset);
4888   }
4889 
4890   SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4891 };
4892 
4893 }  // namespace
4894 
4895 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
4896                               const Expr *OrigFormatExpr,
4897                               ArrayRef<const Expr *> Args,
4898                               bool HasVAListArg, unsigned format_idx,
4899                               unsigned firstDataArg,
4900                               Sema::FormatStringType Type,
4901                               bool inFunctionCall,
4902                               Sema::VariadicCallType CallType,
4903                               llvm::SmallBitVector &CheckedVarArgs,
4904                               UncoveredArgHandler &UncoveredArg);
4905 
4906 // Determine if an expression is a string literal or constant string.
4907 // If this function returns false on the arguments to a function expecting a
4908 // format string, we will usually need to emit a warning.
4909 // True string literals are then checked by CheckFormatString.
4910 static StringLiteralCheckType
4911 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4912                       bool HasVAListArg, unsigned format_idx,
4913                       unsigned firstDataArg, Sema::FormatStringType Type,
4914                       Sema::VariadicCallType CallType, bool InFunctionCall,
4915                       llvm::SmallBitVector &CheckedVarArgs,
4916                       UncoveredArgHandler &UncoveredArg,
4917                       llvm::APSInt Offset) {
4918  tryAgain:
4919   assert(Offset.isSigned() && "invalid offset");
4920 
4921   if (E->isTypeDependent() || E->isValueDependent())
4922     return SLCT_NotALiteral;
4923 
4924   E = E->IgnoreParenCasts();
4925 
4926   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
4927     // Technically -Wformat-nonliteral does not warn about this case.
4928     // The behavior of printf and friends in this case is implementation
4929     // dependent.  Ideally if the format string cannot be null then
4930     // it should have a 'nonnull' attribute in the function prototype.
4931     return SLCT_UncheckedLiteral;
4932 
4933   switch (E->getStmtClass()) {
4934   case Stmt::BinaryConditionalOperatorClass:
4935   case Stmt::ConditionalOperatorClass: {
4936     // The expression is a literal if both sub-expressions were, and it was
4937     // completely checked only if both sub-expressions were checked.
4938     const AbstractConditionalOperator *C =
4939         cast<AbstractConditionalOperator>(E);
4940 
4941     // Determine whether it is necessary to check both sub-expressions, for
4942     // example, because the condition expression is a constant that can be
4943     // evaluated at compile time.
4944     bool CheckLeft = true, CheckRight = true;
4945 
4946     bool Cond;
4947     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4948       if (Cond)
4949         CheckRight = false;
4950       else
4951         CheckLeft = false;
4952     }
4953 
4954     // We need to maintain the offsets for the right and the left hand side
4955     // separately to check if every possible indexed expression is a valid
4956     // string literal. They might have different offsets for different string
4957     // literals in the end.
4958     StringLiteralCheckType Left;
4959     if (!CheckLeft)
4960       Left = SLCT_UncheckedLiteral;
4961     else {
4962       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4963                                    HasVAListArg, format_idx, firstDataArg,
4964                                    Type, CallType, InFunctionCall,
4965                                    CheckedVarArgs, UncoveredArg, Offset);
4966       if (Left == SLCT_NotALiteral || !CheckRight) {
4967         return Left;
4968       }
4969     }
4970 
4971     StringLiteralCheckType Right =
4972         checkFormatStringExpr(S, C->getFalseExpr(), Args,
4973                               HasVAListArg, format_idx, firstDataArg,
4974                               Type, CallType, InFunctionCall, CheckedVarArgs,
4975                               UncoveredArg, Offset);
4976 
4977     return (CheckLeft && Left < Right) ? Left : Right;
4978   }
4979 
4980   case Stmt::ImplicitCastExprClass:
4981     E = cast<ImplicitCastExpr>(E)->getSubExpr();
4982     goto tryAgain;
4983 
4984   case Stmt::OpaqueValueExprClass:
4985     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4986       E = src;
4987       goto tryAgain;
4988     }
4989     return SLCT_NotALiteral;
4990 
4991   case Stmt::PredefinedExprClass:
4992     // While __func__, etc., are technically not string literals, they
4993     // cannot contain format specifiers and thus are not a security
4994     // liability.
4995     return SLCT_UncheckedLiteral;
4996 
4997   case Stmt::DeclRefExprClass: {
4998     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
4999 
5000     // As an exception, do not flag errors for variables binding to
5001     // const string literals.
5002     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
5003       bool isConstant = false;
5004       QualType T = DR->getType();
5005 
5006       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
5007         isConstant = AT->getElementType().isConstant(S.Context);
5008       } else if (const PointerType *PT = T->getAs<PointerType>()) {
5009         isConstant = T.isConstant(S.Context) &&
5010                      PT->getPointeeType().isConstant(S.Context);
5011       } else if (T->isObjCObjectPointerType()) {
5012         // In ObjC, there is usually no "const ObjectPointer" type,
5013         // so don't check if the pointee type is constant.
5014         isConstant = T.isConstant(S.Context);
5015       }
5016 
5017       if (isConstant) {
5018         if (const Expr *Init = VD->getAnyInitializer()) {
5019           // Look through initializers like const char c[] = { "foo" }
5020           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
5021             if (InitList->isStringLiteralInit())
5022               Init = InitList->getInit(0)->IgnoreParenImpCasts();
5023           }
5024           return checkFormatStringExpr(S, Init, Args,
5025                                        HasVAListArg, format_idx,
5026                                        firstDataArg, Type, CallType,
5027                                        /*InFunctionCall*/ false, CheckedVarArgs,
5028                                        UncoveredArg, Offset);
5029         }
5030       }
5031 
5032       // For vprintf* functions (i.e., HasVAListArg==true), we add a
5033       // special check to see if the format string is a function parameter
5034       // of the function calling the printf function.  If the function
5035       // has an attribute indicating it is a printf-like function, then we
5036       // should suppress warnings concerning non-literals being used in a call
5037       // to a vprintf function.  For example:
5038       //
5039       // void
5040       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
5041       //      va_list ap;
5042       //      va_start(ap, fmt);
5043       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
5044       //      ...
5045       // }
5046       if (HasVAListArg) {
5047         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
5048           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
5049             int PVIndex = PV->getFunctionScopeIndex() + 1;
5050             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
5051               // adjust for implicit parameter
5052               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5053                 if (MD->isInstance())
5054                   ++PVIndex;
5055               // We also check if the formats are compatible.
5056               // We can't pass a 'scanf' string to a 'printf' function.
5057               if (PVIndex == PVFormat->getFormatIdx() &&
5058                   Type == S.GetFormatStringType(PVFormat))
5059                 return SLCT_UncheckedLiteral;
5060             }
5061           }
5062         }
5063       }
5064     }
5065 
5066     return SLCT_NotALiteral;
5067   }
5068 
5069   case Stmt::CallExprClass:
5070   case Stmt::CXXMemberCallExprClass: {
5071     const CallExpr *CE = cast<CallExpr>(E);
5072     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
5073       if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
5074         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
5075         return checkFormatStringExpr(S, Arg, Args,
5076                                      HasVAListArg, format_idx, firstDataArg,
5077                                      Type, CallType, InFunctionCall,
5078                                      CheckedVarArgs, UncoveredArg, Offset);
5079       } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5080         unsigned BuiltinID = FD->getBuiltinID();
5081         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
5082             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
5083           const Expr *Arg = CE->getArg(0);
5084           return checkFormatStringExpr(S, Arg, Args,
5085                                        HasVAListArg, format_idx,
5086                                        firstDataArg, Type, CallType,
5087                                        InFunctionCall, CheckedVarArgs,
5088                                        UncoveredArg, Offset);
5089         }
5090       }
5091     }
5092 
5093     return SLCT_NotALiteral;
5094   }
5095   case Stmt::ObjCMessageExprClass: {
5096     const auto *ME = cast<ObjCMessageExpr>(E);
5097     if (const auto *ND = ME->getMethodDecl()) {
5098       if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
5099         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
5100         return checkFormatStringExpr(
5101             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
5102             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
5103       }
5104     }
5105 
5106     return SLCT_NotALiteral;
5107   }
5108   case Stmt::ObjCStringLiteralClass:
5109   case Stmt::StringLiteralClass: {
5110     const StringLiteral *StrE = nullptr;
5111 
5112     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
5113       StrE = ObjCFExpr->getString();
5114     else
5115       StrE = cast<StringLiteral>(E);
5116 
5117     if (StrE) {
5118       if (Offset.isNegative() || Offset > StrE->getLength()) {
5119         // TODO: It would be better to have an explicit warning for out of
5120         // bounds literals.
5121         return SLCT_NotALiteral;
5122       }
5123       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
5124       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
5125                         firstDataArg, Type, InFunctionCall, CallType,
5126                         CheckedVarArgs, UncoveredArg);
5127       return SLCT_CheckedLiteral;
5128     }
5129 
5130     return SLCT_NotALiteral;
5131   }
5132   case Stmt::BinaryOperatorClass: {
5133     llvm::APSInt LResult;
5134     llvm::APSInt RResult;
5135 
5136     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
5137 
5138     // A string literal + an int offset is still a string literal.
5139     if (BinOp->isAdditiveOp()) {
5140       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
5141       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
5142 
5143       if (LIsInt != RIsInt) {
5144         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
5145 
5146         if (LIsInt) {
5147           if (BinOpKind == BO_Add) {
5148             sumOffsets(Offset, LResult, BinOpKind, RIsInt);
5149             E = BinOp->getRHS();
5150             goto tryAgain;
5151           }
5152         } else {
5153           sumOffsets(Offset, RResult, BinOpKind, RIsInt);
5154           E = BinOp->getLHS();
5155           goto tryAgain;
5156         }
5157       }
5158     }
5159 
5160     return SLCT_NotALiteral;
5161   }
5162   case Stmt::UnaryOperatorClass: {
5163     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
5164     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
5165     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
5166       llvm::APSInt IndexResult;
5167       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
5168         sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
5169         E = ASE->getBase();
5170         goto tryAgain;
5171       }
5172     }
5173 
5174     return SLCT_NotALiteral;
5175   }
5176 
5177   default:
5178     return SLCT_NotALiteral;
5179   }
5180 }
5181 
5182 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
5183   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
5184       .Case("scanf", FST_Scanf)
5185       .Cases("printf", "printf0", FST_Printf)
5186       .Cases("NSString", "CFString", FST_NSString)
5187       .Case("strftime", FST_Strftime)
5188       .Case("strfmon", FST_Strfmon)
5189       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
5190       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
5191       .Case("os_trace", FST_OSLog)
5192       .Case("os_log", FST_OSLog)
5193       .Default(FST_Unknown);
5194 }
5195 
5196 /// CheckFormatArguments - Check calls to printf and scanf (and similar
5197 /// functions) for correct use of format strings.
5198 /// Returns true if a format string has been fully checked.
5199 bool Sema::CheckFormatArguments(const FormatAttr *Format,
5200                                 ArrayRef<const Expr *> Args,
5201                                 bool IsCXXMember,
5202                                 VariadicCallType CallType,
5203                                 SourceLocation Loc, SourceRange Range,
5204                                 llvm::SmallBitVector &CheckedVarArgs) {
5205   FormatStringInfo FSI;
5206   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
5207     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
5208                                 FSI.FirstDataArg, GetFormatStringType(Format),
5209                                 CallType, Loc, Range, CheckedVarArgs);
5210   return false;
5211 }
5212 
5213 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
5214                                 bool HasVAListArg, unsigned format_idx,
5215                                 unsigned firstDataArg, FormatStringType Type,
5216                                 VariadicCallType CallType,
5217                                 SourceLocation Loc, SourceRange Range,
5218                                 llvm::SmallBitVector &CheckedVarArgs) {
5219   // CHECK: printf/scanf-like function is called with no format string.
5220   if (format_idx >= Args.size()) {
5221     Diag(Loc, diag::warn_missing_format_string) << Range;
5222     return false;
5223   }
5224 
5225   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
5226 
5227   // CHECK: format string is not a string literal.
5228   //
5229   // Dynamically generated format strings are difficult to
5230   // automatically vet at compile time.  Requiring that format strings
5231   // are string literals: (1) permits the checking of format strings by
5232   // the compiler and thereby (2) can practically remove the source of
5233   // many format string exploits.
5234 
5235   // Format string can be either ObjC string (e.g. @"%d") or
5236   // C string (e.g. "%d")
5237   // ObjC string uses the same format specifiers as C string, so we can use
5238   // the same format string checking logic for both ObjC and C strings.
5239   UncoveredArgHandler UncoveredArg;
5240   StringLiteralCheckType CT =
5241       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
5242                             format_idx, firstDataArg, Type, CallType,
5243                             /*IsFunctionCall*/ true, CheckedVarArgs,
5244                             UncoveredArg,
5245                             /*no string offset*/ llvm::APSInt(64, false) = 0);
5246 
5247   // Generate a diagnostic where an uncovered argument is detected.
5248   if (UncoveredArg.hasUncoveredArg()) {
5249     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
5250     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
5251     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
5252   }
5253 
5254   if (CT != SLCT_NotALiteral)
5255     // Literal format string found, check done!
5256     return CT == SLCT_CheckedLiteral;
5257 
5258   // Strftime is particular as it always uses a single 'time' argument,
5259   // so it is safe to pass a non-literal string.
5260   if (Type == FST_Strftime)
5261     return false;
5262 
5263   // Do not emit diag when the string param is a macro expansion and the
5264   // format is either NSString or CFString. This is a hack to prevent
5265   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
5266   // which are usually used in place of NS and CF string literals.
5267   SourceLocation FormatLoc = Args[format_idx]->getLocStart();
5268   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
5269     return false;
5270 
5271   // If there are no arguments specified, warn with -Wformat-security, otherwise
5272   // warn only with -Wformat-nonliteral.
5273   if (Args.size() == firstDataArg) {
5274     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
5275       << OrigFormatExpr->getSourceRange();
5276     switch (Type) {
5277     default:
5278       break;
5279     case FST_Kprintf:
5280     case FST_FreeBSDKPrintf:
5281     case FST_Printf:
5282       Diag(FormatLoc, diag::note_format_security_fixit)
5283         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
5284       break;
5285     case FST_NSString:
5286       Diag(FormatLoc, diag::note_format_security_fixit)
5287         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
5288       break;
5289     }
5290   } else {
5291     Diag(FormatLoc, diag::warn_format_nonliteral)
5292       << OrigFormatExpr->getSourceRange();
5293   }
5294   return false;
5295 }
5296 
5297 namespace {
5298 
5299 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
5300 protected:
5301   Sema &S;
5302   const FormatStringLiteral *FExpr;
5303   const Expr *OrigFormatExpr;
5304   const Sema::FormatStringType FSType;
5305   const unsigned FirstDataArg;
5306   const unsigned NumDataArgs;
5307   const char *Beg; // Start of format string.
5308   const bool HasVAListArg;
5309   ArrayRef<const Expr *> Args;
5310   unsigned FormatIdx;
5311   llvm::SmallBitVector CoveredArgs;
5312   bool usesPositionalArgs = false;
5313   bool atFirstArg = true;
5314   bool inFunctionCall;
5315   Sema::VariadicCallType CallType;
5316   llvm::SmallBitVector &CheckedVarArgs;
5317   UncoveredArgHandler &UncoveredArg;
5318 
5319 public:
5320   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
5321                      const Expr *origFormatExpr,
5322                      const Sema::FormatStringType type, unsigned firstDataArg,
5323                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
5324                      ArrayRef<const Expr *> Args, unsigned formatIdx,
5325                      bool inFunctionCall, Sema::VariadicCallType callType,
5326                      llvm::SmallBitVector &CheckedVarArgs,
5327                      UncoveredArgHandler &UncoveredArg)
5328       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
5329         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
5330         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
5331         inFunctionCall(inFunctionCall), CallType(callType),
5332         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
5333     CoveredArgs.resize(numDataArgs);
5334     CoveredArgs.reset();
5335   }
5336 
5337   void DoneProcessing();
5338 
5339   void HandleIncompleteSpecifier(const char *startSpecifier,
5340                                  unsigned specifierLen) override;
5341 
5342   void HandleInvalidLengthModifier(
5343                            const analyze_format_string::FormatSpecifier &FS,
5344                            const analyze_format_string::ConversionSpecifier &CS,
5345                            const char *startSpecifier, unsigned specifierLen,
5346                            unsigned DiagID);
5347 
5348   void HandleNonStandardLengthModifier(
5349                     const analyze_format_string::FormatSpecifier &FS,
5350                     const char *startSpecifier, unsigned specifierLen);
5351 
5352   void HandleNonStandardConversionSpecifier(
5353                     const analyze_format_string::ConversionSpecifier &CS,
5354                     const char *startSpecifier, unsigned specifierLen);
5355 
5356   void HandlePosition(const char *startPos, unsigned posLen) override;
5357 
5358   void HandleInvalidPosition(const char *startSpecifier,
5359                              unsigned specifierLen,
5360                              analyze_format_string::PositionContext p) override;
5361 
5362   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
5363 
5364   void HandleNullChar(const char *nullCharacter) override;
5365 
5366   template <typename Range>
5367   static void
5368   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
5369                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
5370                        bool IsStringLocation, Range StringRange,
5371                        ArrayRef<FixItHint> Fixit = None);
5372 
5373 protected:
5374   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
5375                                         const char *startSpec,
5376                                         unsigned specifierLen,
5377                                         const char *csStart, unsigned csLen);
5378 
5379   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
5380                                          const char *startSpec,
5381                                          unsigned specifierLen);
5382 
5383   SourceRange getFormatStringRange();
5384   CharSourceRange getSpecifierRange(const char *startSpecifier,
5385                                     unsigned specifierLen);
5386   SourceLocation getLocationOfByte(const char *x);
5387 
5388   const Expr *getDataArg(unsigned i) const;
5389 
5390   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
5391                     const analyze_format_string::ConversionSpecifier &CS,
5392                     const char *startSpecifier, unsigned specifierLen,
5393                     unsigned argIndex);
5394 
5395   template <typename Range>
5396   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5397                             bool IsStringLocation, Range StringRange,
5398                             ArrayRef<FixItHint> Fixit = None);
5399 };
5400 
5401 } // namespace
5402 
5403 SourceRange CheckFormatHandler::getFormatStringRange() {
5404   return OrigFormatExpr->getSourceRange();
5405 }
5406 
5407 CharSourceRange CheckFormatHandler::
5408 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
5409   SourceLocation Start = getLocationOfByte(startSpecifier);
5410   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
5411 
5412   // Advance the end SourceLocation by one due to half-open ranges.
5413   End = End.getLocWithOffset(1);
5414 
5415   return CharSourceRange::getCharRange(Start, End);
5416 }
5417 
5418 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
5419   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
5420                                   S.getLangOpts(), S.Context.getTargetInfo());
5421 }
5422 
5423 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
5424                                                    unsigned specifierLen){
5425   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
5426                        getLocationOfByte(startSpecifier),
5427                        /*IsStringLocation*/true,
5428                        getSpecifierRange(startSpecifier, specifierLen));
5429 }
5430 
5431 void CheckFormatHandler::HandleInvalidLengthModifier(
5432     const analyze_format_string::FormatSpecifier &FS,
5433     const analyze_format_string::ConversionSpecifier &CS,
5434     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
5435   using namespace analyze_format_string;
5436 
5437   const LengthModifier &LM = FS.getLengthModifier();
5438   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5439 
5440   // See if we know how to fix this length modifier.
5441   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
5442   if (FixedLM) {
5443     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
5444                          getLocationOfByte(LM.getStart()),
5445                          /*IsStringLocation*/true,
5446                          getSpecifierRange(startSpecifier, specifierLen));
5447 
5448     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5449       << FixedLM->toString()
5450       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5451 
5452   } else {
5453     FixItHint Hint;
5454     if (DiagID == diag::warn_format_nonsensical_length)
5455       Hint = FixItHint::CreateRemoval(LMRange);
5456 
5457     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
5458                          getLocationOfByte(LM.getStart()),
5459                          /*IsStringLocation*/true,
5460                          getSpecifierRange(startSpecifier, specifierLen),
5461                          Hint);
5462   }
5463 }
5464 
5465 void CheckFormatHandler::HandleNonStandardLengthModifier(
5466     const analyze_format_string::FormatSpecifier &FS,
5467     const char *startSpecifier, unsigned specifierLen) {
5468   using namespace analyze_format_string;
5469 
5470   const LengthModifier &LM = FS.getLengthModifier();
5471   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5472 
5473   // See if we know how to fix this length modifier.
5474   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
5475   if (FixedLM) {
5476     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5477                            << LM.toString() << 0,
5478                          getLocationOfByte(LM.getStart()),
5479                          /*IsStringLocation*/true,
5480                          getSpecifierRange(startSpecifier, specifierLen));
5481 
5482     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5483       << FixedLM->toString()
5484       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5485 
5486   } else {
5487     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5488                            << LM.toString() << 0,
5489                          getLocationOfByte(LM.getStart()),
5490                          /*IsStringLocation*/true,
5491                          getSpecifierRange(startSpecifier, specifierLen));
5492   }
5493 }
5494 
5495 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5496     const analyze_format_string::ConversionSpecifier &CS,
5497     const char *startSpecifier, unsigned specifierLen) {
5498   using namespace analyze_format_string;
5499 
5500   // See if we know how to fix this conversion specifier.
5501   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
5502   if (FixedCS) {
5503     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5504                           << CS.toString() << /*conversion specifier*/1,
5505                          getLocationOfByte(CS.getStart()),
5506                          /*IsStringLocation*/true,
5507                          getSpecifierRange(startSpecifier, specifierLen));
5508 
5509     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5510     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5511       << FixedCS->toString()
5512       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5513   } else {
5514     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5515                           << CS.toString() << /*conversion specifier*/1,
5516                          getLocationOfByte(CS.getStart()),
5517                          /*IsStringLocation*/true,
5518                          getSpecifierRange(startSpecifier, specifierLen));
5519   }
5520 }
5521 
5522 void CheckFormatHandler::HandlePosition(const char *startPos,
5523                                         unsigned posLen) {
5524   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5525                                getLocationOfByte(startPos),
5526                                /*IsStringLocation*/true,
5527                                getSpecifierRange(startPos, posLen));
5528 }
5529 
5530 void
5531 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5532                                      analyze_format_string::PositionContext p) {
5533   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5534                          << (unsigned) p,
5535                        getLocationOfByte(startPos), /*IsStringLocation*/true,
5536                        getSpecifierRange(startPos, posLen));
5537 }
5538 
5539 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
5540                                             unsigned posLen) {
5541   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5542                                getLocationOfByte(startPos),
5543                                /*IsStringLocation*/true,
5544                                getSpecifierRange(startPos, posLen));
5545 }
5546 
5547 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
5548   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
5549     // The presence of a null character is likely an error.
5550     EmitFormatDiagnostic(
5551       S.PDiag(diag::warn_printf_format_string_contains_null_char),
5552       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5553       getFormatStringRange());
5554   }
5555 }
5556 
5557 // Note that this may return NULL if there was an error parsing or building
5558 // one of the argument expressions.
5559 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
5560   return Args[FirstDataArg + i];
5561 }
5562 
5563 void CheckFormatHandler::DoneProcessing() {
5564   // Does the number of data arguments exceed the number of
5565   // format conversions in the format string?
5566   if (!HasVAListArg) {
5567       // Find any arguments that weren't covered.
5568     CoveredArgs.flip();
5569     signed notCoveredArg = CoveredArgs.find_first();
5570     if (notCoveredArg >= 0) {
5571       assert((unsigned)notCoveredArg < NumDataArgs);
5572       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5573     } else {
5574       UncoveredArg.setAllCovered();
5575     }
5576   }
5577 }
5578 
5579 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5580                                    const Expr *ArgExpr) {
5581   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5582          "Invalid state");
5583 
5584   if (!ArgExpr)
5585     return;
5586 
5587   SourceLocation Loc = ArgExpr->getLocStart();
5588 
5589   if (S.getSourceManager().isInSystemMacro(Loc))
5590     return;
5591 
5592   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5593   for (auto E : DiagnosticExprs)
5594     PDiag << E->getSourceRange();
5595 
5596   CheckFormatHandler::EmitFormatDiagnostic(
5597                                   S, IsFunctionCall, DiagnosticExprs[0],
5598                                   PDiag, Loc, /*IsStringLocation*/false,
5599                                   DiagnosticExprs[0]->getSourceRange());
5600 }
5601 
5602 bool
5603 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5604                                                      SourceLocation Loc,
5605                                                      const char *startSpec,
5606                                                      unsigned specifierLen,
5607                                                      const char *csStart,
5608                                                      unsigned csLen) {
5609   bool keepGoing = true;
5610   if (argIndex < NumDataArgs) {
5611     // Consider the argument coverered, even though the specifier doesn't
5612     // make sense.
5613     CoveredArgs.set(argIndex);
5614   }
5615   else {
5616     // If argIndex exceeds the number of data arguments we
5617     // don't issue a warning because that is just a cascade of warnings (and
5618     // they may have intended '%%' anyway). We don't want to continue processing
5619     // the format string after this point, however, as we will like just get
5620     // gibberish when trying to match arguments.
5621     keepGoing = false;
5622   }
5623 
5624   StringRef Specifier(csStart, csLen);
5625 
5626   // If the specifier in non-printable, it could be the first byte of a UTF-8
5627   // sequence. In that case, print the UTF-8 code point. If not, print the byte
5628   // hex value.
5629   std::string CodePointStr;
5630   if (!llvm::sys::locale::isPrint(*csStart)) {
5631     llvm::UTF32 CodePoint;
5632     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5633     const llvm::UTF8 *E =
5634         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5635     llvm::ConversionResult Result =
5636         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
5637 
5638     if (Result != llvm::conversionOK) {
5639       unsigned char FirstChar = *csStart;
5640       CodePoint = (llvm::UTF32)FirstChar;
5641     }
5642 
5643     llvm::raw_string_ostream OS(CodePointStr);
5644     if (CodePoint < 256)
5645       OS << "\\x" << llvm::format("%02x", CodePoint);
5646     else if (CodePoint <= 0xFFFF)
5647       OS << "\\u" << llvm::format("%04x", CodePoint);
5648     else
5649       OS << "\\U" << llvm::format("%08x", CodePoint);
5650     OS.flush();
5651     Specifier = CodePointStr;
5652   }
5653 
5654   EmitFormatDiagnostic(
5655       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5656       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5657 
5658   return keepGoing;
5659 }
5660 
5661 void
5662 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5663                                                       const char *startSpec,
5664                                                       unsigned specifierLen) {
5665   EmitFormatDiagnostic(
5666     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5667     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5668 }
5669 
5670 bool
5671 CheckFormatHandler::CheckNumArgs(
5672   const analyze_format_string::FormatSpecifier &FS,
5673   const analyze_format_string::ConversionSpecifier &CS,
5674   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5675 
5676   if (argIndex >= NumDataArgs) {
5677     PartialDiagnostic PDiag = FS.usesPositionalArg()
5678       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5679            << (argIndex+1) << NumDataArgs)
5680       : S.PDiag(diag::warn_printf_insufficient_data_args);
5681     EmitFormatDiagnostic(
5682       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5683       getSpecifierRange(startSpecifier, specifierLen));
5684 
5685     // Since more arguments than conversion tokens are given, by extension
5686     // all arguments are covered, so mark this as so.
5687     UncoveredArg.setAllCovered();
5688     return false;
5689   }
5690   return true;
5691 }
5692 
5693 template<typename Range>
5694 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5695                                               SourceLocation Loc,
5696                                               bool IsStringLocation,
5697                                               Range StringRange,
5698                                               ArrayRef<FixItHint> FixIt) {
5699   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
5700                        Loc, IsStringLocation, StringRange, FixIt);
5701 }
5702 
5703 /// \brief If the format string is not within the function call, emit a note
5704 /// so that the function call and string are in diagnostic messages.
5705 ///
5706 /// \param InFunctionCall if true, the format string is within the function
5707 /// call and only one diagnostic message will be produced.  Otherwise, an
5708 /// extra note will be emitted pointing to location of the format string.
5709 ///
5710 /// \param ArgumentExpr the expression that is passed as the format string
5711 /// argument in the function call.  Used for getting locations when two
5712 /// diagnostics are emitted.
5713 ///
5714 /// \param PDiag the callee should already have provided any strings for the
5715 /// diagnostic message.  This function only adds locations and fixits
5716 /// to diagnostics.
5717 ///
5718 /// \param Loc primary location for diagnostic.  If two diagnostics are
5719 /// required, one will be at Loc and a new SourceLocation will be created for
5720 /// the other one.
5721 ///
5722 /// \param IsStringLocation if true, Loc points to the format string should be
5723 /// used for the note.  Otherwise, Loc points to the argument list and will
5724 /// be used with PDiag.
5725 ///
5726 /// \param StringRange some or all of the string to highlight.  This is
5727 /// templated so it can accept either a CharSourceRange or a SourceRange.
5728 ///
5729 /// \param FixIt optional fix it hint for the format string.
5730 template <typename Range>
5731 void CheckFormatHandler::EmitFormatDiagnostic(
5732     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5733     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5734     Range StringRange, ArrayRef<FixItHint> FixIt) {
5735   if (InFunctionCall) {
5736     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5737     D << StringRange;
5738     D << FixIt;
5739   } else {
5740     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5741       << ArgumentExpr->getSourceRange();
5742 
5743     const Sema::SemaDiagnosticBuilder &Note =
5744       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5745              diag::note_format_string_defined);
5746 
5747     Note << StringRange;
5748     Note << FixIt;
5749   }
5750 }
5751 
5752 //===--- CHECK: Printf format string checking ------------------------------===//
5753 
5754 namespace {
5755 
5756 class CheckPrintfHandler : public CheckFormatHandler {
5757 public:
5758   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
5759                      const Expr *origFormatExpr,
5760                      const Sema::FormatStringType type, unsigned firstDataArg,
5761                      unsigned numDataArgs, bool isObjC, const char *beg,
5762                      bool hasVAListArg, ArrayRef<const Expr *> Args,
5763                      unsigned formatIdx, bool inFunctionCall,
5764                      Sema::VariadicCallType CallType,
5765                      llvm::SmallBitVector &CheckedVarArgs,
5766                      UncoveredArgHandler &UncoveredArg)
5767       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5768                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
5769                            inFunctionCall, CallType, CheckedVarArgs,
5770                            UncoveredArg) {}
5771 
5772   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5773 
5774   /// Returns true if '%@' specifiers are allowed in the format string.
5775   bool allowsObjCArg() const {
5776     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5777            FSType == Sema::FST_OSTrace;
5778   }
5779 
5780   bool HandleInvalidPrintfConversionSpecifier(
5781                                       const analyze_printf::PrintfSpecifier &FS,
5782                                       const char *startSpecifier,
5783                                       unsigned specifierLen) override;
5784 
5785   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5786                              const char *startSpecifier,
5787                              unsigned specifierLen) override;
5788   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5789                        const char *StartSpecifier,
5790                        unsigned SpecifierLen,
5791                        const Expr *E);
5792 
5793   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5794                     const char *startSpecifier, unsigned specifierLen);
5795   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5796                            const analyze_printf::OptionalAmount &Amt,
5797                            unsigned type,
5798                            const char *startSpecifier, unsigned specifierLen);
5799   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5800                   const analyze_printf::OptionalFlag &flag,
5801                   const char *startSpecifier, unsigned specifierLen);
5802   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5803                          const analyze_printf::OptionalFlag &ignoredFlag,
5804                          const analyze_printf::OptionalFlag &flag,
5805                          const char *startSpecifier, unsigned specifierLen);
5806   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
5807                            const Expr *E);
5808 
5809   void HandleEmptyObjCModifierFlag(const char *startFlag,
5810                                    unsigned flagLen) override;
5811 
5812   void HandleInvalidObjCModifierFlag(const char *startFlag,
5813                                             unsigned flagLen) override;
5814 
5815   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5816                                            const char *flagsEnd,
5817                                            const char *conversionPosition)
5818                                              override;
5819 };
5820 
5821 } // namespace
5822 
5823 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5824                                       const analyze_printf::PrintfSpecifier &FS,
5825                                       const char *startSpecifier,
5826                                       unsigned specifierLen) {
5827   const analyze_printf::PrintfConversionSpecifier &CS =
5828     FS.getConversionSpecifier();
5829 
5830   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5831                                           getLocationOfByte(CS.getStart()),
5832                                           startSpecifier, specifierLen,
5833                                           CS.getStart(), CS.getLength());
5834 }
5835 
5836 bool CheckPrintfHandler::HandleAmount(
5837                                const analyze_format_string::OptionalAmount &Amt,
5838                                unsigned k, const char *startSpecifier,
5839                                unsigned specifierLen) {
5840   if (Amt.hasDataArgument()) {
5841     if (!HasVAListArg) {
5842       unsigned argIndex = Amt.getArgIndex();
5843       if (argIndex >= NumDataArgs) {
5844         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5845                                << k,
5846                              getLocationOfByte(Amt.getStart()),
5847                              /*IsStringLocation*/true,
5848                              getSpecifierRange(startSpecifier, specifierLen));
5849         // Don't do any more checking.  We will just emit
5850         // spurious errors.
5851         return false;
5852       }
5853 
5854       // Type check the data argument.  It should be an 'int'.
5855       // Although not in conformance with C99, we also allow the argument to be
5856       // an 'unsigned int' as that is a reasonably safe case.  GCC also
5857       // doesn't emit a warning for that case.
5858       CoveredArgs.set(argIndex);
5859       const Expr *Arg = getDataArg(argIndex);
5860       if (!Arg)
5861         return false;
5862 
5863       QualType T = Arg->getType();
5864 
5865       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5866       assert(AT.isValid());
5867 
5868       if (!AT.matchesType(S.Context, T)) {
5869         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
5870                                << k << AT.getRepresentativeTypeName(S.Context)
5871                                << T << Arg->getSourceRange(),
5872                              getLocationOfByte(Amt.getStart()),
5873                              /*IsStringLocation*/true,
5874                              getSpecifierRange(startSpecifier, specifierLen));
5875         // Don't do any more checking.  We will just emit
5876         // spurious errors.
5877         return false;
5878       }
5879     }
5880   }
5881   return true;
5882 }
5883 
5884 void CheckPrintfHandler::HandleInvalidAmount(
5885                                       const analyze_printf::PrintfSpecifier &FS,
5886                                       const analyze_printf::OptionalAmount &Amt,
5887                                       unsigned type,
5888                                       const char *startSpecifier,
5889                                       unsigned specifierLen) {
5890   const analyze_printf::PrintfConversionSpecifier &CS =
5891     FS.getConversionSpecifier();
5892 
5893   FixItHint fixit =
5894     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5895       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5896                                  Amt.getConstantLength()))
5897       : FixItHint();
5898 
5899   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5900                          << type << CS.toString(),
5901                        getLocationOfByte(Amt.getStart()),
5902                        /*IsStringLocation*/true,
5903                        getSpecifierRange(startSpecifier, specifierLen),
5904                        fixit);
5905 }
5906 
5907 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5908                                     const analyze_printf::OptionalFlag &flag,
5909                                     const char *startSpecifier,
5910                                     unsigned specifierLen) {
5911   // Warn about pointless flag with a fixit removal.
5912   const analyze_printf::PrintfConversionSpecifier &CS =
5913     FS.getConversionSpecifier();
5914   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5915                          << flag.toString() << CS.toString(),
5916                        getLocationOfByte(flag.getPosition()),
5917                        /*IsStringLocation*/true,
5918                        getSpecifierRange(startSpecifier, specifierLen),
5919                        FixItHint::CreateRemoval(
5920                          getSpecifierRange(flag.getPosition(), 1)));
5921 }
5922 
5923 void CheckPrintfHandler::HandleIgnoredFlag(
5924                                 const analyze_printf::PrintfSpecifier &FS,
5925                                 const analyze_printf::OptionalFlag &ignoredFlag,
5926                                 const analyze_printf::OptionalFlag &flag,
5927                                 const char *startSpecifier,
5928                                 unsigned specifierLen) {
5929   // Warn about ignored flag with a fixit removal.
5930   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5931                          << ignoredFlag.toString() << flag.toString(),
5932                        getLocationOfByte(ignoredFlag.getPosition()),
5933                        /*IsStringLocation*/true,
5934                        getSpecifierRange(startSpecifier, specifierLen),
5935                        FixItHint::CreateRemoval(
5936                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
5937 }
5938 
5939 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5940                                                      unsigned flagLen) {
5941   // Warn about an empty flag.
5942   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5943                        getLocationOfByte(startFlag),
5944                        /*IsStringLocation*/true,
5945                        getSpecifierRange(startFlag, flagLen));
5946 }
5947 
5948 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5949                                                        unsigned flagLen) {
5950   // Warn about an invalid flag.
5951   auto Range = getSpecifierRange(startFlag, flagLen);
5952   StringRef flag(startFlag, flagLen);
5953   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5954                       getLocationOfByte(startFlag),
5955                       /*IsStringLocation*/true,
5956                       Range, FixItHint::CreateRemoval(Range));
5957 }
5958 
5959 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5960     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5961     // Warn about using '[...]' without a '@' conversion.
5962     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5963     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5964     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5965                          getLocationOfByte(conversionPosition),
5966                          /*IsStringLocation*/true,
5967                          Range, FixItHint::CreateRemoval(Range));
5968 }
5969 
5970 // Determines if the specified is a C++ class or struct containing
5971 // a member with the specified name and kind (e.g. a CXXMethodDecl named
5972 // "c_str()").
5973 template<typename MemberKind>
5974 static llvm::SmallPtrSet<MemberKind*, 1>
5975 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5976   const RecordType *RT = Ty->getAs<RecordType>();
5977   llvm::SmallPtrSet<MemberKind*, 1> Results;
5978 
5979   if (!RT)
5980     return Results;
5981   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
5982   if (!RD || !RD->getDefinition())
5983     return Results;
5984 
5985   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
5986                  Sema::LookupMemberName);
5987   R.suppressDiagnostics();
5988 
5989   // We just need to include all members of the right kind turned up by the
5990   // filter, at this point.
5991   if (S.LookupQualifiedName(R, RT->getDecl()))
5992     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5993       NamedDecl *decl = (*I)->getUnderlyingDecl();
5994       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5995         Results.insert(FK);
5996     }
5997   return Results;
5998 }
5999 
6000 /// Check if we could call '.c_str()' on an object.
6001 ///
6002 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
6003 /// allow the call, or if it would be ambiguous).
6004 bool Sema::hasCStrMethod(const Expr *E) {
6005   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
6006 
6007   MethodSet Results =
6008       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
6009   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
6010        MI != ME; ++MI)
6011     if ((*MI)->getMinRequiredArguments() == 0)
6012       return true;
6013   return false;
6014 }
6015 
6016 // Check if a (w)string was passed when a (w)char* was needed, and offer a
6017 // better diagnostic if so. AT is assumed to be valid.
6018 // Returns true when a c_str() conversion method is found.
6019 bool CheckPrintfHandler::checkForCStrMembers(
6020     const analyze_printf::ArgType &AT, const Expr *E) {
6021   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
6022 
6023   MethodSet Results =
6024       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
6025 
6026   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
6027        MI != ME; ++MI) {
6028     const CXXMethodDecl *Method = *MI;
6029     if (Method->getMinRequiredArguments() == 0 &&
6030         AT.matchesType(S.Context, Method->getReturnType())) {
6031       // FIXME: Suggest parens if the expression needs them.
6032       SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
6033       S.Diag(E->getLocStart(), diag::note_printf_c_str)
6034           << "c_str()"
6035           << FixItHint::CreateInsertion(EndLoc, ".c_str()");
6036       return true;
6037     }
6038   }
6039 
6040   return false;
6041 }
6042 
6043 bool
6044 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
6045                                             &FS,
6046                                           const char *startSpecifier,
6047                                           unsigned specifierLen) {
6048   using namespace analyze_format_string;
6049   using namespace analyze_printf;
6050 
6051   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
6052 
6053   if (FS.consumesDataArgument()) {
6054     if (atFirstArg) {
6055         atFirstArg = false;
6056         usesPositionalArgs = FS.usesPositionalArg();
6057     }
6058     else if (usesPositionalArgs != FS.usesPositionalArg()) {
6059       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6060                                         startSpecifier, specifierLen);
6061       return false;
6062     }
6063   }
6064 
6065   // First check if the field width, precision, and conversion specifier
6066   // have matching data arguments.
6067   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
6068                     startSpecifier, specifierLen)) {
6069     return false;
6070   }
6071 
6072   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
6073                     startSpecifier, specifierLen)) {
6074     return false;
6075   }
6076 
6077   if (!CS.consumesDataArgument()) {
6078     // FIXME: Technically specifying a precision or field width here
6079     // makes no sense.  Worth issuing a warning at some point.
6080     return true;
6081   }
6082 
6083   // Consume the argument.
6084   unsigned argIndex = FS.getArgIndex();
6085   if (argIndex < NumDataArgs) {
6086     // The check to see if the argIndex is valid will come later.
6087     // We set the bit here because we may exit early from this
6088     // function if we encounter some other error.
6089     CoveredArgs.set(argIndex);
6090   }
6091 
6092   // FreeBSD kernel extensions.
6093   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
6094       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
6095     // We need at least two arguments.
6096     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
6097       return false;
6098 
6099     // Claim the second argument.
6100     CoveredArgs.set(argIndex + 1);
6101 
6102     // Type check the first argument (int for %b, pointer for %D)
6103     const Expr *Ex = getDataArg(argIndex);
6104     const analyze_printf::ArgType &AT =
6105       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
6106         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
6107     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
6108       EmitFormatDiagnostic(
6109         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6110         << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
6111         << false << Ex->getSourceRange(),
6112         Ex->getLocStart(), /*IsStringLocation*/false,
6113         getSpecifierRange(startSpecifier, specifierLen));
6114 
6115     // Type check the second argument (char * for both %b and %D)
6116     Ex = getDataArg(argIndex + 1);
6117     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
6118     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
6119       EmitFormatDiagnostic(
6120         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6121         << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
6122         << false << Ex->getSourceRange(),
6123         Ex->getLocStart(), /*IsStringLocation*/false,
6124         getSpecifierRange(startSpecifier, specifierLen));
6125 
6126      return true;
6127   }
6128 
6129   // Check for using an Objective-C specific conversion specifier
6130   // in a non-ObjC literal.
6131   if (!allowsObjCArg() && CS.isObjCArg()) {
6132     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6133                                                   specifierLen);
6134   }
6135 
6136   // %P can only be used with os_log.
6137   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
6138     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6139                                                   specifierLen);
6140   }
6141 
6142   // %n is not allowed with os_log.
6143   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
6144     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
6145                          getLocationOfByte(CS.getStart()),
6146                          /*IsStringLocation*/ false,
6147                          getSpecifierRange(startSpecifier, specifierLen));
6148 
6149     return true;
6150   }
6151 
6152   // Only scalars are allowed for os_trace.
6153   if (FSType == Sema::FST_OSTrace &&
6154       (CS.getKind() == ConversionSpecifier::PArg ||
6155        CS.getKind() == ConversionSpecifier::sArg ||
6156        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
6157     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6158                                                   specifierLen);
6159   }
6160 
6161   // Check for use of public/private annotation outside of os_log().
6162   if (FSType != Sema::FST_OSLog) {
6163     if (FS.isPublic().isSet()) {
6164       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6165                                << "public",
6166                            getLocationOfByte(FS.isPublic().getPosition()),
6167                            /*IsStringLocation*/ false,
6168                            getSpecifierRange(startSpecifier, specifierLen));
6169     }
6170     if (FS.isPrivate().isSet()) {
6171       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6172                                << "private",
6173                            getLocationOfByte(FS.isPrivate().getPosition()),
6174                            /*IsStringLocation*/ false,
6175                            getSpecifierRange(startSpecifier, specifierLen));
6176     }
6177   }
6178 
6179   // Check for invalid use of field width
6180   if (!FS.hasValidFieldWidth()) {
6181     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
6182         startSpecifier, specifierLen);
6183   }
6184 
6185   // Check for invalid use of precision
6186   if (!FS.hasValidPrecision()) {
6187     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
6188         startSpecifier, specifierLen);
6189   }
6190 
6191   // Precision is mandatory for %P specifier.
6192   if (CS.getKind() == ConversionSpecifier::PArg &&
6193       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
6194     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
6195                          getLocationOfByte(startSpecifier),
6196                          /*IsStringLocation*/ false,
6197                          getSpecifierRange(startSpecifier, specifierLen));
6198   }
6199 
6200   // Check each flag does not conflict with any other component.
6201   if (!FS.hasValidThousandsGroupingPrefix())
6202     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
6203   if (!FS.hasValidLeadingZeros())
6204     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
6205   if (!FS.hasValidPlusPrefix())
6206     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
6207   if (!FS.hasValidSpacePrefix())
6208     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
6209   if (!FS.hasValidAlternativeForm())
6210     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
6211   if (!FS.hasValidLeftJustified())
6212     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
6213 
6214   // Check that flags are not ignored by another flag
6215   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
6216     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
6217         startSpecifier, specifierLen);
6218   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
6219     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
6220             startSpecifier, specifierLen);
6221 
6222   // Check the length modifier is valid with the given conversion specifier.
6223   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
6224     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6225                                 diag::warn_format_nonsensical_length);
6226   else if (!FS.hasStandardLengthModifier())
6227     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
6228   else if (!FS.hasStandardLengthConversionCombination())
6229     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6230                                 diag::warn_format_non_standard_conversion_spec);
6231 
6232   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6233     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6234 
6235   // The remaining checks depend on the data arguments.
6236   if (HasVAListArg)
6237     return true;
6238 
6239   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
6240     return false;
6241 
6242   const Expr *Arg = getDataArg(argIndex);
6243   if (!Arg)
6244     return true;
6245 
6246   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
6247 }
6248 
6249 static bool requiresParensToAddCast(const Expr *E) {
6250   // FIXME: We should have a general way to reason about operator
6251   // precedence and whether parens are actually needed here.
6252   // Take care of a few common cases where they aren't.
6253   const Expr *Inside = E->IgnoreImpCasts();
6254   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
6255     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
6256 
6257   switch (Inside->getStmtClass()) {
6258   case Stmt::ArraySubscriptExprClass:
6259   case Stmt::CallExprClass:
6260   case Stmt::CharacterLiteralClass:
6261   case Stmt::CXXBoolLiteralExprClass:
6262   case Stmt::DeclRefExprClass:
6263   case Stmt::FloatingLiteralClass:
6264   case Stmt::IntegerLiteralClass:
6265   case Stmt::MemberExprClass:
6266   case Stmt::ObjCArrayLiteralClass:
6267   case Stmt::ObjCBoolLiteralExprClass:
6268   case Stmt::ObjCBoxedExprClass:
6269   case Stmt::ObjCDictionaryLiteralClass:
6270   case Stmt::ObjCEncodeExprClass:
6271   case Stmt::ObjCIvarRefExprClass:
6272   case Stmt::ObjCMessageExprClass:
6273   case Stmt::ObjCPropertyRefExprClass:
6274   case Stmt::ObjCStringLiteralClass:
6275   case Stmt::ObjCSubscriptRefExprClass:
6276   case Stmt::ParenExprClass:
6277   case Stmt::StringLiteralClass:
6278   case Stmt::UnaryOperatorClass:
6279     return false;
6280   default:
6281     return true;
6282   }
6283 }
6284 
6285 static std::pair<QualType, StringRef>
6286 shouldNotPrintDirectly(const ASTContext &Context,
6287                        QualType IntendedTy,
6288                        const Expr *E) {
6289   // Use a 'while' to peel off layers of typedefs.
6290   QualType TyTy = IntendedTy;
6291   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
6292     StringRef Name = UserTy->getDecl()->getName();
6293     QualType CastTy = llvm::StringSwitch<QualType>(Name)
6294       .Case("CFIndex", Context.getNSIntegerType())
6295       .Case("NSInteger", Context.getNSIntegerType())
6296       .Case("NSUInteger", Context.getNSUIntegerType())
6297       .Case("SInt32", Context.IntTy)
6298       .Case("UInt32", Context.UnsignedIntTy)
6299       .Default(QualType());
6300 
6301     if (!CastTy.isNull())
6302       return std::make_pair(CastTy, Name);
6303 
6304     TyTy = UserTy->desugar();
6305   }
6306 
6307   // Strip parens if necessary.
6308   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
6309     return shouldNotPrintDirectly(Context,
6310                                   PE->getSubExpr()->getType(),
6311                                   PE->getSubExpr());
6312 
6313   // If this is a conditional expression, then its result type is constructed
6314   // via usual arithmetic conversions and thus there might be no necessary
6315   // typedef sugar there.  Recurse to operands to check for NSInteger &
6316   // Co. usage condition.
6317   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6318     QualType TrueTy, FalseTy;
6319     StringRef TrueName, FalseName;
6320 
6321     std::tie(TrueTy, TrueName) =
6322       shouldNotPrintDirectly(Context,
6323                              CO->getTrueExpr()->getType(),
6324                              CO->getTrueExpr());
6325     std::tie(FalseTy, FalseName) =
6326       shouldNotPrintDirectly(Context,
6327                              CO->getFalseExpr()->getType(),
6328                              CO->getFalseExpr());
6329 
6330     if (TrueTy == FalseTy)
6331       return std::make_pair(TrueTy, TrueName);
6332     else if (TrueTy.isNull())
6333       return std::make_pair(FalseTy, FalseName);
6334     else if (FalseTy.isNull())
6335       return std::make_pair(TrueTy, TrueName);
6336   }
6337 
6338   return std::make_pair(QualType(), StringRef());
6339 }
6340 
6341 bool
6342 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6343                                     const char *StartSpecifier,
6344                                     unsigned SpecifierLen,
6345                                     const Expr *E) {
6346   using namespace analyze_format_string;
6347   using namespace analyze_printf;
6348 
6349   // Now type check the data expression that matches the
6350   // format specifier.
6351   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
6352   if (!AT.isValid())
6353     return true;
6354 
6355   QualType ExprTy = E->getType();
6356   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
6357     ExprTy = TET->getUnderlyingExpr()->getType();
6358   }
6359 
6360   analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
6361 
6362   if (match == analyze_printf::ArgType::Match) {
6363     return true;
6364   }
6365 
6366   // Look through argument promotions for our error message's reported type.
6367   // This includes the integral and floating promotions, but excludes array
6368   // and function pointer decay; seeing that an argument intended to be a
6369   // string has type 'char [6]' is probably more confusing than 'char *'.
6370   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6371     if (ICE->getCastKind() == CK_IntegralCast ||
6372         ICE->getCastKind() == CK_FloatingCast) {
6373       E = ICE->getSubExpr();
6374       ExprTy = E->getType();
6375 
6376       // Check if we didn't match because of an implicit cast from a 'char'
6377       // or 'short' to an 'int'.  This is done because printf is a varargs
6378       // function.
6379       if (ICE->getType() == S.Context.IntTy ||
6380           ICE->getType() == S.Context.UnsignedIntTy) {
6381         // All further checking is done on the subexpression.
6382         if (AT.matchesType(S.Context, ExprTy))
6383           return true;
6384       }
6385     }
6386   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
6387     // Special case for 'a', which has type 'int' in C.
6388     // Note, however, that we do /not/ want to treat multibyte constants like
6389     // 'MooV' as characters! This form is deprecated but still exists.
6390     if (ExprTy == S.Context.IntTy)
6391       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6392         ExprTy = S.Context.CharTy;
6393   }
6394 
6395   // Look through enums to their underlying type.
6396   bool IsEnum = false;
6397   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
6398     ExprTy = EnumTy->getDecl()->getIntegerType();
6399     IsEnum = true;
6400   }
6401 
6402   // %C in an Objective-C context prints a unichar, not a wchar_t.
6403   // If the argument is an integer of some kind, believe the %C and suggest
6404   // a cast instead of changing the conversion specifier.
6405   QualType IntendedTy = ExprTy;
6406   if (isObjCContext() &&
6407       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
6408     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6409         !ExprTy->isCharType()) {
6410       // 'unichar' is defined as a typedef of unsigned short, but we should
6411       // prefer using the typedef if it is visible.
6412       IntendedTy = S.Context.UnsignedShortTy;
6413 
6414       // While we are here, check if the value is an IntegerLiteral that happens
6415       // to be within the valid range.
6416       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
6417         const llvm::APInt &V = IL->getValue();
6418         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6419           return true;
6420       }
6421 
6422       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
6423                           Sema::LookupOrdinaryName);
6424       if (S.LookupName(Result, S.getCurScope())) {
6425         NamedDecl *ND = Result.getFoundDecl();
6426         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
6427           if (TD->getUnderlyingType() == IntendedTy)
6428             IntendedTy = S.Context.getTypedefType(TD);
6429       }
6430     }
6431   }
6432 
6433   // Special-case some of Darwin's platform-independence types by suggesting
6434   // casts to primitive types that are known to be large enough.
6435   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
6436   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
6437     QualType CastTy;
6438     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
6439     if (!CastTy.isNull()) {
6440       IntendedTy = CastTy;
6441       ShouldNotPrintDirectly = true;
6442     }
6443   }
6444 
6445   // We may be able to offer a FixItHint if it is a supported type.
6446   PrintfSpecifier fixedFS = FS;
6447   bool success =
6448       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
6449 
6450   if (success) {
6451     // Get the fix string from the fixed format specifier
6452     SmallString<16> buf;
6453     llvm::raw_svector_ostream os(buf);
6454     fixedFS.toString(os);
6455 
6456     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6457 
6458     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
6459       unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6460       if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6461         diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6462       }
6463       // In this case, the specifier is wrong and should be changed to match
6464       // the argument.
6465       EmitFormatDiagnostic(S.PDiag(diag)
6466                                << AT.getRepresentativeTypeName(S.Context)
6467                                << IntendedTy << IsEnum << E->getSourceRange(),
6468                            E->getLocStart(),
6469                            /*IsStringLocation*/ false, SpecRange,
6470                            FixItHint::CreateReplacement(SpecRange, os.str()));
6471     } else {
6472       // The canonical type for formatting this value is different from the
6473       // actual type of the expression. (This occurs, for example, with Darwin's
6474       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6475       // should be printed as 'long' for 64-bit compatibility.)
6476       // Rather than emitting a normal format/argument mismatch, we want to
6477       // add a cast to the recommended type (and correct the format string
6478       // if necessary).
6479       SmallString<16> CastBuf;
6480       llvm::raw_svector_ostream CastFix(CastBuf);
6481       CastFix << "(";
6482       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6483       CastFix << ")";
6484 
6485       SmallVector<FixItHint,4> Hints;
6486       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
6487         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6488 
6489       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6490         // If there's already a cast present, just replace it.
6491         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6492         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6493 
6494       } else if (!requiresParensToAddCast(E)) {
6495         // If the expression has high enough precedence,
6496         // just write the C-style cast.
6497         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6498                                                    CastFix.str()));
6499       } else {
6500         // Otherwise, add parens around the expression as well as the cast.
6501         CastFix << "(";
6502         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6503                                                    CastFix.str()));
6504 
6505         SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
6506         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6507       }
6508 
6509       if (ShouldNotPrintDirectly) {
6510         // The expression has a type that should not be printed directly.
6511         // We extract the name from the typedef because we don't want to show
6512         // the underlying type in the diagnostic.
6513         StringRef Name;
6514         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6515           Name = TypedefTy->getDecl()->getName();
6516         else
6517           Name = CastTyName;
6518         EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
6519                                << Name << IntendedTy << IsEnum
6520                                << E->getSourceRange(),
6521                              E->getLocStart(), /*IsStringLocation=*/false,
6522                              SpecRange, Hints);
6523       } else {
6524         // In this case, the expression could be printed using a different
6525         // specifier, but we've decided that the specifier is probably correct
6526         // and we should cast instead. Just use the normal warning message.
6527         EmitFormatDiagnostic(
6528           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6529             << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
6530             << E->getSourceRange(),
6531           E->getLocStart(), /*IsStringLocation*/false,
6532           SpecRange, Hints);
6533       }
6534     }
6535   } else {
6536     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6537                                                    SpecifierLen);
6538     // Since the warning for passing non-POD types to variadic functions
6539     // was deferred until now, we emit a warning for non-POD
6540     // arguments here.
6541     switch (S.isValidVarArgType(ExprTy)) {
6542     case Sema::VAK_Valid:
6543     case Sema::VAK_ValidInCXX11: {
6544       unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6545       if (match == analyze_printf::ArgType::NoMatchPedantic) {
6546         diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6547       }
6548 
6549       EmitFormatDiagnostic(
6550           S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6551                         << IsEnum << CSR << E->getSourceRange(),
6552           E->getLocStart(), /*IsStringLocation*/ false, CSR);
6553       break;
6554     }
6555     case Sema::VAK_Undefined:
6556     case Sema::VAK_MSVCUndefined:
6557       EmitFormatDiagnostic(
6558         S.PDiag(diag::warn_non_pod_vararg_with_format_string)
6559           << S.getLangOpts().CPlusPlus11
6560           << ExprTy
6561           << CallType
6562           << AT.getRepresentativeTypeName(S.Context)
6563           << CSR
6564           << E->getSourceRange(),
6565         E->getLocStart(), /*IsStringLocation*/false, CSR);
6566       checkForCStrMembers(AT, E);
6567       break;
6568 
6569     case Sema::VAK_Invalid:
6570       if (ExprTy->isObjCObjectType())
6571         EmitFormatDiagnostic(
6572           S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6573             << S.getLangOpts().CPlusPlus11
6574             << ExprTy
6575             << CallType
6576             << AT.getRepresentativeTypeName(S.Context)
6577             << CSR
6578             << E->getSourceRange(),
6579           E->getLocStart(), /*IsStringLocation*/false, CSR);
6580       else
6581         // FIXME: If this is an initializer list, suggest removing the braces
6582         // or inserting a cast to the target type.
6583         S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6584           << isa<InitListExpr>(E) << ExprTy << CallType
6585           << AT.getRepresentativeTypeName(S.Context)
6586           << E->getSourceRange();
6587       break;
6588     }
6589 
6590     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6591            "format string specifier index out of range");
6592     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
6593   }
6594 
6595   return true;
6596 }
6597 
6598 //===--- CHECK: Scanf format string checking ------------------------------===//
6599 
6600 namespace {
6601 
6602 class CheckScanfHandler : public CheckFormatHandler {
6603 public:
6604   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
6605                     const Expr *origFormatExpr, Sema::FormatStringType type,
6606                     unsigned firstDataArg, unsigned numDataArgs,
6607                     const char *beg, bool hasVAListArg,
6608                     ArrayRef<const Expr *> Args, unsigned formatIdx,
6609                     bool inFunctionCall, Sema::VariadicCallType CallType,
6610                     llvm::SmallBitVector &CheckedVarArgs,
6611                     UncoveredArgHandler &UncoveredArg)
6612       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6613                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
6614                            inFunctionCall, CallType, CheckedVarArgs,
6615                            UncoveredArg) {}
6616 
6617   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6618                             const char *startSpecifier,
6619                             unsigned specifierLen) override;
6620 
6621   bool HandleInvalidScanfConversionSpecifier(
6622           const analyze_scanf::ScanfSpecifier &FS,
6623           const char *startSpecifier,
6624           unsigned specifierLen) override;
6625 
6626   void HandleIncompleteScanList(const char *start, const char *end) override;
6627 };
6628 
6629 } // namespace
6630 
6631 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6632                                                  const char *end) {
6633   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6634                        getLocationOfByte(end), /*IsStringLocation*/true,
6635                        getSpecifierRange(start, end - start));
6636 }
6637 
6638 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6639                                         const analyze_scanf::ScanfSpecifier &FS,
6640                                         const char *startSpecifier,
6641                                         unsigned specifierLen) {
6642   const analyze_scanf::ScanfConversionSpecifier &CS =
6643     FS.getConversionSpecifier();
6644 
6645   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6646                                           getLocationOfByte(CS.getStart()),
6647                                           startSpecifier, specifierLen,
6648                                           CS.getStart(), CS.getLength());
6649 }
6650 
6651 bool CheckScanfHandler::HandleScanfSpecifier(
6652                                        const analyze_scanf::ScanfSpecifier &FS,
6653                                        const char *startSpecifier,
6654                                        unsigned specifierLen) {
6655   using namespace analyze_scanf;
6656   using namespace analyze_format_string;
6657 
6658   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
6659 
6660   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
6661   // be used to decide if we are using positional arguments consistently.
6662   if (FS.consumesDataArgument()) {
6663     if (atFirstArg) {
6664       atFirstArg = false;
6665       usesPositionalArgs = FS.usesPositionalArg();
6666     }
6667     else if (usesPositionalArgs != FS.usesPositionalArg()) {
6668       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6669                                         startSpecifier, specifierLen);
6670       return false;
6671     }
6672   }
6673 
6674   // Check if the field with is non-zero.
6675   const OptionalAmount &Amt = FS.getFieldWidth();
6676   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6677     if (Amt.getConstantAmount() == 0) {
6678       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6679                                                    Amt.getConstantLength());
6680       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6681                            getLocationOfByte(Amt.getStart()),
6682                            /*IsStringLocation*/true, R,
6683                            FixItHint::CreateRemoval(R));
6684     }
6685   }
6686 
6687   if (!FS.consumesDataArgument()) {
6688     // FIXME: Technically specifying a precision or field width here
6689     // makes no sense.  Worth issuing a warning at some point.
6690     return true;
6691   }
6692 
6693   // Consume the argument.
6694   unsigned argIndex = FS.getArgIndex();
6695   if (argIndex < NumDataArgs) {
6696       // The check to see if the argIndex is valid will come later.
6697       // We set the bit here because we may exit early from this
6698       // function if we encounter some other error.
6699     CoveredArgs.set(argIndex);
6700   }
6701 
6702   // Check the length modifier is valid with the given conversion specifier.
6703   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
6704     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6705                                 diag::warn_format_nonsensical_length);
6706   else if (!FS.hasStandardLengthModifier())
6707     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
6708   else if (!FS.hasStandardLengthConversionCombination())
6709     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6710                                 diag::warn_format_non_standard_conversion_spec);
6711 
6712   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6713     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6714 
6715   // The remaining checks depend on the data arguments.
6716   if (HasVAListArg)
6717     return true;
6718 
6719   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
6720     return false;
6721 
6722   // Check that the argument type matches the format specifier.
6723   const Expr *Ex = getDataArg(argIndex);
6724   if (!Ex)
6725     return true;
6726 
6727   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
6728 
6729   if (!AT.isValid()) {
6730     return true;
6731   }
6732 
6733   analyze_format_string::ArgType::MatchKind match =
6734       AT.matchesType(S.Context, Ex->getType());
6735   if (match == analyze_format_string::ArgType::Match) {
6736     return true;
6737   }
6738 
6739   ScanfSpecifier fixedFS = FS;
6740   bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6741                                  S.getLangOpts(), S.Context);
6742 
6743   unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6744   if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6745     diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6746   }
6747 
6748   if (success) {
6749     // Get the fix string from the fixed format specifier.
6750     SmallString<128> buf;
6751     llvm::raw_svector_ostream os(buf);
6752     fixedFS.toString(os);
6753 
6754     EmitFormatDiagnostic(
6755         S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6756                       << Ex->getType() << false << Ex->getSourceRange(),
6757         Ex->getLocStart(),
6758         /*IsStringLocation*/ false,
6759         getSpecifierRange(startSpecifier, specifierLen),
6760         FixItHint::CreateReplacement(
6761             getSpecifierRange(startSpecifier, specifierLen), os.str()));
6762   } else {
6763     EmitFormatDiagnostic(S.PDiag(diag)
6764                              << AT.getRepresentativeTypeName(S.Context)
6765                              << Ex->getType() << false << Ex->getSourceRange(),
6766                          Ex->getLocStart(),
6767                          /*IsStringLocation*/ false,
6768                          getSpecifierRange(startSpecifier, specifierLen));
6769   }
6770 
6771   return true;
6772 }
6773 
6774 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6775                               const Expr *OrigFormatExpr,
6776                               ArrayRef<const Expr *> Args,
6777                               bool HasVAListArg, unsigned format_idx,
6778                               unsigned firstDataArg,
6779                               Sema::FormatStringType Type,
6780                               bool inFunctionCall,
6781                               Sema::VariadicCallType CallType,
6782                               llvm::SmallBitVector &CheckedVarArgs,
6783                               UncoveredArgHandler &UncoveredArg) {
6784   // CHECK: is the format string a wide literal?
6785   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
6786     CheckFormatHandler::EmitFormatDiagnostic(
6787       S, inFunctionCall, Args[format_idx],
6788       S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
6789       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
6790     return;
6791   }
6792 
6793   // Str - The format string.  NOTE: this is NOT null-terminated!
6794   StringRef StrRef = FExpr->getString();
6795   const char *Str = StrRef.data();
6796   // Account for cases where the string literal is truncated in a declaration.
6797   const ConstantArrayType *T =
6798     S.Context.getAsConstantArrayType(FExpr->getType());
6799   assert(T && "String literal not of constant array type!");
6800   size_t TypeSize = T->getSize().getZExtValue();
6801   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6802   const unsigned numDataArgs = Args.size() - firstDataArg;
6803 
6804   // Emit a warning if the string literal is truncated and does not contain an
6805   // embedded null character.
6806   if (TypeSize <= StrRef.size() &&
6807       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6808     CheckFormatHandler::EmitFormatDiagnostic(
6809         S, inFunctionCall, Args[format_idx],
6810         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
6811         FExpr->getLocStart(),
6812         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6813     return;
6814   }
6815 
6816   // CHECK: empty format string?
6817   if (StrLen == 0 && numDataArgs > 0) {
6818     CheckFormatHandler::EmitFormatDiagnostic(
6819       S, inFunctionCall, Args[format_idx],
6820       S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
6821       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
6822     return;
6823   }
6824 
6825   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
6826       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6827       Type == Sema::FST_OSTrace) {
6828     CheckPrintfHandler H(
6829         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6830         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6831         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6832         CheckedVarArgs, UncoveredArg);
6833 
6834     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
6835                                                   S.getLangOpts(),
6836                                                   S.Context.getTargetInfo(),
6837                                             Type == Sema::FST_FreeBSDKPrintf))
6838       H.DoneProcessing();
6839   } else if (Type == Sema::FST_Scanf) {
6840     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6841                         numDataArgs, Str, HasVAListArg, Args, format_idx,
6842                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
6843 
6844     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
6845                                                  S.getLangOpts(),
6846                                                  S.Context.getTargetInfo()))
6847       H.DoneProcessing();
6848   } // TODO: handle other formats
6849 }
6850 
6851 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6852   // Str - The format string.  NOTE: this is NOT null-terminated!
6853   StringRef StrRef = FExpr->getString();
6854   const char *Str = StrRef.data();
6855   // Account for cases where the string literal is truncated in a declaration.
6856   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6857   assert(T && "String literal not of constant array type!");
6858   size_t TypeSize = T->getSize().getZExtValue();
6859   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6860   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6861                                                          getLangOpts(),
6862                                                          Context.getTargetInfo());
6863 }
6864 
6865 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6866 
6867 // Returns the related absolute value function that is larger, of 0 if one
6868 // does not exist.
6869 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6870   switch (AbsFunction) {
6871   default:
6872     return 0;
6873 
6874   case Builtin::BI__builtin_abs:
6875     return Builtin::BI__builtin_labs;
6876   case Builtin::BI__builtin_labs:
6877     return Builtin::BI__builtin_llabs;
6878   case Builtin::BI__builtin_llabs:
6879     return 0;
6880 
6881   case Builtin::BI__builtin_fabsf:
6882     return Builtin::BI__builtin_fabs;
6883   case Builtin::BI__builtin_fabs:
6884     return Builtin::BI__builtin_fabsl;
6885   case Builtin::BI__builtin_fabsl:
6886     return 0;
6887 
6888   case Builtin::BI__builtin_cabsf:
6889     return Builtin::BI__builtin_cabs;
6890   case Builtin::BI__builtin_cabs:
6891     return Builtin::BI__builtin_cabsl;
6892   case Builtin::BI__builtin_cabsl:
6893     return 0;
6894 
6895   case Builtin::BIabs:
6896     return Builtin::BIlabs;
6897   case Builtin::BIlabs:
6898     return Builtin::BIllabs;
6899   case Builtin::BIllabs:
6900     return 0;
6901 
6902   case Builtin::BIfabsf:
6903     return Builtin::BIfabs;
6904   case Builtin::BIfabs:
6905     return Builtin::BIfabsl;
6906   case Builtin::BIfabsl:
6907     return 0;
6908 
6909   case Builtin::BIcabsf:
6910    return Builtin::BIcabs;
6911   case Builtin::BIcabs:
6912     return Builtin::BIcabsl;
6913   case Builtin::BIcabsl:
6914     return 0;
6915   }
6916 }
6917 
6918 // Returns the argument type of the absolute value function.
6919 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6920                                              unsigned AbsType) {
6921   if (AbsType == 0)
6922     return QualType();
6923 
6924   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6925   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6926   if (Error != ASTContext::GE_None)
6927     return QualType();
6928 
6929   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6930   if (!FT)
6931     return QualType();
6932 
6933   if (FT->getNumParams() != 1)
6934     return QualType();
6935 
6936   return FT->getParamType(0);
6937 }
6938 
6939 // Returns the best absolute value function, or zero, based on type and
6940 // current absolute value function.
6941 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6942                                    unsigned AbsFunctionKind) {
6943   unsigned BestKind = 0;
6944   uint64_t ArgSize = Context.getTypeSize(ArgType);
6945   for (unsigned Kind = AbsFunctionKind; Kind != 0;
6946        Kind = getLargerAbsoluteValueFunction(Kind)) {
6947     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6948     if (Context.getTypeSize(ParamType) >= ArgSize) {
6949       if (BestKind == 0)
6950         BestKind = Kind;
6951       else if (Context.hasSameType(ParamType, ArgType)) {
6952         BestKind = Kind;
6953         break;
6954       }
6955     }
6956   }
6957   return BestKind;
6958 }
6959 
6960 enum AbsoluteValueKind {
6961   AVK_Integer,
6962   AVK_Floating,
6963   AVK_Complex
6964 };
6965 
6966 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6967   if (T->isIntegralOrEnumerationType())
6968     return AVK_Integer;
6969   if (T->isRealFloatingType())
6970     return AVK_Floating;
6971   if (T->isAnyComplexType())
6972     return AVK_Complex;
6973 
6974   llvm_unreachable("Type not integer, floating, or complex");
6975 }
6976 
6977 // Changes the absolute value function to a different type.  Preserves whether
6978 // the function is a builtin.
6979 static unsigned changeAbsFunction(unsigned AbsKind,
6980                                   AbsoluteValueKind ValueKind) {
6981   switch (ValueKind) {
6982   case AVK_Integer:
6983     switch (AbsKind) {
6984     default:
6985       return 0;
6986     case Builtin::BI__builtin_fabsf:
6987     case Builtin::BI__builtin_fabs:
6988     case Builtin::BI__builtin_fabsl:
6989     case Builtin::BI__builtin_cabsf:
6990     case Builtin::BI__builtin_cabs:
6991     case Builtin::BI__builtin_cabsl:
6992       return Builtin::BI__builtin_abs;
6993     case Builtin::BIfabsf:
6994     case Builtin::BIfabs:
6995     case Builtin::BIfabsl:
6996     case Builtin::BIcabsf:
6997     case Builtin::BIcabs:
6998     case Builtin::BIcabsl:
6999       return Builtin::BIabs;
7000     }
7001   case AVK_Floating:
7002     switch (AbsKind) {
7003     default:
7004       return 0;
7005     case Builtin::BI__builtin_abs:
7006     case Builtin::BI__builtin_labs:
7007     case Builtin::BI__builtin_llabs:
7008     case Builtin::BI__builtin_cabsf:
7009     case Builtin::BI__builtin_cabs:
7010     case Builtin::BI__builtin_cabsl:
7011       return Builtin::BI__builtin_fabsf;
7012     case Builtin::BIabs:
7013     case Builtin::BIlabs:
7014     case Builtin::BIllabs:
7015     case Builtin::BIcabsf:
7016     case Builtin::BIcabs:
7017     case Builtin::BIcabsl:
7018       return Builtin::BIfabsf;
7019     }
7020   case AVK_Complex:
7021     switch (AbsKind) {
7022     default:
7023       return 0;
7024     case Builtin::BI__builtin_abs:
7025     case Builtin::BI__builtin_labs:
7026     case Builtin::BI__builtin_llabs:
7027     case Builtin::BI__builtin_fabsf:
7028     case Builtin::BI__builtin_fabs:
7029     case Builtin::BI__builtin_fabsl:
7030       return Builtin::BI__builtin_cabsf;
7031     case Builtin::BIabs:
7032     case Builtin::BIlabs:
7033     case Builtin::BIllabs:
7034     case Builtin::BIfabsf:
7035     case Builtin::BIfabs:
7036     case Builtin::BIfabsl:
7037       return Builtin::BIcabsf;
7038     }
7039   }
7040   llvm_unreachable("Unable to convert function");
7041 }
7042 
7043 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
7044   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
7045   if (!FnInfo)
7046     return 0;
7047 
7048   switch (FDecl->getBuiltinID()) {
7049   default:
7050     return 0;
7051   case Builtin::BI__builtin_abs:
7052   case Builtin::BI__builtin_fabs:
7053   case Builtin::BI__builtin_fabsf:
7054   case Builtin::BI__builtin_fabsl:
7055   case Builtin::BI__builtin_labs:
7056   case Builtin::BI__builtin_llabs:
7057   case Builtin::BI__builtin_cabs:
7058   case Builtin::BI__builtin_cabsf:
7059   case Builtin::BI__builtin_cabsl:
7060   case Builtin::BIabs:
7061   case Builtin::BIlabs:
7062   case Builtin::BIllabs:
7063   case Builtin::BIfabs:
7064   case Builtin::BIfabsf:
7065   case Builtin::BIfabsl:
7066   case Builtin::BIcabs:
7067   case Builtin::BIcabsf:
7068   case Builtin::BIcabsl:
7069     return FDecl->getBuiltinID();
7070   }
7071   llvm_unreachable("Unknown Builtin type");
7072 }
7073 
7074 // If the replacement is valid, emit a note with replacement function.
7075 // Additionally, suggest including the proper header if not already included.
7076 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
7077                             unsigned AbsKind, QualType ArgType) {
7078   bool EmitHeaderHint = true;
7079   const char *HeaderName = nullptr;
7080   const char *FunctionName = nullptr;
7081   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
7082     FunctionName = "std::abs";
7083     if (ArgType->isIntegralOrEnumerationType()) {
7084       HeaderName = "cstdlib";
7085     } else if (ArgType->isRealFloatingType()) {
7086       HeaderName = "cmath";
7087     } else {
7088       llvm_unreachable("Invalid Type");
7089     }
7090 
7091     // Lookup all std::abs
7092     if (NamespaceDecl *Std = S.getStdNamespace()) {
7093       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
7094       R.suppressDiagnostics();
7095       S.LookupQualifiedName(R, Std);
7096 
7097       for (const auto *I : R) {
7098         const FunctionDecl *FDecl = nullptr;
7099         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
7100           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
7101         } else {
7102           FDecl = dyn_cast<FunctionDecl>(I);
7103         }
7104         if (!FDecl)
7105           continue;
7106 
7107         // Found std::abs(), check that they are the right ones.
7108         if (FDecl->getNumParams() != 1)
7109           continue;
7110 
7111         // Check that the parameter type can handle the argument.
7112         QualType ParamType = FDecl->getParamDecl(0)->getType();
7113         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
7114             S.Context.getTypeSize(ArgType) <=
7115                 S.Context.getTypeSize(ParamType)) {
7116           // Found a function, don't need the header hint.
7117           EmitHeaderHint = false;
7118           break;
7119         }
7120       }
7121     }
7122   } else {
7123     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
7124     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
7125 
7126     if (HeaderName) {
7127       DeclarationName DN(&S.Context.Idents.get(FunctionName));
7128       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
7129       R.suppressDiagnostics();
7130       S.LookupName(R, S.getCurScope());
7131 
7132       if (R.isSingleResult()) {
7133         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
7134         if (FD && FD->getBuiltinID() == AbsKind) {
7135           EmitHeaderHint = false;
7136         } else {
7137           return;
7138         }
7139       } else if (!R.empty()) {
7140         return;
7141       }
7142     }
7143   }
7144 
7145   S.Diag(Loc, diag::note_replace_abs_function)
7146       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
7147 
7148   if (!HeaderName)
7149     return;
7150 
7151   if (!EmitHeaderHint)
7152     return;
7153 
7154   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
7155                                                     << FunctionName;
7156 }
7157 
7158 template <std::size_t StrLen>
7159 static bool IsStdFunction(const FunctionDecl *FDecl,
7160                           const char (&Str)[StrLen]) {
7161   if (!FDecl)
7162     return false;
7163   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
7164     return false;
7165   if (!FDecl->isInStdNamespace())
7166     return false;
7167 
7168   return true;
7169 }
7170 
7171 // Warn when using the wrong abs() function.
7172 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
7173                                       const FunctionDecl *FDecl) {
7174   if (Call->getNumArgs() != 1)
7175     return;
7176 
7177   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
7178   bool IsStdAbs = IsStdFunction(FDecl, "abs");
7179   if (AbsKind == 0 && !IsStdAbs)
7180     return;
7181 
7182   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7183   QualType ParamType = Call->getArg(0)->getType();
7184 
7185   // Unsigned types cannot be negative.  Suggest removing the absolute value
7186   // function call.
7187   if (ArgType->isUnsignedIntegerType()) {
7188     const char *FunctionName =
7189         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
7190     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
7191     Diag(Call->getExprLoc(), diag::note_remove_abs)
7192         << FunctionName
7193         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
7194     return;
7195   }
7196 
7197   // Taking the absolute value of a pointer is very suspicious, they probably
7198   // wanted to index into an array, dereference a pointer, call a function, etc.
7199   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
7200     unsigned DiagType = 0;
7201     if (ArgType->isFunctionType())
7202       DiagType = 1;
7203     else if (ArgType->isArrayType())
7204       DiagType = 2;
7205 
7206     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
7207     return;
7208   }
7209 
7210   // std::abs has overloads which prevent most of the absolute value problems
7211   // from occurring.
7212   if (IsStdAbs)
7213     return;
7214 
7215   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
7216   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
7217 
7218   // The argument and parameter are the same kind.  Check if they are the right
7219   // size.
7220   if (ArgValueKind == ParamValueKind) {
7221     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
7222       return;
7223 
7224     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
7225     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
7226         << FDecl << ArgType << ParamType;
7227 
7228     if (NewAbsKind == 0)
7229       return;
7230 
7231     emitReplacement(*this, Call->getExprLoc(),
7232                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
7233     return;
7234   }
7235 
7236   // ArgValueKind != ParamValueKind
7237   // The wrong type of absolute value function was used.  Attempt to find the
7238   // proper one.
7239   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
7240   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
7241   if (NewAbsKind == 0)
7242     return;
7243 
7244   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
7245       << FDecl << ParamValueKind << ArgValueKind;
7246 
7247   emitReplacement(*this, Call->getExprLoc(),
7248                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
7249 }
7250 
7251 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
7252 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
7253                                 const FunctionDecl *FDecl) {
7254   if (!Call || !FDecl) return;
7255 
7256   // Ignore template specializations and macros.
7257   if (inTemplateInstantiation()) return;
7258   if (Call->getExprLoc().isMacroID()) return;
7259 
7260   // Only care about the one template argument, two function parameter std::max
7261   if (Call->getNumArgs() != 2) return;
7262   if (!IsStdFunction(FDecl, "max")) return;
7263   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
7264   if (!ArgList) return;
7265   if (ArgList->size() != 1) return;
7266 
7267   // Check that template type argument is unsigned integer.
7268   const auto& TA = ArgList->get(0);
7269   if (TA.getKind() != TemplateArgument::Type) return;
7270   QualType ArgType = TA.getAsType();
7271   if (!ArgType->isUnsignedIntegerType()) return;
7272 
7273   // See if either argument is a literal zero.
7274   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
7275     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
7276     if (!MTE) return false;
7277     const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
7278     if (!Num) return false;
7279     if (Num->getValue() != 0) return false;
7280     return true;
7281   };
7282 
7283   const Expr *FirstArg = Call->getArg(0);
7284   const Expr *SecondArg = Call->getArg(1);
7285   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
7286   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
7287 
7288   // Only warn when exactly one argument is zero.
7289   if (IsFirstArgZero == IsSecondArgZero) return;
7290 
7291   SourceRange FirstRange = FirstArg->getSourceRange();
7292   SourceRange SecondRange = SecondArg->getSourceRange();
7293 
7294   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
7295 
7296   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
7297       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
7298 
7299   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
7300   SourceRange RemovalRange;
7301   if (IsFirstArgZero) {
7302     RemovalRange = SourceRange(FirstRange.getBegin(),
7303                                SecondRange.getBegin().getLocWithOffset(-1));
7304   } else {
7305     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
7306                                SecondRange.getEnd());
7307   }
7308 
7309   Diag(Call->getExprLoc(), diag::note_remove_max_call)
7310         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
7311         << FixItHint::CreateRemoval(RemovalRange);
7312 }
7313 
7314 //===--- CHECK: Standard memory functions ---------------------------------===//
7315 
7316 /// \brief Takes the expression passed to the size_t parameter of functions
7317 /// such as memcmp, strncat, etc and warns if it's a comparison.
7318 ///
7319 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
7320 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
7321                                            IdentifierInfo *FnName,
7322                                            SourceLocation FnLoc,
7323                                            SourceLocation RParenLoc) {
7324   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
7325   if (!Size)
7326     return false;
7327 
7328   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
7329   if (!Size->isComparisonOp() && !Size->isLogicalOp())
7330     return false;
7331 
7332   SourceRange SizeRange = Size->getSourceRange();
7333   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
7334       << SizeRange << FnName;
7335   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
7336       << FnName << FixItHint::CreateInsertion(
7337                        S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
7338       << FixItHint::CreateRemoval(RParenLoc);
7339   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
7340       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
7341       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
7342                                     ")");
7343 
7344   return true;
7345 }
7346 
7347 /// \brief Determine whether the given type is or contains a dynamic class type
7348 /// (e.g., whether it has a vtable).
7349 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
7350                                                      bool &IsContained) {
7351   // Look through array types while ignoring qualifiers.
7352   const Type *Ty = T->getBaseElementTypeUnsafe();
7353   IsContained = false;
7354 
7355   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
7356   RD = RD ? RD->getDefinition() : nullptr;
7357   if (!RD || RD->isInvalidDecl())
7358     return nullptr;
7359 
7360   if (RD->isDynamicClass())
7361     return RD;
7362 
7363   // Check all the fields.  If any bases were dynamic, the class is dynamic.
7364   // It's impossible for a class to transitively contain itself by value, so
7365   // infinite recursion is impossible.
7366   for (auto *FD : RD->fields()) {
7367     bool SubContained;
7368     if (const CXXRecordDecl *ContainedRD =
7369             getContainedDynamicClass(FD->getType(), SubContained)) {
7370       IsContained = true;
7371       return ContainedRD;
7372     }
7373   }
7374 
7375   return nullptr;
7376 }
7377 
7378 /// \brief If E is a sizeof expression, returns its argument expression,
7379 /// otherwise returns NULL.
7380 static const Expr *getSizeOfExprArg(const Expr *E) {
7381   if (const UnaryExprOrTypeTraitExpr *SizeOf =
7382       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7383     if (SizeOf->getKind() == UETT_SizeOf && !SizeOf->isArgumentType())
7384       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
7385 
7386   return nullptr;
7387 }
7388 
7389 /// \brief If E is a sizeof expression, returns its argument type.
7390 static QualType getSizeOfArgType(const Expr *E) {
7391   if (const UnaryExprOrTypeTraitExpr *SizeOf =
7392       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7393     if (SizeOf->getKind() == UETT_SizeOf)
7394       return SizeOf->getTypeOfArgument();
7395 
7396   return QualType();
7397 }
7398 
7399 namespace {
7400 
7401 struct SearchNonTrivialToInitializeField
7402     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
7403   using Super =
7404       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
7405 
7406   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
7407 
7408   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
7409                      SourceLocation SL) {
7410     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
7411       asDerived().visitArray(PDIK, AT, SL);
7412       return;
7413     }
7414 
7415     Super::visitWithKind(PDIK, FT, SL);
7416   }
7417 
7418   void visitARCStrong(QualType FT, SourceLocation SL) {
7419     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
7420   }
7421   void visitARCWeak(QualType FT, SourceLocation SL) {
7422     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
7423   }
7424   void visitStruct(QualType FT, SourceLocation SL) {
7425     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
7426       visit(FD->getType(), FD->getLocation());
7427   }
7428   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
7429                   const ArrayType *AT, SourceLocation SL) {
7430     visit(getContext().getBaseElementType(AT), SL);
7431   }
7432   void visitTrivial(QualType FT, SourceLocation SL) {}
7433 
7434   static void diag(QualType RT, const Expr *E, Sema &S) {
7435     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
7436   }
7437 
7438   ASTContext &getContext() { return S.getASTContext(); }
7439 
7440   const Expr *E;
7441   Sema &S;
7442 };
7443 
7444 struct SearchNonTrivialToCopyField
7445     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
7446   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
7447 
7448   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
7449 
7450   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
7451                      SourceLocation SL) {
7452     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
7453       asDerived().visitArray(PCK, AT, SL);
7454       return;
7455     }
7456 
7457     Super::visitWithKind(PCK, FT, SL);
7458   }
7459 
7460   void visitARCStrong(QualType FT, SourceLocation SL) {
7461     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
7462   }
7463   void visitARCWeak(QualType FT, SourceLocation SL) {
7464     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
7465   }
7466   void visitStruct(QualType FT, SourceLocation SL) {
7467     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
7468       visit(FD->getType(), FD->getLocation());
7469   }
7470   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
7471                   SourceLocation SL) {
7472     visit(getContext().getBaseElementType(AT), SL);
7473   }
7474   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
7475                 SourceLocation SL) {}
7476   void visitTrivial(QualType FT, SourceLocation SL) {}
7477   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
7478 
7479   static void diag(QualType RT, const Expr *E, Sema &S) {
7480     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
7481   }
7482 
7483   ASTContext &getContext() { return S.getASTContext(); }
7484 
7485   const Expr *E;
7486   Sema &S;
7487 };
7488 
7489 }
7490 
7491 /// \brief Check for dangerous or invalid arguments to memset().
7492 ///
7493 /// This issues warnings on known problematic, dangerous or unspecified
7494 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
7495 /// function calls.
7496 ///
7497 /// \param Call The call expression to diagnose.
7498 void Sema::CheckMemaccessArguments(const CallExpr *Call,
7499                                    unsigned BId,
7500                                    IdentifierInfo *FnName) {
7501   assert(BId != 0);
7502 
7503   // It is possible to have a non-standard definition of memset.  Validate
7504   // we have enough arguments, and if not, abort further checking.
7505   unsigned ExpectedNumArgs =
7506       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
7507   if (Call->getNumArgs() < ExpectedNumArgs)
7508     return;
7509 
7510   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
7511                       BId == Builtin::BIstrndup ? 1 : 2);
7512   unsigned LenArg =
7513       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
7514   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
7515 
7516   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
7517                                      Call->getLocStart(), Call->getRParenLoc()))
7518     return;
7519 
7520   // We have special checking when the length is a sizeof expression.
7521   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
7522   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
7523   llvm::FoldingSetNodeID SizeOfArgID;
7524 
7525   // Although widely used, 'bzero' is not a standard function. Be more strict
7526   // with the argument types before allowing diagnostics and only allow the
7527   // form bzero(ptr, sizeof(...)).
7528   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7529   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
7530     return;
7531 
7532   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7533     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
7534     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
7535 
7536     QualType DestTy = Dest->getType();
7537     QualType PointeeTy;
7538     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
7539       PointeeTy = DestPtrTy->getPointeeType();
7540 
7541       // Never warn about void type pointers. This can be used to suppress
7542       // false positives.
7543       if (PointeeTy->isVoidType())
7544         continue;
7545 
7546       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
7547       // actually comparing the expressions for equality. Because computing the
7548       // expression IDs can be expensive, we only do this if the diagnostic is
7549       // enabled.
7550       if (SizeOfArg &&
7551           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
7552                            SizeOfArg->getExprLoc())) {
7553         // We only compute IDs for expressions if the warning is enabled, and
7554         // cache the sizeof arg's ID.
7555         if (SizeOfArgID == llvm::FoldingSetNodeID())
7556           SizeOfArg->Profile(SizeOfArgID, Context, true);
7557         llvm::FoldingSetNodeID DestID;
7558         Dest->Profile(DestID, Context, true);
7559         if (DestID == SizeOfArgID) {
7560           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
7561           //       over sizeof(src) as well.
7562           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
7563           StringRef ReadableName = FnName->getName();
7564 
7565           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
7566             if (UnaryOp->getOpcode() == UO_AddrOf)
7567               ActionIdx = 1; // If its an address-of operator, just remove it.
7568           if (!PointeeTy->isIncompleteType() &&
7569               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
7570             ActionIdx = 2; // If the pointee's size is sizeof(char),
7571                            // suggest an explicit length.
7572 
7573           // If the function is defined as a builtin macro, do not show macro
7574           // expansion.
7575           SourceLocation SL = SizeOfArg->getExprLoc();
7576           SourceRange DSR = Dest->getSourceRange();
7577           SourceRange SSR = SizeOfArg->getSourceRange();
7578           SourceManager &SM = getSourceManager();
7579 
7580           if (SM.isMacroArgExpansion(SL)) {
7581             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7582             SL = SM.getSpellingLoc(SL);
7583             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7584                              SM.getSpellingLoc(DSR.getEnd()));
7585             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7586                              SM.getSpellingLoc(SSR.getEnd()));
7587           }
7588 
7589           DiagRuntimeBehavior(SL, SizeOfArg,
7590                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
7591                                 << ReadableName
7592                                 << PointeeTy
7593                                 << DestTy
7594                                 << DSR
7595                                 << SSR);
7596           DiagRuntimeBehavior(SL, SizeOfArg,
7597                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7598                                 << ActionIdx
7599                                 << SSR);
7600 
7601           break;
7602         }
7603       }
7604 
7605       // Also check for cases where the sizeof argument is the exact same
7606       // type as the memory argument, and where it points to a user-defined
7607       // record type.
7608       if (SizeOfArgTy != QualType()) {
7609         if (PointeeTy->isRecordType() &&
7610             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7611           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7612                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
7613                                 << FnName << SizeOfArgTy << ArgIdx
7614                                 << PointeeTy << Dest->getSourceRange()
7615                                 << LenExpr->getSourceRange());
7616           break;
7617         }
7618       }
7619     } else if (DestTy->isArrayType()) {
7620       PointeeTy = DestTy;
7621     }
7622 
7623     if (PointeeTy == QualType())
7624       continue;
7625 
7626     // Always complain about dynamic classes.
7627     bool IsContained;
7628     if (const CXXRecordDecl *ContainedRD =
7629             getContainedDynamicClass(PointeeTy, IsContained)) {
7630 
7631       unsigned OperationType = 0;
7632       // "overwritten" if we're warning about the destination for any call
7633       // but memcmp; otherwise a verb appropriate to the call.
7634       if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7635         if (BId == Builtin::BImemcpy)
7636           OperationType = 1;
7637         else if(BId == Builtin::BImemmove)
7638           OperationType = 2;
7639         else if (BId == Builtin::BImemcmp)
7640           OperationType = 3;
7641       }
7642 
7643       DiagRuntimeBehavior(
7644         Dest->getExprLoc(), Dest,
7645         PDiag(diag::warn_dyn_class_memaccess)
7646           << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7647           << FnName << IsContained << ContainedRD << OperationType
7648           << Call->getCallee()->getSourceRange());
7649     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7650              BId != Builtin::BImemset)
7651       DiagRuntimeBehavior(
7652         Dest->getExprLoc(), Dest,
7653         PDiag(diag::warn_arc_object_memaccess)
7654           << ArgIdx << FnName << PointeeTy
7655           << Call->getCallee()->getSourceRange());
7656     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
7657       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
7658           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
7659         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
7660                             PDiag(diag::warn_cstruct_memaccess)
7661                                 << ArgIdx << FnName << PointeeTy << 0);
7662         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
7663       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
7664                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
7665         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
7666                             PDiag(diag::warn_cstruct_memaccess)
7667                                 << ArgIdx << FnName << PointeeTy << 1);
7668         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
7669       } else {
7670         continue;
7671       }
7672     } else
7673       continue;
7674 
7675     DiagRuntimeBehavior(
7676       Dest->getExprLoc(), Dest,
7677       PDiag(diag::note_bad_memaccess_silence)
7678         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7679     break;
7680   }
7681 }
7682 
7683 // A little helper routine: ignore addition and subtraction of integer literals.
7684 // This intentionally does not ignore all integer constant expressions because
7685 // we don't want to remove sizeof().
7686 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7687   Ex = Ex->IgnoreParenCasts();
7688 
7689   while (true) {
7690     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7691     if (!BO || !BO->isAdditiveOp())
7692       break;
7693 
7694     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7695     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7696 
7697     if (isa<IntegerLiteral>(RHS))
7698       Ex = LHS;
7699     else if (isa<IntegerLiteral>(LHS))
7700       Ex = RHS;
7701     else
7702       break;
7703   }
7704 
7705   return Ex;
7706 }
7707 
7708 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7709                                                       ASTContext &Context) {
7710   // Only handle constant-sized or VLAs, but not flexible members.
7711   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7712     // Only issue the FIXIT for arrays of size > 1.
7713     if (CAT->getSize().getSExtValue() <= 1)
7714       return false;
7715   } else if (!Ty->isVariableArrayType()) {
7716     return false;
7717   }
7718   return true;
7719 }
7720 
7721 // Warn if the user has made the 'size' argument to strlcpy or strlcat
7722 // be the size of the source, instead of the destination.
7723 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7724                                     IdentifierInfo *FnName) {
7725 
7726   // Don't crash if the user has the wrong number of arguments
7727   unsigned NumArgs = Call->getNumArgs();
7728   if ((NumArgs != 3) && (NumArgs != 4))
7729     return;
7730 
7731   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7732   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
7733   const Expr *CompareWithSrc = nullptr;
7734 
7735   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7736                                      Call->getLocStart(), Call->getRParenLoc()))
7737     return;
7738 
7739   // Look for 'strlcpy(dst, x, sizeof(x))'
7740   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7741     CompareWithSrc = Ex;
7742   else {
7743     // Look for 'strlcpy(dst, x, strlen(x))'
7744     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
7745       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7746           SizeCall->getNumArgs() == 1)
7747         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7748     }
7749   }
7750 
7751   if (!CompareWithSrc)
7752     return;
7753 
7754   // Determine if the argument to sizeof/strlen is equal to the source
7755   // argument.  In principle there's all kinds of things you could do
7756   // here, for instance creating an == expression and evaluating it with
7757   // EvaluateAsBooleanCondition, but this uses a more direct technique:
7758   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7759   if (!SrcArgDRE)
7760     return;
7761 
7762   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7763   if (!CompareWithSrcDRE ||
7764       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7765     return;
7766 
7767   const Expr *OriginalSizeArg = Call->getArg(2);
7768   Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7769     << OriginalSizeArg->getSourceRange() << FnName;
7770 
7771   // Output a FIXIT hint if the destination is an array (rather than a
7772   // pointer to an array).  This could be enhanced to handle some
7773   // pointers if we know the actual size, like if DstArg is 'array+2'
7774   // we could say 'sizeof(array)-2'.
7775   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
7776   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
7777     return;
7778 
7779   SmallString<128> sizeString;
7780   llvm::raw_svector_ostream OS(sizeString);
7781   OS << "sizeof(";
7782   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7783   OS << ")";
7784 
7785   Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7786     << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7787                                     OS.str());
7788 }
7789 
7790 /// Check if two expressions refer to the same declaration.
7791 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7792   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7793     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7794       return D1->getDecl() == D2->getDecl();
7795   return false;
7796 }
7797 
7798 static const Expr *getStrlenExprArg(const Expr *E) {
7799   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7800     const FunctionDecl *FD = CE->getDirectCallee();
7801     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
7802       return nullptr;
7803     return CE->getArg(0)->IgnoreParenCasts();
7804   }
7805   return nullptr;
7806 }
7807 
7808 // Warn on anti-patterns as the 'size' argument to strncat.
7809 // The correct size argument should look like following:
7810 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7811 void Sema::CheckStrncatArguments(const CallExpr *CE,
7812                                  IdentifierInfo *FnName) {
7813   // Don't crash if the user has the wrong number of arguments.
7814   if (CE->getNumArgs() < 3)
7815     return;
7816   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7817   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7818   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7819 
7820   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7821                                      CE->getRParenLoc()))
7822     return;
7823 
7824   // Identify common expressions, which are wrongly used as the size argument
7825   // to strncat and may lead to buffer overflows.
7826   unsigned PatternType = 0;
7827   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7828     // - sizeof(dst)
7829     if (referToTheSameDecl(SizeOfArg, DstArg))
7830       PatternType = 1;
7831     // - sizeof(src)
7832     else if (referToTheSameDecl(SizeOfArg, SrcArg))
7833       PatternType = 2;
7834   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7835     if (BE->getOpcode() == BO_Sub) {
7836       const Expr *L = BE->getLHS()->IgnoreParenCasts();
7837       const Expr *R = BE->getRHS()->IgnoreParenCasts();
7838       // - sizeof(dst) - strlen(dst)
7839       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7840           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7841         PatternType = 1;
7842       // - sizeof(src) - (anything)
7843       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7844         PatternType = 2;
7845     }
7846   }
7847 
7848   if (PatternType == 0)
7849     return;
7850 
7851   // Generate the diagnostic.
7852   SourceLocation SL = LenArg->getLocStart();
7853   SourceRange SR = LenArg->getSourceRange();
7854   SourceManager &SM = getSourceManager();
7855 
7856   // If the function is defined as a builtin macro, do not show macro expansion.
7857   if (SM.isMacroArgExpansion(SL)) {
7858     SL = SM.getSpellingLoc(SL);
7859     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7860                      SM.getSpellingLoc(SR.getEnd()));
7861   }
7862 
7863   // Check if the destination is an array (rather than a pointer to an array).
7864   QualType DstTy = DstArg->getType();
7865   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7866                                                                     Context);
7867   if (!isKnownSizeArray) {
7868     if (PatternType == 1)
7869       Diag(SL, diag::warn_strncat_wrong_size) << SR;
7870     else
7871       Diag(SL, diag::warn_strncat_src_size) << SR;
7872     return;
7873   }
7874 
7875   if (PatternType == 1)
7876     Diag(SL, diag::warn_strncat_large_size) << SR;
7877   else
7878     Diag(SL, diag::warn_strncat_src_size) << SR;
7879 
7880   SmallString<128> sizeString;
7881   llvm::raw_svector_ostream OS(sizeString);
7882   OS << "sizeof(";
7883   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7884   OS << ") - ";
7885   OS << "strlen(";
7886   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7887   OS << ") - 1";
7888 
7889   Diag(SL, diag::note_strncat_wrong_size)
7890     << FixItHint::CreateReplacement(SR, OS.str());
7891 }
7892 
7893 //===--- CHECK: Return Address of Stack Variable --------------------------===//
7894 
7895 static const Expr *EvalVal(const Expr *E,
7896                            SmallVectorImpl<const DeclRefExpr *> &refVars,
7897                            const Decl *ParentDecl);
7898 static const Expr *EvalAddr(const Expr *E,
7899                             SmallVectorImpl<const DeclRefExpr *> &refVars,
7900                             const Decl *ParentDecl);
7901 
7902 /// CheckReturnStackAddr - Check if a return statement returns the address
7903 ///   of a stack variable.
7904 static void
7905 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7906                      SourceLocation ReturnLoc) {
7907   const Expr *stackE = nullptr;
7908   SmallVector<const DeclRefExpr *, 8> refVars;
7909 
7910   // Perform checking for returned stack addresses, local blocks,
7911   // label addresses or references to temporaries.
7912   if (lhsType->isPointerType() ||
7913       (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
7914     stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
7915   } else if (lhsType->isReferenceType()) {
7916     stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
7917   }
7918 
7919   if (!stackE)
7920     return; // Nothing suspicious was found.
7921 
7922   // Parameters are initialized in the calling scope, so taking the address
7923   // of a parameter reference doesn't need a warning.
7924   for (auto *DRE : refVars)
7925     if (isa<ParmVarDecl>(DRE->getDecl()))
7926       return;
7927 
7928   SourceLocation diagLoc;
7929   SourceRange diagRange;
7930   if (refVars.empty()) {
7931     diagLoc = stackE->getLocStart();
7932     diagRange = stackE->getSourceRange();
7933   } else {
7934     // We followed through a reference variable. 'stackE' contains the
7935     // problematic expression but we will warn at the return statement pointing
7936     // at the reference variable. We will later display the "trail" of
7937     // reference variables using notes.
7938     diagLoc = refVars[0]->getLocStart();
7939     diagRange = refVars[0]->getSourceRange();
7940   }
7941 
7942   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7943     // address of local var
7944     S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
7945      << DR->getDecl()->getDeclName() << diagRange;
7946   } else if (isa<BlockExpr>(stackE)) { // local block.
7947     S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
7948   } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
7949     S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
7950   } else { // local temporary.
7951     // If there is an LValue->RValue conversion, then the value of the
7952     // reference type is used, not the reference.
7953     if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7954       if (ICE->getCastKind() == CK_LValueToRValue) {
7955         return;
7956       }
7957     }
7958     S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7959      << lhsType->isReferenceType() << diagRange;
7960   }
7961 
7962   // Display the "trail" of reference variables that we followed until we
7963   // found the problematic expression using notes.
7964   for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
7965     const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
7966     // If this var binds to another reference var, show the range of the next
7967     // var, otherwise the var binds to the problematic expression, in which case
7968     // show the range of the expression.
7969     SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7970                                     : stackE->getSourceRange();
7971     S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7972         << VD->getDeclName() << range;
7973   }
7974 }
7975 
7976 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7977 ///  check if the expression in a return statement evaluates to an address
7978 ///  to a location on the stack, a local block, an address of a label, or a
7979 ///  reference to local temporary. The recursion is used to traverse the
7980 ///  AST of the return expression, with recursion backtracking when we
7981 ///  encounter a subexpression that (1) clearly does not lead to one of the
7982 ///  above problematic expressions (2) is something we cannot determine leads to
7983 ///  a problematic expression based on such local checking.
7984 ///
7985 ///  Both EvalAddr and EvalVal follow through reference variables to evaluate
7986 ///  the expression that they point to. Such variables are added to the
7987 ///  'refVars' vector so that we know what the reference variable "trail" was.
7988 ///
7989 ///  EvalAddr processes expressions that are pointers that are used as
7990 ///  references (and not L-values).  EvalVal handles all other values.
7991 ///  At the base case of the recursion is a check for the above problematic
7992 ///  expressions.
7993 ///
7994 ///  This implementation handles:
7995 ///
7996 ///   * pointer-to-pointer casts
7997 ///   * implicit conversions from array references to pointers
7998 ///   * taking the address of fields
7999 ///   * arbitrary interplay between "&" and "*" operators
8000 ///   * pointer arithmetic from an address of a stack variable
8001 ///   * taking the address of an array element where the array is on the stack
8002 static const Expr *EvalAddr(const Expr *E,
8003                             SmallVectorImpl<const DeclRefExpr *> &refVars,
8004                             const Decl *ParentDecl) {
8005   if (E->isTypeDependent())
8006     return nullptr;
8007 
8008   // We should only be called for evaluating pointer expressions.
8009   assert((E->getType()->isAnyPointerType() ||
8010           E->getType()->isBlockPointerType() ||
8011           E->getType()->isObjCQualifiedIdType()) &&
8012          "EvalAddr only works on pointers");
8013 
8014   E = E->IgnoreParens();
8015 
8016   // Our "symbolic interpreter" is just a dispatch off the currently
8017   // viewed AST node.  We then recursively traverse the AST by calling
8018   // EvalAddr and EvalVal appropriately.
8019   switch (E->getStmtClass()) {
8020   case Stmt::DeclRefExprClass: {
8021     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
8022 
8023     // If we leave the immediate function, the lifetime isn't about to end.
8024     if (DR->refersToEnclosingVariableOrCapture())
8025       return nullptr;
8026 
8027     if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
8028       // If this is a reference variable, follow through to the expression that
8029       // it points to.
8030       if (V->hasLocalStorage() &&
8031           V->getType()->isReferenceType() && V->hasInit()) {
8032         // Add the reference variable to the "trail".
8033         refVars.push_back(DR);
8034         return EvalAddr(V->getInit(), refVars, ParentDecl);
8035       }
8036 
8037     return nullptr;
8038   }
8039 
8040   case Stmt::UnaryOperatorClass: {
8041     // The only unary operator that make sense to handle here
8042     // is AddrOf.  All others don't make sense as pointers.
8043     const UnaryOperator *U = cast<UnaryOperator>(E);
8044 
8045     if (U->getOpcode() == UO_AddrOf)
8046       return EvalVal(U->getSubExpr(), refVars, ParentDecl);
8047     return nullptr;
8048   }
8049 
8050   case Stmt::BinaryOperatorClass: {
8051     // Handle pointer arithmetic.  All other binary operators are not valid
8052     // in this context.
8053     const BinaryOperator *B = cast<BinaryOperator>(E);
8054     BinaryOperatorKind op = B->getOpcode();
8055 
8056     if (op != BO_Add && op != BO_Sub)
8057       return nullptr;
8058 
8059     const Expr *Base = B->getLHS();
8060 
8061     // Determine which argument is the real pointer base.  It could be
8062     // the RHS argument instead of the LHS.
8063     if (!Base->getType()->isPointerType())
8064       Base = B->getRHS();
8065 
8066     assert(Base->getType()->isPointerType());
8067     return EvalAddr(Base, refVars, ParentDecl);
8068   }
8069 
8070   // For conditional operators we need to see if either the LHS or RHS are
8071   // valid DeclRefExpr*s.  If one of them is valid, we return it.
8072   case Stmt::ConditionalOperatorClass: {
8073     const ConditionalOperator *C = cast<ConditionalOperator>(E);
8074 
8075     // Handle the GNU extension for missing LHS.
8076     // FIXME: That isn't a ConditionalOperator, so doesn't get here.
8077     if (const Expr *LHSExpr = C->getLHS()) {
8078       // In C++, we can have a throw-expression, which has 'void' type.
8079       if (!LHSExpr->getType()->isVoidType())
8080         if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
8081           return LHS;
8082     }
8083 
8084     // In C++, we can have a throw-expression, which has 'void' type.
8085     if (C->getRHS()->getType()->isVoidType())
8086       return nullptr;
8087 
8088     return EvalAddr(C->getRHS(), refVars, ParentDecl);
8089   }
8090 
8091   case Stmt::BlockExprClass:
8092     if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
8093       return E; // local block.
8094     return nullptr;
8095 
8096   case Stmt::AddrLabelExprClass:
8097     return E; // address of label.
8098 
8099   case Stmt::ExprWithCleanupsClass:
8100     return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
8101                     ParentDecl);
8102 
8103   // For casts, we need to handle conversions from arrays to
8104   // pointer values, and pointer-to-pointer conversions.
8105   case Stmt::ImplicitCastExprClass:
8106   case Stmt::CStyleCastExprClass:
8107   case Stmt::CXXFunctionalCastExprClass:
8108   case Stmt::ObjCBridgedCastExprClass:
8109   case Stmt::CXXStaticCastExprClass:
8110   case Stmt::CXXDynamicCastExprClass:
8111   case Stmt::CXXConstCastExprClass:
8112   case Stmt::CXXReinterpretCastExprClass: {
8113     const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
8114     switch (cast<CastExpr>(E)->getCastKind()) {
8115     case CK_LValueToRValue:
8116     case CK_NoOp:
8117     case CK_BaseToDerived:
8118     case CK_DerivedToBase:
8119     case CK_UncheckedDerivedToBase:
8120     case CK_Dynamic:
8121     case CK_CPointerToObjCPointerCast:
8122     case CK_BlockPointerToObjCPointerCast:
8123     case CK_AnyPointerToBlockPointerCast:
8124       return EvalAddr(SubExpr, refVars, ParentDecl);
8125 
8126     case CK_ArrayToPointerDecay:
8127       return EvalVal(SubExpr, refVars, ParentDecl);
8128 
8129     case CK_BitCast:
8130       if (SubExpr->getType()->isAnyPointerType() ||
8131           SubExpr->getType()->isBlockPointerType() ||
8132           SubExpr->getType()->isObjCQualifiedIdType())
8133         return EvalAddr(SubExpr, refVars, ParentDecl);
8134       else
8135         return nullptr;
8136 
8137     default:
8138       return nullptr;
8139     }
8140   }
8141 
8142   case Stmt::MaterializeTemporaryExprClass:
8143     if (const Expr *Result =
8144             EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8145                      refVars, ParentDecl))
8146       return Result;
8147     return E;
8148 
8149   // Everything else: we simply don't reason about them.
8150   default:
8151     return nullptr;
8152   }
8153 }
8154 
8155 ///  EvalVal - This function is complements EvalAddr in the mutual recursion.
8156 ///   See the comments for EvalAddr for more details.
8157 static const Expr *EvalVal(const Expr *E,
8158                            SmallVectorImpl<const DeclRefExpr *> &refVars,
8159                            const Decl *ParentDecl) {
8160   do {
8161     // We should only be called for evaluating non-pointer expressions, or
8162     // expressions with a pointer type that are not used as references but
8163     // instead
8164     // are l-values (e.g., DeclRefExpr with a pointer type).
8165 
8166     // Our "symbolic interpreter" is just a dispatch off the currently
8167     // viewed AST node.  We then recursively traverse the AST by calling
8168     // EvalAddr and EvalVal appropriately.
8169 
8170     E = E->IgnoreParens();
8171     switch (E->getStmtClass()) {
8172     case Stmt::ImplicitCastExprClass: {
8173       const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
8174       if (IE->getValueKind() == VK_LValue) {
8175         E = IE->getSubExpr();
8176         continue;
8177       }
8178       return nullptr;
8179     }
8180 
8181     case Stmt::ExprWithCleanupsClass:
8182       return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
8183                      ParentDecl);
8184 
8185     case Stmt::DeclRefExprClass: {
8186       // When we hit a DeclRefExpr we are looking at code that refers to a
8187       // variable's name. If it's not a reference variable we check if it has
8188       // local storage within the function, and if so, return the expression.
8189       const DeclRefExpr *DR = cast<DeclRefExpr>(E);
8190 
8191       // If we leave the immediate function, the lifetime isn't about to end.
8192       if (DR->refersToEnclosingVariableOrCapture())
8193         return nullptr;
8194 
8195       if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
8196         // Check if it refers to itself, e.g. "int& i = i;".
8197         if (V == ParentDecl)
8198           return DR;
8199 
8200         if (V->hasLocalStorage()) {
8201           if (!V->getType()->isReferenceType())
8202             return DR;
8203 
8204           // Reference variable, follow through to the expression that
8205           // it points to.
8206           if (V->hasInit()) {
8207             // Add the reference variable to the "trail".
8208             refVars.push_back(DR);
8209             return EvalVal(V->getInit(), refVars, V);
8210           }
8211         }
8212       }
8213 
8214       return nullptr;
8215     }
8216 
8217     case Stmt::UnaryOperatorClass: {
8218       // The only unary operator that make sense to handle here
8219       // is Deref.  All others don't resolve to a "name."  This includes
8220       // handling all sorts of rvalues passed to a unary operator.
8221       const UnaryOperator *U = cast<UnaryOperator>(E);
8222 
8223       if (U->getOpcode() == UO_Deref)
8224         return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
8225 
8226       return nullptr;
8227     }
8228 
8229     case Stmt::ArraySubscriptExprClass: {
8230       // Array subscripts are potential references to data on the stack.  We
8231       // retrieve the DeclRefExpr* for the array variable if it indeed
8232       // has local storage.
8233       const auto *ASE = cast<ArraySubscriptExpr>(E);
8234       if (ASE->isTypeDependent())
8235         return nullptr;
8236       return EvalAddr(ASE->getBase(), refVars, ParentDecl);
8237     }
8238 
8239     case Stmt::OMPArraySectionExprClass: {
8240       return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
8241                       ParentDecl);
8242     }
8243 
8244     case Stmt::ConditionalOperatorClass: {
8245       // For conditional operators we need to see if either the LHS or RHS are
8246       // non-NULL Expr's.  If one is non-NULL, we return it.
8247       const ConditionalOperator *C = cast<ConditionalOperator>(E);
8248 
8249       // Handle the GNU extension for missing LHS.
8250       if (const Expr *LHSExpr = C->getLHS()) {
8251         // In C++, we can have a throw-expression, which has 'void' type.
8252         if (!LHSExpr->getType()->isVoidType())
8253           if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
8254             return LHS;
8255       }
8256 
8257       // In C++, we can have a throw-expression, which has 'void' type.
8258       if (C->getRHS()->getType()->isVoidType())
8259         return nullptr;
8260 
8261       return EvalVal(C->getRHS(), refVars, ParentDecl);
8262     }
8263 
8264     // Accesses to members are potential references to data on the stack.
8265     case Stmt::MemberExprClass: {
8266       const MemberExpr *M = cast<MemberExpr>(E);
8267 
8268       // Check for indirect access.  We only want direct field accesses.
8269       if (M->isArrow())
8270         return nullptr;
8271 
8272       // Check whether the member type is itself a reference, in which case
8273       // we're not going to refer to the member, but to what the member refers
8274       // to.
8275       if (M->getMemberDecl()->getType()->isReferenceType())
8276         return nullptr;
8277 
8278       return EvalVal(M->getBase(), refVars, ParentDecl);
8279     }
8280 
8281     case Stmt::MaterializeTemporaryExprClass:
8282       if (const Expr *Result =
8283               EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8284                       refVars, ParentDecl))
8285         return Result;
8286       return E;
8287 
8288     default:
8289       // Check that we don't return or take the address of a reference to a
8290       // temporary. This is only useful in C++.
8291       if (!E->isTypeDependent() && E->isRValue())
8292         return E;
8293 
8294       // Everything else: we simply don't reason about them.
8295       return nullptr;
8296     }
8297   } while (true);
8298 }
8299 
8300 void
8301 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
8302                          SourceLocation ReturnLoc,
8303                          bool isObjCMethod,
8304                          const AttrVec *Attrs,
8305                          const FunctionDecl *FD) {
8306   CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
8307 
8308   // Check if the return value is null but should not be.
8309   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
8310        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
8311       CheckNonNullExpr(*this, RetValExp))
8312     Diag(ReturnLoc, diag::warn_null_ret)
8313       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
8314 
8315   // C++11 [basic.stc.dynamic.allocation]p4:
8316   //   If an allocation function declared with a non-throwing
8317   //   exception-specification fails to allocate storage, it shall return
8318   //   a null pointer. Any other allocation function that fails to allocate
8319   //   storage shall indicate failure only by throwing an exception [...]
8320   if (FD) {
8321     OverloadedOperatorKind Op = FD->getOverloadedOperator();
8322     if (Op == OO_New || Op == OO_Array_New) {
8323       const FunctionProtoType *Proto
8324         = FD->getType()->castAs<FunctionProtoType>();
8325       if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
8326           CheckNonNullExpr(*this, RetValExp))
8327         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
8328           << FD << getLangOpts().CPlusPlus11;
8329     }
8330   }
8331 }
8332 
8333 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
8334 
8335 /// Check for comparisons of floating point operands using != and ==.
8336 /// Issue a warning if these are no self-comparisons, as they are not likely
8337 /// to do what the programmer intended.
8338 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
8339   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
8340   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
8341 
8342   // Special case: check for x == x (which is OK).
8343   // Do not emit warnings for such cases.
8344   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
8345     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
8346       if (DRL->getDecl() == DRR->getDecl())
8347         return;
8348 
8349   // Special case: check for comparisons against literals that can be exactly
8350   //  represented by APFloat.  In such cases, do not emit a warning.  This
8351   //  is a heuristic: often comparison against such literals are used to
8352   //  detect if a value in a variable has not changed.  This clearly can
8353   //  lead to false negatives.
8354   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
8355     if (FLL->isExact())
8356       return;
8357   } else
8358     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
8359       if (FLR->isExact())
8360         return;
8361 
8362   // Check for comparisons with builtin types.
8363   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
8364     if (CL->getBuiltinCallee())
8365       return;
8366 
8367   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
8368     if (CR->getBuiltinCallee())
8369       return;
8370 
8371   // Emit the diagnostic.
8372   Diag(Loc, diag::warn_floatingpoint_eq)
8373     << LHS->getSourceRange() << RHS->getSourceRange();
8374 }
8375 
8376 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
8377 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
8378 
8379 namespace {
8380 
8381 /// Structure recording the 'active' range of an integer-valued
8382 /// expression.
8383 struct IntRange {
8384   /// The number of bits active in the int.
8385   unsigned Width;
8386 
8387   /// True if the int is known not to have negative values.
8388   bool NonNegative;
8389 
8390   IntRange(unsigned Width, bool NonNegative)
8391       : Width(Width), NonNegative(NonNegative) {}
8392 
8393   /// Returns the range of the bool type.
8394   static IntRange forBoolType() {
8395     return IntRange(1, true);
8396   }
8397 
8398   /// Returns the range of an opaque value of the given integral type.
8399   static IntRange forValueOfType(ASTContext &C, QualType T) {
8400     return forValueOfCanonicalType(C,
8401                           T->getCanonicalTypeInternal().getTypePtr());
8402   }
8403 
8404   /// Returns the range of an opaque value of a canonical integral type.
8405   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
8406     assert(T->isCanonicalUnqualified());
8407 
8408     if (const VectorType *VT = dyn_cast<VectorType>(T))
8409       T = VT->getElementType().getTypePtr();
8410     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8411       T = CT->getElementType().getTypePtr();
8412     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8413       T = AT->getValueType().getTypePtr();
8414 
8415     if (!C.getLangOpts().CPlusPlus) {
8416       // For enum types in C code, use the underlying datatype.
8417       if (const EnumType *ET = dyn_cast<EnumType>(T))
8418         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
8419     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
8420       // For enum types in C++, use the known bit width of the enumerators.
8421       EnumDecl *Enum = ET->getDecl();
8422       // In C++11, enums can have a fixed underlying type. Use this type to
8423       // compute the range.
8424       if (Enum->isFixed()) {
8425         return IntRange(C.getIntWidth(QualType(T, 0)),
8426                         !ET->isSignedIntegerOrEnumerationType());
8427       }
8428 
8429       unsigned NumPositive = Enum->getNumPositiveBits();
8430       unsigned NumNegative = Enum->getNumNegativeBits();
8431 
8432       if (NumNegative == 0)
8433         return IntRange(NumPositive, true/*NonNegative*/);
8434       else
8435         return IntRange(std::max(NumPositive + 1, NumNegative),
8436                         false/*NonNegative*/);
8437     }
8438 
8439     const BuiltinType *BT = cast<BuiltinType>(T);
8440     assert(BT->isInteger());
8441 
8442     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8443   }
8444 
8445   /// Returns the "target" range of a canonical integral type, i.e.
8446   /// the range of values expressible in the type.
8447   ///
8448   /// This matches forValueOfCanonicalType except that enums have the
8449   /// full range of their type, not the range of their enumerators.
8450   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
8451     assert(T->isCanonicalUnqualified());
8452 
8453     if (const VectorType *VT = dyn_cast<VectorType>(T))
8454       T = VT->getElementType().getTypePtr();
8455     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8456       T = CT->getElementType().getTypePtr();
8457     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8458       T = AT->getValueType().getTypePtr();
8459     if (const EnumType *ET = dyn_cast<EnumType>(T))
8460       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
8461 
8462     const BuiltinType *BT = cast<BuiltinType>(T);
8463     assert(BT->isInteger());
8464 
8465     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8466   }
8467 
8468   /// Returns the supremum of two ranges: i.e. their conservative merge.
8469   static IntRange join(IntRange L, IntRange R) {
8470     return IntRange(std::max(L.Width, R.Width),
8471                     L.NonNegative && R.NonNegative);
8472   }
8473 
8474   /// Returns the infinum of two ranges: i.e. their aggressive merge.
8475   static IntRange meet(IntRange L, IntRange R) {
8476     return IntRange(std::min(L.Width, R.Width),
8477                     L.NonNegative || R.NonNegative);
8478   }
8479 };
8480 
8481 } // namespace
8482 
8483 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
8484                               unsigned MaxWidth) {
8485   if (value.isSigned() && value.isNegative())
8486     return IntRange(value.getMinSignedBits(), false);
8487 
8488   if (value.getBitWidth() > MaxWidth)
8489     value = value.trunc(MaxWidth);
8490 
8491   // isNonNegative() just checks the sign bit without considering
8492   // signedness.
8493   return IntRange(value.getActiveBits(), true);
8494 }
8495 
8496 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
8497                               unsigned MaxWidth) {
8498   if (result.isInt())
8499     return GetValueRange(C, result.getInt(), MaxWidth);
8500 
8501   if (result.isVector()) {
8502     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
8503     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
8504       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
8505       R = IntRange::join(R, El);
8506     }
8507     return R;
8508   }
8509 
8510   if (result.isComplexInt()) {
8511     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
8512     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
8513     return IntRange::join(R, I);
8514   }
8515 
8516   // This can happen with lossless casts to intptr_t of "based" lvalues.
8517   // Assume it might use arbitrary bits.
8518   // FIXME: The only reason we need to pass the type in here is to get
8519   // the sign right on this one case.  It would be nice if APValue
8520   // preserved this.
8521   assert(result.isLValue() || result.isAddrLabelDiff());
8522   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
8523 }
8524 
8525 static QualType GetExprType(const Expr *E) {
8526   QualType Ty = E->getType();
8527   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
8528     Ty = AtomicRHS->getValueType();
8529   return Ty;
8530 }
8531 
8532 /// Pseudo-evaluate the given integer expression, estimating the
8533 /// range of values it might take.
8534 ///
8535 /// \param MaxWidth - the width to which the value will be truncated
8536 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
8537   E = E->IgnoreParens();
8538 
8539   // Try a full evaluation first.
8540   Expr::EvalResult result;
8541   if (E->EvaluateAsRValue(result, C))
8542     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
8543 
8544   // I think we only want to look through implicit casts here; if the
8545   // user has an explicit widening cast, we should treat the value as
8546   // being of the new, wider type.
8547   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
8548     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
8549       return GetExprRange(C, CE->getSubExpr(), MaxWidth);
8550 
8551     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
8552 
8553     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
8554                          CE->getCastKind() == CK_BooleanToSignedIntegral;
8555 
8556     // Assume that non-integer casts can span the full range of the type.
8557     if (!isIntegerCast)
8558       return OutputTypeRange;
8559 
8560     IntRange SubRange
8561       = GetExprRange(C, CE->getSubExpr(),
8562                      std::min(MaxWidth, OutputTypeRange.Width));
8563 
8564     // Bail out if the subexpr's range is as wide as the cast type.
8565     if (SubRange.Width >= OutputTypeRange.Width)
8566       return OutputTypeRange;
8567 
8568     // Otherwise, we take the smaller width, and we're non-negative if
8569     // either the output type or the subexpr is.
8570     return IntRange(SubRange.Width,
8571                     SubRange.NonNegative || OutputTypeRange.NonNegative);
8572   }
8573 
8574   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
8575     // If we can fold the condition, just take that operand.
8576     bool CondResult;
8577     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
8578       return GetExprRange(C, CondResult ? CO->getTrueExpr()
8579                                         : CO->getFalseExpr(),
8580                           MaxWidth);
8581 
8582     // Otherwise, conservatively merge.
8583     IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
8584     IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
8585     return IntRange::join(L, R);
8586   }
8587 
8588   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
8589     switch (BO->getOpcode()) {
8590     case BO_Cmp:
8591       llvm_unreachable("builtin <=> should have class type");
8592 
8593     // Boolean-valued operations are single-bit and positive.
8594     case BO_LAnd:
8595     case BO_LOr:
8596     case BO_LT:
8597     case BO_GT:
8598     case BO_LE:
8599     case BO_GE:
8600     case BO_EQ:
8601     case BO_NE:
8602       return IntRange::forBoolType();
8603 
8604     // The type of the assignments is the type of the LHS, so the RHS
8605     // is not necessarily the same type.
8606     case BO_MulAssign:
8607     case BO_DivAssign:
8608     case BO_RemAssign:
8609     case BO_AddAssign:
8610     case BO_SubAssign:
8611     case BO_XorAssign:
8612     case BO_OrAssign:
8613       // TODO: bitfields?
8614       return IntRange::forValueOfType(C, GetExprType(E));
8615 
8616     // Simple assignments just pass through the RHS, which will have
8617     // been coerced to the LHS type.
8618     case BO_Assign:
8619       // TODO: bitfields?
8620       return GetExprRange(C, BO->getRHS(), MaxWidth);
8621 
8622     // Operations with opaque sources are black-listed.
8623     case BO_PtrMemD:
8624     case BO_PtrMemI:
8625       return IntRange::forValueOfType(C, GetExprType(E));
8626 
8627     // Bitwise-and uses the *infinum* of the two source ranges.
8628     case BO_And:
8629     case BO_AndAssign:
8630       return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8631                             GetExprRange(C, BO->getRHS(), MaxWidth));
8632 
8633     // Left shift gets black-listed based on a judgement call.
8634     case BO_Shl:
8635       // ...except that we want to treat '1 << (blah)' as logically
8636       // positive.  It's an important idiom.
8637       if (IntegerLiteral *I
8638             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8639         if (I->getValue() == 1) {
8640           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
8641           return IntRange(R.Width, /*NonNegative*/ true);
8642         }
8643       }
8644       LLVM_FALLTHROUGH;
8645 
8646     case BO_ShlAssign:
8647       return IntRange::forValueOfType(C, GetExprType(E));
8648 
8649     // Right shift by a constant can narrow its left argument.
8650     case BO_Shr:
8651     case BO_ShrAssign: {
8652       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8653 
8654       // If the shift amount is a positive constant, drop the width by
8655       // that much.
8656       llvm::APSInt shift;
8657       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8658           shift.isNonNegative()) {
8659         unsigned zext = shift.getZExtValue();
8660         if (zext >= L.Width)
8661           L.Width = (L.NonNegative ? 0 : 1);
8662         else
8663           L.Width -= zext;
8664       }
8665 
8666       return L;
8667     }
8668 
8669     // Comma acts as its right operand.
8670     case BO_Comma:
8671       return GetExprRange(C, BO->getRHS(), MaxWidth);
8672 
8673     // Black-list pointer subtractions.
8674     case BO_Sub:
8675       if (BO->getLHS()->getType()->isPointerType())
8676         return IntRange::forValueOfType(C, GetExprType(E));
8677       break;
8678 
8679     // The width of a division result is mostly determined by the size
8680     // of the LHS.
8681     case BO_Div: {
8682       // Don't 'pre-truncate' the operands.
8683       unsigned opWidth = C.getIntWidth(GetExprType(E));
8684       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8685 
8686       // If the divisor is constant, use that.
8687       llvm::APSInt divisor;
8688       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8689         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8690         if (log2 >= L.Width)
8691           L.Width = (L.NonNegative ? 0 : 1);
8692         else
8693           L.Width = std::min(L.Width - log2, MaxWidth);
8694         return L;
8695       }
8696 
8697       // Otherwise, just use the LHS's width.
8698       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8699       return IntRange(L.Width, L.NonNegative && R.NonNegative);
8700     }
8701 
8702     // The result of a remainder can't be larger than the result of
8703     // either side.
8704     case BO_Rem: {
8705       // Don't 'pre-truncate' the operands.
8706       unsigned opWidth = C.getIntWidth(GetExprType(E));
8707       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8708       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8709 
8710       IntRange meet = IntRange::meet(L, R);
8711       meet.Width = std::min(meet.Width, MaxWidth);
8712       return meet;
8713     }
8714 
8715     // The default behavior is okay for these.
8716     case BO_Mul:
8717     case BO_Add:
8718     case BO_Xor:
8719     case BO_Or:
8720       break;
8721     }
8722 
8723     // The default case is to treat the operation as if it were closed
8724     // on the narrowest type that encompasses both operands.
8725     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8726     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8727     return IntRange::join(L, R);
8728   }
8729 
8730   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
8731     switch (UO->getOpcode()) {
8732     // Boolean-valued operations are white-listed.
8733     case UO_LNot:
8734       return IntRange::forBoolType();
8735 
8736     // Operations with opaque sources are black-listed.
8737     case UO_Deref:
8738     case UO_AddrOf: // should be impossible
8739       return IntRange::forValueOfType(C, GetExprType(E));
8740 
8741     default:
8742       return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8743     }
8744   }
8745 
8746   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
8747     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8748 
8749   if (const auto *BitField = E->getSourceBitField())
8750     return IntRange(BitField->getBitWidthValue(C),
8751                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
8752 
8753   return IntRange::forValueOfType(C, GetExprType(E));
8754 }
8755 
8756 static IntRange GetExprRange(ASTContext &C, const Expr *E) {
8757   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
8758 }
8759 
8760 /// Checks whether the given value, which currently has the given
8761 /// source semantics, has the same value when coerced through the
8762 /// target semantics.
8763 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
8764                                  const llvm::fltSemantics &Src,
8765                                  const llvm::fltSemantics &Tgt) {
8766   llvm::APFloat truncated = value;
8767 
8768   bool ignored;
8769   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8770   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8771 
8772   return truncated.bitwiseIsEqual(value);
8773 }
8774 
8775 /// Checks whether the given value, which currently has the given
8776 /// source semantics, has the same value when coerced through the
8777 /// target semantics.
8778 ///
8779 /// The value might be a vector of floats (or a complex number).
8780 static bool IsSameFloatAfterCast(const APValue &value,
8781                                  const llvm::fltSemantics &Src,
8782                                  const llvm::fltSemantics &Tgt) {
8783   if (value.isFloat())
8784     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8785 
8786   if (value.isVector()) {
8787     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8788       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8789         return false;
8790     return true;
8791   }
8792 
8793   assert(value.isComplexFloat());
8794   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8795           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8796 }
8797 
8798 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
8799 
8800 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
8801   // Suppress cases where we are comparing against an enum constant.
8802   if (const DeclRefExpr *DR =
8803       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8804     if (isa<EnumConstantDecl>(DR->getDecl()))
8805       return true;
8806 
8807   // Suppress cases where the '0' value is expanded from a macro.
8808   if (E->getLocStart().isMacroID())
8809     return true;
8810 
8811   return false;
8812 }
8813 
8814 static bool isKnownToHaveUnsignedValue(Expr *E) {
8815   return E->getType()->isIntegerType() &&
8816          (!E->getType()->isSignedIntegerType() ||
8817           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
8818 }
8819 
8820 namespace {
8821 /// The promoted range of values of a type. In general this has the
8822 /// following structure:
8823 ///
8824 ///     |-----------| . . . |-----------|
8825 ///     ^           ^       ^           ^
8826 ///    Min       HoleMin  HoleMax      Max
8827 ///
8828 /// ... where there is only a hole if a signed type is promoted to unsigned
8829 /// (in which case Min and Max are the smallest and largest representable
8830 /// values).
8831 struct PromotedRange {
8832   // Min, or HoleMax if there is a hole.
8833   llvm::APSInt PromotedMin;
8834   // Max, or HoleMin if there is a hole.
8835   llvm::APSInt PromotedMax;
8836 
8837   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
8838     if (R.Width == 0)
8839       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
8840     else if (R.Width >= BitWidth && !Unsigned) {
8841       // Promotion made the type *narrower*. This happens when promoting
8842       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
8843       // Treat all values of 'signed int' as being in range for now.
8844       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
8845       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
8846     } else {
8847       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
8848                         .extOrTrunc(BitWidth);
8849       PromotedMin.setIsUnsigned(Unsigned);
8850 
8851       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
8852                         .extOrTrunc(BitWidth);
8853       PromotedMax.setIsUnsigned(Unsigned);
8854     }
8855   }
8856 
8857   // Determine whether this range is contiguous (has no hole).
8858   bool isContiguous() const { return PromotedMin <= PromotedMax; }
8859 
8860   // Where a constant value is within the range.
8861   enum ComparisonResult {
8862     LT = 0x1,
8863     LE = 0x2,
8864     GT = 0x4,
8865     GE = 0x8,
8866     EQ = 0x10,
8867     NE = 0x20,
8868     InRangeFlag = 0x40,
8869 
8870     Less = LE | LT | NE,
8871     Min = LE | InRangeFlag,
8872     InRange = InRangeFlag,
8873     Max = GE | InRangeFlag,
8874     Greater = GE | GT | NE,
8875 
8876     OnlyValue = LE | GE | EQ | InRangeFlag,
8877     InHole = NE
8878   };
8879 
8880   ComparisonResult compare(const llvm::APSInt &Value) const {
8881     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
8882            Value.isUnsigned() == PromotedMin.isUnsigned());
8883     if (!isContiguous()) {
8884       assert(Value.isUnsigned() && "discontiguous range for signed compare");
8885       if (Value.isMinValue()) return Min;
8886       if (Value.isMaxValue()) return Max;
8887       if (Value >= PromotedMin) return InRange;
8888       if (Value <= PromotedMax) return InRange;
8889       return InHole;
8890     }
8891 
8892     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
8893     case -1: return Less;
8894     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
8895     case 1:
8896       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
8897       case -1: return InRange;
8898       case 0: return Max;
8899       case 1: return Greater;
8900       }
8901     }
8902 
8903     llvm_unreachable("impossible compare result");
8904   }
8905 
8906   static llvm::Optional<StringRef>
8907   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
8908     if (Op == BO_Cmp) {
8909       ComparisonResult LTFlag = LT, GTFlag = GT;
8910       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
8911 
8912       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
8913       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
8914       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
8915       return llvm::None;
8916     }
8917 
8918     ComparisonResult TrueFlag, FalseFlag;
8919     if (Op == BO_EQ) {
8920       TrueFlag = EQ;
8921       FalseFlag = NE;
8922     } else if (Op == BO_NE) {
8923       TrueFlag = NE;
8924       FalseFlag = EQ;
8925     } else {
8926       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
8927         TrueFlag = LT;
8928         FalseFlag = GE;
8929       } else {
8930         TrueFlag = GT;
8931         FalseFlag = LE;
8932       }
8933       if (Op == BO_GE || Op == BO_LE)
8934         std::swap(TrueFlag, FalseFlag);
8935     }
8936     if (R & TrueFlag)
8937       return StringRef("true");
8938     if (R & FalseFlag)
8939       return StringRef("false");
8940     return llvm::None;
8941   }
8942 };
8943 }
8944 
8945 static bool HasEnumType(Expr *E) {
8946   // Strip off implicit integral promotions.
8947   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8948     if (ICE->getCastKind() != CK_IntegralCast &&
8949         ICE->getCastKind() != CK_NoOp)
8950       break;
8951     E = ICE->getSubExpr();
8952   }
8953 
8954   return E->getType()->isEnumeralType();
8955 }
8956 
8957 static int classifyConstantValue(Expr *Constant) {
8958   // The values of this enumeration are used in the diagnostics
8959   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
8960   enum ConstantValueKind {
8961     Miscellaneous = 0,
8962     LiteralTrue,
8963     LiteralFalse
8964   };
8965   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
8966     return BL->getValue() ? ConstantValueKind::LiteralTrue
8967                           : ConstantValueKind::LiteralFalse;
8968   return ConstantValueKind::Miscellaneous;
8969 }
8970 
8971 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
8972                                         Expr *Constant, Expr *Other,
8973                                         const llvm::APSInt &Value,
8974                                         bool RhsConstant) {
8975   if (S.inTemplateInstantiation())
8976     return false;
8977 
8978   Expr *OriginalOther = Other;
8979 
8980   Constant = Constant->IgnoreParenImpCasts();
8981   Other = Other->IgnoreParenImpCasts();
8982 
8983   // Suppress warnings on tautological comparisons between values of the same
8984   // enumeration type. There are only two ways we could warn on this:
8985   //  - If the constant is outside the range of representable values of
8986   //    the enumeration. In such a case, we should warn about the cast
8987   //    to enumeration type, not about the comparison.
8988   //  - If the constant is the maximum / minimum in-range value. For an
8989   //    enumeratin type, such comparisons can be meaningful and useful.
8990   if (Constant->getType()->isEnumeralType() &&
8991       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
8992     return false;
8993 
8994   // TODO: Investigate using GetExprRange() to get tighter bounds
8995   // on the bit ranges.
8996   QualType OtherT = Other->getType();
8997   if (const auto *AT = OtherT->getAs<AtomicType>())
8998     OtherT = AT->getValueType();
8999   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
9000 
9001   // Whether we're treating Other as being a bool because of the form of
9002   // expression despite it having another type (typically 'int' in C).
9003   bool OtherIsBooleanDespiteType =
9004       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
9005   if (OtherIsBooleanDespiteType)
9006     OtherRange = IntRange::forBoolType();
9007 
9008   // Determine the promoted range of the other type and see if a comparison of
9009   // the constant against that range is tautological.
9010   PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
9011                                    Value.isUnsigned());
9012   auto Cmp = OtherPromotedRange.compare(Value);
9013   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
9014   if (!Result)
9015     return false;
9016 
9017   // Suppress the diagnostic for an in-range comparison if the constant comes
9018   // from a macro or enumerator. We don't want to diagnose
9019   //
9020   //   some_long_value <= INT_MAX
9021   //
9022   // when sizeof(int) == sizeof(long).
9023   bool InRange = Cmp & PromotedRange::InRangeFlag;
9024   if (InRange && IsEnumConstOrFromMacro(S, Constant))
9025     return false;
9026 
9027   // If this is a comparison to an enum constant, include that
9028   // constant in the diagnostic.
9029   const EnumConstantDecl *ED = nullptr;
9030   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
9031     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
9032 
9033   // Should be enough for uint128 (39 decimal digits)
9034   SmallString<64> PrettySourceValue;
9035   llvm::raw_svector_ostream OS(PrettySourceValue);
9036   if (ED)
9037     OS << '\'' << *ED << "' (" << Value << ")";
9038   else
9039     OS << Value;
9040 
9041   // FIXME: We use a somewhat different formatting for the in-range cases and
9042   // cases involving boolean values for historical reasons. We should pick a
9043   // consistent way of presenting these diagnostics.
9044   if (!InRange || Other->isKnownToHaveBooleanValue()) {
9045     S.DiagRuntimeBehavior(
9046       E->getOperatorLoc(), E,
9047       S.PDiag(!InRange ? diag::warn_out_of_range_compare
9048                        : diag::warn_tautological_bool_compare)
9049           << OS.str() << classifyConstantValue(Constant)
9050           << OtherT << OtherIsBooleanDespiteType << *Result
9051           << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
9052   } else {
9053     unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
9054                         ? (HasEnumType(OriginalOther)
9055                                ? diag::warn_unsigned_enum_always_true_comparison
9056                                : diag::warn_unsigned_always_true_comparison)
9057                         : diag::warn_tautological_constant_compare;
9058 
9059     S.Diag(E->getOperatorLoc(), Diag)
9060         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
9061         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
9062   }
9063 
9064   return true;
9065 }
9066 
9067 /// Analyze the operands of the given comparison.  Implements the
9068 /// fallback case from AnalyzeComparison.
9069 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
9070   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9071   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9072 }
9073 
9074 /// \brief Implements -Wsign-compare.
9075 ///
9076 /// \param E the binary operator to check for warnings
9077 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
9078   // The type the comparison is being performed in.
9079   QualType T = E->getLHS()->getType();
9080 
9081   // Only analyze comparison operators where both sides have been converted to
9082   // the same type.
9083   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
9084     return AnalyzeImpConvsInComparison(S, E);
9085 
9086   // Don't analyze value-dependent comparisons directly.
9087   if (E->isValueDependent())
9088     return AnalyzeImpConvsInComparison(S, E);
9089 
9090   Expr *LHS = E->getLHS();
9091   Expr *RHS = E->getRHS();
9092 
9093   if (T->isIntegralType(S.Context)) {
9094     llvm::APSInt RHSValue;
9095     llvm::APSInt LHSValue;
9096 
9097     bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
9098     bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
9099 
9100     // We don't care about expressions whose result is a constant.
9101     if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
9102       return AnalyzeImpConvsInComparison(S, E);
9103 
9104     // We only care about expressions where just one side is literal
9105     if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
9106       // Is the constant on the RHS or LHS?
9107       const bool RhsConstant = IsRHSIntegralLiteral;
9108       Expr *Const = RhsConstant ? RHS : LHS;
9109       Expr *Other = RhsConstant ? LHS : RHS;
9110       const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
9111 
9112       // Check whether an integer constant comparison results in a value
9113       // of 'true' or 'false'.
9114       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
9115         return AnalyzeImpConvsInComparison(S, E);
9116     }
9117   }
9118 
9119   if (!T->hasUnsignedIntegerRepresentation()) {
9120     // We don't do anything special if this isn't an unsigned integral
9121     // comparison:  we're only interested in integral comparisons, and
9122     // signed comparisons only happen in cases we don't care to warn about.
9123     return AnalyzeImpConvsInComparison(S, E);
9124   }
9125 
9126   LHS = LHS->IgnoreParenImpCasts();
9127   RHS = RHS->IgnoreParenImpCasts();
9128 
9129   if (!S.getLangOpts().CPlusPlus) {
9130     // Avoid warning about comparison of integers with different signs when
9131     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
9132     // the type of `E`.
9133     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
9134       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
9135     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
9136       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
9137   }
9138 
9139   // Check to see if one of the (unmodified) operands is of different
9140   // signedness.
9141   Expr *signedOperand, *unsignedOperand;
9142   if (LHS->getType()->hasSignedIntegerRepresentation()) {
9143     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
9144            "unsigned comparison between two signed integer expressions?");
9145     signedOperand = LHS;
9146     unsignedOperand = RHS;
9147   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
9148     signedOperand = RHS;
9149     unsignedOperand = LHS;
9150   } else {
9151     return AnalyzeImpConvsInComparison(S, E);
9152   }
9153 
9154   // Otherwise, calculate the effective range of the signed operand.
9155   IntRange signedRange = GetExprRange(S.Context, signedOperand);
9156 
9157   // Go ahead and analyze implicit conversions in the operands.  Note
9158   // that we skip the implicit conversions on both sides.
9159   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
9160   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
9161 
9162   // If the signed range is non-negative, -Wsign-compare won't fire.
9163   if (signedRange.NonNegative)
9164     return;
9165 
9166   // For (in)equality comparisons, if the unsigned operand is a
9167   // constant which cannot collide with a overflowed signed operand,
9168   // then reinterpreting the signed operand as unsigned will not
9169   // change the result of the comparison.
9170   if (E->isEqualityOp()) {
9171     unsigned comparisonWidth = S.Context.getIntWidth(T);
9172     IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
9173 
9174     // We should never be unable to prove that the unsigned operand is
9175     // non-negative.
9176     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
9177 
9178     if (unsignedRange.Width < comparisonWidth)
9179       return;
9180   }
9181 
9182   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
9183     S.PDiag(diag::warn_mixed_sign_comparison)
9184       << LHS->getType() << RHS->getType()
9185       << LHS->getSourceRange() << RHS->getSourceRange());
9186 }
9187 
9188 /// Analyzes an attempt to assign the given value to a bitfield.
9189 ///
9190 /// Returns true if there was something fishy about the attempt.
9191 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
9192                                       SourceLocation InitLoc) {
9193   assert(Bitfield->isBitField());
9194   if (Bitfield->isInvalidDecl())
9195     return false;
9196 
9197   // White-list bool bitfields.
9198   QualType BitfieldType = Bitfield->getType();
9199   if (BitfieldType->isBooleanType())
9200      return false;
9201 
9202   if (BitfieldType->isEnumeralType()) {
9203     EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
9204     // If the underlying enum type was not explicitly specified as an unsigned
9205     // type and the enum contain only positive values, MSVC++ will cause an
9206     // inconsistency by storing this as a signed type.
9207     if (S.getLangOpts().CPlusPlus11 &&
9208         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
9209         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
9210         BitfieldEnumDecl->getNumNegativeBits() == 0) {
9211       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
9212         << BitfieldEnumDecl->getNameAsString();
9213     }
9214   }
9215 
9216   if (Bitfield->getType()->isBooleanType())
9217     return false;
9218 
9219   // Ignore value- or type-dependent expressions.
9220   if (Bitfield->getBitWidth()->isValueDependent() ||
9221       Bitfield->getBitWidth()->isTypeDependent() ||
9222       Init->isValueDependent() ||
9223       Init->isTypeDependent())
9224     return false;
9225 
9226   Expr *OriginalInit = Init->IgnoreParenImpCasts();
9227   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
9228 
9229   llvm::APSInt Value;
9230   if (!OriginalInit->EvaluateAsInt(Value, S.Context,
9231                                    Expr::SE_AllowSideEffects)) {
9232     // The RHS is not constant.  If the RHS has an enum type, make sure the
9233     // bitfield is wide enough to hold all the values of the enum without
9234     // truncation.
9235     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
9236       EnumDecl *ED = EnumTy->getDecl();
9237       bool SignedBitfield = BitfieldType->isSignedIntegerType();
9238 
9239       // Enum types are implicitly signed on Windows, so check if there are any
9240       // negative enumerators to see if the enum was intended to be signed or
9241       // not.
9242       bool SignedEnum = ED->getNumNegativeBits() > 0;
9243 
9244       // Check for surprising sign changes when assigning enum values to a
9245       // bitfield of different signedness.  If the bitfield is signed and we
9246       // have exactly the right number of bits to store this unsigned enum,
9247       // suggest changing the enum to an unsigned type. This typically happens
9248       // on Windows where unfixed enums always use an underlying type of 'int'.
9249       unsigned DiagID = 0;
9250       if (SignedEnum && !SignedBitfield) {
9251         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
9252       } else if (SignedBitfield && !SignedEnum &&
9253                  ED->getNumPositiveBits() == FieldWidth) {
9254         DiagID = diag::warn_signed_bitfield_enum_conversion;
9255       }
9256 
9257       if (DiagID) {
9258         S.Diag(InitLoc, DiagID) << Bitfield << ED;
9259         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
9260         SourceRange TypeRange =
9261             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
9262         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
9263             << SignedEnum << TypeRange;
9264       }
9265 
9266       // Compute the required bitwidth. If the enum has negative values, we need
9267       // one more bit than the normal number of positive bits to represent the
9268       // sign bit.
9269       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
9270                                                   ED->getNumNegativeBits())
9271                                        : ED->getNumPositiveBits();
9272 
9273       // Check the bitwidth.
9274       if (BitsNeeded > FieldWidth) {
9275         Expr *WidthExpr = Bitfield->getBitWidth();
9276         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
9277             << Bitfield << ED;
9278         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
9279             << BitsNeeded << ED << WidthExpr->getSourceRange();
9280       }
9281     }
9282 
9283     return false;
9284   }
9285 
9286   unsigned OriginalWidth = Value.getBitWidth();
9287 
9288   if (!Value.isSigned() || Value.isNegative())
9289     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
9290       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
9291         OriginalWidth = Value.getMinSignedBits();
9292 
9293   if (OriginalWidth <= FieldWidth)
9294     return false;
9295 
9296   // Compute the value which the bitfield will contain.
9297   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
9298   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
9299 
9300   // Check whether the stored value is equal to the original value.
9301   TruncatedValue = TruncatedValue.extend(OriginalWidth);
9302   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
9303     return false;
9304 
9305   // Special-case bitfields of width 1: booleans are naturally 0/1, and
9306   // therefore don't strictly fit into a signed bitfield of width 1.
9307   if (FieldWidth == 1 && Value == 1)
9308     return false;
9309 
9310   std::string PrettyValue = Value.toString(10);
9311   std::string PrettyTrunc = TruncatedValue.toString(10);
9312 
9313   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
9314     << PrettyValue << PrettyTrunc << OriginalInit->getType()
9315     << Init->getSourceRange();
9316 
9317   return true;
9318 }
9319 
9320 /// Analyze the given simple or compound assignment for warning-worthy
9321 /// operations.
9322 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
9323   // Just recurse on the LHS.
9324   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9325 
9326   // We want to recurse on the RHS as normal unless we're assigning to
9327   // a bitfield.
9328   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
9329     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
9330                                   E->getOperatorLoc())) {
9331       // Recurse, ignoring any implicit conversions on the RHS.
9332       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
9333                                         E->getOperatorLoc());
9334     }
9335   }
9336 
9337   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9338 }
9339 
9340 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
9341 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
9342                             SourceLocation CContext, unsigned diag,
9343                             bool pruneControlFlow = false) {
9344   if (pruneControlFlow) {
9345     S.DiagRuntimeBehavior(E->getExprLoc(), E,
9346                           S.PDiag(diag)
9347                             << SourceType << T << E->getSourceRange()
9348                             << SourceRange(CContext));
9349     return;
9350   }
9351   S.Diag(E->getExprLoc(), diag)
9352     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
9353 }
9354 
9355 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
9356 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
9357                             SourceLocation CContext,
9358                             unsigned diag, bool pruneControlFlow = false) {
9359   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
9360 }
9361 
9362 /// Analyze the given compound assignment for the possible losing of
9363 /// floating-point precision.
9364 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
9365   assert(isa<CompoundAssignOperator>(E) &&
9366          "Must be compound assignment operation");
9367   // Recurse on the LHS and RHS in here
9368   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9369   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9370 
9371   // Now check the outermost expression
9372   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
9373   const auto *RBT = cast<CompoundAssignOperator>(E)
9374                         ->getComputationResultType()
9375                         ->getAs<BuiltinType>();
9376 
9377   // If both source and target are floating points.
9378   if (ResultBT && ResultBT->isFloatingPoint() && RBT && RBT->isFloatingPoint())
9379     // Builtin FP kinds are ordered by increasing FP rank.
9380     if (ResultBT->getKind() < RBT->getKind())
9381       // We don't want to warn for system macro.
9382       if (!S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
9383         // warn about dropping FP rank.
9384         DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(),
9385                         E->getOperatorLoc(),
9386                         diag::warn_impcast_float_result_precision);
9387 }
9388 
9389 /// Diagnose an implicit cast from a floating point value to an integer value.
9390 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
9391                                     SourceLocation CContext) {
9392   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
9393   const bool PruneWarnings = S.inTemplateInstantiation();
9394 
9395   Expr *InnerE = E->IgnoreParenImpCasts();
9396   // We also want to warn on, e.g., "int i = -1.234"
9397   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
9398     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
9399       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
9400 
9401   const bool IsLiteral =
9402       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
9403 
9404   llvm::APFloat Value(0.0);
9405   bool IsConstant =
9406     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
9407   if (!IsConstant) {
9408     return DiagnoseImpCast(S, E, T, CContext,
9409                            diag::warn_impcast_float_integer, PruneWarnings);
9410   }
9411 
9412   bool isExact = false;
9413 
9414   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
9415                             T->hasUnsignedIntegerRepresentation());
9416   if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
9417                              &isExact) == llvm::APFloat::opOK &&
9418       isExact) {
9419     if (IsLiteral) return;
9420     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
9421                            PruneWarnings);
9422   }
9423 
9424   unsigned DiagID = 0;
9425   if (IsLiteral) {
9426     // Warn on floating point literal to integer.
9427     DiagID = diag::warn_impcast_literal_float_to_integer;
9428   } else if (IntegerValue == 0) {
9429     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
9430       return DiagnoseImpCast(S, E, T, CContext,
9431                              diag::warn_impcast_float_integer, PruneWarnings);
9432     }
9433     // Warn on non-zero to zero conversion.
9434     DiagID = diag::warn_impcast_float_to_integer_zero;
9435   } else {
9436     if (IntegerValue.isUnsigned()) {
9437       if (!IntegerValue.isMaxValue()) {
9438         return DiagnoseImpCast(S, E, T, CContext,
9439                                diag::warn_impcast_float_integer, PruneWarnings);
9440       }
9441     } else {  // IntegerValue.isSigned()
9442       if (!IntegerValue.isMaxSignedValue() &&
9443           !IntegerValue.isMinSignedValue()) {
9444         return DiagnoseImpCast(S, E, T, CContext,
9445                                diag::warn_impcast_float_integer, PruneWarnings);
9446       }
9447     }
9448     // Warn on evaluatable floating point expression to integer conversion.
9449     DiagID = diag::warn_impcast_float_to_integer;
9450   }
9451 
9452   // FIXME: Force the precision of the source value down so we don't print
9453   // digits which are usually useless (we don't really care here if we
9454   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
9455   // would automatically print the shortest representation, but it's a bit
9456   // tricky to implement.
9457   SmallString<16> PrettySourceValue;
9458   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
9459   precision = (precision * 59 + 195) / 196;
9460   Value.toString(PrettySourceValue, precision);
9461 
9462   SmallString<16> PrettyTargetValue;
9463   if (IsBool)
9464     PrettyTargetValue = Value.isZero() ? "false" : "true";
9465   else
9466     IntegerValue.toString(PrettyTargetValue);
9467 
9468   if (PruneWarnings) {
9469     S.DiagRuntimeBehavior(E->getExprLoc(), E,
9470                           S.PDiag(DiagID)
9471                               << E->getType() << T.getUnqualifiedType()
9472                               << PrettySourceValue << PrettyTargetValue
9473                               << E->getSourceRange() << SourceRange(CContext));
9474   } else {
9475     S.Diag(E->getExprLoc(), DiagID)
9476         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
9477         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
9478   }
9479 }
9480 
9481 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
9482                                       IntRange Range) {
9483   if (!Range.Width) return "0";
9484 
9485   llvm::APSInt ValueInRange = Value;
9486   ValueInRange.setIsSigned(!Range.NonNegative);
9487   ValueInRange = ValueInRange.trunc(Range.Width);
9488   return ValueInRange.toString(10);
9489 }
9490 
9491 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
9492   if (!isa<ImplicitCastExpr>(Ex))
9493     return false;
9494 
9495   Expr *InnerE = Ex->IgnoreParenImpCasts();
9496   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
9497   const Type *Source =
9498     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
9499   if (Target->isDependentType())
9500     return false;
9501 
9502   const BuiltinType *FloatCandidateBT =
9503     dyn_cast<BuiltinType>(ToBool ? Source : Target);
9504   const Type *BoolCandidateType = ToBool ? Target : Source;
9505 
9506   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
9507           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
9508 }
9509 
9510 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
9511                                              SourceLocation CC) {
9512   unsigned NumArgs = TheCall->getNumArgs();
9513   for (unsigned i = 0; i < NumArgs; ++i) {
9514     Expr *CurrA = TheCall->getArg(i);
9515     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
9516       continue;
9517 
9518     bool IsSwapped = ((i > 0) &&
9519         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
9520     IsSwapped |= ((i < (NumArgs - 1)) &&
9521         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
9522     if (IsSwapped) {
9523       // Warn on this floating-point to bool conversion.
9524       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
9525                       CurrA->getType(), CC,
9526                       diag::warn_impcast_floating_point_to_bool);
9527     }
9528   }
9529 }
9530 
9531 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
9532                                    SourceLocation CC) {
9533   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
9534                         E->getExprLoc()))
9535     return;
9536 
9537   // Don't warn on functions which have return type nullptr_t.
9538   if (isa<CallExpr>(E))
9539     return;
9540 
9541   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
9542   const Expr::NullPointerConstantKind NullKind =
9543       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
9544   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
9545     return;
9546 
9547   // Return if target type is a safe conversion.
9548   if (T->isAnyPointerType() || T->isBlockPointerType() ||
9549       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
9550     return;
9551 
9552   SourceLocation Loc = E->getSourceRange().getBegin();
9553 
9554   // Venture through the macro stacks to get to the source of macro arguments.
9555   // The new location is a better location than the complete location that was
9556   // passed in.
9557   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
9558   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
9559 
9560   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
9561   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
9562     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
9563         Loc, S.SourceMgr, S.getLangOpts());
9564     if (MacroName == "NULL")
9565       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
9566   }
9567 
9568   // Only warn if the null and context location are in the same macro expansion.
9569   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
9570     return;
9571 
9572   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
9573       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
9574       << FixItHint::CreateReplacement(Loc,
9575                                       S.getFixItZeroLiteralForType(T, Loc));
9576 }
9577 
9578 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9579                                   ObjCArrayLiteral *ArrayLiteral);
9580 
9581 static void
9582 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9583                            ObjCDictionaryLiteral *DictionaryLiteral);
9584 
9585 /// Check a single element within a collection literal against the
9586 /// target element type.
9587 static void checkObjCCollectionLiteralElement(Sema &S,
9588                                               QualType TargetElementType,
9589                                               Expr *Element,
9590                                               unsigned ElementKind) {
9591   // Skip a bitcast to 'id' or qualified 'id'.
9592   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
9593     if (ICE->getCastKind() == CK_BitCast &&
9594         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
9595       Element = ICE->getSubExpr();
9596   }
9597 
9598   QualType ElementType = Element->getType();
9599   ExprResult ElementResult(Element);
9600   if (ElementType->getAs<ObjCObjectPointerType>() &&
9601       S.CheckSingleAssignmentConstraints(TargetElementType,
9602                                          ElementResult,
9603                                          false, false)
9604         != Sema::Compatible) {
9605     S.Diag(Element->getLocStart(),
9606            diag::warn_objc_collection_literal_element)
9607       << ElementType << ElementKind << TargetElementType
9608       << Element->getSourceRange();
9609   }
9610 
9611   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
9612     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
9613   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
9614     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
9615 }
9616 
9617 /// Check an Objective-C array literal being converted to the given
9618 /// target type.
9619 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9620                                   ObjCArrayLiteral *ArrayLiteral) {
9621   if (!S.NSArrayDecl)
9622     return;
9623 
9624   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9625   if (!TargetObjCPtr)
9626     return;
9627 
9628   if (TargetObjCPtr->isUnspecialized() ||
9629       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9630         != S.NSArrayDecl->getCanonicalDecl())
9631     return;
9632 
9633   auto TypeArgs = TargetObjCPtr->getTypeArgs();
9634   if (TypeArgs.size() != 1)
9635     return;
9636 
9637   QualType TargetElementType = TypeArgs[0];
9638   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
9639     checkObjCCollectionLiteralElement(S, TargetElementType,
9640                                       ArrayLiteral->getElement(I),
9641                                       0);
9642   }
9643 }
9644 
9645 /// Check an Objective-C dictionary literal being converted to the given
9646 /// target type.
9647 static void
9648 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9649                            ObjCDictionaryLiteral *DictionaryLiteral) {
9650   if (!S.NSDictionaryDecl)
9651     return;
9652 
9653   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9654   if (!TargetObjCPtr)
9655     return;
9656 
9657   if (TargetObjCPtr->isUnspecialized() ||
9658       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9659         != S.NSDictionaryDecl->getCanonicalDecl())
9660     return;
9661 
9662   auto TypeArgs = TargetObjCPtr->getTypeArgs();
9663   if (TypeArgs.size() != 2)
9664     return;
9665 
9666   QualType TargetKeyType = TypeArgs[0];
9667   QualType TargetObjectType = TypeArgs[1];
9668   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
9669     auto Element = DictionaryLiteral->getKeyValueElement(I);
9670     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
9671     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
9672   }
9673 }
9674 
9675 // Helper function to filter out cases for constant width constant conversion.
9676 // Don't warn on char array initialization or for non-decimal values.
9677 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
9678                                           SourceLocation CC) {
9679   // If initializing from a constant, and the constant starts with '0',
9680   // then it is a binary, octal, or hexadecimal.  Allow these constants
9681   // to fill all the bits, even if there is a sign change.
9682   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
9683     const char FirstLiteralCharacter =
9684         S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
9685     if (FirstLiteralCharacter == '0')
9686       return false;
9687   }
9688 
9689   // If the CC location points to a '{', and the type is char, then assume
9690   // assume it is an array initialization.
9691   if (CC.isValid() && T->isCharType()) {
9692     const char FirstContextCharacter =
9693         S.getSourceManager().getCharacterData(CC)[0];
9694     if (FirstContextCharacter == '{')
9695       return false;
9696   }
9697 
9698   return true;
9699 }
9700 
9701 static void
9702 CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
9703                         bool *ICContext = nullptr) {
9704   if (E->isTypeDependent() || E->isValueDependent()) return;
9705 
9706   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
9707   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
9708   if (Source == Target) return;
9709   if (Target->isDependentType()) return;
9710 
9711   // If the conversion context location is invalid don't complain. We also
9712   // don't want to emit a warning if the issue occurs from the expansion of
9713   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
9714   // delay this check as long as possible. Once we detect we are in that
9715   // scenario, we just return.
9716   if (CC.isInvalid())
9717     return;
9718 
9719   // Diagnose implicit casts to bool.
9720   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
9721     if (isa<StringLiteral>(E))
9722       // Warn on string literal to bool.  Checks for string literals in logical
9723       // and expressions, for instance, assert(0 && "error here"), are
9724       // prevented by a check in AnalyzeImplicitConversions().
9725       return DiagnoseImpCast(S, E, T, CC,
9726                              diag::warn_impcast_string_literal_to_bool);
9727     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
9728         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
9729       // This covers the literal expressions that evaluate to Objective-C
9730       // objects.
9731       return DiagnoseImpCast(S, E, T, CC,
9732                              diag::warn_impcast_objective_c_literal_to_bool);
9733     }
9734     if (Source->isPointerType() || Source->canDecayToPointerType()) {
9735       // Warn on pointer to bool conversion that is always true.
9736       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
9737                                      SourceRange(CC));
9738     }
9739   }
9740 
9741   // Check implicit casts from Objective-C collection literals to specialized
9742   // collection types, e.g., NSArray<NSString *> *.
9743   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
9744     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
9745   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
9746     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
9747 
9748   // Strip vector types.
9749   if (isa<VectorType>(Source)) {
9750     if (!isa<VectorType>(Target)) {
9751       if (S.SourceMgr.isInSystemMacro(CC))
9752         return;
9753       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
9754     }
9755 
9756     // If the vector cast is cast between two vectors of the same size, it is
9757     // a bitcast, not a conversion.
9758     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
9759       return;
9760 
9761     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
9762     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
9763   }
9764   if (auto VecTy = dyn_cast<VectorType>(Target))
9765     Target = VecTy->getElementType().getTypePtr();
9766 
9767   // Strip complex types.
9768   if (isa<ComplexType>(Source)) {
9769     if (!isa<ComplexType>(Target)) {
9770       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
9771         return;
9772 
9773       return DiagnoseImpCast(S, E, T, CC,
9774                              S.getLangOpts().CPlusPlus
9775                                  ? diag::err_impcast_complex_scalar
9776                                  : diag::warn_impcast_complex_scalar);
9777     }
9778 
9779     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
9780     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
9781   }
9782 
9783   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
9784   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
9785 
9786   // If the source is floating point...
9787   if (SourceBT && SourceBT->isFloatingPoint()) {
9788     // ...and the target is floating point...
9789     if (TargetBT && TargetBT->isFloatingPoint()) {
9790       // ...then warn if we're dropping FP rank.
9791 
9792       // Builtin FP kinds are ordered by increasing FP rank.
9793       if (SourceBT->getKind() > TargetBT->getKind()) {
9794         // Don't warn about float constants that are precisely
9795         // representable in the target type.
9796         Expr::EvalResult result;
9797         if (E->EvaluateAsRValue(result, S.Context)) {
9798           // Value might be a float, a float vector, or a float complex.
9799           if (IsSameFloatAfterCast(result.Val,
9800                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9801                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
9802             return;
9803         }
9804 
9805         if (S.SourceMgr.isInSystemMacro(CC))
9806           return;
9807 
9808         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
9809       }
9810       // ... or possibly if we're increasing rank, too
9811       else if (TargetBT->getKind() > SourceBT->getKind()) {
9812         if (S.SourceMgr.isInSystemMacro(CC))
9813           return;
9814 
9815         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
9816       }
9817       return;
9818     }
9819 
9820     // If the target is integral, always warn.
9821     if (TargetBT && TargetBT->isInteger()) {
9822       if (S.SourceMgr.isInSystemMacro(CC))
9823         return;
9824 
9825       DiagnoseFloatingImpCast(S, E, T, CC);
9826     }
9827 
9828     // Detect the case where a call result is converted from floating-point to
9829     // to bool, and the final argument to the call is converted from bool, to
9830     // discover this typo:
9831     //
9832     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
9833     //
9834     // FIXME: This is an incredibly special case; is there some more general
9835     // way to detect this class of misplaced-parentheses bug?
9836     if (Target->isBooleanType() && isa<CallExpr>(E)) {
9837       // Check last argument of function call to see if it is an
9838       // implicit cast from a type matching the type the result
9839       // is being cast to.
9840       CallExpr *CEx = cast<CallExpr>(E);
9841       if (unsigned NumArgs = CEx->getNumArgs()) {
9842         Expr *LastA = CEx->getArg(NumArgs - 1);
9843         Expr *InnerE = LastA->IgnoreParenImpCasts();
9844         if (isa<ImplicitCastExpr>(LastA) &&
9845             InnerE->getType()->isBooleanType()) {
9846           // Warn on this floating-point to bool conversion
9847           DiagnoseImpCast(S, E, T, CC,
9848                           diag::warn_impcast_floating_point_to_bool);
9849         }
9850       }
9851     }
9852     return;
9853   }
9854 
9855   DiagnoseNullConversion(S, E, T, CC);
9856 
9857   S.DiscardMisalignedMemberAddress(Target, E);
9858 
9859   if (!Source->isIntegerType() || !Target->isIntegerType())
9860     return;
9861 
9862   // TODO: remove this early return once the false positives for constant->bool
9863   // in templates, macros, etc, are reduced or removed.
9864   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9865     return;
9866 
9867   IntRange SourceRange = GetExprRange(S.Context, E);
9868   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
9869 
9870   if (SourceRange.Width > TargetRange.Width) {
9871     // If the source is a constant, use a default-on diagnostic.
9872     // TODO: this should happen for bitfield stores, too.
9873     llvm::APSInt Value(32);
9874     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
9875       if (S.SourceMgr.isInSystemMacro(CC))
9876         return;
9877 
9878       std::string PrettySourceValue = Value.toString(10);
9879       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
9880 
9881       S.DiagRuntimeBehavior(E->getExprLoc(), E,
9882         S.PDiag(diag::warn_impcast_integer_precision_constant)
9883             << PrettySourceValue << PrettyTargetValue
9884             << E->getType() << T << E->getSourceRange()
9885             << clang::SourceRange(CC));
9886       return;
9887     }
9888 
9889     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9890     if (S.SourceMgr.isInSystemMacro(CC))
9891       return;
9892 
9893     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
9894       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9895                              /* pruneControlFlow */ true);
9896     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
9897   }
9898 
9899   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9900       SourceRange.NonNegative && Source->isSignedIntegerType()) {
9901     // Warn when doing a signed to signed conversion, warn if the positive
9902     // source value is exactly the width of the target type, which will
9903     // cause a negative value to be stored.
9904 
9905     llvm::APSInt Value;
9906     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9907         !S.SourceMgr.isInSystemMacro(CC)) {
9908       if (isSameWidthConstantConversion(S, E, T, CC)) {
9909         std::string PrettySourceValue = Value.toString(10);
9910         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
9911 
9912         S.DiagRuntimeBehavior(
9913             E->getExprLoc(), E,
9914             S.PDiag(diag::warn_impcast_integer_precision_constant)
9915                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
9916                 << E->getSourceRange() << clang::SourceRange(CC));
9917         return;
9918       }
9919     }
9920 
9921     // Fall through for non-constants to give a sign conversion warning.
9922   }
9923 
9924   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9925       (!TargetRange.NonNegative && SourceRange.NonNegative &&
9926        SourceRange.Width == TargetRange.Width)) {
9927     if (S.SourceMgr.isInSystemMacro(CC))
9928       return;
9929 
9930     unsigned DiagID = diag::warn_impcast_integer_sign;
9931 
9932     // Traditionally, gcc has warned about this under -Wsign-compare.
9933     // We also want to warn about it in -Wconversion.
9934     // So if -Wconversion is off, use a completely identical diagnostic
9935     // in the sign-compare group.
9936     // The conditional-checking code will
9937     if (ICContext) {
9938       DiagID = diag::warn_impcast_integer_sign_conditional;
9939       *ICContext = true;
9940     }
9941 
9942     return DiagnoseImpCast(S, E, T, CC, DiagID);
9943   }
9944 
9945   // Diagnose conversions between different enumeration types.
9946   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9947   // type, to give us better diagnostics.
9948   QualType SourceType = E->getType();
9949   if (!S.getLangOpts().CPlusPlus) {
9950     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9951       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9952         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9953         SourceType = S.Context.getTypeDeclType(Enum);
9954         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9955       }
9956   }
9957 
9958   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9959     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
9960       if (SourceEnum->getDecl()->hasNameForLinkage() &&
9961           TargetEnum->getDecl()->hasNameForLinkage() &&
9962           SourceEnum != TargetEnum) {
9963         if (S.SourceMgr.isInSystemMacro(CC))
9964           return;
9965 
9966         return DiagnoseImpCast(S, E, SourceType, T, CC,
9967                                diag::warn_impcast_different_enum_types);
9968       }
9969 }
9970 
9971 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9972                                      SourceLocation CC, QualType T);
9973 
9974 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
9975                                     SourceLocation CC, bool &ICContext) {
9976   E = E->IgnoreParenImpCasts();
9977 
9978   if (isa<ConditionalOperator>(E))
9979     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
9980 
9981   AnalyzeImplicitConversions(S, E, CC);
9982   if (E->getType() != T)
9983     return CheckImplicitConversion(S, E, T, CC, &ICContext);
9984 }
9985 
9986 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9987                                      SourceLocation CC, QualType T) {
9988   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
9989 
9990   bool Suspicious = false;
9991   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9992   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
9993 
9994   // If -Wconversion would have warned about either of the candidates
9995   // for a signedness conversion to the context type...
9996   if (!Suspicious) return;
9997 
9998   // ...but it's currently ignored...
9999   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
10000     return;
10001 
10002   // ...then check whether it would have warned about either of the
10003   // candidates for a signedness conversion to the condition type.
10004   if (E->getType() == T) return;
10005 
10006   Suspicious = false;
10007   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
10008                           E->getType(), CC, &Suspicious);
10009   if (!Suspicious)
10010     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
10011                             E->getType(), CC, &Suspicious);
10012 }
10013 
10014 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10015 /// Input argument E is a logical expression.
10016 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
10017   if (S.getLangOpts().Bool)
10018     return;
10019   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
10020 }
10021 
10022 /// AnalyzeImplicitConversions - Find and report any interesting
10023 /// implicit conversions in the given expression.  There are a couple
10024 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
10025 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
10026                                        SourceLocation CC) {
10027   QualType T = OrigE->getType();
10028   Expr *E = OrigE->IgnoreParenImpCasts();
10029 
10030   if (E->isTypeDependent() || E->isValueDependent())
10031     return;
10032 
10033   // For conditional operators, we analyze the arguments as if they
10034   // were being fed directly into the output.
10035   if (isa<ConditionalOperator>(E)) {
10036     ConditionalOperator *CO = cast<ConditionalOperator>(E);
10037     CheckConditionalOperator(S, CO, CC, T);
10038     return;
10039   }
10040 
10041   // Check implicit argument conversions for function calls.
10042   if (CallExpr *Call = dyn_cast<CallExpr>(E))
10043     CheckImplicitArgumentConversions(S, Call, CC);
10044 
10045   // Go ahead and check any implicit conversions we might have skipped.
10046   // The non-canonical typecheck is just an optimization;
10047   // CheckImplicitConversion will filter out dead implicit conversions.
10048   if (E->getType() != T)
10049     CheckImplicitConversion(S, E, T, CC);
10050 
10051   // Now continue drilling into this expression.
10052 
10053   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
10054     // The bound subexpressions in a PseudoObjectExpr are not reachable
10055     // as transitive children.
10056     // FIXME: Use a more uniform representation for this.
10057     for (auto *SE : POE->semantics())
10058       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
10059         AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
10060   }
10061 
10062   // Skip past explicit casts.
10063   if (isa<ExplicitCastExpr>(E)) {
10064     E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
10065     return AnalyzeImplicitConversions(S, E, CC);
10066   }
10067 
10068   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10069     // Do a somewhat different check with comparison operators.
10070     if (BO->isComparisonOp())
10071       return AnalyzeComparison(S, BO);
10072 
10073     // And with simple assignments.
10074     if (BO->getOpcode() == BO_Assign)
10075       return AnalyzeAssignment(S, BO);
10076     // And with compound assignments.
10077     if (BO->isAssignmentOp())
10078       return AnalyzeCompoundAssignment(S, BO);
10079   }
10080 
10081   // These break the otherwise-useful invariant below.  Fortunately,
10082   // we don't really need to recurse into them, because any internal
10083   // expressions should have been analyzed already when they were
10084   // built into statements.
10085   if (isa<StmtExpr>(E)) return;
10086 
10087   // Don't descend into unevaluated contexts.
10088   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
10089 
10090   // Now just recurse over the expression's children.
10091   CC = E->getExprLoc();
10092   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
10093   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
10094   for (Stmt *SubStmt : E->children()) {
10095     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
10096     if (!ChildExpr)
10097       continue;
10098 
10099     if (IsLogicalAndOperator &&
10100         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
10101       // Ignore checking string literals that are in logical and operators.
10102       // This is a common pattern for asserts.
10103       continue;
10104     AnalyzeImplicitConversions(S, ChildExpr, CC);
10105   }
10106 
10107   if (BO && BO->isLogicalOp()) {
10108     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
10109     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
10110       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
10111 
10112     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
10113     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
10114       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
10115   }
10116 
10117   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
10118     if (U->getOpcode() == UO_LNot)
10119       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
10120 }
10121 
10122 /// Diagnose integer type and any valid implicit conversion to it.
10123 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
10124   // Taking into account implicit conversions,
10125   // allow any integer.
10126   if (!E->getType()->isIntegerType()) {
10127     S.Diag(E->getLocStart(),
10128            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
10129     return true;
10130   }
10131   // Potentially emit standard warnings for implicit conversions if enabled
10132   // using -Wconversion.
10133   CheckImplicitConversion(S, E, IntT, E->getLocStart());
10134   return false;
10135 }
10136 
10137 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
10138 // Returns true when emitting a warning about taking the address of a reference.
10139 static bool CheckForReference(Sema &SemaRef, const Expr *E,
10140                               const PartialDiagnostic &PD) {
10141   E = E->IgnoreParenImpCasts();
10142 
10143   const FunctionDecl *FD = nullptr;
10144 
10145   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10146     if (!DRE->getDecl()->getType()->isReferenceType())
10147       return false;
10148   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10149     if (!M->getMemberDecl()->getType()->isReferenceType())
10150       return false;
10151   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
10152     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
10153       return false;
10154     FD = Call->getDirectCallee();
10155   } else {
10156     return false;
10157   }
10158 
10159   SemaRef.Diag(E->getExprLoc(), PD);
10160 
10161   // If possible, point to location of function.
10162   if (FD) {
10163     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
10164   }
10165 
10166   return true;
10167 }
10168 
10169 // Returns true if the SourceLocation is expanded from any macro body.
10170 // Returns false if the SourceLocation is invalid, is from not in a macro
10171 // expansion, or is from expanded from a top-level macro argument.
10172 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
10173   if (Loc.isInvalid())
10174     return false;
10175 
10176   while (Loc.isMacroID()) {
10177     if (SM.isMacroBodyExpansion(Loc))
10178       return true;
10179     Loc = SM.getImmediateMacroCallerLoc(Loc);
10180   }
10181 
10182   return false;
10183 }
10184 
10185 /// \brief Diagnose pointers that are always non-null.
10186 /// \param E the expression containing the pointer
10187 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
10188 /// compared to a null pointer
10189 /// \param IsEqual True when the comparison is equal to a null pointer
10190 /// \param Range Extra SourceRange to highlight in the diagnostic
10191 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
10192                                         Expr::NullPointerConstantKind NullKind,
10193                                         bool IsEqual, SourceRange Range) {
10194   if (!E)
10195     return;
10196 
10197   // Don't warn inside macros.
10198   if (E->getExprLoc().isMacroID()) {
10199     const SourceManager &SM = getSourceManager();
10200     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
10201         IsInAnyMacroBody(SM, Range.getBegin()))
10202       return;
10203   }
10204   E = E->IgnoreImpCasts();
10205 
10206   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
10207 
10208   if (isa<CXXThisExpr>(E)) {
10209     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
10210                                 : diag::warn_this_bool_conversion;
10211     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
10212     return;
10213   }
10214 
10215   bool IsAddressOf = false;
10216 
10217   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10218     if (UO->getOpcode() != UO_AddrOf)
10219       return;
10220     IsAddressOf = true;
10221     E = UO->getSubExpr();
10222   }
10223 
10224   if (IsAddressOf) {
10225     unsigned DiagID = IsCompare
10226                           ? diag::warn_address_of_reference_null_compare
10227                           : diag::warn_address_of_reference_bool_conversion;
10228     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
10229                                          << IsEqual;
10230     if (CheckForReference(*this, E, PD)) {
10231       return;
10232     }
10233   }
10234 
10235   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
10236     bool IsParam = isa<NonNullAttr>(NonnullAttr);
10237     std::string Str;
10238     llvm::raw_string_ostream S(Str);
10239     E->printPretty(S, nullptr, getPrintingPolicy());
10240     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
10241                                 : diag::warn_cast_nonnull_to_bool;
10242     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
10243       << E->getSourceRange() << Range << IsEqual;
10244     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
10245   };
10246 
10247   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
10248   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
10249     if (auto *Callee = Call->getDirectCallee()) {
10250       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
10251         ComplainAboutNonnullParamOrCall(A);
10252         return;
10253       }
10254     }
10255   }
10256 
10257   // Expect to find a single Decl.  Skip anything more complicated.
10258   ValueDecl *D = nullptr;
10259   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
10260     D = R->getDecl();
10261   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10262     D = M->getMemberDecl();
10263   }
10264 
10265   // Weak Decls can be null.
10266   if (!D || D->isWeak())
10267     return;
10268 
10269   // Check for parameter decl with nonnull attribute
10270   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
10271     if (getCurFunction() &&
10272         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
10273       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
10274         ComplainAboutNonnullParamOrCall(A);
10275         return;
10276       }
10277 
10278       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
10279         auto ParamIter = llvm::find(FD->parameters(), PV);
10280         assert(ParamIter != FD->param_end());
10281         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
10282 
10283         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
10284           if (!NonNull->args_size()) {
10285               ComplainAboutNonnullParamOrCall(NonNull);
10286               return;
10287           }
10288 
10289           for (const ParamIdx &ArgNo : NonNull->args()) {
10290             if (ArgNo.getASTIndex() == ParamNo) {
10291               ComplainAboutNonnullParamOrCall(NonNull);
10292               return;
10293             }
10294           }
10295         }
10296       }
10297     }
10298   }
10299 
10300   QualType T = D->getType();
10301   const bool IsArray = T->isArrayType();
10302   const bool IsFunction = T->isFunctionType();
10303 
10304   // Address of function is used to silence the function warning.
10305   if (IsAddressOf && IsFunction) {
10306     return;
10307   }
10308 
10309   // Found nothing.
10310   if (!IsAddressOf && !IsFunction && !IsArray)
10311     return;
10312 
10313   // Pretty print the expression for the diagnostic.
10314   std::string Str;
10315   llvm::raw_string_ostream S(Str);
10316   E->printPretty(S, nullptr, getPrintingPolicy());
10317 
10318   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
10319                               : diag::warn_impcast_pointer_to_bool;
10320   enum {
10321     AddressOf,
10322     FunctionPointer,
10323     ArrayPointer
10324   } DiagType;
10325   if (IsAddressOf)
10326     DiagType = AddressOf;
10327   else if (IsFunction)
10328     DiagType = FunctionPointer;
10329   else if (IsArray)
10330     DiagType = ArrayPointer;
10331   else
10332     llvm_unreachable("Could not determine diagnostic.");
10333   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
10334                                 << Range << IsEqual;
10335 
10336   if (!IsFunction)
10337     return;
10338 
10339   // Suggest '&' to silence the function warning.
10340   Diag(E->getExprLoc(), diag::note_function_warning_silence)
10341       << FixItHint::CreateInsertion(E->getLocStart(), "&");
10342 
10343   // Check to see if '()' fixit should be emitted.
10344   QualType ReturnType;
10345   UnresolvedSet<4> NonTemplateOverloads;
10346   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
10347   if (ReturnType.isNull())
10348     return;
10349 
10350   if (IsCompare) {
10351     // There are two cases here.  If there is null constant, the only suggest
10352     // for a pointer return type.  If the null is 0, then suggest if the return
10353     // type is a pointer or an integer type.
10354     if (!ReturnType->isPointerType()) {
10355       if (NullKind == Expr::NPCK_ZeroExpression ||
10356           NullKind == Expr::NPCK_ZeroLiteral) {
10357         if (!ReturnType->isIntegerType())
10358           return;
10359       } else {
10360         return;
10361       }
10362     }
10363   } else { // !IsCompare
10364     // For function to bool, only suggest if the function pointer has bool
10365     // return type.
10366     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
10367       return;
10368   }
10369   Diag(E->getExprLoc(), diag::note_function_to_function_call)
10370       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
10371 }
10372 
10373 /// Diagnoses "dangerous" implicit conversions within the given
10374 /// expression (which is a full expression).  Implements -Wconversion
10375 /// and -Wsign-compare.
10376 ///
10377 /// \param CC the "context" location of the implicit conversion, i.e.
10378 ///   the most location of the syntactic entity requiring the implicit
10379 ///   conversion
10380 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
10381   // Don't diagnose in unevaluated contexts.
10382   if (isUnevaluatedContext())
10383     return;
10384 
10385   // Don't diagnose for value- or type-dependent expressions.
10386   if (E->isTypeDependent() || E->isValueDependent())
10387     return;
10388 
10389   // Check for array bounds violations in cases where the check isn't triggered
10390   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
10391   // ArraySubscriptExpr is on the RHS of a variable initialization.
10392   CheckArrayAccess(E);
10393 
10394   // This is not the right CC for (e.g.) a variable initialization.
10395   AnalyzeImplicitConversions(*this, E, CC);
10396 }
10397 
10398 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10399 /// Input argument E is a logical expression.
10400 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
10401   ::CheckBoolLikeConversion(*this, E, CC);
10402 }
10403 
10404 /// Diagnose when expression is an integer constant expression and its evaluation
10405 /// results in integer overflow
10406 void Sema::CheckForIntOverflow (Expr *E) {
10407   // Use a work list to deal with nested struct initializers.
10408   SmallVector<Expr *, 2> Exprs(1, E);
10409 
10410   do {
10411     Expr *OriginalE = Exprs.pop_back_val();
10412     Expr *E = OriginalE->IgnoreParenCasts();
10413 
10414     if (isa<BinaryOperator>(E)) {
10415       E->EvaluateForOverflow(Context);
10416       continue;
10417     }
10418 
10419     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
10420       Exprs.append(InitList->inits().begin(), InitList->inits().end());
10421     else if (isa<ObjCBoxedExpr>(OriginalE))
10422       E->EvaluateForOverflow(Context);
10423     else if (auto Call = dyn_cast<CallExpr>(E))
10424       Exprs.append(Call->arg_begin(), Call->arg_end());
10425     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
10426       Exprs.append(Message->arg_begin(), Message->arg_end());
10427   } while (!Exprs.empty());
10428 }
10429 
10430 namespace {
10431 
10432 /// \brief Visitor for expressions which looks for unsequenced operations on the
10433 /// same object.
10434 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
10435   using Base = EvaluatedExprVisitor<SequenceChecker>;
10436 
10437   /// \brief A tree of sequenced regions within an expression. Two regions are
10438   /// unsequenced if one is an ancestor or a descendent of the other. When we
10439   /// finish processing an expression with sequencing, such as a comma
10440   /// expression, we fold its tree nodes into its parent, since they are
10441   /// unsequenced with respect to nodes we will visit later.
10442   class SequenceTree {
10443     struct Value {
10444       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
10445       unsigned Parent : 31;
10446       unsigned Merged : 1;
10447     };
10448     SmallVector<Value, 8> Values;
10449 
10450   public:
10451     /// \brief A region within an expression which may be sequenced with respect
10452     /// to some other region.
10453     class Seq {
10454       friend class SequenceTree;
10455 
10456       unsigned Index = 0;
10457 
10458       explicit Seq(unsigned N) : Index(N) {}
10459 
10460     public:
10461       Seq() = default;
10462     };
10463 
10464     SequenceTree() { Values.push_back(Value(0)); }
10465     Seq root() const { return Seq(0); }
10466 
10467     /// \brief Create a new sequence of operations, which is an unsequenced
10468     /// subset of \p Parent. This sequence of operations is sequenced with
10469     /// respect to other children of \p Parent.
10470     Seq allocate(Seq Parent) {
10471       Values.push_back(Value(Parent.Index));
10472       return Seq(Values.size() - 1);
10473     }
10474 
10475     /// \brief Merge a sequence of operations into its parent.
10476     void merge(Seq S) {
10477       Values[S.Index].Merged = true;
10478     }
10479 
10480     /// \brief Determine whether two operations are unsequenced. This operation
10481     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
10482     /// should have been merged into its parent as appropriate.
10483     bool isUnsequenced(Seq Cur, Seq Old) {
10484       unsigned C = representative(Cur.Index);
10485       unsigned Target = representative(Old.Index);
10486       while (C >= Target) {
10487         if (C == Target)
10488           return true;
10489         C = Values[C].Parent;
10490       }
10491       return false;
10492     }
10493 
10494   private:
10495     /// \brief Pick a representative for a sequence.
10496     unsigned representative(unsigned K) {
10497       if (Values[K].Merged)
10498         // Perform path compression as we go.
10499         return Values[K].Parent = representative(Values[K].Parent);
10500       return K;
10501     }
10502   };
10503 
10504   /// An object for which we can track unsequenced uses.
10505   using Object = NamedDecl *;
10506 
10507   /// Different flavors of object usage which we track. We only track the
10508   /// least-sequenced usage of each kind.
10509   enum UsageKind {
10510     /// A read of an object. Multiple unsequenced reads are OK.
10511     UK_Use,
10512 
10513     /// A modification of an object which is sequenced before the value
10514     /// computation of the expression, such as ++n in C++.
10515     UK_ModAsValue,
10516 
10517     /// A modification of an object which is not sequenced before the value
10518     /// computation of the expression, such as n++.
10519     UK_ModAsSideEffect,
10520 
10521     UK_Count = UK_ModAsSideEffect + 1
10522   };
10523 
10524   struct Usage {
10525     Expr *Use = nullptr;
10526     SequenceTree::Seq Seq;
10527 
10528     Usage() = default;
10529   };
10530 
10531   struct UsageInfo {
10532     Usage Uses[UK_Count];
10533 
10534     /// Have we issued a diagnostic for this variable already?
10535     bool Diagnosed = false;
10536 
10537     UsageInfo() = default;
10538   };
10539   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
10540 
10541   Sema &SemaRef;
10542 
10543   /// Sequenced regions within the expression.
10544   SequenceTree Tree;
10545 
10546   /// Declaration modifications and references which we have seen.
10547   UsageInfoMap UsageMap;
10548 
10549   /// The region we are currently within.
10550   SequenceTree::Seq Region;
10551 
10552   /// Filled in with declarations which were modified as a side-effect
10553   /// (that is, post-increment operations).
10554   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
10555 
10556   /// Expressions to check later. We defer checking these to reduce
10557   /// stack usage.
10558   SmallVectorImpl<Expr *> &WorkList;
10559 
10560   /// RAII object wrapping the visitation of a sequenced subexpression of an
10561   /// expression. At the end of this process, the side-effects of the evaluation
10562   /// become sequenced with respect to the value computation of the result, so
10563   /// we downgrade any UK_ModAsSideEffect within the evaluation to
10564   /// UK_ModAsValue.
10565   struct SequencedSubexpression {
10566     SequencedSubexpression(SequenceChecker &Self)
10567       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
10568       Self.ModAsSideEffect = &ModAsSideEffect;
10569     }
10570 
10571     ~SequencedSubexpression() {
10572       for (auto &M : llvm::reverse(ModAsSideEffect)) {
10573         UsageInfo &U = Self.UsageMap[M.first];
10574         auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
10575         Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
10576         SideEffectUsage = M.second;
10577       }
10578       Self.ModAsSideEffect = OldModAsSideEffect;
10579     }
10580 
10581     SequenceChecker &Self;
10582     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
10583     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
10584   };
10585 
10586   /// RAII object wrapping the visitation of a subexpression which we might
10587   /// choose to evaluate as a constant. If any subexpression is evaluated and
10588   /// found to be non-constant, this allows us to suppress the evaluation of
10589   /// the outer expression.
10590   class EvaluationTracker {
10591   public:
10592     EvaluationTracker(SequenceChecker &Self)
10593         : Self(Self), Prev(Self.EvalTracker) {
10594       Self.EvalTracker = this;
10595     }
10596 
10597     ~EvaluationTracker() {
10598       Self.EvalTracker = Prev;
10599       if (Prev)
10600         Prev->EvalOK &= EvalOK;
10601     }
10602 
10603     bool evaluate(const Expr *E, bool &Result) {
10604       if (!EvalOK || E->isValueDependent())
10605         return false;
10606       EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
10607       return EvalOK;
10608     }
10609 
10610   private:
10611     SequenceChecker &Self;
10612     EvaluationTracker *Prev;
10613     bool EvalOK = true;
10614   } *EvalTracker = nullptr;
10615 
10616   /// \brief Find the object which is produced by the specified expression,
10617   /// if any.
10618   Object getObject(Expr *E, bool Mod) const {
10619     E = E->IgnoreParenCasts();
10620     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10621       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
10622         return getObject(UO->getSubExpr(), Mod);
10623     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10624       if (BO->getOpcode() == BO_Comma)
10625         return getObject(BO->getRHS(), Mod);
10626       if (Mod && BO->isAssignmentOp())
10627         return getObject(BO->getLHS(), Mod);
10628     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10629       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
10630       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
10631         return ME->getMemberDecl();
10632     } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10633       // FIXME: If this is a reference, map through to its value.
10634       return DRE->getDecl();
10635     return nullptr;
10636   }
10637 
10638   /// \brief Note that an object was modified or used by an expression.
10639   void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
10640     Usage &U = UI.Uses[UK];
10641     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
10642       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
10643         ModAsSideEffect->push_back(std::make_pair(O, U));
10644       U.Use = Ref;
10645       U.Seq = Region;
10646     }
10647   }
10648 
10649   /// \brief Check whether a modification or use conflicts with a prior usage.
10650   void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
10651                   bool IsModMod) {
10652     if (UI.Diagnosed)
10653       return;
10654 
10655     const Usage &U = UI.Uses[OtherKind];
10656     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
10657       return;
10658 
10659     Expr *Mod = U.Use;
10660     Expr *ModOrUse = Ref;
10661     if (OtherKind == UK_Use)
10662       std::swap(Mod, ModOrUse);
10663 
10664     SemaRef.Diag(Mod->getExprLoc(),
10665                  IsModMod ? diag::warn_unsequenced_mod_mod
10666                           : diag::warn_unsequenced_mod_use)
10667       << O << SourceRange(ModOrUse->getExprLoc());
10668     UI.Diagnosed = true;
10669   }
10670 
10671   void notePreUse(Object O, Expr *Use) {
10672     UsageInfo &U = UsageMap[O];
10673     // Uses conflict with other modifications.
10674     checkUsage(O, U, Use, UK_ModAsValue, false);
10675   }
10676 
10677   void notePostUse(Object O, Expr *Use) {
10678     UsageInfo &U = UsageMap[O];
10679     checkUsage(O, U, Use, UK_ModAsSideEffect, false);
10680     addUsage(U, O, Use, UK_Use);
10681   }
10682 
10683   void notePreMod(Object O, Expr *Mod) {
10684     UsageInfo &U = UsageMap[O];
10685     // Modifications conflict with other modifications and with uses.
10686     checkUsage(O, U, Mod, UK_ModAsValue, true);
10687     checkUsage(O, U, Mod, UK_Use, false);
10688   }
10689 
10690   void notePostMod(Object O, Expr *Use, UsageKind UK) {
10691     UsageInfo &U = UsageMap[O];
10692     checkUsage(O, U, Use, UK_ModAsSideEffect, true);
10693     addUsage(U, O, Use, UK);
10694   }
10695 
10696 public:
10697   SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
10698       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
10699     Visit(E);
10700   }
10701 
10702   void VisitStmt(Stmt *S) {
10703     // Skip all statements which aren't expressions for now.
10704   }
10705 
10706   void VisitExpr(Expr *E) {
10707     // By default, just recurse to evaluated subexpressions.
10708     Base::VisitStmt(E);
10709   }
10710 
10711   void VisitCastExpr(CastExpr *E) {
10712     Object O = Object();
10713     if (E->getCastKind() == CK_LValueToRValue)
10714       O = getObject(E->getSubExpr(), false);
10715 
10716     if (O)
10717       notePreUse(O, E);
10718     VisitExpr(E);
10719     if (O)
10720       notePostUse(O, E);
10721   }
10722 
10723   void VisitBinComma(BinaryOperator *BO) {
10724     // C++11 [expr.comma]p1:
10725     //   Every value computation and side effect associated with the left
10726     //   expression is sequenced before every value computation and side
10727     //   effect associated with the right expression.
10728     SequenceTree::Seq LHS = Tree.allocate(Region);
10729     SequenceTree::Seq RHS = Tree.allocate(Region);
10730     SequenceTree::Seq OldRegion = Region;
10731 
10732     {
10733       SequencedSubexpression SeqLHS(*this);
10734       Region = LHS;
10735       Visit(BO->getLHS());
10736     }
10737 
10738     Region = RHS;
10739     Visit(BO->getRHS());
10740 
10741     Region = OldRegion;
10742 
10743     // Forget that LHS and RHS are sequenced. They are both unsequenced
10744     // with respect to other stuff.
10745     Tree.merge(LHS);
10746     Tree.merge(RHS);
10747   }
10748 
10749   void VisitBinAssign(BinaryOperator *BO) {
10750     // The modification is sequenced after the value computation of the LHS
10751     // and RHS, so check it before inspecting the operands and update the
10752     // map afterwards.
10753     Object O = getObject(BO->getLHS(), true);
10754     if (!O)
10755       return VisitExpr(BO);
10756 
10757     notePreMod(O, BO);
10758 
10759     // C++11 [expr.ass]p7:
10760     //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
10761     //   only once.
10762     //
10763     // Therefore, for a compound assignment operator, O is considered used
10764     // everywhere except within the evaluation of E1 itself.
10765     if (isa<CompoundAssignOperator>(BO))
10766       notePreUse(O, BO);
10767 
10768     Visit(BO->getLHS());
10769 
10770     if (isa<CompoundAssignOperator>(BO))
10771       notePostUse(O, BO);
10772 
10773     Visit(BO->getRHS());
10774 
10775     // C++11 [expr.ass]p1:
10776     //   the assignment is sequenced [...] before the value computation of the
10777     //   assignment expression.
10778     // C11 6.5.16/3 has no such rule.
10779     notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10780                                                        : UK_ModAsSideEffect);
10781   }
10782 
10783   void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
10784     VisitBinAssign(CAO);
10785   }
10786 
10787   void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10788   void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10789   void VisitUnaryPreIncDec(UnaryOperator *UO) {
10790     Object O = getObject(UO->getSubExpr(), true);
10791     if (!O)
10792       return VisitExpr(UO);
10793 
10794     notePreMod(O, UO);
10795     Visit(UO->getSubExpr());
10796     // C++11 [expr.pre.incr]p1:
10797     //   the expression ++x is equivalent to x+=1
10798     notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10799                                                        : UK_ModAsSideEffect);
10800   }
10801 
10802   void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10803   void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10804   void VisitUnaryPostIncDec(UnaryOperator *UO) {
10805     Object O = getObject(UO->getSubExpr(), true);
10806     if (!O)
10807       return VisitExpr(UO);
10808 
10809     notePreMod(O, UO);
10810     Visit(UO->getSubExpr());
10811     notePostMod(O, UO, UK_ModAsSideEffect);
10812   }
10813 
10814   /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
10815   void VisitBinLOr(BinaryOperator *BO) {
10816     // The side-effects of the LHS of an '&&' are sequenced before the
10817     // value computation of the RHS, and hence before the value computation
10818     // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10819     // as if they were unconditionally sequenced.
10820     EvaluationTracker Eval(*this);
10821     {
10822       SequencedSubexpression Sequenced(*this);
10823       Visit(BO->getLHS());
10824     }
10825 
10826     bool Result;
10827     if (Eval.evaluate(BO->getLHS(), Result)) {
10828       if (!Result)
10829         Visit(BO->getRHS());
10830     } else {
10831       // Check for unsequenced operations in the RHS, treating it as an
10832       // entirely separate evaluation.
10833       //
10834       // FIXME: If there are operations in the RHS which are unsequenced
10835       // with respect to operations outside the RHS, and those operations
10836       // are unconditionally evaluated, diagnose them.
10837       WorkList.push_back(BO->getRHS());
10838     }
10839   }
10840   void VisitBinLAnd(BinaryOperator *BO) {
10841     EvaluationTracker Eval(*this);
10842     {
10843       SequencedSubexpression Sequenced(*this);
10844       Visit(BO->getLHS());
10845     }
10846 
10847     bool Result;
10848     if (Eval.evaluate(BO->getLHS(), Result)) {
10849       if (Result)
10850         Visit(BO->getRHS());
10851     } else {
10852       WorkList.push_back(BO->getRHS());
10853     }
10854   }
10855 
10856   // Only visit the condition, unless we can be sure which subexpression will
10857   // be chosen.
10858   void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
10859     EvaluationTracker Eval(*this);
10860     {
10861       SequencedSubexpression Sequenced(*this);
10862       Visit(CO->getCond());
10863     }
10864 
10865     bool Result;
10866     if (Eval.evaluate(CO->getCond(), Result))
10867       Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
10868     else {
10869       WorkList.push_back(CO->getTrueExpr());
10870       WorkList.push_back(CO->getFalseExpr());
10871     }
10872   }
10873 
10874   void VisitCallExpr(CallExpr *CE) {
10875     // C++11 [intro.execution]p15:
10876     //   When calling a function [...], every value computation and side effect
10877     //   associated with any argument expression, or with the postfix expression
10878     //   designating the called function, is sequenced before execution of every
10879     //   expression or statement in the body of the function [and thus before
10880     //   the value computation of its result].
10881     SequencedSubexpression Sequenced(*this);
10882     Base::VisitCallExpr(CE);
10883 
10884     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10885   }
10886 
10887   void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
10888     // This is a call, so all subexpressions are sequenced before the result.
10889     SequencedSubexpression Sequenced(*this);
10890 
10891     if (!CCE->isListInitialization())
10892       return VisitExpr(CCE);
10893 
10894     // In C++11, list initializations are sequenced.
10895     SmallVector<SequenceTree::Seq, 32> Elts;
10896     SequenceTree::Seq Parent = Region;
10897     for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10898                                         E = CCE->arg_end();
10899          I != E; ++I) {
10900       Region = Tree.allocate(Parent);
10901       Elts.push_back(Region);
10902       Visit(*I);
10903     }
10904 
10905     // Forget that the initializers are sequenced.
10906     Region = Parent;
10907     for (unsigned I = 0; I < Elts.size(); ++I)
10908       Tree.merge(Elts[I]);
10909   }
10910 
10911   void VisitInitListExpr(InitListExpr *ILE) {
10912     if (!SemaRef.getLangOpts().CPlusPlus11)
10913       return VisitExpr(ILE);
10914 
10915     // In C++11, list initializations are sequenced.
10916     SmallVector<SequenceTree::Seq, 32> Elts;
10917     SequenceTree::Seq Parent = Region;
10918     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10919       Expr *E = ILE->getInit(I);
10920       if (!E) continue;
10921       Region = Tree.allocate(Parent);
10922       Elts.push_back(Region);
10923       Visit(E);
10924     }
10925 
10926     // Forget that the initializers are sequenced.
10927     Region = Parent;
10928     for (unsigned I = 0; I < Elts.size(); ++I)
10929       Tree.merge(Elts[I]);
10930   }
10931 };
10932 
10933 } // namespace
10934 
10935 void Sema::CheckUnsequencedOperations(Expr *E) {
10936   SmallVector<Expr *, 8> WorkList;
10937   WorkList.push_back(E);
10938   while (!WorkList.empty()) {
10939     Expr *Item = WorkList.pop_back_val();
10940     SequenceChecker(*this, Item, WorkList);
10941   }
10942 }
10943 
10944 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10945                               bool IsConstexpr) {
10946   CheckImplicitConversions(E, CheckLoc);
10947   if (!E->isInstantiationDependent())
10948     CheckUnsequencedOperations(E);
10949   if (!IsConstexpr && !E->isValueDependent())
10950     CheckForIntOverflow(E);
10951   DiagnoseMisalignedMembers();
10952 }
10953 
10954 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10955                                        FieldDecl *BitField,
10956                                        Expr *Init) {
10957   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10958 }
10959 
10960 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
10961                                          SourceLocation Loc) {
10962   if (!PType->isVariablyModifiedType())
10963     return;
10964   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10965     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10966     return;
10967   }
10968   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10969     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10970     return;
10971   }
10972   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10973     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10974     return;
10975   }
10976 
10977   const ArrayType *AT = S.Context.getAsArrayType(PType);
10978   if (!AT)
10979     return;
10980 
10981   if (AT->getSizeModifier() != ArrayType::Star) {
10982     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
10983     return;
10984   }
10985 
10986   S.Diag(Loc, diag::err_array_star_in_function_definition);
10987 }
10988 
10989 /// CheckParmsForFunctionDef - Check that the parameters of the given
10990 /// function are appropriate for the definition of a function. This
10991 /// takes care of any checks that cannot be performed on the
10992 /// declaration itself, e.g., that the types of each of the function
10993 /// parameters are complete.
10994 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
10995                                     bool CheckParameterNames) {
10996   bool HasInvalidParm = false;
10997   for (ParmVarDecl *Param : Parameters) {
10998     // C99 6.7.5.3p4: the parameters in a parameter type list in a
10999     // function declarator that is part of a function definition of
11000     // that function shall not have incomplete type.
11001     //
11002     // This is also C++ [dcl.fct]p6.
11003     if (!Param->isInvalidDecl() &&
11004         RequireCompleteType(Param->getLocation(), Param->getType(),
11005                             diag::err_typecheck_decl_incomplete_type)) {
11006       Param->setInvalidDecl();
11007       HasInvalidParm = true;
11008     }
11009 
11010     // C99 6.9.1p5: If the declarator includes a parameter type list, the
11011     // declaration of each parameter shall include an identifier.
11012     if (CheckParameterNames &&
11013         Param->getIdentifier() == nullptr &&
11014         !Param->isImplicit() &&
11015         !getLangOpts().CPlusPlus)
11016       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
11017 
11018     // C99 6.7.5.3p12:
11019     //   If the function declarator is not part of a definition of that
11020     //   function, parameters may have incomplete type and may use the [*]
11021     //   notation in their sequences of declarator specifiers to specify
11022     //   variable length array types.
11023     QualType PType = Param->getOriginalType();
11024     // FIXME: This diagnostic should point the '[*]' if source-location
11025     // information is added for it.
11026     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
11027 
11028     // If the parameter is a c++ class type and it has to be destructed in the
11029     // callee function, declare the destructor so that it can be called by the
11030     // callee function. Do not perform any direct access check on the dtor here.
11031     if (!Param->isInvalidDecl()) {
11032       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
11033         if (!ClassDecl->isInvalidDecl() &&
11034             !ClassDecl->hasIrrelevantDestructor() &&
11035             !ClassDecl->isDependentContext() &&
11036             Context.isParamDestroyedInCallee(Param->getType())) {
11037           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
11038           MarkFunctionReferenced(Param->getLocation(), Destructor);
11039           DiagnoseUseOfDecl(Destructor, Param->getLocation());
11040         }
11041       }
11042     }
11043 
11044     // Parameters with the pass_object_size attribute only need to be marked
11045     // constant at function definitions. Because we lack information about
11046     // whether we're on a declaration or definition when we're instantiating the
11047     // attribute, we need to check for constness here.
11048     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
11049       if (!Param->getType().isConstQualified())
11050         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
11051             << Attr->getSpelling() << 1;
11052   }
11053 
11054   return HasInvalidParm;
11055 }
11056 
11057 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
11058 /// or MemberExpr.
11059 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
11060                               ASTContext &Context) {
11061   if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
11062     return Context.getDeclAlign(DRE->getDecl());
11063 
11064   if (const auto *ME = dyn_cast<MemberExpr>(E))
11065     return Context.getDeclAlign(ME->getMemberDecl());
11066 
11067   return TypeAlign;
11068 }
11069 
11070 /// CheckCastAlign - Implements -Wcast-align, which warns when a
11071 /// pointer cast increases the alignment requirements.
11072 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
11073   // This is actually a lot of work to potentially be doing on every
11074   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
11075   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
11076     return;
11077 
11078   // Ignore dependent types.
11079   if (T->isDependentType() || Op->getType()->isDependentType())
11080     return;
11081 
11082   // Require that the destination be a pointer type.
11083   const PointerType *DestPtr = T->getAs<PointerType>();
11084   if (!DestPtr) return;
11085 
11086   // If the destination has alignment 1, we're done.
11087   QualType DestPointee = DestPtr->getPointeeType();
11088   if (DestPointee->isIncompleteType()) return;
11089   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
11090   if (DestAlign.isOne()) return;
11091 
11092   // Require that the source be a pointer type.
11093   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
11094   if (!SrcPtr) return;
11095   QualType SrcPointee = SrcPtr->getPointeeType();
11096 
11097   // Whitelist casts from cv void*.  We already implicitly
11098   // whitelisted casts to cv void*, since they have alignment 1.
11099   // Also whitelist casts involving incomplete types, which implicitly
11100   // includes 'void'.
11101   if (SrcPointee->isIncompleteType()) return;
11102 
11103   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
11104 
11105   if (auto *CE = dyn_cast<CastExpr>(Op)) {
11106     if (CE->getCastKind() == CK_ArrayToPointerDecay)
11107       SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
11108   } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
11109     if (UO->getOpcode() == UO_AddrOf)
11110       SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
11111   }
11112 
11113   if (SrcAlign >= DestAlign) return;
11114 
11115   Diag(TRange.getBegin(), diag::warn_cast_align)
11116     << Op->getType() << T
11117     << static_cast<unsigned>(SrcAlign.getQuantity())
11118     << static_cast<unsigned>(DestAlign.getQuantity())
11119     << TRange << Op->getSourceRange();
11120 }
11121 
11122 /// \brief Check whether this array fits the idiom of a size-one tail padded
11123 /// array member of a struct.
11124 ///
11125 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
11126 /// commonly used to emulate flexible arrays in C89 code.
11127 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
11128                                     const NamedDecl *ND) {
11129   if (Size != 1 || !ND) return false;
11130 
11131   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
11132   if (!FD) return false;
11133 
11134   // Don't consider sizes resulting from macro expansions or template argument
11135   // substitution to form C89 tail-padded arrays.
11136 
11137   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
11138   while (TInfo) {
11139     TypeLoc TL = TInfo->getTypeLoc();
11140     // Look through typedefs.
11141     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
11142       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
11143       TInfo = TDL->getTypeSourceInfo();
11144       continue;
11145     }
11146     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
11147       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
11148       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
11149         return false;
11150     }
11151     break;
11152   }
11153 
11154   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
11155   if (!RD) return false;
11156   if (RD->isUnion()) return false;
11157   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
11158     if (!CRD->isStandardLayout()) return false;
11159   }
11160 
11161   // See if this is the last field decl in the record.
11162   const Decl *D = FD;
11163   while ((D = D->getNextDeclInContext()))
11164     if (isa<FieldDecl>(D))
11165       return false;
11166   return true;
11167 }
11168 
11169 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
11170                             const ArraySubscriptExpr *ASE,
11171                             bool AllowOnePastEnd, bool IndexNegated) {
11172   IndexExpr = IndexExpr->IgnoreParenImpCasts();
11173   if (IndexExpr->isValueDependent())
11174     return;
11175 
11176   const Type *EffectiveType =
11177       BaseExpr->getType()->getPointeeOrArrayElementType();
11178   BaseExpr = BaseExpr->IgnoreParenCasts();
11179   const ConstantArrayType *ArrayTy =
11180     Context.getAsConstantArrayType(BaseExpr->getType());
11181   if (!ArrayTy)
11182     return;
11183 
11184   llvm::APSInt index;
11185   if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
11186     return;
11187   if (IndexNegated)
11188     index = -index;
11189 
11190   const NamedDecl *ND = nullptr;
11191   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
11192     ND = DRE->getDecl();
11193   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
11194     ND = ME->getMemberDecl();
11195 
11196   if (index.isUnsigned() || !index.isNegative()) {
11197     llvm::APInt size = ArrayTy->getSize();
11198     if (!size.isStrictlyPositive())
11199       return;
11200 
11201     const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
11202     if (BaseType != EffectiveType) {
11203       // Make sure we're comparing apples to apples when comparing index to size
11204       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
11205       uint64_t array_typesize = Context.getTypeSize(BaseType);
11206       // Handle ptrarith_typesize being zero, such as when casting to void*
11207       if (!ptrarith_typesize) ptrarith_typesize = 1;
11208       if (ptrarith_typesize != array_typesize) {
11209         // There's a cast to a different size type involved
11210         uint64_t ratio = array_typesize / ptrarith_typesize;
11211         // TODO: Be smarter about handling cases where array_typesize is not a
11212         // multiple of ptrarith_typesize
11213         if (ptrarith_typesize * ratio == array_typesize)
11214           size *= llvm::APInt(size.getBitWidth(), ratio);
11215       }
11216     }
11217 
11218     if (size.getBitWidth() > index.getBitWidth())
11219       index = index.zext(size.getBitWidth());
11220     else if (size.getBitWidth() < index.getBitWidth())
11221       size = size.zext(index.getBitWidth());
11222 
11223     // For array subscripting the index must be less than size, but for pointer
11224     // arithmetic also allow the index (offset) to be equal to size since
11225     // computing the next address after the end of the array is legal and
11226     // commonly done e.g. in C++ iterators and range-based for loops.
11227     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
11228       return;
11229 
11230     // Also don't warn for arrays of size 1 which are members of some
11231     // structure. These are often used to approximate flexible arrays in C89
11232     // code.
11233     if (IsTailPaddedMemberArray(*this, size, ND))
11234       return;
11235 
11236     // Suppress the warning if the subscript expression (as identified by the
11237     // ']' location) and the index expression are both from macro expansions
11238     // within a system header.
11239     if (ASE) {
11240       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
11241           ASE->getRBracketLoc());
11242       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
11243         SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
11244             IndexExpr->getLocStart());
11245         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
11246           return;
11247       }
11248     }
11249 
11250     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
11251     if (ASE)
11252       DiagID = diag::warn_array_index_exceeds_bounds;
11253 
11254     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11255                         PDiag(DiagID) << index.toString(10, true)
11256                           << size.toString(10, true)
11257                           << (unsigned)size.getLimitedValue(~0U)
11258                           << IndexExpr->getSourceRange());
11259   } else {
11260     unsigned DiagID = diag::warn_array_index_precedes_bounds;
11261     if (!ASE) {
11262       DiagID = diag::warn_ptr_arith_precedes_bounds;
11263       if (index.isNegative()) index = -index;
11264     }
11265 
11266     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11267                         PDiag(DiagID) << index.toString(10, true)
11268                           << IndexExpr->getSourceRange());
11269   }
11270 
11271   if (!ND) {
11272     // Try harder to find a NamedDecl to point at in the note.
11273     while (const ArraySubscriptExpr *ASE =
11274            dyn_cast<ArraySubscriptExpr>(BaseExpr))
11275       BaseExpr = ASE->getBase()->IgnoreParenCasts();
11276     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
11277       ND = DRE->getDecl();
11278     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
11279       ND = ME->getMemberDecl();
11280   }
11281 
11282   if (ND)
11283     DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
11284                         PDiag(diag::note_array_index_out_of_bounds)
11285                           << ND->getDeclName());
11286 }
11287 
11288 void Sema::CheckArrayAccess(const Expr *expr) {
11289   int AllowOnePastEnd = 0;
11290   while (expr) {
11291     expr = expr->IgnoreParenImpCasts();
11292     switch (expr->getStmtClass()) {
11293       case Stmt::ArraySubscriptExprClass: {
11294         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
11295         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
11296                          AllowOnePastEnd > 0);
11297         expr = ASE->getBase();
11298         break;
11299       }
11300       case Stmt::MemberExprClass: {
11301         expr = cast<MemberExpr>(expr)->getBase();
11302         break;
11303       }
11304       case Stmt::OMPArraySectionExprClass: {
11305         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
11306         if (ASE->getLowerBound())
11307           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
11308                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
11309         return;
11310       }
11311       case Stmt::UnaryOperatorClass: {
11312         // Only unwrap the * and & unary operators
11313         const UnaryOperator *UO = cast<UnaryOperator>(expr);
11314         expr = UO->getSubExpr();
11315         switch (UO->getOpcode()) {
11316           case UO_AddrOf:
11317             AllowOnePastEnd++;
11318             break;
11319           case UO_Deref:
11320             AllowOnePastEnd--;
11321             break;
11322           default:
11323             return;
11324         }
11325         break;
11326       }
11327       case Stmt::ConditionalOperatorClass: {
11328         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
11329         if (const Expr *lhs = cond->getLHS())
11330           CheckArrayAccess(lhs);
11331         if (const Expr *rhs = cond->getRHS())
11332           CheckArrayAccess(rhs);
11333         return;
11334       }
11335       case Stmt::CXXOperatorCallExprClass: {
11336         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
11337         for (const auto *Arg : OCE->arguments())
11338           CheckArrayAccess(Arg);
11339         return;
11340       }
11341       default:
11342         return;
11343     }
11344   }
11345 }
11346 
11347 //===--- CHECK: Objective-C retain cycles ----------------------------------//
11348 
11349 namespace {
11350 
11351 struct RetainCycleOwner {
11352   VarDecl *Variable = nullptr;
11353   SourceRange Range;
11354   SourceLocation Loc;
11355   bool Indirect = false;
11356 
11357   RetainCycleOwner() = default;
11358 
11359   void setLocsFrom(Expr *e) {
11360     Loc = e->getExprLoc();
11361     Range = e->getSourceRange();
11362   }
11363 };
11364 
11365 } // namespace
11366 
11367 /// Consider whether capturing the given variable can possibly lead to
11368 /// a retain cycle.
11369 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
11370   // In ARC, it's captured strongly iff the variable has __strong
11371   // lifetime.  In MRR, it's captured strongly if the variable is
11372   // __block and has an appropriate type.
11373   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11374     return false;
11375 
11376   owner.Variable = var;
11377   if (ref)
11378     owner.setLocsFrom(ref);
11379   return true;
11380 }
11381 
11382 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
11383   while (true) {
11384     e = e->IgnoreParens();
11385     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
11386       switch (cast->getCastKind()) {
11387       case CK_BitCast:
11388       case CK_LValueBitCast:
11389       case CK_LValueToRValue:
11390       case CK_ARCReclaimReturnedObject:
11391         e = cast->getSubExpr();
11392         continue;
11393 
11394       default:
11395         return false;
11396       }
11397     }
11398 
11399     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
11400       ObjCIvarDecl *ivar = ref->getDecl();
11401       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11402         return false;
11403 
11404       // Try to find a retain cycle in the base.
11405       if (!findRetainCycleOwner(S, ref->getBase(), owner))
11406         return false;
11407 
11408       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
11409       owner.Indirect = true;
11410       return true;
11411     }
11412 
11413     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
11414       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
11415       if (!var) return false;
11416       return considerVariable(var, ref, owner);
11417     }
11418 
11419     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
11420       if (member->isArrow()) return false;
11421 
11422       // Don't count this as an indirect ownership.
11423       e = member->getBase();
11424       continue;
11425     }
11426 
11427     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
11428       // Only pay attention to pseudo-objects on property references.
11429       ObjCPropertyRefExpr *pre
11430         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
11431                                               ->IgnoreParens());
11432       if (!pre) return false;
11433       if (pre->isImplicitProperty()) return false;
11434       ObjCPropertyDecl *property = pre->getExplicitProperty();
11435       if (!property->isRetaining() &&
11436           !(property->getPropertyIvarDecl() &&
11437             property->getPropertyIvarDecl()->getType()
11438               .getObjCLifetime() == Qualifiers::OCL_Strong))
11439           return false;
11440 
11441       owner.Indirect = true;
11442       if (pre->isSuperReceiver()) {
11443         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
11444         if (!owner.Variable)
11445           return false;
11446         owner.Loc = pre->getLocation();
11447         owner.Range = pre->getSourceRange();
11448         return true;
11449       }
11450       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
11451                               ->getSourceExpr());
11452       continue;
11453     }
11454 
11455     // Array ivars?
11456 
11457     return false;
11458   }
11459 }
11460 
11461 namespace {
11462 
11463   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
11464     ASTContext &Context;
11465     VarDecl *Variable;
11466     Expr *Capturer = nullptr;
11467     bool VarWillBeReased = false;
11468 
11469     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
11470         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
11471           Context(Context), Variable(variable) {}
11472 
11473     void VisitDeclRefExpr(DeclRefExpr *ref) {
11474       if (ref->getDecl() == Variable && !Capturer)
11475         Capturer = ref;
11476     }
11477 
11478     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
11479       if (Capturer) return;
11480       Visit(ref->getBase());
11481       if (Capturer && ref->isFreeIvar())
11482         Capturer = ref;
11483     }
11484 
11485     void VisitBlockExpr(BlockExpr *block) {
11486       // Look inside nested blocks
11487       if (block->getBlockDecl()->capturesVariable(Variable))
11488         Visit(block->getBlockDecl()->getBody());
11489     }
11490 
11491     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
11492       if (Capturer) return;
11493       if (OVE->getSourceExpr())
11494         Visit(OVE->getSourceExpr());
11495     }
11496 
11497     void VisitBinaryOperator(BinaryOperator *BinOp) {
11498       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
11499         return;
11500       Expr *LHS = BinOp->getLHS();
11501       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
11502         if (DRE->getDecl() != Variable)
11503           return;
11504         if (Expr *RHS = BinOp->getRHS()) {
11505           RHS = RHS->IgnoreParenCasts();
11506           llvm::APSInt Value;
11507           VarWillBeReased =
11508             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
11509         }
11510       }
11511     }
11512   };
11513 
11514 } // namespace
11515 
11516 /// Check whether the given argument is a block which captures a
11517 /// variable.
11518 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
11519   assert(owner.Variable && owner.Loc.isValid());
11520 
11521   e = e->IgnoreParenCasts();
11522 
11523   // Look through [^{...} copy] and Block_copy(^{...}).
11524   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
11525     Selector Cmd = ME->getSelector();
11526     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
11527       e = ME->getInstanceReceiver();
11528       if (!e)
11529         return nullptr;
11530       e = e->IgnoreParenCasts();
11531     }
11532   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
11533     if (CE->getNumArgs() == 1) {
11534       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
11535       if (Fn) {
11536         const IdentifierInfo *FnI = Fn->getIdentifier();
11537         if (FnI && FnI->isStr("_Block_copy")) {
11538           e = CE->getArg(0)->IgnoreParenCasts();
11539         }
11540       }
11541     }
11542   }
11543 
11544   BlockExpr *block = dyn_cast<BlockExpr>(e);
11545   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
11546     return nullptr;
11547 
11548   FindCaptureVisitor visitor(S.Context, owner.Variable);
11549   visitor.Visit(block->getBlockDecl()->getBody());
11550   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
11551 }
11552 
11553 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
11554                                 RetainCycleOwner &owner) {
11555   assert(capturer);
11556   assert(owner.Variable && owner.Loc.isValid());
11557 
11558   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
11559     << owner.Variable << capturer->getSourceRange();
11560   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
11561     << owner.Indirect << owner.Range;
11562 }
11563 
11564 /// Check for a keyword selector that starts with the word 'add' or
11565 /// 'set'.
11566 static bool isSetterLikeSelector(Selector sel) {
11567   if (sel.isUnarySelector()) return false;
11568 
11569   StringRef str = sel.getNameForSlot(0);
11570   while (!str.empty() && str.front() == '_') str = str.substr(1);
11571   if (str.startswith("set"))
11572     str = str.substr(3);
11573   else if (str.startswith("add")) {
11574     // Specially whitelist 'addOperationWithBlock:'.
11575     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
11576       return false;
11577     str = str.substr(3);
11578   }
11579   else
11580     return false;
11581 
11582   if (str.empty()) return true;
11583   return !isLowercase(str.front());
11584 }
11585 
11586 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
11587                                                     ObjCMessageExpr *Message) {
11588   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
11589                                                 Message->getReceiverInterface(),
11590                                                 NSAPI::ClassId_NSMutableArray);
11591   if (!IsMutableArray) {
11592     return None;
11593   }
11594 
11595   Selector Sel = Message->getSelector();
11596 
11597   Optional<NSAPI::NSArrayMethodKind> MKOpt =
11598     S.NSAPIObj->getNSArrayMethodKind(Sel);
11599   if (!MKOpt) {
11600     return None;
11601   }
11602 
11603   NSAPI::NSArrayMethodKind MK = *MKOpt;
11604 
11605   switch (MK) {
11606     case NSAPI::NSMutableArr_addObject:
11607     case NSAPI::NSMutableArr_insertObjectAtIndex:
11608     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
11609       return 0;
11610     case NSAPI::NSMutableArr_replaceObjectAtIndex:
11611       return 1;
11612 
11613     default:
11614       return None;
11615   }
11616 
11617   return None;
11618 }
11619 
11620 static
11621 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
11622                                                   ObjCMessageExpr *Message) {
11623   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
11624                                             Message->getReceiverInterface(),
11625                                             NSAPI::ClassId_NSMutableDictionary);
11626   if (!IsMutableDictionary) {
11627     return None;
11628   }
11629 
11630   Selector Sel = Message->getSelector();
11631 
11632   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
11633     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
11634   if (!MKOpt) {
11635     return None;
11636   }
11637 
11638   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
11639 
11640   switch (MK) {
11641     case NSAPI::NSMutableDict_setObjectForKey:
11642     case NSAPI::NSMutableDict_setValueForKey:
11643     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
11644       return 0;
11645 
11646     default:
11647       return None;
11648   }
11649 
11650   return None;
11651 }
11652 
11653 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
11654   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
11655                                                 Message->getReceiverInterface(),
11656                                                 NSAPI::ClassId_NSMutableSet);
11657 
11658   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
11659                                             Message->getReceiverInterface(),
11660                                             NSAPI::ClassId_NSMutableOrderedSet);
11661   if (!IsMutableSet && !IsMutableOrderedSet) {
11662     return None;
11663   }
11664 
11665   Selector Sel = Message->getSelector();
11666 
11667   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
11668   if (!MKOpt) {
11669     return None;
11670   }
11671 
11672   NSAPI::NSSetMethodKind MK = *MKOpt;
11673 
11674   switch (MK) {
11675     case NSAPI::NSMutableSet_addObject:
11676     case NSAPI::NSOrderedSet_setObjectAtIndex:
11677     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
11678     case NSAPI::NSOrderedSet_insertObjectAtIndex:
11679       return 0;
11680     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
11681       return 1;
11682   }
11683 
11684   return None;
11685 }
11686 
11687 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
11688   if (!Message->isInstanceMessage()) {
11689     return;
11690   }
11691 
11692   Optional<int> ArgOpt;
11693 
11694   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
11695       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
11696       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
11697     return;
11698   }
11699 
11700   int ArgIndex = *ArgOpt;
11701 
11702   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
11703   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
11704     Arg = OE->getSourceExpr()->IgnoreImpCasts();
11705   }
11706 
11707   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
11708     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11709       if (ArgRE->isObjCSelfExpr()) {
11710         Diag(Message->getSourceRange().getBegin(),
11711              diag::warn_objc_circular_container)
11712           << ArgRE->getDecl() << StringRef("'super'");
11713       }
11714     }
11715   } else {
11716     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
11717 
11718     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
11719       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
11720     }
11721 
11722     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
11723       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11724         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
11725           ValueDecl *Decl = ReceiverRE->getDecl();
11726           Diag(Message->getSourceRange().getBegin(),
11727                diag::warn_objc_circular_container)
11728             << Decl << Decl;
11729           if (!ArgRE->isObjCSelfExpr()) {
11730             Diag(Decl->getLocation(),
11731                  diag::note_objc_circular_container_declared_here)
11732               << Decl;
11733           }
11734         }
11735       }
11736     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
11737       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
11738         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
11739           ObjCIvarDecl *Decl = IvarRE->getDecl();
11740           Diag(Message->getSourceRange().getBegin(),
11741                diag::warn_objc_circular_container)
11742             << Decl << Decl;
11743           Diag(Decl->getLocation(),
11744                diag::note_objc_circular_container_declared_here)
11745             << Decl;
11746         }
11747       }
11748     }
11749   }
11750 }
11751 
11752 /// Check a message send to see if it's likely to cause a retain cycle.
11753 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
11754   // Only check instance methods whose selector looks like a setter.
11755   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
11756     return;
11757 
11758   // Try to find a variable that the receiver is strongly owned by.
11759   RetainCycleOwner owner;
11760   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
11761     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
11762       return;
11763   } else {
11764     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
11765     owner.Variable = getCurMethodDecl()->getSelfDecl();
11766     owner.Loc = msg->getSuperLoc();
11767     owner.Range = msg->getSuperLoc();
11768   }
11769 
11770   // Check whether the receiver is captured by any of the arguments.
11771   const ObjCMethodDecl *MD = msg->getMethodDecl();
11772   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
11773     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
11774       // noescape blocks should not be retained by the method.
11775       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
11776         continue;
11777       return diagnoseRetainCycle(*this, capturer, owner);
11778     }
11779   }
11780 }
11781 
11782 /// Check a property assign to see if it's likely to cause a retain cycle.
11783 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
11784   RetainCycleOwner owner;
11785   if (!findRetainCycleOwner(*this, receiver, owner))
11786     return;
11787 
11788   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
11789     diagnoseRetainCycle(*this, capturer, owner);
11790 }
11791 
11792 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
11793   RetainCycleOwner Owner;
11794   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
11795     return;
11796 
11797   // Because we don't have an expression for the variable, we have to set the
11798   // location explicitly here.
11799   Owner.Loc = Var->getLocation();
11800   Owner.Range = Var->getSourceRange();
11801 
11802   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
11803     diagnoseRetainCycle(*this, Capturer, Owner);
11804 }
11805 
11806 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
11807                                      Expr *RHS, bool isProperty) {
11808   // Check if RHS is an Objective-C object literal, which also can get
11809   // immediately zapped in a weak reference.  Note that we explicitly
11810   // allow ObjCStringLiterals, since those are designed to never really die.
11811   RHS = RHS->IgnoreParenImpCasts();
11812 
11813   // This enum needs to match with the 'select' in
11814   // warn_objc_arc_literal_assign (off-by-1).
11815   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
11816   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
11817     return false;
11818 
11819   S.Diag(Loc, diag::warn_arc_literal_assign)
11820     << (unsigned) Kind
11821     << (isProperty ? 0 : 1)
11822     << RHS->getSourceRange();
11823 
11824   return true;
11825 }
11826 
11827 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
11828                                     Qualifiers::ObjCLifetime LT,
11829                                     Expr *RHS, bool isProperty) {
11830   // Strip off any implicit cast added to get to the one ARC-specific.
11831   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11832     if (cast->getCastKind() == CK_ARCConsumeObject) {
11833       S.Diag(Loc, diag::warn_arc_retained_assign)
11834         << (LT == Qualifiers::OCL_ExplicitNone)
11835         << (isProperty ? 0 : 1)
11836         << RHS->getSourceRange();
11837       return true;
11838     }
11839     RHS = cast->getSubExpr();
11840   }
11841 
11842   if (LT == Qualifiers::OCL_Weak &&
11843       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
11844     return true;
11845 
11846   return false;
11847 }
11848 
11849 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
11850                               QualType LHS, Expr *RHS) {
11851   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
11852 
11853   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
11854     return false;
11855 
11856   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
11857     return true;
11858 
11859   return false;
11860 }
11861 
11862 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
11863                               Expr *LHS, Expr *RHS) {
11864   QualType LHSType;
11865   // PropertyRef on LHS type need be directly obtained from
11866   // its declaration as it has a PseudoType.
11867   ObjCPropertyRefExpr *PRE
11868     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11869   if (PRE && !PRE->isImplicitProperty()) {
11870     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11871     if (PD)
11872       LHSType = PD->getType();
11873   }
11874 
11875   if (LHSType.isNull())
11876     LHSType = LHS->getType();
11877 
11878   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
11879 
11880   if (LT == Qualifiers::OCL_Weak) {
11881     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
11882       getCurFunction()->markSafeWeakUse(LHS);
11883   }
11884 
11885   if (checkUnsafeAssigns(Loc, LHSType, RHS))
11886     return;
11887 
11888   // FIXME. Check for other life times.
11889   if (LT != Qualifiers::OCL_None)
11890     return;
11891 
11892   if (PRE) {
11893     if (PRE->isImplicitProperty())
11894       return;
11895     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11896     if (!PD)
11897       return;
11898 
11899     unsigned Attributes = PD->getPropertyAttributes();
11900     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
11901       // when 'assign' attribute was not explicitly specified
11902       // by user, ignore it and rely on property type itself
11903       // for lifetime info.
11904       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11905       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11906           LHSType->isObjCRetainableType())
11907         return;
11908 
11909       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11910         if (cast->getCastKind() == CK_ARCConsumeObject) {
11911           Diag(Loc, diag::warn_arc_retained_property_assign)
11912           << RHS->getSourceRange();
11913           return;
11914         }
11915         RHS = cast->getSubExpr();
11916       }
11917     }
11918     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
11919       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11920         return;
11921     }
11922   }
11923 }
11924 
11925 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11926 
11927 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11928                                         SourceLocation StmtLoc,
11929                                         const NullStmt *Body) {
11930   // Do not warn if the body is a macro that expands to nothing, e.g:
11931   //
11932   // #define CALL(x)
11933   // if (condition)
11934   //   CALL(0);
11935   if (Body->hasLeadingEmptyMacro())
11936     return false;
11937 
11938   // Get line numbers of statement and body.
11939   bool StmtLineInvalid;
11940   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
11941                                                       &StmtLineInvalid);
11942   if (StmtLineInvalid)
11943     return false;
11944 
11945   bool BodyLineInvalid;
11946   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11947                                                       &BodyLineInvalid);
11948   if (BodyLineInvalid)
11949     return false;
11950 
11951   // Warn if null statement and body are on the same line.
11952   if (StmtLine != BodyLine)
11953     return false;
11954 
11955   return true;
11956 }
11957 
11958 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
11959                                  const Stmt *Body,
11960                                  unsigned DiagID) {
11961   // Since this is a syntactic check, don't emit diagnostic for template
11962   // instantiations, this just adds noise.
11963   if (CurrentInstantiationScope)
11964     return;
11965 
11966   // The body should be a null statement.
11967   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11968   if (!NBody)
11969     return;
11970 
11971   // Do the usual checks.
11972   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11973     return;
11974 
11975   Diag(NBody->getSemiLoc(), DiagID);
11976   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11977 }
11978 
11979 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
11980                                  const Stmt *PossibleBody) {
11981   assert(!CurrentInstantiationScope); // Ensured by caller
11982 
11983   SourceLocation StmtLoc;
11984   const Stmt *Body;
11985   unsigned DiagID;
11986   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11987     StmtLoc = FS->getRParenLoc();
11988     Body = FS->getBody();
11989     DiagID = diag::warn_empty_for_body;
11990   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11991     StmtLoc = WS->getCond()->getSourceRange().getEnd();
11992     Body = WS->getBody();
11993     DiagID = diag::warn_empty_while_body;
11994   } else
11995     return; // Neither `for' nor `while'.
11996 
11997   // The body should be a null statement.
11998   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11999   if (!NBody)
12000     return;
12001 
12002   // Skip expensive checks if diagnostic is disabled.
12003   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
12004     return;
12005 
12006   // Do the usual checks.
12007   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
12008     return;
12009 
12010   // `for(...);' and `while(...);' are popular idioms, so in order to keep
12011   // noise level low, emit diagnostics only if for/while is followed by a
12012   // CompoundStmt, e.g.:
12013   //    for (int i = 0; i < n; i++);
12014   //    {
12015   //      a(i);
12016   //    }
12017   // or if for/while is followed by a statement with more indentation
12018   // than for/while itself:
12019   //    for (int i = 0; i < n; i++);
12020   //      a(i);
12021   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
12022   if (!ProbableTypo) {
12023     bool BodyColInvalid;
12024     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
12025                              PossibleBody->getLocStart(),
12026                              &BodyColInvalid);
12027     if (BodyColInvalid)
12028       return;
12029 
12030     bool StmtColInvalid;
12031     unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
12032                              S->getLocStart(),
12033                              &StmtColInvalid);
12034     if (StmtColInvalid)
12035       return;
12036 
12037     if (BodyCol > StmtCol)
12038       ProbableTypo = true;
12039   }
12040 
12041   if (ProbableTypo) {
12042     Diag(NBody->getSemiLoc(), DiagID);
12043     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
12044   }
12045 }
12046 
12047 //===--- CHECK: Warn on self move with std::move. -------------------------===//
12048 
12049 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
12050 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
12051                              SourceLocation OpLoc) {
12052   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
12053     return;
12054 
12055   if (inTemplateInstantiation())
12056     return;
12057 
12058   // Strip parens and casts away.
12059   LHSExpr = LHSExpr->IgnoreParenImpCasts();
12060   RHSExpr = RHSExpr->IgnoreParenImpCasts();
12061 
12062   // Check for a call expression
12063   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
12064   if (!CE || CE->getNumArgs() != 1)
12065     return;
12066 
12067   // Check for a call to std::move
12068   if (!CE->isCallToStdMove())
12069     return;
12070 
12071   // Get argument from std::move
12072   RHSExpr = CE->getArg(0);
12073 
12074   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
12075   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
12076 
12077   // Two DeclRefExpr's, check that the decls are the same.
12078   if (LHSDeclRef && RHSDeclRef) {
12079     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
12080       return;
12081     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
12082         RHSDeclRef->getDecl()->getCanonicalDecl())
12083       return;
12084 
12085     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12086                                         << LHSExpr->getSourceRange()
12087                                         << RHSExpr->getSourceRange();
12088     return;
12089   }
12090 
12091   // Member variables require a different approach to check for self moves.
12092   // MemberExpr's are the same if every nested MemberExpr refers to the same
12093   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
12094   // the base Expr's are CXXThisExpr's.
12095   const Expr *LHSBase = LHSExpr;
12096   const Expr *RHSBase = RHSExpr;
12097   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
12098   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
12099   if (!LHSME || !RHSME)
12100     return;
12101 
12102   while (LHSME && RHSME) {
12103     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
12104         RHSME->getMemberDecl()->getCanonicalDecl())
12105       return;
12106 
12107     LHSBase = LHSME->getBase();
12108     RHSBase = RHSME->getBase();
12109     LHSME = dyn_cast<MemberExpr>(LHSBase);
12110     RHSME = dyn_cast<MemberExpr>(RHSBase);
12111   }
12112 
12113   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
12114   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
12115   if (LHSDeclRef && RHSDeclRef) {
12116     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
12117       return;
12118     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
12119         RHSDeclRef->getDecl()->getCanonicalDecl())
12120       return;
12121 
12122     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12123                                         << LHSExpr->getSourceRange()
12124                                         << RHSExpr->getSourceRange();
12125     return;
12126   }
12127 
12128   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
12129     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12130                                         << LHSExpr->getSourceRange()
12131                                         << RHSExpr->getSourceRange();
12132 }
12133 
12134 //===--- Layout compatibility ----------------------------------------------//
12135 
12136 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
12137 
12138 /// \brief Check if two enumeration types are layout-compatible.
12139 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
12140   // C++11 [dcl.enum] p8:
12141   // Two enumeration types are layout-compatible if they have the same
12142   // underlying type.
12143   return ED1->isComplete() && ED2->isComplete() &&
12144          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
12145 }
12146 
12147 /// \brief Check if two fields are layout-compatible.
12148 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
12149                                FieldDecl *Field2) {
12150   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
12151     return false;
12152 
12153   if (Field1->isBitField() != Field2->isBitField())
12154     return false;
12155 
12156   if (Field1->isBitField()) {
12157     // Make sure that the bit-fields are the same length.
12158     unsigned Bits1 = Field1->getBitWidthValue(C);
12159     unsigned Bits2 = Field2->getBitWidthValue(C);
12160 
12161     if (Bits1 != Bits2)
12162       return false;
12163   }
12164 
12165   return true;
12166 }
12167 
12168 /// \brief Check if two standard-layout structs are layout-compatible.
12169 /// (C++11 [class.mem] p17)
12170 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
12171                                      RecordDecl *RD2) {
12172   // If both records are C++ classes, check that base classes match.
12173   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
12174     // If one of records is a CXXRecordDecl we are in C++ mode,
12175     // thus the other one is a CXXRecordDecl, too.
12176     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
12177     // Check number of base classes.
12178     if (D1CXX->getNumBases() != D2CXX->getNumBases())
12179       return false;
12180 
12181     // Check the base classes.
12182     for (CXXRecordDecl::base_class_const_iterator
12183                Base1 = D1CXX->bases_begin(),
12184            BaseEnd1 = D1CXX->bases_end(),
12185               Base2 = D2CXX->bases_begin();
12186          Base1 != BaseEnd1;
12187          ++Base1, ++Base2) {
12188       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
12189         return false;
12190     }
12191   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
12192     // If only RD2 is a C++ class, it should have zero base classes.
12193     if (D2CXX->getNumBases() > 0)
12194       return false;
12195   }
12196 
12197   // Check the fields.
12198   RecordDecl::field_iterator Field2 = RD2->field_begin(),
12199                              Field2End = RD2->field_end(),
12200                              Field1 = RD1->field_begin(),
12201                              Field1End = RD1->field_end();
12202   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
12203     if (!isLayoutCompatible(C, *Field1, *Field2))
12204       return false;
12205   }
12206   if (Field1 != Field1End || Field2 != Field2End)
12207     return false;
12208 
12209   return true;
12210 }
12211 
12212 /// \brief Check if two standard-layout unions are layout-compatible.
12213 /// (C++11 [class.mem] p18)
12214 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
12215                                     RecordDecl *RD2) {
12216   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
12217   for (auto *Field2 : RD2->fields())
12218     UnmatchedFields.insert(Field2);
12219 
12220   for (auto *Field1 : RD1->fields()) {
12221     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
12222         I = UnmatchedFields.begin(),
12223         E = UnmatchedFields.end();
12224 
12225     for ( ; I != E; ++I) {
12226       if (isLayoutCompatible(C, Field1, *I)) {
12227         bool Result = UnmatchedFields.erase(*I);
12228         (void) Result;
12229         assert(Result);
12230         break;
12231       }
12232     }
12233     if (I == E)
12234       return false;
12235   }
12236 
12237   return UnmatchedFields.empty();
12238 }
12239 
12240 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
12241                                RecordDecl *RD2) {
12242   if (RD1->isUnion() != RD2->isUnion())
12243     return false;
12244 
12245   if (RD1->isUnion())
12246     return isLayoutCompatibleUnion(C, RD1, RD2);
12247   else
12248     return isLayoutCompatibleStruct(C, RD1, RD2);
12249 }
12250 
12251 /// \brief Check if two types are layout-compatible in C++11 sense.
12252 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
12253   if (T1.isNull() || T2.isNull())
12254     return false;
12255 
12256   // C++11 [basic.types] p11:
12257   // If two types T1 and T2 are the same type, then T1 and T2 are
12258   // layout-compatible types.
12259   if (C.hasSameType(T1, T2))
12260     return true;
12261 
12262   T1 = T1.getCanonicalType().getUnqualifiedType();
12263   T2 = T2.getCanonicalType().getUnqualifiedType();
12264 
12265   const Type::TypeClass TC1 = T1->getTypeClass();
12266   const Type::TypeClass TC2 = T2->getTypeClass();
12267 
12268   if (TC1 != TC2)
12269     return false;
12270 
12271   if (TC1 == Type::Enum) {
12272     return isLayoutCompatible(C,
12273                               cast<EnumType>(T1)->getDecl(),
12274                               cast<EnumType>(T2)->getDecl());
12275   } else if (TC1 == Type::Record) {
12276     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
12277       return false;
12278 
12279     return isLayoutCompatible(C,
12280                               cast<RecordType>(T1)->getDecl(),
12281                               cast<RecordType>(T2)->getDecl());
12282   }
12283 
12284   return false;
12285 }
12286 
12287 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
12288 
12289 /// \brief Given a type tag expression find the type tag itself.
12290 ///
12291 /// \param TypeExpr Type tag expression, as it appears in user's code.
12292 ///
12293 /// \param VD Declaration of an identifier that appears in a type tag.
12294 ///
12295 /// \param MagicValue Type tag magic value.
12296 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
12297                             const ValueDecl **VD, uint64_t *MagicValue) {
12298   while(true) {
12299     if (!TypeExpr)
12300       return false;
12301 
12302     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
12303 
12304     switch (TypeExpr->getStmtClass()) {
12305     case Stmt::UnaryOperatorClass: {
12306       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
12307       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
12308         TypeExpr = UO->getSubExpr();
12309         continue;
12310       }
12311       return false;
12312     }
12313 
12314     case Stmt::DeclRefExprClass: {
12315       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
12316       *VD = DRE->getDecl();
12317       return true;
12318     }
12319 
12320     case Stmt::IntegerLiteralClass: {
12321       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
12322       llvm::APInt MagicValueAPInt = IL->getValue();
12323       if (MagicValueAPInt.getActiveBits() <= 64) {
12324         *MagicValue = MagicValueAPInt.getZExtValue();
12325         return true;
12326       } else
12327         return false;
12328     }
12329 
12330     case Stmt::BinaryConditionalOperatorClass:
12331     case Stmt::ConditionalOperatorClass: {
12332       const AbstractConditionalOperator *ACO =
12333           cast<AbstractConditionalOperator>(TypeExpr);
12334       bool Result;
12335       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
12336         if (Result)
12337           TypeExpr = ACO->getTrueExpr();
12338         else
12339           TypeExpr = ACO->getFalseExpr();
12340         continue;
12341       }
12342       return false;
12343     }
12344 
12345     case Stmt::BinaryOperatorClass: {
12346       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
12347       if (BO->getOpcode() == BO_Comma) {
12348         TypeExpr = BO->getRHS();
12349         continue;
12350       }
12351       return false;
12352     }
12353 
12354     default:
12355       return false;
12356     }
12357   }
12358 }
12359 
12360 /// \brief Retrieve the C type corresponding to type tag TypeExpr.
12361 ///
12362 /// \param TypeExpr Expression that specifies a type tag.
12363 ///
12364 /// \param MagicValues Registered magic values.
12365 ///
12366 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
12367 ///        kind.
12368 ///
12369 /// \param TypeInfo Information about the corresponding C type.
12370 ///
12371 /// \returns true if the corresponding C type was found.
12372 static bool GetMatchingCType(
12373         const IdentifierInfo *ArgumentKind,
12374         const Expr *TypeExpr, const ASTContext &Ctx,
12375         const llvm::DenseMap<Sema::TypeTagMagicValue,
12376                              Sema::TypeTagData> *MagicValues,
12377         bool &FoundWrongKind,
12378         Sema::TypeTagData &TypeInfo) {
12379   FoundWrongKind = false;
12380 
12381   // Variable declaration that has type_tag_for_datatype attribute.
12382   const ValueDecl *VD = nullptr;
12383 
12384   uint64_t MagicValue;
12385 
12386   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
12387     return false;
12388 
12389   if (VD) {
12390     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
12391       if (I->getArgumentKind() != ArgumentKind) {
12392         FoundWrongKind = true;
12393         return false;
12394       }
12395       TypeInfo.Type = I->getMatchingCType();
12396       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
12397       TypeInfo.MustBeNull = I->getMustBeNull();
12398       return true;
12399     }
12400     return false;
12401   }
12402 
12403   if (!MagicValues)
12404     return false;
12405 
12406   llvm::DenseMap<Sema::TypeTagMagicValue,
12407                  Sema::TypeTagData>::const_iterator I =
12408       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
12409   if (I == MagicValues->end())
12410     return false;
12411 
12412   TypeInfo = I->second;
12413   return true;
12414 }
12415 
12416 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
12417                                       uint64_t MagicValue, QualType Type,
12418                                       bool LayoutCompatible,
12419                                       bool MustBeNull) {
12420   if (!TypeTagForDatatypeMagicValues)
12421     TypeTagForDatatypeMagicValues.reset(
12422         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
12423 
12424   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
12425   (*TypeTagForDatatypeMagicValues)[Magic] =
12426       TypeTagData(Type, LayoutCompatible, MustBeNull);
12427 }
12428 
12429 static bool IsSameCharType(QualType T1, QualType T2) {
12430   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
12431   if (!BT1)
12432     return false;
12433 
12434   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
12435   if (!BT2)
12436     return false;
12437 
12438   BuiltinType::Kind T1Kind = BT1->getKind();
12439   BuiltinType::Kind T2Kind = BT2->getKind();
12440 
12441   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
12442          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
12443          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
12444          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
12445 }
12446 
12447 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
12448                                     const ArrayRef<const Expr *> ExprArgs,
12449                                     SourceLocation CallSiteLoc) {
12450   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
12451   bool IsPointerAttr = Attr->getIsPointer();
12452 
12453   // Retrieve the argument representing the 'type_tag'.
12454   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
12455   if (TypeTagIdxAST >= ExprArgs.size()) {
12456     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
12457         << 0 << Attr->getTypeTagIdx().getSourceIndex();
12458     return;
12459   }
12460   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
12461   bool FoundWrongKind;
12462   TypeTagData TypeInfo;
12463   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
12464                         TypeTagForDatatypeMagicValues.get(),
12465                         FoundWrongKind, TypeInfo)) {
12466     if (FoundWrongKind)
12467       Diag(TypeTagExpr->getExprLoc(),
12468            diag::warn_type_tag_for_datatype_wrong_kind)
12469         << TypeTagExpr->getSourceRange();
12470     return;
12471   }
12472 
12473   // Retrieve the argument representing the 'arg_idx'.
12474   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
12475   if (ArgumentIdxAST >= ExprArgs.size()) {
12476     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
12477         << 1 << Attr->getArgumentIdx().getSourceIndex();
12478     return;
12479   }
12480   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
12481   if (IsPointerAttr) {
12482     // Skip implicit cast of pointer to `void *' (as a function argument).
12483     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
12484       if (ICE->getType()->isVoidPointerType() &&
12485           ICE->getCastKind() == CK_BitCast)
12486         ArgumentExpr = ICE->getSubExpr();
12487   }
12488   QualType ArgumentType = ArgumentExpr->getType();
12489 
12490   // Passing a `void*' pointer shouldn't trigger a warning.
12491   if (IsPointerAttr && ArgumentType->isVoidPointerType())
12492     return;
12493 
12494   if (TypeInfo.MustBeNull) {
12495     // Type tag with matching void type requires a null pointer.
12496     if (!ArgumentExpr->isNullPointerConstant(Context,
12497                                              Expr::NPC_ValueDependentIsNotNull)) {
12498       Diag(ArgumentExpr->getExprLoc(),
12499            diag::warn_type_safety_null_pointer_required)
12500           << ArgumentKind->getName()
12501           << ArgumentExpr->getSourceRange()
12502           << TypeTagExpr->getSourceRange();
12503     }
12504     return;
12505   }
12506 
12507   QualType RequiredType = TypeInfo.Type;
12508   if (IsPointerAttr)
12509     RequiredType = Context.getPointerType(RequiredType);
12510 
12511   bool mismatch = false;
12512   if (!TypeInfo.LayoutCompatible) {
12513     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
12514 
12515     // C++11 [basic.fundamental] p1:
12516     // Plain char, signed char, and unsigned char are three distinct types.
12517     //
12518     // But we treat plain `char' as equivalent to `signed char' or `unsigned
12519     // char' depending on the current char signedness mode.
12520     if (mismatch)
12521       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
12522                                            RequiredType->getPointeeType())) ||
12523           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
12524         mismatch = false;
12525   } else
12526     if (IsPointerAttr)
12527       mismatch = !isLayoutCompatible(Context,
12528                                      ArgumentType->getPointeeType(),
12529                                      RequiredType->getPointeeType());
12530     else
12531       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
12532 
12533   if (mismatch)
12534     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
12535         << ArgumentType << ArgumentKind
12536         << TypeInfo.LayoutCompatible << RequiredType
12537         << ArgumentExpr->getSourceRange()
12538         << TypeTagExpr->getSourceRange();
12539 }
12540 
12541 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
12542                                          CharUnits Alignment) {
12543   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
12544 }
12545 
12546 void Sema::DiagnoseMisalignedMembers() {
12547   for (MisalignedMember &m : MisalignedMembers) {
12548     const NamedDecl *ND = m.RD;
12549     if (ND->getName().empty()) {
12550       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
12551         ND = TD;
12552     }
12553     Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
12554         << m.MD << ND << m.E->getSourceRange();
12555   }
12556   MisalignedMembers.clear();
12557 }
12558 
12559 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
12560   E = E->IgnoreParens();
12561   if (!T->isPointerType() && !T->isIntegerType())
12562     return;
12563   if (isa<UnaryOperator>(E) &&
12564       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
12565     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12566     if (isa<MemberExpr>(Op)) {
12567       auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
12568                           MisalignedMember(Op));
12569       if (MA != MisalignedMembers.end() &&
12570           (T->isIntegerType() ||
12571            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
12572                                    Context.getTypeAlignInChars(
12573                                        T->getPointeeType()) <= MA->Alignment))))
12574         MisalignedMembers.erase(MA);
12575     }
12576   }
12577 }
12578 
12579 void Sema::RefersToMemberWithReducedAlignment(
12580     Expr *E,
12581     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
12582         Action) {
12583   const auto *ME = dyn_cast<MemberExpr>(E);
12584   if (!ME)
12585     return;
12586 
12587   // No need to check expressions with an __unaligned-qualified type.
12588   if (E->getType().getQualifiers().hasUnaligned())
12589     return;
12590 
12591   // For a chain of MemberExpr like "a.b.c.d" this list
12592   // will keep FieldDecl's like [d, c, b].
12593   SmallVector<FieldDecl *, 4> ReverseMemberChain;
12594   const MemberExpr *TopME = nullptr;
12595   bool AnyIsPacked = false;
12596   do {
12597     QualType BaseType = ME->getBase()->getType();
12598     if (ME->isArrow())
12599       BaseType = BaseType->getPointeeType();
12600     RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
12601     if (RD->isInvalidDecl())
12602       return;
12603 
12604     ValueDecl *MD = ME->getMemberDecl();
12605     auto *FD = dyn_cast<FieldDecl>(MD);
12606     // We do not care about non-data members.
12607     if (!FD || FD->isInvalidDecl())
12608       return;
12609 
12610     AnyIsPacked =
12611         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
12612     ReverseMemberChain.push_back(FD);
12613 
12614     TopME = ME;
12615     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
12616   } while (ME);
12617   assert(TopME && "We did not compute a topmost MemberExpr!");
12618 
12619   // Not the scope of this diagnostic.
12620   if (!AnyIsPacked)
12621     return;
12622 
12623   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
12624   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
12625   // TODO: The innermost base of the member expression may be too complicated.
12626   // For now, just disregard these cases. This is left for future
12627   // improvement.
12628   if (!DRE && !isa<CXXThisExpr>(TopBase))
12629       return;
12630 
12631   // Alignment expected by the whole expression.
12632   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
12633 
12634   // No need to do anything else with this case.
12635   if (ExpectedAlignment.isOne())
12636     return;
12637 
12638   // Synthesize offset of the whole access.
12639   CharUnits Offset;
12640   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
12641        I++) {
12642     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
12643   }
12644 
12645   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
12646   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
12647       ReverseMemberChain.back()->getParent()->getTypeForDecl());
12648 
12649   // The base expression of the innermost MemberExpr may give
12650   // stronger guarantees than the class containing the member.
12651   if (DRE && !TopME->isArrow()) {
12652     const ValueDecl *VD = DRE->getDecl();
12653     if (!VD->getType()->isReferenceType())
12654       CompleteObjectAlignment =
12655           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
12656   }
12657 
12658   // Check if the synthesized offset fulfills the alignment.
12659   if (Offset % ExpectedAlignment != 0 ||
12660       // It may fulfill the offset it but the effective alignment may still be
12661       // lower than the expected expression alignment.
12662       CompleteObjectAlignment < ExpectedAlignment) {
12663     // If this happens, we want to determine a sensible culprit of this.
12664     // Intuitively, watching the chain of member expressions from right to
12665     // left, we start with the required alignment (as required by the field
12666     // type) but some packed attribute in that chain has reduced the alignment.
12667     // It may happen that another packed structure increases it again. But if
12668     // we are here such increase has not been enough. So pointing the first
12669     // FieldDecl that either is packed or else its RecordDecl is,
12670     // seems reasonable.
12671     FieldDecl *FD = nullptr;
12672     CharUnits Alignment;
12673     for (FieldDecl *FDI : ReverseMemberChain) {
12674       if (FDI->hasAttr<PackedAttr>() ||
12675           FDI->getParent()->hasAttr<PackedAttr>()) {
12676         FD = FDI;
12677         Alignment = std::min(
12678             Context.getTypeAlignInChars(FD->getType()),
12679             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
12680         break;
12681       }
12682     }
12683     assert(FD && "We did not find a packed FieldDecl!");
12684     Action(E, FD->getParent(), FD, Alignment);
12685   }
12686 }
12687 
12688 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
12689   using namespace std::placeholders;
12690 
12691   RefersToMemberWithReducedAlignment(
12692       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
12693                      _2, _3, _4));
12694 }
12695