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     ExprResult Arg = TheCall->getArg(I);
201     QualType Ty = Arg.get()->getType();
202     if (!Ty->isIntegerType()) {
203       S.Diag(Arg.get()->getLocStart(), diag::err_overflow_builtin_must_be_int)
204           << Ty << Arg.get()->getSourceRange();
205       return true;
206     }
207     InitializedEntity Entity = InitializedEntity::InitializeParameter(
208         S.getASTContext(), Ty, /*consume*/ false);
209     Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
210     if (Arg.isInvalid())
211       return true;
212     TheCall->setArg(I, Arg.get());
213   }
214 
215   // Third argument should be a pointer to a non-const integer.
216   // IRGen correctly handles volatile, restrict, and address spaces, and
217   // the other qualifiers aren't possible.
218   {
219     ExprResult Arg = TheCall->getArg(2);
220     QualType Ty = Arg.get()->getType();
221     const auto *PtrTy = Ty->getAs<PointerType>();
222     if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
223           !PtrTy->getPointeeType().isConstQualified())) {
224       S.Diag(Arg.get()->getLocStart(),
225              diag::err_overflow_builtin_must_be_ptr_int)
226           << Ty << Arg.get()->getSourceRange();
227       return true;
228     }
229     InitializedEntity Entity = InitializedEntity::InitializeParameter(
230         S.getASTContext(), Ty, /*consume*/ false);
231     Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
232     if (Arg.isInvalid())
233       return true;
234     TheCall->setArg(2, Arg.get());
235   }
236   return false;
237 }
238 
239 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
240 		                  CallExpr *TheCall, unsigned SizeIdx,
241                                   unsigned DstSizeIdx) {
242   if (TheCall->getNumArgs() <= SizeIdx ||
243       TheCall->getNumArgs() <= DstSizeIdx)
244     return;
245 
246   const Expr *SizeArg = TheCall->getArg(SizeIdx);
247   const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
248 
249   llvm::APSInt Size, DstSize;
250 
251   // find out if both sizes are known at compile time
252   if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
253       !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
254     return;
255 
256   if (Size.ule(DstSize))
257     return;
258 
259   // confirmed overflow so generate the diagnostic.
260   IdentifierInfo *FnName = FDecl->getIdentifier();
261   SourceLocation SL = TheCall->getLocStart();
262   SourceRange SR = TheCall->getSourceRange();
263 
264   S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
265 }
266 
267 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
268   if (checkArgCount(S, BuiltinCall, 2))
269     return true;
270 
271   SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
272   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
273   Expr *Call = BuiltinCall->getArg(0);
274   Expr *Chain = BuiltinCall->getArg(1);
275 
276   if (Call->getStmtClass() != Stmt::CallExprClass) {
277     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
278         << Call->getSourceRange();
279     return true;
280   }
281 
282   auto CE = cast<CallExpr>(Call);
283   if (CE->getCallee()->getType()->isBlockPointerType()) {
284     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
285         << Call->getSourceRange();
286     return true;
287   }
288 
289   const Decl *TargetDecl = CE->getCalleeDecl();
290   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
291     if (FD->getBuiltinID()) {
292       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
293           << Call->getSourceRange();
294       return true;
295     }
296 
297   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
298     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
299         << Call->getSourceRange();
300     return true;
301   }
302 
303   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
304   if (ChainResult.isInvalid())
305     return true;
306   if (!ChainResult.get()->getType()->isPointerType()) {
307     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
308         << Chain->getSourceRange();
309     return true;
310   }
311 
312   QualType ReturnTy = CE->getCallReturnType(S.Context);
313   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
314   QualType BuiltinTy = S.Context.getFunctionType(
315       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
316   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
317 
318   Builtin =
319       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
320 
321   BuiltinCall->setType(CE->getType());
322   BuiltinCall->setValueKind(CE->getValueKind());
323   BuiltinCall->setObjectKind(CE->getObjectKind());
324   BuiltinCall->setCallee(Builtin);
325   BuiltinCall->setArg(1, ChainResult.get());
326 
327   return false;
328 }
329 
330 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
331                                      Scope::ScopeFlags NeededScopeFlags,
332                                      unsigned DiagID) {
333   // Scopes aren't available during instantiation. Fortunately, builtin
334   // functions cannot be template args so they cannot be formed through template
335   // instantiation. Therefore checking once during the parse is sufficient.
336   if (SemaRef.inTemplateInstantiation())
337     return false;
338 
339   Scope *S = SemaRef.getCurScope();
340   while (S && !S->isSEHExceptScope())
341     S = S->getParent();
342   if (!S || !(S->getFlags() & NeededScopeFlags)) {
343     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
344     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
345         << DRE->getDecl()->getIdentifier();
346     return true;
347   }
348 
349   return false;
350 }
351 
352 static inline bool isBlockPointer(Expr *Arg) {
353   return Arg->getType()->isBlockPointerType();
354 }
355 
356 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
357 /// void*, which is a requirement of device side enqueue.
358 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
359   const BlockPointerType *BPT =
360       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
361   ArrayRef<QualType> Params =
362       BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
363   unsigned ArgCounter = 0;
364   bool IllegalParams = false;
365   // Iterate through the block parameters until either one is found that is not
366   // a local void*, or the block is valid.
367   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
368        I != E; ++I, ++ArgCounter) {
369     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
370         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
371             LangAS::opencl_local) {
372       // Get the location of the error. If a block literal has been passed
373       // (BlockExpr) then we can point straight to the offending argument,
374       // else we just point to the variable reference.
375       SourceLocation ErrorLoc;
376       if (isa<BlockExpr>(BlockArg)) {
377         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
378         ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
379       } else if (isa<DeclRefExpr>(BlockArg)) {
380         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
381       }
382       S.Diag(ErrorLoc,
383              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
384       IllegalParams = true;
385     }
386   }
387 
388   return IllegalParams;
389 }
390 
391 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
392   if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
393     S.Diag(Call->getLocStart(), diag::err_opencl_requires_extension)
394           << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
395     return true;
396   }
397   return false;
398 }
399 
400 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
401   if (checkArgCount(S, TheCall, 2))
402     return true;
403 
404   if (checkOpenCLSubgroupExt(S, TheCall))
405     return true;
406 
407   // First argument is an ndrange_t type.
408   Expr *NDRangeArg = TheCall->getArg(0);
409   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
410     S.Diag(NDRangeArg->getLocStart(),
411            diag::err_opencl_builtin_expected_type)
412         << TheCall->getDirectCallee() << "'ndrange_t'";
413     return true;
414   }
415 
416   Expr *BlockArg = TheCall->getArg(1);
417   if (!isBlockPointer(BlockArg)) {
418     S.Diag(BlockArg->getLocStart(),
419            diag::err_opencl_builtin_expected_type)
420         << TheCall->getDirectCallee() << "block";
421     return true;
422   }
423   return checkOpenCLBlockArgs(S, BlockArg);
424 }
425 
426 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
427 /// get_kernel_work_group_size
428 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
429 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
430   if (checkArgCount(S, TheCall, 1))
431     return true;
432 
433   Expr *BlockArg = TheCall->getArg(0);
434   if (!isBlockPointer(BlockArg)) {
435     S.Diag(BlockArg->getLocStart(),
436            diag::err_opencl_builtin_expected_type)
437         << TheCall->getDirectCallee() << "block";
438     return true;
439   }
440   return checkOpenCLBlockArgs(S, BlockArg);
441 }
442 
443 /// Diagnose integer type and any valid implicit conversion to it.
444 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
445                                       const QualType &IntType);
446 
447 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
448                                             unsigned Start, unsigned End) {
449   bool IllegalParams = false;
450   for (unsigned I = Start; I <= End; ++I)
451     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
452                                               S.Context.getSizeType());
453   return IllegalParams;
454 }
455 
456 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
457 /// 'local void*' parameter of passed block.
458 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
459                                            Expr *BlockArg,
460                                            unsigned NumNonVarArgs) {
461   const BlockPointerType *BPT =
462       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
463   unsigned NumBlockParams =
464       BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
465   unsigned TotalNumArgs = TheCall->getNumArgs();
466 
467   // For each argument passed to the block, a corresponding uint needs to
468   // be passed to describe the size of the local memory.
469   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
470     S.Diag(TheCall->getLocStart(),
471            diag::err_opencl_enqueue_kernel_local_size_args);
472     return true;
473   }
474 
475   // Check that the sizes of the local memory are specified by integers.
476   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
477                                          TotalNumArgs - 1);
478 }
479 
480 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
481 /// overload formats specified in Table 6.13.17.1.
482 /// int enqueue_kernel(queue_t queue,
483 ///                    kernel_enqueue_flags_t flags,
484 ///                    const ndrange_t ndrange,
485 ///                    void (^block)(void))
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)(void))
493 /// int enqueue_kernel(queue_t queue,
494 ///                    kernel_enqueue_flags_t flags,
495 ///                    const ndrange_t ndrange,
496 ///                    void (^block)(local void*, ...),
497 ///                    uint size0, ...)
498 /// int enqueue_kernel(queue_t queue,
499 ///                    kernel_enqueue_flags_t flags,
500 ///                    const ndrange_t ndrange,
501 ///                    uint num_events_in_wait_list,
502 ///                    clk_event_t *event_wait_list,
503 ///                    clk_event_t *event_ret,
504 ///                    void (^block)(local void*, ...),
505 ///                    uint size0, ...)
506 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
507   unsigned NumArgs = TheCall->getNumArgs();
508 
509   if (NumArgs < 4) {
510     S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
511     return true;
512   }
513 
514   Expr *Arg0 = TheCall->getArg(0);
515   Expr *Arg1 = TheCall->getArg(1);
516   Expr *Arg2 = TheCall->getArg(2);
517   Expr *Arg3 = TheCall->getArg(3);
518 
519   // First argument always needs to be a queue_t type.
520   if (!Arg0->getType()->isQueueT()) {
521     S.Diag(TheCall->getArg(0)->getLocStart(),
522            diag::err_opencl_builtin_expected_type)
523         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
524     return true;
525   }
526 
527   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
528   if (!Arg1->getType()->isIntegerType()) {
529     S.Diag(TheCall->getArg(1)->getLocStart(),
530            diag::err_opencl_builtin_expected_type)
531         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
532     return true;
533   }
534 
535   // Third argument is always an ndrange_t type.
536   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
537     S.Diag(TheCall->getArg(2)->getLocStart(),
538            diag::err_opencl_builtin_expected_type)
539         << TheCall->getDirectCallee() << "'ndrange_t'";
540     return true;
541   }
542 
543   // With four arguments, there is only one form that the function could be
544   // called in: no events and no variable arguments.
545   if (NumArgs == 4) {
546     // check that the last argument is the right block type.
547     if (!isBlockPointer(Arg3)) {
548       S.Diag(Arg3->getLocStart(), diag::err_opencl_builtin_expected_type)
549           << TheCall->getDirectCallee() << "block";
550       return true;
551     }
552     // we have a block type, check the prototype
553     const BlockPointerType *BPT =
554         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
555     if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
556       S.Diag(Arg3->getLocStart(),
557              diag::err_opencl_enqueue_kernel_blocks_no_args);
558       return true;
559     }
560     return false;
561   }
562   // we can have block + varargs.
563   if (isBlockPointer(Arg3))
564     return (checkOpenCLBlockArgs(S, Arg3) ||
565             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
566   // last two cases with either exactly 7 args or 7 args and varargs.
567   if (NumArgs >= 7) {
568     // check common block argument.
569     Expr *Arg6 = TheCall->getArg(6);
570     if (!isBlockPointer(Arg6)) {
571       S.Diag(Arg6->getLocStart(), diag::err_opencl_builtin_expected_type)
572           << TheCall->getDirectCallee() << "block";
573       return true;
574     }
575     if (checkOpenCLBlockArgs(S, Arg6))
576       return true;
577 
578     // Forth argument has to be any integer type.
579     if (!Arg3->getType()->isIntegerType()) {
580       S.Diag(TheCall->getArg(3)->getLocStart(),
581              diag::err_opencl_builtin_expected_type)
582           << TheCall->getDirectCallee() << "integer";
583       return true;
584     }
585     // check remaining common arguments.
586     Expr *Arg4 = TheCall->getArg(4);
587     Expr *Arg5 = TheCall->getArg(5);
588 
589     // Fifth argument is always passed as a pointer to clk_event_t.
590     if (!Arg4->isNullPointerConstant(S.Context,
591                                      Expr::NPC_ValueDependentIsNotNull) &&
592         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
593       S.Diag(TheCall->getArg(4)->getLocStart(),
594              diag::err_opencl_builtin_expected_type)
595           << TheCall->getDirectCallee()
596           << S.Context.getPointerType(S.Context.OCLClkEventTy);
597       return true;
598     }
599 
600     // Sixth argument is always passed as a pointer to clk_event_t.
601     if (!Arg5->isNullPointerConstant(S.Context,
602                                      Expr::NPC_ValueDependentIsNotNull) &&
603         !(Arg5->getType()->isPointerType() &&
604           Arg5->getType()->getPointeeType()->isClkEventT())) {
605       S.Diag(TheCall->getArg(5)->getLocStart(),
606              diag::err_opencl_builtin_expected_type)
607           << TheCall->getDirectCallee()
608           << S.Context.getPointerType(S.Context.OCLClkEventTy);
609       return true;
610     }
611 
612     if (NumArgs == 7)
613       return false;
614 
615     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
616   }
617 
618   // None of the specific case has been detected, give generic error
619   S.Diag(TheCall->getLocStart(),
620          diag::err_opencl_enqueue_kernel_incorrect_args);
621   return true;
622 }
623 
624 /// Returns OpenCL access qual.
625 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
626     return D->getAttr<OpenCLAccessAttr>();
627 }
628 
629 /// Returns true if pipe element type is different from the pointer.
630 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
631   const Expr *Arg0 = Call->getArg(0);
632   // First argument type should always be pipe.
633   if (!Arg0->getType()->isPipeType()) {
634     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
635         << Call->getDirectCallee() << Arg0->getSourceRange();
636     return true;
637   }
638   OpenCLAccessAttr *AccessQual =
639       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
640   // Validates the access qualifier is compatible with the call.
641   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
642   // read_only and write_only, and assumed to be read_only if no qualifier is
643   // specified.
644   switch (Call->getDirectCallee()->getBuiltinID()) {
645   case Builtin::BIread_pipe:
646   case Builtin::BIreserve_read_pipe:
647   case Builtin::BIcommit_read_pipe:
648   case Builtin::BIwork_group_reserve_read_pipe:
649   case Builtin::BIsub_group_reserve_read_pipe:
650   case Builtin::BIwork_group_commit_read_pipe:
651   case Builtin::BIsub_group_commit_read_pipe:
652     if (!(!AccessQual || AccessQual->isReadOnly())) {
653       S.Diag(Arg0->getLocStart(),
654              diag::err_opencl_builtin_pipe_invalid_access_modifier)
655           << "read_only" << Arg0->getSourceRange();
656       return true;
657     }
658     break;
659   case Builtin::BIwrite_pipe:
660   case Builtin::BIreserve_write_pipe:
661   case Builtin::BIcommit_write_pipe:
662   case Builtin::BIwork_group_reserve_write_pipe:
663   case Builtin::BIsub_group_reserve_write_pipe:
664   case Builtin::BIwork_group_commit_write_pipe:
665   case Builtin::BIsub_group_commit_write_pipe:
666     if (!(AccessQual && AccessQual->isWriteOnly())) {
667       S.Diag(Arg0->getLocStart(),
668              diag::err_opencl_builtin_pipe_invalid_access_modifier)
669           << "write_only" << Arg0->getSourceRange();
670       return true;
671     }
672     break;
673   default:
674     break;
675   }
676   return false;
677 }
678 
679 /// Returns true if pipe element type is different from the pointer.
680 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
681   const Expr *Arg0 = Call->getArg(0);
682   const Expr *ArgIdx = Call->getArg(Idx);
683   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
684   const QualType EltTy = PipeTy->getElementType();
685   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
686   // The Idx argument should be a pointer and the type of the pointer and
687   // the type of pipe element should also be the same.
688   if (!ArgTy ||
689       !S.Context.hasSameType(
690           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
691     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
692         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
693         << ArgIdx->getType() << ArgIdx->getSourceRange();
694     return true;
695   }
696   return false;
697 }
698 
699 // Performs semantic analysis for the read/write_pipe call.
700 // \param S Reference to the semantic analyzer.
701 // \param Call A pointer to the builtin call.
702 // \return True if a semantic error has been found, false otherwise.
703 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
704   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
705   // functions have two forms.
706   switch (Call->getNumArgs()) {
707   case 2:
708     if (checkOpenCLPipeArg(S, Call))
709       return true;
710     // The call with 2 arguments should be
711     // read/write_pipe(pipe T, T*).
712     // Check packet type T.
713     if (checkOpenCLPipePacketType(S, Call, 1))
714       return true;
715     break;
716 
717   case 4: {
718     if (checkOpenCLPipeArg(S, Call))
719       return true;
720     // The call with 4 arguments should be
721     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
722     // Check reserve_id_t.
723     if (!Call->getArg(1)->getType()->isReserveIDT()) {
724       S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
725           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
726           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
727       return true;
728     }
729 
730     // Check the index.
731     const Expr *Arg2 = Call->getArg(2);
732     if (!Arg2->getType()->isIntegerType() &&
733         !Arg2->getType()->isUnsignedIntegerType()) {
734       S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
735           << Call->getDirectCallee() << S.Context.UnsignedIntTy
736           << Arg2->getType() << Arg2->getSourceRange();
737       return true;
738     }
739 
740     // Check packet type T.
741     if (checkOpenCLPipePacketType(S, Call, 3))
742       return true;
743   } break;
744   default:
745     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
746         << Call->getDirectCallee() << Call->getSourceRange();
747     return true;
748   }
749 
750   return false;
751 }
752 
753 // Performs a semantic analysis on the {work_group_/sub_group_
754 //        /_}reserve_{read/write}_pipe
755 // \param S Reference to the semantic analyzer.
756 // \param Call The call to the builtin function to be analyzed.
757 // \return True if a semantic error was found, false otherwise.
758 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
759   if (checkArgCount(S, Call, 2))
760     return true;
761 
762   if (checkOpenCLPipeArg(S, Call))
763     return true;
764 
765   // Check the reserve size.
766   if (!Call->getArg(1)->getType()->isIntegerType() &&
767       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
768     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
769         << Call->getDirectCallee() << S.Context.UnsignedIntTy
770         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
771     return true;
772   }
773 
774   // Since return type of reserve_read/write_pipe built-in function is
775   // reserve_id_t, which is not defined in the builtin def file , we used int
776   // as return type and need to override the return type of these functions.
777   Call->setType(S.Context.OCLReserveIDTy);
778 
779   return false;
780 }
781 
782 // Performs a semantic analysis on {work_group_/sub_group_
783 //        /_}commit_{read/write}_pipe
784 // \param S Reference to the semantic analyzer.
785 // \param Call The call to the builtin function to be analyzed.
786 // \return True if a semantic error was found, false otherwise.
787 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
788   if (checkArgCount(S, Call, 2))
789     return true;
790 
791   if (checkOpenCLPipeArg(S, Call))
792     return true;
793 
794   // Check reserve_id_t.
795   if (!Call->getArg(1)->getType()->isReserveIDT()) {
796     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
797         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
798         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
799     return true;
800   }
801 
802   return false;
803 }
804 
805 // Performs a semantic analysis on the call to built-in Pipe
806 //        Query Functions.
807 // \param S Reference to the semantic analyzer.
808 // \param Call The call to the builtin function to be analyzed.
809 // \return True if a semantic error was found, false otherwise.
810 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
811   if (checkArgCount(S, Call, 1))
812     return true;
813 
814   if (!Call->getArg(0)->getType()->isPipeType()) {
815     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
816         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
817     return true;
818   }
819 
820   return false;
821 }
822 
823 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
824 // Performs semantic analysis for the to_global/local/private call.
825 // \param S Reference to the semantic analyzer.
826 // \param BuiltinID ID of the builtin function.
827 // \param Call A pointer to the builtin call.
828 // \return True if a semantic error has been found, false otherwise.
829 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
830                                     CallExpr *Call) {
831   if (Call->getNumArgs() != 1) {
832     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
833         << Call->getDirectCallee() << Call->getSourceRange();
834     return true;
835   }
836 
837   auto RT = Call->getArg(0)->getType();
838   if (!RT->isPointerType() || RT->getPointeeType()
839       .getAddressSpace() == LangAS::opencl_constant) {
840     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
841         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
842     return true;
843   }
844 
845   RT = RT->getPointeeType();
846   auto Qual = RT.getQualifiers();
847   switch (BuiltinID) {
848   case Builtin::BIto_global:
849     Qual.setAddressSpace(LangAS::opencl_global);
850     break;
851   case Builtin::BIto_local:
852     Qual.setAddressSpace(LangAS::opencl_local);
853     break;
854   case Builtin::BIto_private:
855     Qual.setAddressSpace(LangAS::opencl_private);
856     break;
857   default:
858     llvm_unreachable("Invalid builtin function");
859   }
860   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
861       RT.getUnqualifiedType(), Qual)));
862 
863   return false;
864 }
865 
866 // Emit an error and return true if the current architecture is not in the list
867 // of supported architectures.
868 static bool
869 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
870                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
871   llvm::Triple::ArchType CurArch =
872       S.getASTContext().getTargetInfo().getTriple().getArch();
873   if (llvm::is_contained(SupportedArchs, CurArch))
874     return false;
875   S.Diag(TheCall->getLocStart(), diag::err_builtin_target_unsupported)
876       << TheCall->getSourceRange();
877   return true;
878 }
879 
880 ExprResult
881 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
882                                CallExpr *TheCall) {
883   ExprResult TheCallResult(TheCall);
884 
885   // Find out if any arguments are required to be integer constant expressions.
886   unsigned ICEArguments = 0;
887   ASTContext::GetBuiltinTypeError Error;
888   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
889   if (Error != ASTContext::GE_None)
890     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
891 
892   // If any arguments are required to be ICE's, check and diagnose.
893   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
894     // Skip arguments not required to be ICE's.
895     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
896 
897     llvm::APSInt Result;
898     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
899       return true;
900     ICEArguments &= ~(1 << ArgNo);
901   }
902 
903   switch (BuiltinID) {
904   case Builtin::BI__builtin___CFStringMakeConstantString:
905     assert(TheCall->getNumArgs() == 1 &&
906            "Wrong # arguments to builtin CFStringMakeConstantString");
907     if (CheckObjCString(TheCall->getArg(0)))
908       return ExprError();
909     break;
910   case Builtin::BI__builtin_ms_va_start:
911   case Builtin::BI__builtin_stdarg_start:
912   case Builtin::BI__builtin_va_start:
913     if (SemaBuiltinVAStart(BuiltinID, TheCall))
914       return ExprError();
915     break;
916   case Builtin::BI__va_start: {
917     switch (Context.getTargetInfo().getTriple().getArch()) {
918     case llvm::Triple::arm:
919     case llvm::Triple::thumb:
920       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
921         return ExprError();
922       break;
923     default:
924       if (SemaBuiltinVAStart(BuiltinID, TheCall))
925         return ExprError();
926       break;
927     }
928     break;
929   }
930 
931   // The acquire, release, and no fence variants are ARM and AArch64 only.
932   case Builtin::BI_interlockedbittestandset_acq:
933   case Builtin::BI_interlockedbittestandset_rel:
934   case Builtin::BI_interlockedbittestandset_nf:
935   case Builtin::BI_interlockedbittestandreset_acq:
936   case Builtin::BI_interlockedbittestandreset_rel:
937   case Builtin::BI_interlockedbittestandreset_nf:
938     if (CheckBuiltinTargetSupport(
939             *this, BuiltinID, TheCall,
940             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
941       return ExprError();
942     break;
943 
944   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
945   case Builtin::BI_bittest64:
946   case Builtin::BI_bittestandcomplement64:
947   case Builtin::BI_bittestandreset64:
948   case Builtin::BI_bittestandset64:
949   case Builtin::BI_interlockedbittestandreset64:
950   case Builtin::BI_interlockedbittestandset64:
951     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
952                                   {llvm::Triple::x86_64, llvm::Triple::arm,
953                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
954       return ExprError();
955     break;
956 
957   case Builtin::BI__builtin_isgreater:
958   case Builtin::BI__builtin_isgreaterequal:
959   case Builtin::BI__builtin_isless:
960   case Builtin::BI__builtin_islessequal:
961   case Builtin::BI__builtin_islessgreater:
962   case Builtin::BI__builtin_isunordered:
963     if (SemaBuiltinUnorderedCompare(TheCall))
964       return ExprError();
965     break;
966   case Builtin::BI__builtin_fpclassify:
967     if (SemaBuiltinFPClassification(TheCall, 6))
968       return ExprError();
969     break;
970   case Builtin::BI__builtin_isfinite:
971   case Builtin::BI__builtin_isinf:
972   case Builtin::BI__builtin_isinf_sign:
973   case Builtin::BI__builtin_isnan:
974   case Builtin::BI__builtin_isnormal:
975   case Builtin::BI__builtin_signbit:
976   case Builtin::BI__builtin_signbitf:
977   case Builtin::BI__builtin_signbitl:
978     if (SemaBuiltinFPClassification(TheCall, 1))
979       return ExprError();
980     break;
981   case Builtin::BI__builtin_shufflevector:
982     return SemaBuiltinShuffleVector(TheCall);
983     // TheCall will be freed by the smart pointer here, but that's fine, since
984     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
985   case Builtin::BI__builtin_prefetch:
986     if (SemaBuiltinPrefetch(TheCall))
987       return ExprError();
988     break;
989   case Builtin::BI__builtin_alloca_with_align:
990     if (SemaBuiltinAllocaWithAlign(TheCall))
991       return ExprError();
992     break;
993   case Builtin::BI__assume:
994   case Builtin::BI__builtin_assume:
995     if (SemaBuiltinAssume(TheCall))
996       return ExprError();
997     break;
998   case Builtin::BI__builtin_assume_aligned:
999     if (SemaBuiltinAssumeAligned(TheCall))
1000       return ExprError();
1001     break;
1002   case Builtin::BI__builtin_object_size:
1003     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1004       return ExprError();
1005     break;
1006   case Builtin::BI__builtin_longjmp:
1007     if (SemaBuiltinLongjmp(TheCall))
1008       return ExprError();
1009     break;
1010   case Builtin::BI__builtin_setjmp:
1011     if (SemaBuiltinSetjmp(TheCall))
1012       return ExprError();
1013     break;
1014   case Builtin::BI_setjmp:
1015   case Builtin::BI_setjmpex:
1016     if (checkArgCount(*this, TheCall, 1))
1017       return true;
1018     break;
1019   case Builtin::BI__builtin_classify_type:
1020     if (checkArgCount(*this, TheCall, 1)) return true;
1021     TheCall->setType(Context.IntTy);
1022     break;
1023   case Builtin::BI__builtin_constant_p:
1024     if (checkArgCount(*this, TheCall, 1)) return true;
1025     TheCall->setType(Context.IntTy);
1026     break;
1027   case Builtin::BI__sync_fetch_and_add:
1028   case Builtin::BI__sync_fetch_and_add_1:
1029   case Builtin::BI__sync_fetch_and_add_2:
1030   case Builtin::BI__sync_fetch_and_add_4:
1031   case Builtin::BI__sync_fetch_and_add_8:
1032   case Builtin::BI__sync_fetch_and_add_16:
1033   case Builtin::BI__sync_fetch_and_sub:
1034   case Builtin::BI__sync_fetch_and_sub_1:
1035   case Builtin::BI__sync_fetch_and_sub_2:
1036   case Builtin::BI__sync_fetch_and_sub_4:
1037   case Builtin::BI__sync_fetch_and_sub_8:
1038   case Builtin::BI__sync_fetch_and_sub_16:
1039   case Builtin::BI__sync_fetch_and_or:
1040   case Builtin::BI__sync_fetch_and_or_1:
1041   case Builtin::BI__sync_fetch_and_or_2:
1042   case Builtin::BI__sync_fetch_and_or_4:
1043   case Builtin::BI__sync_fetch_and_or_8:
1044   case Builtin::BI__sync_fetch_and_or_16:
1045   case Builtin::BI__sync_fetch_and_and:
1046   case Builtin::BI__sync_fetch_and_and_1:
1047   case Builtin::BI__sync_fetch_and_and_2:
1048   case Builtin::BI__sync_fetch_and_and_4:
1049   case Builtin::BI__sync_fetch_and_and_8:
1050   case Builtin::BI__sync_fetch_and_and_16:
1051   case Builtin::BI__sync_fetch_and_xor:
1052   case Builtin::BI__sync_fetch_and_xor_1:
1053   case Builtin::BI__sync_fetch_and_xor_2:
1054   case Builtin::BI__sync_fetch_and_xor_4:
1055   case Builtin::BI__sync_fetch_and_xor_8:
1056   case Builtin::BI__sync_fetch_and_xor_16:
1057   case Builtin::BI__sync_fetch_and_nand:
1058   case Builtin::BI__sync_fetch_and_nand_1:
1059   case Builtin::BI__sync_fetch_and_nand_2:
1060   case Builtin::BI__sync_fetch_and_nand_4:
1061   case Builtin::BI__sync_fetch_and_nand_8:
1062   case Builtin::BI__sync_fetch_and_nand_16:
1063   case Builtin::BI__sync_add_and_fetch:
1064   case Builtin::BI__sync_add_and_fetch_1:
1065   case Builtin::BI__sync_add_and_fetch_2:
1066   case Builtin::BI__sync_add_and_fetch_4:
1067   case Builtin::BI__sync_add_and_fetch_8:
1068   case Builtin::BI__sync_add_and_fetch_16:
1069   case Builtin::BI__sync_sub_and_fetch:
1070   case Builtin::BI__sync_sub_and_fetch_1:
1071   case Builtin::BI__sync_sub_and_fetch_2:
1072   case Builtin::BI__sync_sub_and_fetch_4:
1073   case Builtin::BI__sync_sub_and_fetch_8:
1074   case Builtin::BI__sync_sub_and_fetch_16:
1075   case Builtin::BI__sync_and_and_fetch:
1076   case Builtin::BI__sync_and_and_fetch_1:
1077   case Builtin::BI__sync_and_and_fetch_2:
1078   case Builtin::BI__sync_and_and_fetch_4:
1079   case Builtin::BI__sync_and_and_fetch_8:
1080   case Builtin::BI__sync_and_and_fetch_16:
1081   case Builtin::BI__sync_or_and_fetch:
1082   case Builtin::BI__sync_or_and_fetch_1:
1083   case Builtin::BI__sync_or_and_fetch_2:
1084   case Builtin::BI__sync_or_and_fetch_4:
1085   case Builtin::BI__sync_or_and_fetch_8:
1086   case Builtin::BI__sync_or_and_fetch_16:
1087   case Builtin::BI__sync_xor_and_fetch:
1088   case Builtin::BI__sync_xor_and_fetch_1:
1089   case Builtin::BI__sync_xor_and_fetch_2:
1090   case Builtin::BI__sync_xor_and_fetch_4:
1091   case Builtin::BI__sync_xor_and_fetch_8:
1092   case Builtin::BI__sync_xor_and_fetch_16:
1093   case Builtin::BI__sync_nand_and_fetch:
1094   case Builtin::BI__sync_nand_and_fetch_1:
1095   case Builtin::BI__sync_nand_and_fetch_2:
1096   case Builtin::BI__sync_nand_and_fetch_4:
1097   case Builtin::BI__sync_nand_and_fetch_8:
1098   case Builtin::BI__sync_nand_and_fetch_16:
1099   case Builtin::BI__sync_val_compare_and_swap:
1100   case Builtin::BI__sync_val_compare_and_swap_1:
1101   case Builtin::BI__sync_val_compare_and_swap_2:
1102   case Builtin::BI__sync_val_compare_and_swap_4:
1103   case Builtin::BI__sync_val_compare_and_swap_8:
1104   case Builtin::BI__sync_val_compare_and_swap_16:
1105   case Builtin::BI__sync_bool_compare_and_swap:
1106   case Builtin::BI__sync_bool_compare_and_swap_1:
1107   case Builtin::BI__sync_bool_compare_and_swap_2:
1108   case Builtin::BI__sync_bool_compare_and_swap_4:
1109   case Builtin::BI__sync_bool_compare_and_swap_8:
1110   case Builtin::BI__sync_bool_compare_and_swap_16:
1111   case Builtin::BI__sync_lock_test_and_set:
1112   case Builtin::BI__sync_lock_test_and_set_1:
1113   case Builtin::BI__sync_lock_test_and_set_2:
1114   case Builtin::BI__sync_lock_test_and_set_4:
1115   case Builtin::BI__sync_lock_test_and_set_8:
1116   case Builtin::BI__sync_lock_test_and_set_16:
1117   case Builtin::BI__sync_lock_release:
1118   case Builtin::BI__sync_lock_release_1:
1119   case Builtin::BI__sync_lock_release_2:
1120   case Builtin::BI__sync_lock_release_4:
1121   case Builtin::BI__sync_lock_release_8:
1122   case Builtin::BI__sync_lock_release_16:
1123   case Builtin::BI__sync_swap:
1124   case Builtin::BI__sync_swap_1:
1125   case Builtin::BI__sync_swap_2:
1126   case Builtin::BI__sync_swap_4:
1127   case Builtin::BI__sync_swap_8:
1128   case Builtin::BI__sync_swap_16:
1129     return SemaBuiltinAtomicOverloaded(TheCallResult);
1130   case Builtin::BI__builtin_nontemporal_load:
1131   case Builtin::BI__builtin_nontemporal_store:
1132     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1133 #define BUILTIN(ID, TYPE, ATTRS)
1134 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1135   case Builtin::BI##ID: \
1136     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1137 #include "clang/Basic/Builtins.def"
1138   case Builtin::BI__annotation:
1139     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1140       return ExprError();
1141     break;
1142   case Builtin::BI__builtin_annotation:
1143     if (SemaBuiltinAnnotation(*this, TheCall))
1144       return ExprError();
1145     break;
1146   case Builtin::BI__builtin_addressof:
1147     if (SemaBuiltinAddressof(*this, TheCall))
1148       return ExprError();
1149     break;
1150   case Builtin::BI__builtin_add_overflow:
1151   case Builtin::BI__builtin_sub_overflow:
1152   case Builtin::BI__builtin_mul_overflow:
1153     if (SemaBuiltinOverflow(*this, TheCall))
1154       return ExprError();
1155     break;
1156   case Builtin::BI__builtin_operator_new:
1157   case Builtin::BI__builtin_operator_delete: {
1158     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1159     ExprResult Res =
1160         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1161     if (Res.isInvalid())
1162       CorrectDelayedTyposInExpr(TheCallResult.get());
1163     return Res;
1164   }
1165   case Builtin::BI__builtin_dump_struct: {
1166     // We first want to ensure we are called with 2 arguments
1167     if (checkArgCount(*this, TheCall, 2))
1168       return ExprError();
1169     // Ensure that the first argument is of type 'struct XX *'
1170     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1171     const QualType PtrArgType = PtrArg->getType();
1172     if (!PtrArgType->isPointerType() ||
1173         !PtrArgType->getPointeeType()->isRecordType()) {
1174       Diag(PtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1175           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1176           << "structure pointer";
1177       return ExprError();
1178     }
1179 
1180     // Ensure that the second argument is of type 'FunctionType'
1181     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1182     const QualType FnPtrArgType = FnPtrArg->getType();
1183     if (!FnPtrArgType->isPointerType()) {
1184       Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1185           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1186           << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1187       return ExprError();
1188     }
1189 
1190     const auto *FuncType =
1191         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1192 
1193     if (!FuncType) {
1194       Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1195           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1196           << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1197       return ExprError();
1198     }
1199 
1200     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1201       if (!FT->getNumParams()) {
1202         Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1203             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1204             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1205         return ExprError();
1206       }
1207       QualType PT = FT->getParamType(0);
1208       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1209           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1210           !PT->getPointeeType().isConstQualified()) {
1211         Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1212             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1213             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1214         return ExprError();
1215       }
1216     }
1217 
1218     TheCall->setType(Context.IntTy);
1219     break;
1220   }
1221 
1222   // check secure string manipulation functions where overflows
1223   // are detectable at compile time
1224   case Builtin::BI__builtin___memcpy_chk:
1225   case Builtin::BI__builtin___memmove_chk:
1226   case Builtin::BI__builtin___memset_chk:
1227   case Builtin::BI__builtin___strlcat_chk:
1228   case Builtin::BI__builtin___strlcpy_chk:
1229   case Builtin::BI__builtin___strncat_chk:
1230   case Builtin::BI__builtin___strncpy_chk:
1231   case Builtin::BI__builtin___stpncpy_chk:
1232     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
1233     break;
1234   case Builtin::BI__builtin___memccpy_chk:
1235     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
1236     break;
1237   case Builtin::BI__builtin___snprintf_chk:
1238   case Builtin::BI__builtin___vsnprintf_chk:
1239     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
1240     break;
1241   case Builtin::BI__builtin_call_with_static_chain:
1242     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1243       return ExprError();
1244     break;
1245   case Builtin::BI__exception_code:
1246   case Builtin::BI_exception_code:
1247     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1248                                  diag::err_seh___except_block))
1249       return ExprError();
1250     break;
1251   case Builtin::BI__exception_info:
1252   case Builtin::BI_exception_info:
1253     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1254                                  diag::err_seh___except_filter))
1255       return ExprError();
1256     break;
1257   case Builtin::BI__GetExceptionInfo:
1258     if (checkArgCount(*this, TheCall, 1))
1259       return ExprError();
1260 
1261     if (CheckCXXThrowOperand(
1262             TheCall->getLocStart(),
1263             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1264             TheCall))
1265       return ExprError();
1266 
1267     TheCall->setType(Context.VoidPtrTy);
1268     break;
1269   // OpenCL v2.0, s6.13.16 - Pipe functions
1270   case Builtin::BIread_pipe:
1271   case Builtin::BIwrite_pipe:
1272     // Since those two functions are declared with var args, we need a semantic
1273     // check for the argument.
1274     if (SemaBuiltinRWPipe(*this, TheCall))
1275       return ExprError();
1276     TheCall->setType(Context.IntTy);
1277     break;
1278   case Builtin::BIreserve_read_pipe:
1279   case Builtin::BIreserve_write_pipe:
1280   case Builtin::BIwork_group_reserve_read_pipe:
1281   case Builtin::BIwork_group_reserve_write_pipe:
1282     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1283       return ExprError();
1284     break;
1285   case Builtin::BIsub_group_reserve_read_pipe:
1286   case Builtin::BIsub_group_reserve_write_pipe:
1287     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1288         SemaBuiltinReserveRWPipe(*this, TheCall))
1289       return ExprError();
1290     break;
1291   case Builtin::BIcommit_read_pipe:
1292   case Builtin::BIcommit_write_pipe:
1293   case Builtin::BIwork_group_commit_read_pipe:
1294   case Builtin::BIwork_group_commit_write_pipe:
1295     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1296       return ExprError();
1297     break;
1298   case Builtin::BIsub_group_commit_read_pipe:
1299   case Builtin::BIsub_group_commit_write_pipe:
1300     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1301         SemaBuiltinCommitRWPipe(*this, TheCall))
1302       return ExprError();
1303     break;
1304   case Builtin::BIget_pipe_num_packets:
1305   case Builtin::BIget_pipe_max_packets:
1306     if (SemaBuiltinPipePackets(*this, TheCall))
1307       return ExprError();
1308     TheCall->setType(Context.UnsignedIntTy);
1309     break;
1310   case Builtin::BIto_global:
1311   case Builtin::BIto_local:
1312   case Builtin::BIto_private:
1313     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1314       return ExprError();
1315     break;
1316   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1317   case Builtin::BIenqueue_kernel:
1318     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1319       return ExprError();
1320     break;
1321   case Builtin::BIget_kernel_work_group_size:
1322   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1323     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1324       return ExprError();
1325     break;
1326   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1327   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1328     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1329       return ExprError();
1330     break;
1331   case Builtin::BI__builtin_os_log_format:
1332   case Builtin::BI__builtin_os_log_format_buffer_size:
1333     if (SemaBuiltinOSLogFormat(TheCall))
1334       return ExprError();
1335     break;
1336   }
1337 
1338   // Since the target specific builtins for each arch overlap, only check those
1339   // of the arch we are compiling for.
1340   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1341     switch (Context.getTargetInfo().getTriple().getArch()) {
1342       case llvm::Triple::arm:
1343       case llvm::Triple::armeb:
1344       case llvm::Triple::thumb:
1345       case llvm::Triple::thumbeb:
1346         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1347           return ExprError();
1348         break;
1349       case llvm::Triple::aarch64:
1350       case llvm::Triple::aarch64_be:
1351         if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1352           return ExprError();
1353         break;
1354       case llvm::Triple::hexagon:
1355         if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall))
1356           return ExprError();
1357         break;
1358       case llvm::Triple::mips:
1359       case llvm::Triple::mipsel:
1360       case llvm::Triple::mips64:
1361       case llvm::Triple::mips64el:
1362         if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1363           return ExprError();
1364         break;
1365       case llvm::Triple::systemz:
1366         if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1367           return ExprError();
1368         break;
1369       case llvm::Triple::x86:
1370       case llvm::Triple::x86_64:
1371         if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1372           return ExprError();
1373         break;
1374       case llvm::Triple::ppc:
1375       case llvm::Triple::ppc64:
1376       case llvm::Triple::ppc64le:
1377         if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1378           return ExprError();
1379         break;
1380       default:
1381         break;
1382     }
1383   }
1384 
1385   return TheCallResult;
1386 }
1387 
1388 // Get the valid immediate range for the specified NEON type code.
1389 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1390   NeonTypeFlags Type(t);
1391   int IsQuad = ForceQuad ? true : Type.isQuad();
1392   switch (Type.getEltType()) {
1393   case NeonTypeFlags::Int8:
1394   case NeonTypeFlags::Poly8:
1395     return shift ? 7 : (8 << IsQuad) - 1;
1396   case NeonTypeFlags::Int16:
1397   case NeonTypeFlags::Poly16:
1398     return shift ? 15 : (4 << IsQuad) - 1;
1399   case NeonTypeFlags::Int32:
1400     return shift ? 31 : (2 << IsQuad) - 1;
1401   case NeonTypeFlags::Int64:
1402   case NeonTypeFlags::Poly64:
1403     return shift ? 63 : (1 << IsQuad) - 1;
1404   case NeonTypeFlags::Poly128:
1405     return shift ? 127 : (1 << IsQuad) - 1;
1406   case NeonTypeFlags::Float16:
1407     assert(!shift && "cannot shift float types!");
1408     return (4 << IsQuad) - 1;
1409   case NeonTypeFlags::Float32:
1410     assert(!shift && "cannot shift float types!");
1411     return (2 << IsQuad) - 1;
1412   case NeonTypeFlags::Float64:
1413     assert(!shift && "cannot shift float types!");
1414     return (1 << IsQuad) - 1;
1415   }
1416   llvm_unreachable("Invalid NeonTypeFlag!");
1417 }
1418 
1419 /// getNeonEltType - Return the QualType corresponding to the elements of
1420 /// the vector type specified by the NeonTypeFlags.  This is used to check
1421 /// the pointer arguments for Neon load/store intrinsics.
1422 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1423                                bool IsPolyUnsigned, bool IsInt64Long) {
1424   switch (Flags.getEltType()) {
1425   case NeonTypeFlags::Int8:
1426     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1427   case NeonTypeFlags::Int16:
1428     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1429   case NeonTypeFlags::Int32:
1430     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1431   case NeonTypeFlags::Int64:
1432     if (IsInt64Long)
1433       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1434     else
1435       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1436                                 : Context.LongLongTy;
1437   case NeonTypeFlags::Poly8:
1438     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1439   case NeonTypeFlags::Poly16:
1440     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1441   case NeonTypeFlags::Poly64:
1442     if (IsInt64Long)
1443       return Context.UnsignedLongTy;
1444     else
1445       return Context.UnsignedLongLongTy;
1446   case NeonTypeFlags::Poly128:
1447     break;
1448   case NeonTypeFlags::Float16:
1449     return Context.HalfTy;
1450   case NeonTypeFlags::Float32:
1451     return Context.FloatTy;
1452   case NeonTypeFlags::Float64:
1453     return Context.DoubleTy;
1454   }
1455   llvm_unreachable("Invalid NeonTypeFlag!");
1456 }
1457 
1458 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1459   llvm::APSInt Result;
1460   uint64_t mask = 0;
1461   unsigned TV = 0;
1462   int PtrArgNum = -1;
1463   bool HasConstPtr = false;
1464   switch (BuiltinID) {
1465 #define GET_NEON_OVERLOAD_CHECK
1466 #include "clang/Basic/arm_neon.inc"
1467 #include "clang/Basic/arm_fp16.inc"
1468 #undef GET_NEON_OVERLOAD_CHECK
1469   }
1470 
1471   // For NEON intrinsics which are overloaded on vector element type, validate
1472   // the immediate which specifies which variant to emit.
1473   unsigned ImmArg = TheCall->getNumArgs()-1;
1474   if (mask) {
1475     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1476       return true;
1477 
1478     TV = Result.getLimitedValue(64);
1479     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1480       return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
1481         << TheCall->getArg(ImmArg)->getSourceRange();
1482   }
1483 
1484   if (PtrArgNum >= 0) {
1485     // Check that pointer arguments have the specified type.
1486     Expr *Arg = TheCall->getArg(PtrArgNum);
1487     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1488       Arg = ICE->getSubExpr();
1489     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1490     QualType RHSTy = RHS.get()->getType();
1491 
1492     llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
1493     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1494                           Arch == llvm::Triple::aarch64_be;
1495     bool IsInt64Long =
1496         Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1497     QualType EltTy =
1498         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
1499     if (HasConstPtr)
1500       EltTy = EltTy.withConst();
1501     QualType LHSTy = Context.getPointerType(EltTy);
1502     AssignConvertType ConvTy;
1503     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1504     if (RHS.isInvalid())
1505       return true;
1506     if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1507                                  RHS.get(), AA_Assigning))
1508       return true;
1509   }
1510 
1511   // For NEON intrinsics which take an immediate value as part of the
1512   // instruction, range check them here.
1513   unsigned i = 0, l = 0, u = 0;
1514   switch (BuiltinID) {
1515   default:
1516     return false;
1517   #define GET_NEON_IMMEDIATE_CHECK
1518   #include "clang/Basic/arm_neon.inc"
1519   #include "clang/Basic/arm_fp16.inc"
1520   #undef GET_NEON_IMMEDIATE_CHECK
1521   }
1522 
1523   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1524 }
1525 
1526 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1527                                         unsigned MaxWidth) {
1528   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1529           BuiltinID == ARM::BI__builtin_arm_ldaex ||
1530           BuiltinID == ARM::BI__builtin_arm_strex ||
1531           BuiltinID == ARM::BI__builtin_arm_stlex ||
1532           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1533           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1534           BuiltinID == AArch64::BI__builtin_arm_strex ||
1535           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1536          "unexpected ARM builtin");
1537   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1538                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1539                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1540                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
1541 
1542   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1543 
1544   // Ensure that we have the proper number of arguments.
1545   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1546     return true;
1547 
1548   // Inspect the pointer argument of the atomic builtin.  This should always be
1549   // a pointer type, whose element is an integral scalar or pointer type.
1550   // Because it is a pointer type, we don't have to worry about any implicit
1551   // casts here.
1552   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1553   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1554   if (PointerArgRes.isInvalid())
1555     return true;
1556   PointerArg = PointerArgRes.get();
1557 
1558   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1559   if (!pointerType) {
1560     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1561       << PointerArg->getType() << PointerArg->getSourceRange();
1562     return true;
1563   }
1564 
1565   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1566   // task is to insert the appropriate casts into the AST. First work out just
1567   // what the appropriate type is.
1568   QualType ValType = pointerType->getPointeeType();
1569   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1570   if (IsLdrex)
1571     AddrType.addConst();
1572 
1573   // Issue a warning if the cast is dodgy.
1574   CastKind CastNeeded = CK_NoOp;
1575   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1576     CastNeeded = CK_BitCast;
1577     Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1578       << PointerArg->getType()
1579       << Context.getPointerType(AddrType)
1580       << AA_Passing << PointerArg->getSourceRange();
1581   }
1582 
1583   // Finally, do the cast and replace the argument with the corrected version.
1584   AddrType = Context.getPointerType(AddrType);
1585   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1586   if (PointerArgRes.isInvalid())
1587     return true;
1588   PointerArg = PointerArgRes.get();
1589 
1590   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1591 
1592   // In general, we allow ints, floats and pointers to be loaded and stored.
1593   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1594       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1595     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1596       << PointerArg->getType() << PointerArg->getSourceRange();
1597     return true;
1598   }
1599 
1600   // But ARM doesn't have instructions to deal with 128-bit versions.
1601   if (Context.getTypeSize(ValType) > MaxWidth) {
1602     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
1603     Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1604       << PointerArg->getType() << PointerArg->getSourceRange();
1605     return true;
1606   }
1607 
1608   switch (ValType.getObjCLifetime()) {
1609   case Qualifiers::OCL_None:
1610   case Qualifiers::OCL_ExplicitNone:
1611     // okay
1612     break;
1613 
1614   case Qualifiers::OCL_Weak:
1615   case Qualifiers::OCL_Strong:
1616   case Qualifiers::OCL_Autoreleasing:
1617     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1618       << ValType << PointerArg->getSourceRange();
1619     return true;
1620   }
1621 
1622   if (IsLdrex) {
1623     TheCall->setType(ValType);
1624     return false;
1625   }
1626 
1627   // Initialize the argument to be stored.
1628   ExprResult ValArg = TheCall->getArg(0);
1629   InitializedEntity Entity = InitializedEntity::InitializeParameter(
1630       Context, ValType, /*consume*/ false);
1631   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1632   if (ValArg.isInvalid())
1633     return true;
1634   TheCall->setArg(0, ValArg.get());
1635 
1636   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1637   // but the custom checker bypasses all default analysis.
1638   TheCall->setType(Context.IntTy);
1639   return false;
1640 }
1641 
1642 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1643   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1644       BuiltinID == ARM::BI__builtin_arm_ldaex ||
1645       BuiltinID == ARM::BI__builtin_arm_strex ||
1646       BuiltinID == ARM::BI__builtin_arm_stlex) {
1647     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1648   }
1649 
1650   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1651     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1652       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1653   }
1654 
1655   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1656       BuiltinID == ARM::BI__builtin_arm_wsr64)
1657     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1658 
1659   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1660       BuiltinID == ARM::BI__builtin_arm_rsrp ||
1661       BuiltinID == ARM::BI__builtin_arm_wsr ||
1662       BuiltinID == ARM::BI__builtin_arm_wsrp)
1663     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1664 
1665   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1666     return true;
1667 
1668   // For intrinsics which take an immediate value as part of the instruction,
1669   // range check them here.
1670   // FIXME: VFP Intrinsics should error if VFP not present.
1671   switch (BuiltinID) {
1672   default: return false;
1673   case ARM::BI__builtin_arm_ssat:
1674     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
1675   case ARM::BI__builtin_arm_usat:
1676     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
1677   case ARM::BI__builtin_arm_ssat16:
1678     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
1679   case ARM::BI__builtin_arm_usat16:
1680     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
1681   case ARM::BI__builtin_arm_vcvtr_f:
1682   case ARM::BI__builtin_arm_vcvtr_d:
1683     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
1684   case ARM::BI__builtin_arm_dmb:
1685   case ARM::BI__builtin_arm_dsb:
1686   case ARM::BI__builtin_arm_isb:
1687   case ARM::BI__builtin_arm_dbg:
1688     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
1689   }
1690 }
1691 
1692 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1693                                          CallExpr *TheCall) {
1694   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1695       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1696       BuiltinID == AArch64::BI__builtin_arm_strex ||
1697       BuiltinID == AArch64::BI__builtin_arm_stlex) {
1698     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1699   }
1700 
1701   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1702     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1703       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1704       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1705       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1706   }
1707 
1708   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1709       BuiltinID == AArch64::BI__builtin_arm_wsr64)
1710     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1711 
1712   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1713       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1714       BuiltinID == AArch64::BI__builtin_arm_wsr ||
1715       BuiltinID == AArch64::BI__builtin_arm_wsrp)
1716     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1717 
1718   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1719     return true;
1720 
1721   // For intrinsics which take an immediate value as part of the instruction,
1722   // range check them here.
1723   unsigned i = 0, l = 0, u = 0;
1724   switch (BuiltinID) {
1725   default: return false;
1726   case AArch64::BI__builtin_arm_dmb:
1727   case AArch64::BI__builtin_arm_dsb:
1728   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1729   }
1730 
1731   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1732 }
1733 
1734 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
1735                                            CallExpr *TheCall) {
1736   struct ArgInfo {
1737     ArgInfo(unsigned O, bool S, unsigned W, unsigned A)
1738       : OpNum(O), IsSigned(S), BitWidth(W), Align(A) {}
1739     unsigned OpNum = 0;
1740     bool IsSigned = false;
1741     unsigned BitWidth = 0;
1742     unsigned Align = 0;
1743   };
1744 
1745   static const std::map<unsigned, std::vector<ArgInfo>> Infos = {
1746     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
1747     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
1748     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
1749     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  0 }} },
1750     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
1751     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
1752     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
1753     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
1754     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
1755     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
1756     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
1757 
1758     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
1759     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
1760     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
1761     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
1762     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
1763     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
1764     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
1765     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
1766     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
1767     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
1768     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
1769 
1770     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
1771     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
1772     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
1773     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
1774     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
1775     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
1776     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
1777     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
1778     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
1779     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
1780     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
1781     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
1782     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
1783     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
1784     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
1785     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
1786     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
1787     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
1788     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
1789     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
1790     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
1791     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
1792     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
1793     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
1794     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
1795     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
1796     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
1797     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
1798     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
1799     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
1800     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
1801     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
1802     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
1803     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
1804     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
1805     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
1806     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
1807     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
1808     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
1809     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
1810     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
1811     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
1812     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
1813     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
1814     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
1815     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
1816     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
1817     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
1818     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
1819     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
1820     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
1821     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
1822                                                       {{ 1, false, 6,  0 }} },
1823     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
1824     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
1825     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
1826     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
1827     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
1828     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
1829     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
1830                                                       {{ 1, false, 5,  0 }} },
1831     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
1832     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
1833     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
1834     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
1835     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
1836     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
1837                                                        { 2, false, 5,  0 }} },
1838     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
1839                                                        { 2, false, 6,  0 }} },
1840     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
1841                                                        { 3, false, 5,  0 }} },
1842     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
1843                                                        { 3, false, 6,  0 }} },
1844     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
1845     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
1846     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
1847     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
1848     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
1849     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
1850     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
1851     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
1852     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
1853     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
1854     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
1855     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
1856     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
1857     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
1858     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
1859     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
1860                                                       {{ 2, false, 4,  0 },
1861                                                        { 3, false, 5,  0 }} },
1862     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
1863                                                       {{ 2, false, 4,  0 },
1864                                                        { 3, false, 5,  0 }} },
1865     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
1866                                                       {{ 2, false, 4,  0 },
1867                                                        { 3, false, 5,  0 }} },
1868     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
1869                                                       {{ 2, false, 4,  0 },
1870                                                        { 3, false, 5,  0 }} },
1871     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
1872     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
1873     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
1874     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
1875     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
1876     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
1877     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
1878     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
1879     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
1880     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
1881     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
1882                                                        { 2, false, 5,  0 }} },
1883     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
1884                                                        { 2, false, 6,  0 }} },
1885     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
1886     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
1887     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
1888     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
1889     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
1890     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
1891     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
1892     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
1893     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
1894                                                       {{ 1, false, 4,  0 }} },
1895     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
1896     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
1897                                                       {{ 1, false, 4,  0 }} },
1898     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
1899     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
1900     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
1901     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
1902     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
1903     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
1904     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
1905     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
1906     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
1907     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
1908     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
1909     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
1910     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
1911     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
1912     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
1913     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
1914     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
1915     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
1916     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
1917     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
1918                                                       {{ 3, false, 1,  0 }} },
1919     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
1920     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
1921     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
1922     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
1923                                                       {{ 3, false, 1,  0 }} },
1924     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
1925     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
1926     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
1927     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
1928                                                       {{ 3, false, 1,  0 }} },
1929   };
1930 
1931   auto F = Infos.find(BuiltinID);
1932   if (F == Infos.end())
1933     return false;
1934 
1935   bool Error = false;
1936 
1937   for (const ArgInfo &A : F->second) {
1938     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth-1)) : 0;
1939     int32_t Max = (1 << (A.IsSigned ? A.BitWidth-1 : A.BitWidth)) - 1;
1940     if (!A.Align) {
1941       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
1942     } else {
1943       unsigned M = 1 << A.Align;
1944       Min *= M;
1945       Max *= M;
1946       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
1947                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
1948     }
1949   }
1950   return Error;
1951 }
1952 
1953 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1954 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1955 // ordering for DSP is unspecified. MSA is ordered by the data format used
1956 // by the underlying instruction i.e., df/m, df/n and then by size.
1957 //
1958 // FIXME: The size tests here should instead be tablegen'd along with the
1959 //        definitions from include/clang/Basic/BuiltinsMips.def.
1960 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
1961 //        be too.
1962 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1963   unsigned i = 0, l = 0, u = 0, m = 0;
1964   switch (BuiltinID) {
1965   default: return false;
1966   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1967   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
1968   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1969   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1970   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1971   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1972   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
1973   // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1974   // df/m field.
1975   // These intrinsics take an unsigned 3 bit immediate.
1976   case Mips::BI__builtin_msa_bclri_b:
1977   case Mips::BI__builtin_msa_bnegi_b:
1978   case Mips::BI__builtin_msa_bseti_b:
1979   case Mips::BI__builtin_msa_sat_s_b:
1980   case Mips::BI__builtin_msa_sat_u_b:
1981   case Mips::BI__builtin_msa_slli_b:
1982   case Mips::BI__builtin_msa_srai_b:
1983   case Mips::BI__builtin_msa_srari_b:
1984   case Mips::BI__builtin_msa_srli_b:
1985   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1986   case Mips::BI__builtin_msa_binsli_b:
1987   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1988   // These intrinsics take an unsigned 4 bit immediate.
1989   case Mips::BI__builtin_msa_bclri_h:
1990   case Mips::BI__builtin_msa_bnegi_h:
1991   case Mips::BI__builtin_msa_bseti_h:
1992   case Mips::BI__builtin_msa_sat_s_h:
1993   case Mips::BI__builtin_msa_sat_u_h:
1994   case Mips::BI__builtin_msa_slli_h:
1995   case Mips::BI__builtin_msa_srai_h:
1996   case Mips::BI__builtin_msa_srari_h:
1997   case Mips::BI__builtin_msa_srli_h:
1998   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1999   case Mips::BI__builtin_msa_binsli_h:
2000   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
2001   // These intrinsics take an unsigned 5 bit immediate.
2002   // The first block of intrinsics actually have an unsigned 5 bit field,
2003   // not a df/n field.
2004   case Mips::BI__builtin_msa_clei_u_b:
2005   case Mips::BI__builtin_msa_clei_u_h:
2006   case Mips::BI__builtin_msa_clei_u_w:
2007   case Mips::BI__builtin_msa_clei_u_d:
2008   case Mips::BI__builtin_msa_clti_u_b:
2009   case Mips::BI__builtin_msa_clti_u_h:
2010   case Mips::BI__builtin_msa_clti_u_w:
2011   case Mips::BI__builtin_msa_clti_u_d:
2012   case Mips::BI__builtin_msa_maxi_u_b:
2013   case Mips::BI__builtin_msa_maxi_u_h:
2014   case Mips::BI__builtin_msa_maxi_u_w:
2015   case Mips::BI__builtin_msa_maxi_u_d:
2016   case Mips::BI__builtin_msa_mini_u_b:
2017   case Mips::BI__builtin_msa_mini_u_h:
2018   case Mips::BI__builtin_msa_mini_u_w:
2019   case Mips::BI__builtin_msa_mini_u_d:
2020   case Mips::BI__builtin_msa_addvi_b:
2021   case Mips::BI__builtin_msa_addvi_h:
2022   case Mips::BI__builtin_msa_addvi_w:
2023   case Mips::BI__builtin_msa_addvi_d:
2024   case Mips::BI__builtin_msa_bclri_w:
2025   case Mips::BI__builtin_msa_bnegi_w:
2026   case Mips::BI__builtin_msa_bseti_w:
2027   case Mips::BI__builtin_msa_sat_s_w:
2028   case Mips::BI__builtin_msa_sat_u_w:
2029   case Mips::BI__builtin_msa_slli_w:
2030   case Mips::BI__builtin_msa_srai_w:
2031   case Mips::BI__builtin_msa_srari_w:
2032   case Mips::BI__builtin_msa_srli_w:
2033   case Mips::BI__builtin_msa_srlri_w:
2034   case Mips::BI__builtin_msa_subvi_b:
2035   case Mips::BI__builtin_msa_subvi_h:
2036   case Mips::BI__builtin_msa_subvi_w:
2037   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
2038   case Mips::BI__builtin_msa_binsli_w:
2039   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
2040   // These intrinsics take an unsigned 6 bit immediate.
2041   case Mips::BI__builtin_msa_bclri_d:
2042   case Mips::BI__builtin_msa_bnegi_d:
2043   case Mips::BI__builtin_msa_bseti_d:
2044   case Mips::BI__builtin_msa_sat_s_d:
2045   case Mips::BI__builtin_msa_sat_u_d:
2046   case Mips::BI__builtin_msa_slli_d:
2047   case Mips::BI__builtin_msa_srai_d:
2048   case Mips::BI__builtin_msa_srari_d:
2049   case Mips::BI__builtin_msa_srli_d:
2050   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
2051   case Mips::BI__builtin_msa_binsli_d:
2052   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
2053   // These intrinsics take a signed 5 bit immediate.
2054   case Mips::BI__builtin_msa_ceqi_b:
2055   case Mips::BI__builtin_msa_ceqi_h:
2056   case Mips::BI__builtin_msa_ceqi_w:
2057   case Mips::BI__builtin_msa_ceqi_d:
2058   case Mips::BI__builtin_msa_clti_s_b:
2059   case Mips::BI__builtin_msa_clti_s_h:
2060   case Mips::BI__builtin_msa_clti_s_w:
2061   case Mips::BI__builtin_msa_clti_s_d:
2062   case Mips::BI__builtin_msa_clei_s_b:
2063   case Mips::BI__builtin_msa_clei_s_h:
2064   case Mips::BI__builtin_msa_clei_s_w:
2065   case Mips::BI__builtin_msa_clei_s_d:
2066   case Mips::BI__builtin_msa_maxi_s_b:
2067   case Mips::BI__builtin_msa_maxi_s_h:
2068   case Mips::BI__builtin_msa_maxi_s_w:
2069   case Mips::BI__builtin_msa_maxi_s_d:
2070   case Mips::BI__builtin_msa_mini_s_b:
2071   case Mips::BI__builtin_msa_mini_s_h:
2072   case Mips::BI__builtin_msa_mini_s_w:
2073   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
2074   // These intrinsics take an unsigned 8 bit immediate.
2075   case Mips::BI__builtin_msa_andi_b:
2076   case Mips::BI__builtin_msa_nori_b:
2077   case Mips::BI__builtin_msa_ori_b:
2078   case Mips::BI__builtin_msa_shf_b:
2079   case Mips::BI__builtin_msa_shf_h:
2080   case Mips::BI__builtin_msa_shf_w:
2081   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
2082   case Mips::BI__builtin_msa_bseli_b:
2083   case Mips::BI__builtin_msa_bmnzi_b:
2084   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
2085   // df/n format
2086   // These intrinsics take an unsigned 4 bit immediate.
2087   case Mips::BI__builtin_msa_copy_s_b:
2088   case Mips::BI__builtin_msa_copy_u_b:
2089   case Mips::BI__builtin_msa_insve_b:
2090   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
2091   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
2092   // These intrinsics take an unsigned 3 bit immediate.
2093   case Mips::BI__builtin_msa_copy_s_h:
2094   case Mips::BI__builtin_msa_copy_u_h:
2095   case Mips::BI__builtin_msa_insve_h:
2096   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
2097   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
2098   // These intrinsics take an unsigned 2 bit immediate.
2099   case Mips::BI__builtin_msa_copy_s_w:
2100   case Mips::BI__builtin_msa_copy_u_w:
2101   case Mips::BI__builtin_msa_insve_w:
2102   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
2103   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
2104   // These intrinsics take an unsigned 1 bit immediate.
2105   case Mips::BI__builtin_msa_copy_s_d:
2106   case Mips::BI__builtin_msa_copy_u_d:
2107   case Mips::BI__builtin_msa_insve_d:
2108   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
2109   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
2110   // Memory offsets and immediate loads.
2111   // These intrinsics take a signed 10 bit immediate.
2112   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
2113   case Mips::BI__builtin_msa_ldi_h:
2114   case Mips::BI__builtin_msa_ldi_w:
2115   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
2116   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
2117   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
2118   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
2119   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
2120   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
2121   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
2122   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
2123   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
2124   }
2125 
2126   if (!m)
2127     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2128 
2129   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
2130          SemaBuiltinConstantArgMultiple(TheCall, i, m);
2131 }
2132 
2133 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2134   unsigned i = 0, l = 0, u = 0;
2135   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
2136                       BuiltinID == PPC::BI__builtin_divdeu ||
2137                       BuiltinID == PPC::BI__builtin_bpermd;
2138   bool IsTarget64Bit = Context.getTargetInfo()
2139                               .getTypeWidth(Context
2140                                             .getTargetInfo()
2141                                             .getIntPtrType()) == 64;
2142   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
2143                        BuiltinID == PPC::BI__builtin_divweu ||
2144                        BuiltinID == PPC::BI__builtin_divde ||
2145                        BuiltinID == PPC::BI__builtin_divdeu;
2146 
2147   if (Is64BitBltin && !IsTarget64Bit)
2148       return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
2149              << TheCall->getSourceRange();
2150 
2151   if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
2152       (BuiltinID == PPC::BI__builtin_bpermd &&
2153        !Context.getTargetInfo().hasFeature("bpermd")))
2154     return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
2155            << TheCall->getSourceRange();
2156 
2157   switch (BuiltinID) {
2158   default: return false;
2159   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
2160   case PPC::BI__builtin_altivec_crypto_vshasigmad:
2161     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2162            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
2163   case PPC::BI__builtin_tbegin:
2164   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
2165   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
2166   case PPC::BI__builtin_tabortwc:
2167   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
2168   case PPC::BI__builtin_tabortwci:
2169   case PPC::BI__builtin_tabortdci:
2170     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
2171            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
2172   case PPC::BI__builtin_vsx_xxpermdi:
2173   case PPC::BI__builtin_vsx_xxsldwi:
2174     return SemaBuiltinVSX(TheCall);
2175   }
2176   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2177 }
2178 
2179 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
2180                                            CallExpr *TheCall) {
2181   if (BuiltinID == SystemZ::BI__builtin_tabort) {
2182     Expr *Arg = TheCall->getArg(0);
2183     llvm::APSInt AbortCode(32);
2184     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
2185         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
2186       return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
2187              << Arg->getSourceRange();
2188   }
2189 
2190   // For intrinsics which take an immediate value as part of the instruction,
2191   // range check them here.
2192   unsigned i = 0, l = 0, u = 0;
2193   switch (BuiltinID) {
2194   default: return false;
2195   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
2196   case SystemZ::BI__builtin_s390_verimb:
2197   case SystemZ::BI__builtin_s390_verimh:
2198   case SystemZ::BI__builtin_s390_verimf:
2199   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
2200   case SystemZ::BI__builtin_s390_vfaeb:
2201   case SystemZ::BI__builtin_s390_vfaeh:
2202   case SystemZ::BI__builtin_s390_vfaef:
2203   case SystemZ::BI__builtin_s390_vfaebs:
2204   case SystemZ::BI__builtin_s390_vfaehs:
2205   case SystemZ::BI__builtin_s390_vfaefs:
2206   case SystemZ::BI__builtin_s390_vfaezb:
2207   case SystemZ::BI__builtin_s390_vfaezh:
2208   case SystemZ::BI__builtin_s390_vfaezf:
2209   case SystemZ::BI__builtin_s390_vfaezbs:
2210   case SystemZ::BI__builtin_s390_vfaezhs:
2211   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
2212   case SystemZ::BI__builtin_s390_vfisb:
2213   case SystemZ::BI__builtin_s390_vfidb:
2214     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
2215            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
2216   case SystemZ::BI__builtin_s390_vftcisb:
2217   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
2218   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
2219   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
2220   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
2221   case SystemZ::BI__builtin_s390_vstrcb:
2222   case SystemZ::BI__builtin_s390_vstrch:
2223   case SystemZ::BI__builtin_s390_vstrcf:
2224   case SystemZ::BI__builtin_s390_vstrczb:
2225   case SystemZ::BI__builtin_s390_vstrczh:
2226   case SystemZ::BI__builtin_s390_vstrczf:
2227   case SystemZ::BI__builtin_s390_vstrcbs:
2228   case SystemZ::BI__builtin_s390_vstrchs:
2229   case SystemZ::BI__builtin_s390_vstrcfs:
2230   case SystemZ::BI__builtin_s390_vstrczbs:
2231   case SystemZ::BI__builtin_s390_vstrczhs:
2232   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
2233   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
2234   case SystemZ::BI__builtin_s390_vfminsb:
2235   case SystemZ::BI__builtin_s390_vfmaxsb:
2236   case SystemZ::BI__builtin_s390_vfmindb:
2237   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
2238   }
2239   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2240 }
2241 
2242 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
2243 /// This checks that the target supports __builtin_cpu_supports and
2244 /// that the string argument is constant and valid.
2245 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
2246   Expr *Arg = TheCall->getArg(0);
2247 
2248   // Check if the argument is a string literal.
2249   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
2250     return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
2251            << Arg->getSourceRange();
2252 
2253   // Check the contents of the string.
2254   StringRef Feature =
2255       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
2256   if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
2257     return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
2258            << Arg->getSourceRange();
2259   return false;
2260 }
2261 
2262 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
2263 /// This checks that the target supports __builtin_cpu_is and
2264 /// that the string argument is constant and valid.
2265 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
2266   Expr *Arg = TheCall->getArg(0);
2267 
2268   // Check if the argument is a string literal.
2269   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
2270     return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
2271            << Arg->getSourceRange();
2272 
2273   // Check the contents of the string.
2274   StringRef Feature =
2275       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
2276   if (!S.Context.getTargetInfo().validateCpuIs(Feature))
2277     return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is)
2278            << Arg->getSourceRange();
2279   return false;
2280 }
2281 
2282 // Check if the rounding mode is legal.
2283 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
2284   // Indicates if this instruction has rounding control or just SAE.
2285   bool HasRC = false;
2286 
2287   unsigned ArgNum = 0;
2288   switch (BuiltinID) {
2289   default:
2290     return false;
2291   case X86::BI__builtin_ia32_vcvttsd2si32:
2292   case X86::BI__builtin_ia32_vcvttsd2si64:
2293   case X86::BI__builtin_ia32_vcvttsd2usi32:
2294   case X86::BI__builtin_ia32_vcvttsd2usi64:
2295   case X86::BI__builtin_ia32_vcvttss2si32:
2296   case X86::BI__builtin_ia32_vcvttss2si64:
2297   case X86::BI__builtin_ia32_vcvttss2usi32:
2298   case X86::BI__builtin_ia32_vcvttss2usi64:
2299     ArgNum = 1;
2300     break;
2301   case X86::BI__builtin_ia32_maxpd512:
2302   case X86::BI__builtin_ia32_maxps512:
2303   case X86::BI__builtin_ia32_minpd512:
2304   case X86::BI__builtin_ia32_minps512:
2305     ArgNum = 2;
2306     break;
2307   case X86::BI__builtin_ia32_cvtps2pd512_mask:
2308   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
2309   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
2310   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
2311   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
2312   case X86::BI__builtin_ia32_cvttps2dq512_mask:
2313   case X86::BI__builtin_ia32_cvttps2qq512_mask:
2314   case X86::BI__builtin_ia32_cvttps2udq512_mask:
2315   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
2316   case X86::BI__builtin_ia32_exp2pd_mask:
2317   case X86::BI__builtin_ia32_exp2ps_mask:
2318   case X86::BI__builtin_ia32_getexppd512_mask:
2319   case X86::BI__builtin_ia32_getexpps512_mask:
2320   case X86::BI__builtin_ia32_rcp28pd_mask:
2321   case X86::BI__builtin_ia32_rcp28ps_mask:
2322   case X86::BI__builtin_ia32_rsqrt28pd_mask:
2323   case X86::BI__builtin_ia32_rsqrt28ps_mask:
2324   case X86::BI__builtin_ia32_vcomisd:
2325   case X86::BI__builtin_ia32_vcomiss:
2326   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
2327     ArgNum = 3;
2328     break;
2329   case X86::BI__builtin_ia32_cmppd512_mask:
2330   case X86::BI__builtin_ia32_cmpps512_mask:
2331   case X86::BI__builtin_ia32_cmpsd_mask:
2332   case X86::BI__builtin_ia32_cmpss_mask:
2333   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
2334   case X86::BI__builtin_ia32_getexpsd128_round_mask:
2335   case X86::BI__builtin_ia32_getexpss128_round_mask:
2336   case X86::BI__builtin_ia32_maxsd_round_mask:
2337   case X86::BI__builtin_ia32_maxss_round_mask:
2338   case X86::BI__builtin_ia32_minsd_round_mask:
2339   case X86::BI__builtin_ia32_minss_round_mask:
2340   case X86::BI__builtin_ia32_rcp28sd_round_mask:
2341   case X86::BI__builtin_ia32_rcp28ss_round_mask:
2342   case X86::BI__builtin_ia32_reducepd512_mask:
2343   case X86::BI__builtin_ia32_reduceps512_mask:
2344   case X86::BI__builtin_ia32_rndscalepd_mask:
2345   case X86::BI__builtin_ia32_rndscaleps_mask:
2346   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
2347   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
2348     ArgNum = 4;
2349     break;
2350   case X86::BI__builtin_ia32_fixupimmpd512_mask:
2351   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2352   case X86::BI__builtin_ia32_fixupimmps512_mask:
2353   case X86::BI__builtin_ia32_fixupimmps512_maskz:
2354   case X86::BI__builtin_ia32_fixupimmsd_mask:
2355   case X86::BI__builtin_ia32_fixupimmsd_maskz:
2356   case X86::BI__builtin_ia32_fixupimmss_mask:
2357   case X86::BI__builtin_ia32_fixupimmss_maskz:
2358   case X86::BI__builtin_ia32_rangepd512_mask:
2359   case X86::BI__builtin_ia32_rangeps512_mask:
2360   case X86::BI__builtin_ia32_rangesd128_round_mask:
2361   case X86::BI__builtin_ia32_rangess128_round_mask:
2362   case X86::BI__builtin_ia32_reducesd_mask:
2363   case X86::BI__builtin_ia32_reducess_mask:
2364   case X86::BI__builtin_ia32_rndscalesd_round_mask:
2365   case X86::BI__builtin_ia32_rndscaless_round_mask:
2366     ArgNum = 5;
2367     break;
2368   case X86::BI__builtin_ia32_vcvtsd2si64:
2369   case X86::BI__builtin_ia32_vcvtsd2si32:
2370   case X86::BI__builtin_ia32_vcvtsd2usi32:
2371   case X86::BI__builtin_ia32_vcvtsd2usi64:
2372   case X86::BI__builtin_ia32_vcvtss2si32:
2373   case X86::BI__builtin_ia32_vcvtss2si64:
2374   case X86::BI__builtin_ia32_vcvtss2usi32:
2375   case X86::BI__builtin_ia32_vcvtss2usi64:
2376   case X86::BI__builtin_ia32_sqrtpd512:
2377   case X86::BI__builtin_ia32_sqrtps512:
2378     ArgNum = 1;
2379     HasRC = true;
2380     break;
2381   case X86::BI__builtin_ia32_addpd512:
2382   case X86::BI__builtin_ia32_addps512:
2383   case X86::BI__builtin_ia32_divpd512:
2384   case X86::BI__builtin_ia32_divps512:
2385   case X86::BI__builtin_ia32_mulpd512:
2386   case X86::BI__builtin_ia32_mulps512:
2387   case X86::BI__builtin_ia32_subpd512:
2388   case X86::BI__builtin_ia32_subps512:
2389   case X86::BI__builtin_ia32_cvtsi2sd64:
2390   case X86::BI__builtin_ia32_cvtsi2ss32:
2391   case X86::BI__builtin_ia32_cvtsi2ss64:
2392   case X86::BI__builtin_ia32_cvtusi2sd64:
2393   case X86::BI__builtin_ia32_cvtusi2ss32:
2394   case X86::BI__builtin_ia32_cvtusi2ss64:
2395     ArgNum = 2;
2396     HasRC = true;
2397     break;
2398   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
2399   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
2400   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
2401   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
2402   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
2403   case X86::BI__builtin_ia32_cvtps2qq512_mask:
2404   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
2405   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
2406   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
2407   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
2408   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
2409     ArgNum = 3;
2410     HasRC = true;
2411     break;
2412   case X86::BI__builtin_ia32_addss_round_mask:
2413   case X86::BI__builtin_ia32_addsd_round_mask:
2414   case X86::BI__builtin_ia32_divss_round_mask:
2415   case X86::BI__builtin_ia32_divsd_round_mask:
2416   case X86::BI__builtin_ia32_mulss_round_mask:
2417   case X86::BI__builtin_ia32_mulsd_round_mask:
2418   case X86::BI__builtin_ia32_subss_round_mask:
2419   case X86::BI__builtin_ia32_subsd_round_mask:
2420   case X86::BI__builtin_ia32_scalefpd512_mask:
2421   case X86::BI__builtin_ia32_scalefps512_mask:
2422   case X86::BI__builtin_ia32_scalefsd_round_mask:
2423   case X86::BI__builtin_ia32_scalefss_round_mask:
2424   case X86::BI__builtin_ia32_getmantpd512_mask:
2425   case X86::BI__builtin_ia32_getmantps512_mask:
2426   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
2427   case X86::BI__builtin_ia32_sqrtsd_round_mask:
2428   case X86::BI__builtin_ia32_sqrtss_round_mask:
2429   case X86::BI__builtin_ia32_vfmaddsd3_mask:
2430   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
2431   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
2432   case X86::BI__builtin_ia32_vfmaddss3_mask:
2433   case X86::BI__builtin_ia32_vfmaddss3_maskz:
2434   case X86::BI__builtin_ia32_vfmaddss3_mask3:
2435   case X86::BI__builtin_ia32_vfmaddpd512_mask:
2436   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
2437   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
2438   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
2439   case X86::BI__builtin_ia32_vfmaddps512_mask:
2440   case X86::BI__builtin_ia32_vfmaddps512_maskz:
2441   case X86::BI__builtin_ia32_vfmaddps512_mask3:
2442   case X86::BI__builtin_ia32_vfmsubps512_mask3:
2443   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
2444   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
2445   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
2446   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
2447   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
2448   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
2449   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
2450   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
2451     ArgNum = 4;
2452     HasRC = true;
2453     break;
2454   case X86::BI__builtin_ia32_getmantsd_round_mask:
2455   case X86::BI__builtin_ia32_getmantss_round_mask:
2456     ArgNum = 5;
2457     HasRC = true;
2458     break;
2459   }
2460 
2461   llvm::APSInt Result;
2462 
2463   // We can't check the value of a dependent argument.
2464   Expr *Arg = TheCall->getArg(ArgNum);
2465   if (Arg->isTypeDependent() || Arg->isValueDependent())
2466     return false;
2467 
2468   // Check constant-ness first.
2469   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2470     return true;
2471 
2472   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
2473   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
2474   // combined with ROUND_NO_EXC.
2475   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
2476       Result == 8/*ROUND_NO_EXC*/ ||
2477       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
2478     return false;
2479 
2480   return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
2481     << Arg->getSourceRange();
2482 }
2483 
2484 // Check if the gather/scatter scale is legal.
2485 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
2486                                              CallExpr *TheCall) {
2487   unsigned ArgNum = 0;
2488   switch (BuiltinID) {
2489   default:
2490     return false;
2491   case X86::BI__builtin_ia32_gatherpfdpd:
2492   case X86::BI__builtin_ia32_gatherpfdps:
2493   case X86::BI__builtin_ia32_gatherpfqpd:
2494   case X86::BI__builtin_ia32_gatherpfqps:
2495   case X86::BI__builtin_ia32_scatterpfdpd:
2496   case X86::BI__builtin_ia32_scatterpfdps:
2497   case X86::BI__builtin_ia32_scatterpfqpd:
2498   case X86::BI__builtin_ia32_scatterpfqps:
2499     ArgNum = 3;
2500     break;
2501   case X86::BI__builtin_ia32_gatherd_pd:
2502   case X86::BI__builtin_ia32_gatherd_pd256:
2503   case X86::BI__builtin_ia32_gatherq_pd:
2504   case X86::BI__builtin_ia32_gatherq_pd256:
2505   case X86::BI__builtin_ia32_gatherd_ps:
2506   case X86::BI__builtin_ia32_gatherd_ps256:
2507   case X86::BI__builtin_ia32_gatherq_ps:
2508   case X86::BI__builtin_ia32_gatherq_ps256:
2509   case X86::BI__builtin_ia32_gatherd_q:
2510   case X86::BI__builtin_ia32_gatherd_q256:
2511   case X86::BI__builtin_ia32_gatherq_q:
2512   case X86::BI__builtin_ia32_gatherq_q256:
2513   case X86::BI__builtin_ia32_gatherd_d:
2514   case X86::BI__builtin_ia32_gatherd_d256:
2515   case X86::BI__builtin_ia32_gatherq_d:
2516   case X86::BI__builtin_ia32_gatherq_d256:
2517   case X86::BI__builtin_ia32_gather3div2df:
2518   case X86::BI__builtin_ia32_gather3div2di:
2519   case X86::BI__builtin_ia32_gather3div4df:
2520   case X86::BI__builtin_ia32_gather3div4di:
2521   case X86::BI__builtin_ia32_gather3div4sf:
2522   case X86::BI__builtin_ia32_gather3div4si:
2523   case X86::BI__builtin_ia32_gather3div8sf:
2524   case X86::BI__builtin_ia32_gather3div8si:
2525   case X86::BI__builtin_ia32_gather3siv2df:
2526   case X86::BI__builtin_ia32_gather3siv2di:
2527   case X86::BI__builtin_ia32_gather3siv4df:
2528   case X86::BI__builtin_ia32_gather3siv4di:
2529   case X86::BI__builtin_ia32_gather3siv4sf:
2530   case X86::BI__builtin_ia32_gather3siv4si:
2531   case X86::BI__builtin_ia32_gather3siv8sf:
2532   case X86::BI__builtin_ia32_gather3siv8si:
2533   case X86::BI__builtin_ia32_gathersiv8df:
2534   case X86::BI__builtin_ia32_gathersiv16sf:
2535   case X86::BI__builtin_ia32_gatherdiv8df:
2536   case X86::BI__builtin_ia32_gatherdiv16sf:
2537   case X86::BI__builtin_ia32_gathersiv8di:
2538   case X86::BI__builtin_ia32_gathersiv16si:
2539   case X86::BI__builtin_ia32_gatherdiv8di:
2540   case X86::BI__builtin_ia32_gatherdiv16si:
2541   case X86::BI__builtin_ia32_scatterdiv2df:
2542   case X86::BI__builtin_ia32_scatterdiv2di:
2543   case X86::BI__builtin_ia32_scatterdiv4df:
2544   case X86::BI__builtin_ia32_scatterdiv4di:
2545   case X86::BI__builtin_ia32_scatterdiv4sf:
2546   case X86::BI__builtin_ia32_scatterdiv4si:
2547   case X86::BI__builtin_ia32_scatterdiv8sf:
2548   case X86::BI__builtin_ia32_scatterdiv8si:
2549   case X86::BI__builtin_ia32_scattersiv2df:
2550   case X86::BI__builtin_ia32_scattersiv2di:
2551   case X86::BI__builtin_ia32_scattersiv4df:
2552   case X86::BI__builtin_ia32_scattersiv4di:
2553   case X86::BI__builtin_ia32_scattersiv4sf:
2554   case X86::BI__builtin_ia32_scattersiv4si:
2555   case X86::BI__builtin_ia32_scattersiv8sf:
2556   case X86::BI__builtin_ia32_scattersiv8si:
2557   case X86::BI__builtin_ia32_scattersiv8df:
2558   case X86::BI__builtin_ia32_scattersiv16sf:
2559   case X86::BI__builtin_ia32_scatterdiv8df:
2560   case X86::BI__builtin_ia32_scatterdiv16sf:
2561   case X86::BI__builtin_ia32_scattersiv8di:
2562   case X86::BI__builtin_ia32_scattersiv16si:
2563   case X86::BI__builtin_ia32_scatterdiv8di:
2564   case X86::BI__builtin_ia32_scatterdiv16si:
2565     ArgNum = 4;
2566     break;
2567   }
2568 
2569   llvm::APSInt Result;
2570 
2571   // We can't check the value of a dependent argument.
2572   Expr *Arg = TheCall->getArg(ArgNum);
2573   if (Arg->isTypeDependent() || Arg->isValueDependent())
2574     return false;
2575 
2576   // Check constant-ness first.
2577   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2578     return true;
2579 
2580   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
2581     return false;
2582 
2583   return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
2584     << Arg->getSourceRange();
2585 }
2586 
2587 static bool isX86_32Builtin(unsigned BuiltinID) {
2588   // These builtins only work on x86-32 targets.
2589   switch (BuiltinID) {
2590   case X86::BI__builtin_ia32_readeflags_u32:
2591   case X86::BI__builtin_ia32_writeeflags_u32:
2592     return true;
2593   }
2594 
2595   return false;
2596 }
2597 
2598 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2599   if (BuiltinID == X86::BI__builtin_cpu_supports)
2600     return SemaBuiltinCpuSupports(*this, TheCall);
2601 
2602   if (BuiltinID == X86::BI__builtin_cpu_is)
2603     return SemaBuiltinCpuIs(*this, TheCall);
2604 
2605   // Check for 32-bit only builtins on a 64-bit target.
2606   const llvm::Triple &TT = Context.getTargetInfo().getTriple();
2607   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
2608     return Diag(TheCall->getCallee()->getLocStart(),
2609                 diag::err_32_bit_builtin_64_bit_tgt);
2610 
2611   // If the intrinsic has rounding or SAE make sure its valid.
2612   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2613     return true;
2614 
2615   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
2616   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
2617     return true;
2618 
2619   // For intrinsics which take an immediate value as part of the instruction,
2620   // range check them here.
2621   int i = 0, l = 0, u = 0;
2622   switch (BuiltinID) {
2623   default:
2624     return false;
2625   case X86::BI__builtin_ia32_vec_ext_v2si:
2626   case X86::BI__builtin_ia32_vec_ext_v2di:
2627   case X86::BI__builtin_ia32_vextractf128_pd256:
2628   case X86::BI__builtin_ia32_vextractf128_ps256:
2629   case X86::BI__builtin_ia32_vextractf128_si256:
2630   case X86::BI__builtin_ia32_extract128i256:
2631   case X86::BI__builtin_ia32_extractf64x4_mask:
2632   case X86::BI__builtin_ia32_extracti64x4_mask:
2633   case X86::BI__builtin_ia32_extractf32x8_mask:
2634   case X86::BI__builtin_ia32_extracti32x8_mask:
2635   case X86::BI__builtin_ia32_extractf64x2_256_mask:
2636   case X86::BI__builtin_ia32_extracti64x2_256_mask:
2637   case X86::BI__builtin_ia32_extractf32x4_256_mask:
2638   case X86::BI__builtin_ia32_extracti32x4_256_mask:
2639     i = 1; l = 0; u = 1;
2640     break;
2641   case X86::BI__builtin_ia32_vec_set_v2di:
2642   case X86::BI__builtin_ia32_vinsertf128_pd256:
2643   case X86::BI__builtin_ia32_vinsertf128_ps256:
2644   case X86::BI__builtin_ia32_vinsertf128_si256:
2645   case X86::BI__builtin_ia32_insert128i256:
2646   case X86::BI__builtin_ia32_insertf32x8:
2647   case X86::BI__builtin_ia32_inserti32x8:
2648   case X86::BI__builtin_ia32_insertf64x4:
2649   case X86::BI__builtin_ia32_inserti64x4:
2650   case X86::BI__builtin_ia32_insertf64x2_256:
2651   case X86::BI__builtin_ia32_inserti64x2_256:
2652   case X86::BI__builtin_ia32_insertf32x4_256:
2653   case X86::BI__builtin_ia32_inserti32x4_256:
2654     i = 2; l = 0; u = 1;
2655     break;
2656   case X86::BI__builtin_ia32_vpermilpd:
2657   case X86::BI__builtin_ia32_vec_ext_v4hi:
2658   case X86::BI__builtin_ia32_vec_ext_v4si:
2659   case X86::BI__builtin_ia32_vec_ext_v4sf:
2660   case X86::BI__builtin_ia32_vec_ext_v4di:
2661   case X86::BI__builtin_ia32_extractf32x4_mask:
2662   case X86::BI__builtin_ia32_extracti32x4_mask:
2663   case X86::BI__builtin_ia32_extractf64x2_512_mask:
2664   case X86::BI__builtin_ia32_extracti64x2_512_mask:
2665     i = 1; l = 0; u = 3;
2666     break;
2667   case X86::BI_mm_prefetch:
2668   case X86::BI__builtin_ia32_vec_ext_v8hi:
2669   case X86::BI__builtin_ia32_vec_ext_v8si:
2670     i = 1; l = 0; u = 7;
2671     break;
2672   case X86::BI__builtin_ia32_sha1rnds4:
2673   case X86::BI__builtin_ia32_blendpd:
2674   case X86::BI__builtin_ia32_shufpd:
2675   case X86::BI__builtin_ia32_vec_set_v4hi:
2676   case X86::BI__builtin_ia32_vec_set_v4si:
2677   case X86::BI__builtin_ia32_vec_set_v4di:
2678   case X86::BI__builtin_ia32_shuf_f32x4_256:
2679   case X86::BI__builtin_ia32_shuf_f64x2_256:
2680   case X86::BI__builtin_ia32_shuf_i32x4_256:
2681   case X86::BI__builtin_ia32_shuf_i64x2_256:
2682   case X86::BI__builtin_ia32_insertf64x2_512:
2683   case X86::BI__builtin_ia32_inserti64x2_512:
2684   case X86::BI__builtin_ia32_insertf32x4:
2685   case X86::BI__builtin_ia32_inserti32x4:
2686     i = 2; l = 0; u = 3;
2687     break;
2688   case X86::BI__builtin_ia32_vpermil2pd:
2689   case X86::BI__builtin_ia32_vpermil2pd256:
2690   case X86::BI__builtin_ia32_vpermil2ps:
2691   case X86::BI__builtin_ia32_vpermil2ps256:
2692     i = 3; l = 0; u = 3;
2693     break;
2694   case X86::BI__builtin_ia32_cmpb128_mask:
2695   case X86::BI__builtin_ia32_cmpw128_mask:
2696   case X86::BI__builtin_ia32_cmpd128_mask:
2697   case X86::BI__builtin_ia32_cmpq128_mask:
2698   case X86::BI__builtin_ia32_cmpb256_mask:
2699   case X86::BI__builtin_ia32_cmpw256_mask:
2700   case X86::BI__builtin_ia32_cmpd256_mask:
2701   case X86::BI__builtin_ia32_cmpq256_mask:
2702   case X86::BI__builtin_ia32_cmpb512_mask:
2703   case X86::BI__builtin_ia32_cmpw512_mask:
2704   case X86::BI__builtin_ia32_cmpd512_mask:
2705   case X86::BI__builtin_ia32_cmpq512_mask:
2706   case X86::BI__builtin_ia32_ucmpb128_mask:
2707   case X86::BI__builtin_ia32_ucmpw128_mask:
2708   case X86::BI__builtin_ia32_ucmpd128_mask:
2709   case X86::BI__builtin_ia32_ucmpq128_mask:
2710   case X86::BI__builtin_ia32_ucmpb256_mask:
2711   case X86::BI__builtin_ia32_ucmpw256_mask:
2712   case X86::BI__builtin_ia32_ucmpd256_mask:
2713   case X86::BI__builtin_ia32_ucmpq256_mask:
2714   case X86::BI__builtin_ia32_ucmpb512_mask:
2715   case X86::BI__builtin_ia32_ucmpw512_mask:
2716   case X86::BI__builtin_ia32_ucmpd512_mask:
2717   case X86::BI__builtin_ia32_ucmpq512_mask:
2718   case X86::BI__builtin_ia32_vpcomub:
2719   case X86::BI__builtin_ia32_vpcomuw:
2720   case X86::BI__builtin_ia32_vpcomud:
2721   case X86::BI__builtin_ia32_vpcomuq:
2722   case X86::BI__builtin_ia32_vpcomb:
2723   case X86::BI__builtin_ia32_vpcomw:
2724   case X86::BI__builtin_ia32_vpcomd:
2725   case X86::BI__builtin_ia32_vpcomq:
2726   case X86::BI__builtin_ia32_vec_set_v8hi:
2727   case X86::BI__builtin_ia32_vec_set_v8si:
2728     i = 2; l = 0; u = 7;
2729     break;
2730   case X86::BI__builtin_ia32_vpermilpd256:
2731   case X86::BI__builtin_ia32_roundps:
2732   case X86::BI__builtin_ia32_roundpd:
2733   case X86::BI__builtin_ia32_roundps256:
2734   case X86::BI__builtin_ia32_roundpd256:
2735   case X86::BI__builtin_ia32_getmantpd128_mask:
2736   case X86::BI__builtin_ia32_getmantpd256_mask:
2737   case X86::BI__builtin_ia32_getmantps128_mask:
2738   case X86::BI__builtin_ia32_getmantps256_mask:
2739   case X86::BI__builtin_ia32_getmantpd512_mask:
2740   case X86::BI__builtin_ia32_getmantps512_mask:
2741   case X86::BI__builtin_ia32_vec_ext_v16qi:
2742   case X86::BI__builtin_ia32_vec_ext_v16hi:
2743     i = 1; l = 0; u = 15;
2744     break;
2745   case X86::BI__builtin_ia32_pblendd128:
2746   case X86::BI__builtin_ia32_blendps:
2747   case X86::BI__builtin_ia32_blendpd256:
2748   case X86::BI__builtin_ia32_shufpd256:
2749   case X86::BI__builtin_ia32_roundss:
2750   case X86::BI__builtin_ia32_roundsd:
2751   case X86::BI__builtin_ia32_rangepd128_mask:
2752   case X86::BI__builtin_ia32_rangepd256_mask:
2753   case X86::BI__builtin_ia32_rangepd512_mask:
2754   case X86::BI__builtin_ia32_rangeps128_mask:
2755   case X86::BI__builtin_ia32_rangeps256_mask:
2756   case X86::BI__builtin_ia32_rangeps512_mask:
2757   case X86::BI__builtin_ia32_getmantsd_round_mask:
2758   case X86::BI__builtin_ia32_getmantss_round_mask:
2759   case X86::BI__builtin_ia32_vec_set_v16qi:
2760   case X86::BI__builtin_ia32_vec_set_v16hi:
2761     i = 2; l = 0; u = 15;
2762     break;
2763   case X86::BI__builtin_ia32_vec_ext_v32qi:
2764     i = 1; l = 0; u = 31;
2765     break;
2766   case X86::BI__builtin_ia32_cmpps:
2767   case X86::BI__builtin_ia32_cmpss:
2768   case X86::BI__builtin_ia32_cmppd:
2769   case X86::BI__builtin_ia32_cmpsd:
2770   case X86::BI__builtin_ia32_cmpps256:
2771   case X86::BI__builtin_ia32_cmppd256:
2772   case X86::BI__builtin_ia32_cmpps128_mask:
2773   case X86::BI__builtin_ia32_cmppd128_mask:
2774   case X86::BI__builtin_ia32_cmpps256_mask:
2775   case X86::BI__builtin_ia32_cmppd256_mask:
2776   case X86::BI__builtin_ia32_cmpps512_mask:
2777   case X86::BI__builtin_ia32_cmppd512_mask:
2778   case X86::BI__builtin_ia32_cmpsd_mask:
2779   case X86::BI__builtin_ia32_cmpss_mask:
2780   case X86::BI__builtin_ia32_vec_set_v32qi:
2781     i = 2; l = 0; u = 31;
2782     break;
2783   case X86::BI__builtin_ia32_permdf256:
2784   case X86::BI__builtin_ia32_permdi256:
2785   case X86::BI__builtin_ia32_permdf512:
2786   case X86::BI__builtin_ia32_permdi512:
2787   case X86::BI__builtin_ia32_vpermilps:
2788   case X86::BI__builtin_ia32_vpermilps256:
2789   case X86::BI__builtin_ia32_vpermilpd512:
2790   case X86::BI__builtin_ia32_vpermilps512:
2791   case X86::BI__builtin_ia32_pshufd:
2792   case X86::BI__builtin_ia32_pshufd256:
2793   case X86::BI__builtin_ia32_pshufd512:
2794   case X86::BI__builtin_ia32_pshufhw:
2795   case X86::BI__builtin_ia32_pshufhw256:
2796   case X86::BI__builtin_ia32_pshufhw512:
2797   case X86::BI__builtin_ia32_pshuflw:
2798   case X86::BI__builtin_ia32_pshuflw256:
2799   case X86::BI__builtin_ia32_pshuflw512:
2800   case X86::BI__builtin_ia32_vcvtps2ph:
2801   case X86::BI__builtin_ia32_vcvtps2ph_mask:
2802   case X86::BI__builtin_ia32_vcvtps2ph256:
2803   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
2804   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
2805   case X86::BI__builtin_ia32_rndscaleps_128_mask:
2806   case X86::BI__builtin_ia32_rndscalepd_128_mask:
2807   case X86::BI__builtin_ia32_rndscaleps_256_mask:
2808   case X86::BI__builtin_ia32_rndscalepd_256_mask:
2809   case X86::BI__builtin_ia32_rndscaleps_mask:
2810   case X86::BI__builtin_ia32_rndscalepd_mask:
2811   case X86::BI__builtin_ia32_reducepd128_mask:
2812   case X86::BI__builtin_ia32_reducepd256_mask:
2813   case X86::BI__builtin_ia32_reducepd512_mask:
2814   case X86::BI__builtin_ia32_reduceps128_mask:
2815   case X86::BI__builtin_ia32_reduceps256_mask:
2816   case X86::BI__builtin_ia32_reduceps512_mask:
2817   case X86::BI__builtin_ia32_prold512:
2818   case X86::BI__builtin_ia32_prolq512:
2819   case X86::BI__builtin_ia32_prold128:
2820   case X86::BI__builtin_ia32_prold256:
2821   case X86::BI__builtin_ia32_prolq128:
2822   case X86::BI__builtin_ia32_prolq256:
2823   case X86::BI__builtin_ia32_prord512:
2824   case X86::BI__builtin_ia32_prorq512:
2825   case X86::BI__builtin_ia32_prord128:
2826   case X86::BI__builtin_ia32_prord256:
2827   case X86::BI__builtin_ia32_prorq128:
2828   case X86::BI__builtin_ia32_prorq256:
2829   case X86::BI__builtin_ia32_fpclasspd128_mask:
2830   case X86::BI__builtin_ia32_fpclasspd256_mask:
2831   case X86::BI__builtin_ia32_fpclassps128_mask:
2832   case X86::BI__builtin_ia32_fpclassps256_mask:
2833   case X86::BI__builtin_ia32_fpclassps512_mask:
2834   case X86::BI__builtin_ia32_fpclasspd512_mask:
2835   case X86::BI__builtin_ia32_fpclasssd_mask:
2836   case X86::BI__builtin_ia32_fpclassss_mask:
2837   case X86::BI__builtin_ia32_pslldqi128_byteshift:
2838   case X86::BI__builtin_ia32_pslldqi256_byteshift:
2839   case X86::BI__builtin_ia32_pslldqi512_byteshift:
2840   case X86::BI__builtin_ia32_psrldqi128_byteshift:
2841   case X86::BI__builtin_ia32_psrldqi256_byteshift:
2842   case X86::BI__builtin_ia32_psrldqi512_byteshift:
2843     i = 1; l = 0; u = 255;
2844     break;
2845   case X86::BI__builtin_ia32_vperm2f128_pd256:
2846   case X86::BI__builtin_ia32_vperm2f128_ps256:
2847   case X86::BI__builtin_ia32_vperm2f128_si256:
2848   case X86::BI__builtin_ia32_permti256:
2849   case X86::BI__builtin_ia32_pblendw128:
2850   case X86::BI__builtin_ia32_pblendw256:
2851   case X86::BI__builtin_ia32_blendps256:
2852   case X86::BI__builtin_ia32_pblendd256:
2853   case X86::BI__builtin_ia32_palignr128:
2854   case X86::BI__builtin_ia32_palignr256:
2855   case X86::BI__builtin_ia32_palignr512:
2856   case X86::BI__builtin_ia32_alignq512:
2857   case X86::BI__builtin_ia32_alignd512:
2858   case X86::BI__builtin_ia32_alignd128:
2859   case X86::BI__builtin_ia32_alignd256:
2860   case X86::BI__builtin_ia32_alignq128:
2861   case X86::BI__builtin_ia32_alignq256:
2862   case X86::BI__builtin_ia32_vcomisd:
2863   case X86::BI__builtin_ia32_vcomiss:
2864   case X86::BI__builtin_ia32_shuf_f32x4:
2865   case X86::BI__builtin_ia32_shuf_f64x2:
2866   case X86::BI__builtin_ia32_shuf_i32x4:
2867   case X86::BI__builtin_ia32_shuf_i64x2:
2868   case X86::BI__builtin_ia32_shufpd512:
2869   case X86::BI__builtin_ia32_shufps:
2870   case X86::BI__builtin_ia32_shufps256:
2871   case X86::BI__builtin_ia32_shufps512:
2872   case X86::BI__builtin_ia32_dbpsadbw128:
2873   case X86::BI__builtin_ia32_dbpsadbw256:
2874   case X86::BI__builtin_ia32_dbpsadbw512:
2875   case X86::BI__builtin_ia32_vpshldd128:
2876   case X86::BI__builtin_ia32_vpshldd256:
2877   case X86::BI__builtin_ia32_vpshldd512:
2878   case X86::BI__builtin_ia32_vpshldq128:
2879   case X86::BI__builtin_ia32_vpshldq256:
2880   case X86::BI__builtin_ia32_vpshldq512:
2881   case X86::BI__builtin_ia32_vpshldw128:
2882   case X86::BI__builtin_ia32_vpshldw256:
2883   case X86::BI__builtin_ia32_vpshldw512:
2884   case X86::BI__builtin_ia32_vpshrdd128:
2885   case X86::BI__builtin_ia32_vpshrdd256:
2886   case X86::BI__builtin_ia32_vpshrdd512:
2887   case X86::BI__builtin_ia32_vpshrdq128:
2888   case X86::BI__builtin_ia32_vpshrdq256:
2889   case X86::BI__builtin_ia32_vpshrdq512:
2890   case X86::BI__builtin_ia32_vpshrdw128:
2891   case X86::BI__builtin_ia32_vpshrdw256:
2892   case X86::BI__builtin_ia32_vpshrdw512:
2893     i = 2; l = 0; u = 255;
2894     break;
2895   case X86::BI__builtin_ia32_fixupimmpd512_mask:
2896   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2897   case X86::BI__builtin_ia32_fixupimmps512_mask:
2898   case X86::BI__builtin_ia32_fixupimmps512_maskz:
2899   case X86::BI__builtin_ia32_fixupimmsd_mask:
2900   case X86::BI__builtin_ia32_fixupimmsd_maskz:
2901   case X86::BI__builtin_ia32_fixupimmss_mask:
2902   case X86::BI__builtin_ia32_fixupimmss_maskz:
2903   case X86::BI__builtin_ia32_fixupimmpd128_mask:
2904   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2905   case X86::BI__builtin_ia32_fixupimmpd256_mask:
2906   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2907   case X86::BI__builtin_ia32_fixupimmps128_mask:
2908   case X86::BI__builtin_ia32_fixupimmps128_maskz:
2909   case X86::BI__builtin_ia32_fixupimmps256_mask:
2910   case X86::BI__builtin_ia32_fixupimmps256_maskz:
2911   case X86::BI__builtin_ia32_pternlogd512_mask:
2912   case X86::BI__builtin_ia32_pternlogd512_maskz:
2913   case X86::BI__builtin_ia32_pternlogq512_mask:
2914   case X86::BI__builtin_ia32_pternlogq512_maskz:
2915   case X86::BI__builtin_ia32_pternlogd128_mask:
2916   case X86::BI__builtin_ia32_pternlogd128_maskz:
2917   case X86::BI__builtin_ia32_pternlogd256_mask:
2918   case X86::BI__builtin_ia32_pternlogd256_maskz:
2919   case X86::BI__builtin_ia32_pternlogq128_mask:
2920   case X86::BI__builtin_ia32_pternlogq128_maskz:
2921   case X86::BI__builtin_ia32_pternlogq256_mask:
2922   case X86::BI__builtin_ia32_pternlogq256_maskz:
2923     i = 3; l = 0; u = 255;
2924     break;
2925   case X86::BI__builtin_ia32_gatherpfdpd:
2926   case X86::BI__builtin_ia32_gatherpfdps:
2927   case X86::BI__builtin_ia32_gatherpfqpd:
2928   case X86::BI__builtin_ia32_gatherpfqps:
2929   case X86::BI__builtin_ia32_scatterpfdpd:
2930   case X86::BI__builtin_ia32_scatterpfdps:
2931   case X86::BI__builtin_ia32_scatterpfqpd:
2932   case X86::BI__builtin_ia32_scatterpfqps:
2933     i = 4; l = 2; u = 3;
2934     break;
2935   case X86::BI__builtin_ia32_rndscalesd_round_mask:
2936   case X86::BI__builtin_ia32_rndscaless_round_mask:
2937     i = 4; l = 0; u = 255;
2938     break;
2939   }
2940 
2941   // Note that we don't force a hard error on the range check here, allowing
2942   // template-generated or macro-generated dead code to potentially have out-of-
2943   // range values. These need to code generate, but don't need to necessarily
2944   // make any sense. We use a warning that defaults to an error.
2945   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
2946 }
2947 
2948 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2949 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
2950 /// Returns true when the format fits the function and the FormatStringInfo has
2951 /// been populated.
2952 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2953                                FormatStringInfo *FSI) {
2954   FSI->HasVAListArg = Format->getFirstArg() == 0;
2955   FSI->FormatIdx = Format->getFormatIdx() - 1;
2956   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
2957 
2958   // The way the format attribute works in GCC, the implicit this argument
2959   // of member functions is counted. However, it doesn't appear in our own
2960   // lists, so decrement format_idx in that case.
2961   if (IsCXXMember) {
2962     if(FSI->FormatIdx == 0)
2963       return false;
2964     --FSI->FormatIdx;
2965     if (FSI->FirstDataArg != 0)
2966       --FSI->FirstDataArg;
2967   }
2968   return true;
2969 }
2970 
2971 /// Checks if a the given expression evaluates to null.
2972 ///
2973 /// Returns true if the value evaluates to null.
2974 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
2975   // If the expression has non-null type, it doesn't evaluate to null.
2976   if (auto nullability
2977         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2978     if (*nullability == NullabilityKind::NonNull)
2979       return false;
2980   }
2981 
2982   // As a special case, transparent unions initialized with zero are
2983   // considered null for the purposes of the nonnull attribute.
2984   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
2985     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2986       if (const CompoundLiteralExpr *CLE =
2987           dyn_cast<CompoundLiteralExpr>(Expr))
2988         if (const InitListExpr *ILE =
2989             dyn_cast<InitListExpr>(CLE->getInitializer()))
2990           Expr = ILE->getInit(0);
2991   }
2992 
2993   bool Result;
2994   return (!Expr->isValueDependent() &&
2995           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2996           !Result);
2997 }
2998 
2999 static void CheckNonNullArgument(Sema &S,
3000                                  const Expr *ArgExpr,
3001                                  SourceLocation CallSiteLoc) {
3002   if (CheckNonNullExpr(S, ArgExpr))
3003     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
3004            S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
3005 }
3006 
3007 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
3008   FormatStringInfo FSI;
3009   if ((GetFormatStringType(Format) == FST_NSString) &&
3010       getFormatStringInfo(Format, false, &FSI)) {
3011     Idx = FSI.FormatIdx;
3012     return true;
3013   }
3014   return false;
3015 }
3016 
3017 /// Diagnose use of %s directive in an NSString which is being passed
3018 /// as formatting string to formatting method.
3019 static void
3020 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
3021                                         const NamedDecl *FDecl,
3022                                         Expr **Args,
3023                                         unsigned NumArgs) {
3024   unsigned Idx = 0;
3025   bool Format = false;
3026   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
3027   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
3028     Idx = 2;
3029     Format = true;
3030   }
3031   else
3032     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
3033       if (S.GetFormatNSStringIdx(I, Idx)) {
3034         Format = true;
3035         break;
3036       }
3037     }
3038   if (!Format || NumArgs <= Idx)
3039     return;
3040   const Expr *FormatExpr = Args[Idx];
3041   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
3042     FormatExpr = CSCE->getSubExpr();
3043   const StringLiteral *FormatString;
3044   if (const ObjCStringLiteral *OSL =
3045       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
3046     FormatString = OSL->getString();
3047   else
3048     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
3049   if (!FormatString)
3050     return;
3051   if (S.FormatStringHasSArg(FormatString)) {
3052     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
3053       << "%s" << 1 << 1;
3054     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
3055       << FDecl->getDeclName();
3056   }
3057 }
3058 
3059 /// Determine whether the given type has a non-null nullability annotation.
3060 static bool isNonNullType(ASTContext &ctx, QualType type) {
3061   if (auto nullability = type->getNullability(ctx))
3062     return *nullability == NullabilityKind::NonNull;
3063 
3064   return false;
3065 }
3066 
3067 static void CheckNonNullArguments(Sema &S,
3068                                   const NamedDecl *FDecl,
3069                                   const FunctionProtoType *Proto,
3070                                   ArrayRef<const Expr *> Args,
3071                                   SourceLocation CallSiteLoc) {
3072   assert((FDecl || Proto) && "Need a function declaration or prototype");
3073 
3074   // Check the attributes attached to the method/function itself.
3075   llvm::SmallBitVector NonNullArgs;
3076   if (FDecl) {
3077     // Handle the nonnull attribute on the function/method declaration itself.
3078     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
3079       if (!NonNull->args_size()) {
3080         // Easy case: all pointer arguments are nonnull.
3081         for (const auto *Arg : Args)
3082           if (S.isValidPointerAttrType(Arg->getType()))
3083             CheckNonNullArgument(S, Arg, CallSiteLoc);
3084         return;
3085       }
3086 
3087       for (const ParamIdx &Idx : NonNull->args()) {
3088         unsigned IdxAST = Idx.getASTIndex();
3089         if (IdxAST >= Args.size())
3090           continue;
3091         if (NonNullArgs.empty())
3092           NonNullArgs.resize(Args.size());
3093         NonNullArgs.set(IdxAST);
3094       }
3095     }
3096   }
3097 
3098   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
3099     // Handle the nonnull attribute on the parameters of the
3100     // function/method.
3101     ArrayRef<ParmVarDecl*> parms;
3102     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
3103       parms = FD->parameters();
3104     else
3105       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
3106 
3107     unsigned ParamIndex = 0;
3108     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
3109          I != E; ++I, ++ParamIndex) {
3110       const ParmVarDecl *PVD = *I;
3111       if (PVD->hasAttr<NonNullAttr>() ||
3112           isNonNullType(S.Context, PVD->getType())) {
3113         if (NonNullArgs.empty())
3114           NonNullArgs.resize(Args.size());
3115 
3116         NonNullArgs.set(ParamIndex);
3117       }
3118     }
3119   } else {
3120     // If we have a non-function, non-method declaration but no
3121     // function prototype, try to dig out the function prototype.
3122     if (!Proto) {
3123       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
3124         QualType type = VD->getType().getNonReferenceType();
3125         if (auto pointerType = type->getAs<PointerType>())
3126           type = pointerType->getPointeeType();
3127         else if (auto blockType = type->getAs<BlockPointerType>())
3128           type = blockType->getPointeeType();
3129         // FIXME: data member pointers?
3130 
3131         // Dig out the function prototype, if there is one.
3132         Proto = type->getAs<FunctionProtoType>();
3133       }
3134     }
3135 
3136     // Fill in non-null argument information from the nullability
3137     // information on the parameter types (if we have them).
3138     if (Proto) {
3139       unsigned Index = 0;
3140       for (auto paramType : Proto->getParamTypes()) {
3141         if (isNonNullType(S.Context, paramType)) {
3142           if (NonNullArgs.empty())
3143             NonNullArgs.resize(Args.size());
3144 
3145           NonNullArgs.set(Index);
3146         }
3147 
3148         ++Index;
3149       }
3150     }
3151   }
3152 
3153   // Check for non-null arguments.
3154   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
3155        ArgIndex != ArgIndexEnd; ++ArgIndex) {
3156     if (NonNullArgs[ArgIndex])
3157       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
3158   }
3159 }
3160 
3161 /// Handles the checks for format strings, non-POD arguments to vararg
3162 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
3163 /// attributes.
3164 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
3165                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
3166                      bool IsMemberFunction, SourceLocation Loc,
3167                      SourceRange Range, VariadicCallType CallType) {
3168   // FIXME: We should check as much as we can in the template definition.
3169   if (CurContext->isDependentContext())
3170     return;
3171 
3172   // Printf and scanf checking.
3173   llvm::SmallBitVector CheckedVarArgs;
3174   if (FDecl) {
3175     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
3176       // Only create vector if there are format attributes.
3177       CheckedVarArgs.resize(Args.size());
3178 
3179       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
3180                            CheckedVarArgs);
3181     }
3182   }
3183 
3184   // Refuse POD arguments that weren't caught by the format string
3185   // checks above.
3186   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
3187   if (CallType != VariadicDoesNotApply &&
3188       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
3189     unsigned NumParams = Proto ? Proto->getNumParams()
3190                        : FDecl && isa<FunctionDecl>(FDecl)
3191                            ? cast<FunctionDecl>(FDecl)->getNumParams()
3192                        : FDecl && isa<ObjCMethodDecl>(FDecl)
3193                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
3194                        : 0;
3195 
3196     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
3197       // Args[ArgIdx] can be null in malformed code.
3198       if (const Expr *Arg = Args[ArgIdx]) {
3199         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
3200           checkVariadicArgument(Arg, CallType);
3201       }
3202     }
3203   }
3204 
3205   if (FDecl || Proto) {
3206     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
3207 
3208     // Type safety checking.
3209     if (FDecl) {
3210       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
3211         CheckArgumentWithTypeTag(I, Args, Loc);
3212     }
3213   }
3214 
3215   if (FD)
3216     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
3217 }
3218 
3219 /// CheckConstructorCall - Check a constructor call for correctness and safety
3220 /// properties not enforced by the C type system.
3221 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
3222                                 ArrayRef<const Expr *> Args,
3223                                 const FunctionProtoType *Proto,
3224                                 SourceLocation Loc) {
3225   VariadicCallType CallType =
3226     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
3227   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
3228             Loc, SourceRange(), CallType);
3229 }
3230 
3231 /// CheckFunctionCall - Check a direct function call for various correctness
3232 /// and safety properties not strictly enforced by the C type system.
3233 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
3234                              const FunctionProtoType *Proto) {
3235   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
3236                               isa<CXXMethodDecl>(FDecl);
3237   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
3238                           IsMemberOperatorCall;
3239   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
3240                                                   TheCall->getCallee());
3241   Expr** Args = TheCall->getArgs();
3242   unsigned NumArgs = TheCall->getNumArgs();
3243 
3244   Expr *ImplicitThis = nullptr;
3245   if (IsMemberOperatorCall) {
3246     // If this is a call to a member operator, hide the first argument
3247     // from checkCall.
3248     // FIXME: Our choice of AST representation here is less than ideal.
3249     ImplicitThis = Args[0];
3250     ++Args;
3251     --NumArgs;
3252   } else if (IsMemberFunction)
3253     ImplicitThis =
3254         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
3255 
3256   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
3257             IsMemberFunction, TheCall->getRParenLoc(),
3258             TheCall->getCallee()->getSourceRange(), CallType);
3259 
3260   IdentifierInfo *FnInfo = FDecl->getIdentifier();
3261   // None of the checks below are needed for functions that don't have
3262   // simple names (e.g., C++ conversion functions).
3263   if (!FnInfo)
3264     return false;
3265 
3266   CheckAbsoluteValueFunction(TheCall, FDecl);
3267   CheckMaxUnsignedZero(TheCall, FDecl);
3268 
3269   if (getLangOpts().ObjC1)
3270     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
3271 
3272   unsigned CMId = FDecl->getMemoryFunctionKind();
3273   if (CMId == 0)
3274     return false;
3275 
3276   // Handle memory setting and copying functions.
3277   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
3278     CheckStrlcpycatArguments(TheCall, FnInfo);
3279   else if (CMId == Builtin::BIstrncat)
3280     CheckStrncatArguments(TheCall, FnInfo);
3281   else
3282     CheckMemaccessArguments(TheCall, CMId, FnInfo);
3283 
3284   return false;
3285 }
3286 
3287 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
3288                                ArrayRef<const Expr *> Args) {
3289   VariadicCallType CallType =
3290       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
3291 
3292   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
3293             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
3294             CallType);
3295 
3296   return false;
3297 }
3298 
3299 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
3300                             const FunctionProtoType *Proto) {
3301   QualType Ty;
3302   if (const auto *V = dyn_cast<VarDecl>(NDecl))
3303     Ty = V->getType().getNonReferenceType();
3304   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
3305     Ty = F->getType().getNonReferenceType();
3306   else
3307     return false;
3308 
3309   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
3310       !Ty->isFunctionProtoType())
3311     return false;
3312 
3313   VariadicCallType CallType;
3314   if (!Proto || !Proto->isVariadic()) {
3315     CallType = VariadicDoesNotApply;
3316   } else if (Ty->isBlockPointerType()) {
3317     CallType = VariadicBlock;
3318   } else { // Ty->isFunctionPointerType()
3319     CallType = VariadicFunction;
3320   }
3321 
3322   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
3323             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
3324             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
3325             TheCall->getCallee()->getSourceRange(), CallType);
3326 
3327   return false;
3328 }
3329 
3330 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
3331 /// such as function pointers returned from functions.
3332 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
3333   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
3334                                                   TheCall->getCallee());
3335   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
3336             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
3337             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
3338             TheCall->getCallee()->getSourceRange(), CallType);
3339 
3340   return false;
3341 }
3342 
3343 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
3344   if (!llvm::isValidAtomicOrderingCABI(Ordering))
3345     return false;
3346 
3347   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
3348   switch (Op) {
3349   case AtomicExpr::AO__c11_atomic_init:
3350   case AtomicExpr::AO__opencl_atomic_init:
3351     llvm_unreachable("There is no ordering argument for an init");
3352 
3353   case AtomicExpr::AO__c11_atomic_load:
3354   case AtomicExpr::AO__opencl_atomic_load:
3355   case AtomicExpr::AO__atomic_load_n:
3356   case AtomicExpr::AO__atomic_load:
3357     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
3358            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
3359 
3360   case AtomicExpr::AO__c11_atomic_store:
3361   case AtomicExpr::AO__opencl_atomic_store:
3362   case AtomicExpr::AO__atomic_store:
3363   case AtomicExpr::AO__atomic_store_n:
3364     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
3365            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
3366            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
3367 
3368   default:
3369     return true;
3370   }
3371 }
3372 
3373 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
3374                                          AtomicExpr::AtomicOp Op) {
3375   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3376   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3377 
3378   // All the non-OpenCL operations take one of the following forms.
3379   // The OpenCL operations take the __c11 forms with one extra argument for
3380   // synchronization scope.
3381   enum {
3382     // C    __c11_atomic_init(A *, C)
3383     Init,
3384 
3385     // C    __c11_atomic_load(A *, int)
3386     Load,
3387 
3388     // void __atomic_load(A *, CP, int)
3389     LoadCopy,
3390 
3391     // void __atomic_store(A *, CP, int)
3392     Copy,
3393 
3394     // C    __c11_atomic_add(A *, M, int)
3395     Arithmetic,
3396 
3397     // C    __atomic_exchange_n(A *, CP, int)
3398     Xchg,
3399 
3400     // void __atomic_exchange(A *, C *, CP, int)
3401     GNUXchg,
3402 
3403     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
3404     C11CmpXchg,
3405 
3406     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
3407     GNUCmpXchg
3408   } Form = Init;
3409 
3410   const unsigned NumForm = GNUCmpXchg + 1;
3411   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
3412   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
3413   // where:
3414   //   C is an appropriate type,
3415   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
3416   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
3417   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
3418   //   the int parameters are for orderings.
3419 
3420   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
3421       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
3422       "need to update code for modified forms");
3423   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
3424                     AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
3425                         AtomicExpr::AO__atomic_load,
3426                 "need to update code for modified C11 atomics");
3427   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
3428                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
3429   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
3430                Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
3431                IsOpenCL;
3432   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
3433              Op == AtomicExpr::AO__atomic_store_n ||
3434              Op == AtomicExpr::AO__atomic_exchange_n ||
3435              Op == AtomicExpr::AO__atomic_compare_exchange_n;
3436   bool IsAddSub = false;
3437   bool IsMinMax = false;
3438 
3439   switch (Op) {
3440   case AtomicExpr::AO__c11_atomic_init:
3441   case AtomicExpr::AO__opencl_atomic_init:
3442     Form = Init;
3443     break;
3444 
3445   case AtomicExpr::AO__c11_atomic_load:
3446   case AtomicExpr::AO__opencl_atomic_load:
3447   case AtomicExpr::AO__atomic_load_n:
3448     Form = Load;
3449     break;
3450 
3451   case AtomicExpr::AO__atomic_load:
3452     Form = LoadCopy;
3453     break;
3454 
3455   case AtomicExpr::AO__c11_atomic_store:
3456   case AtomicExpr::AO__opencl_atomic_store:
3457   case AtomicExpr::AO__atomic_store:
3458   case AtomicExpr::AO__atomic_store_n:
3459     Form = Copy;
3460     break;
3461 
3462   case AtomicExpr::AO__c11_atomic_fetch_add:
3463   case AtomicExpr::AO__c11_atomic_fetch_sub:
3464   case AtomicExpr::AO__opencl_atomic_fetch_add:
3465   case AtomicExpr::AO__opencl_atomic_fetch_sub:
3466   case AtomicExpr::AO__opencl_atomic_fetch_min:
3467   case AtomicExpr::AO__opencl_atomic_fetch_max:
3468   case AtomicExpr::AO__atomic_fetch_add:
3469   case AtomicExpr::AO__atomic_fetch_sub:
3470   case AtomicExpr::AO__atomic_add_fetch:
3471   case AtomicExpr::AO__atomic_sub_fetch:
3472     IsAddSub = true;
3473     LLVM_FALLTHROUGH;
3474   case AtomicExpr::AO__c11_atomic_fetch_and:
3475   case AtomicExpr::AO__c11_atomic_fetch_or:
3476   case AtomicExpr::AO__c11_atomic_fetch_xor:
3477   case AtomicExpr::AO__opencl_atomic_fetch_and:
3478   case AtomicExpr::AO__opencl_atomic_fetch_or:
3479   case AtomicExpr::AO__opencl_atomic_fetch_xor:
3480   case AtomicExpr::AO__atomic_fetch_and:
3481   case AtomicExpr::AO__atomic_fetch_or:
3482   case AtomicExpr::AO__atomic_fetch_xor:
3483   case AtomicExpr::AO__atomic_fetch_nand:
3484   case AtomicExpr::AO__atomic_and_fetch:
3485   case AtomicExpr::AO__atomic_or_fetch:
3486   case AtomicExpr::AO__atomic_xor_fetch:
3487   case AtomicExpr::AO__atomic_nand_fetch:
3488     Form = Arithmetic;
3489     break;
3490 
3491   case AtomicExpr::AO__atomic_fetch_min:
3492   case AtomicExpr::AO__atomic_fetch_max:
3493     IsMinMax = true;
3494     Form = Arithmetic;
3495     break;
3496 
3497   case AtomicExpr::AO__c11_atomic_exchange:
3498   case AtomicExpr::AO__opencl_atomic_exchange:
3499   case AtomicExpr::AO__atomic_exchange_n:
3500     Form = Xchg;
3501     break;
3502 
3503   case AtomicExpr::AO__atomic_exchange:
3504     Form = GNUXchg;
3505     break;
3506 
3507   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3508   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
3509   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
3510   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
3511     Form = C11CmpXchg;
3512     break;
3513 
3514   case AtomicExpr::AO__atomic_compare_exchange:
3515   case AtomicExpr::AO__atomic_compare_exchange_n:
3516     Form = GNUCmpXchg;
3517     break;
3518   }
3519 
3520   unsigned AdjustedNumArgs = NumArgs[Form];
3521   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
3522     ++AdjustedNumArgs;
3523   // Check we have the right number of arguments.
3524   if (TheCall->getNumArgs() < AdjustedNumArgs) {
3525     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3526       << 0 << AdjustedNumArgs << TheCall->getNumArgs()
3527       << TheCall->getCallee()->getSourceRange();
3528     return ExprError();
3529   } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
3530     Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(),
3531          diag::err_typecheck_call_too_many_args)
3532       << 0 << AdjustedNumArgs << TheCall->getNumArgs()
3533       << TheCall->getCallee()->getSourceRange();
3534     return ExprError();
3535   }
3536 
3537   // Inspect the first argument of the atomic operation.
3538   Expr *Ptr = TheCall->getArg(0);
3539   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
3540   if (ConvertedPtr.isInvalid())
3541     return ExprError();
3542 
3543   Ptr = ConvertedPtr.get();
3544   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
3545   if (!pointerType) {
3546     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3547       << Ptr->getType() << Ptr->getSourceRange();
3548     return ExprError();
3549   }
3550 
3551   // For a __c11 builtin, this should be a pointer to an _Atomic type.
3552   QualType AtomTy = pointerType->getPointeeType(); // 'A'
3553   QualType ValType = AtomTy; // 'C'
3554   if (IsC11) {
3555     if (!AtomTy->isAtomicType()) {
3556       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
3557         << Ptr->getType() << Ptr->getSourceRange();
3558       return ExprError();
3559     }
3560     if (AtomTy.isConstQualified() ||
3561         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
3562       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
3563           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
3564           << Ptr->getSourceRange();
3565       return ExprError();
3566     }
3567     ValType = AtomTy->getAs<AtomicType>()->getValueType();
3568   } else if (Form != Load && Form != LoadCopy) {
3569     if (ValType.isConstQualified()) {
3570       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
3571         << Ptr->getType() << Ptr->getSourceRange();
3572       return ExprError();
3573     }
3574   }
3575 
3576   // For an arithmetic operation, the implied arithmetic must be well-formed.
3577   if (Form == Arithmetic) {
3578     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
3579     if (IsAddSub && !ValType->isIntegerType()
3580         && !ValType->isPointerType()) {
3581       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3582         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3583       return ExprError();
3584     }
3585     if (IsMinMax) {
3586       const BuiltinType *BT = ValType->getAs<BuiltinType>();
3587       if (!BT || (BT->getKind() != BuiltinType::Int &&
3588                   BT->getKind() != BuiltinType::UInt)) {
3589         Diag(DRE->getLocStart(), diag::err_atomic_op_needs_int32_or_ptr);
3590         return ExprError();
3591       }
3592     }
3593     if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) {
3594       Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
3595         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3596       return ExprError();
3597     }
3598     if (IsC11 && ValType->isPointerType() &&
3599         RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
3600                             diag::err_incomplete_type)) {
3601       return ExprError();
3602     }
3603   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
3604     // For __atomic_*_n operations, the value type must be a scalar integral or
3605     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
3606     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3607       << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3608     return ExprError();
3609   }
3610 
3611   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
3612       !AtomTy->isScalarType()) {
3613     // For GNU atomics, require a trivially-copyable type. This is not part of
3614     // the GNU atomics specification, but we enforce it for sanity.
3615     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
3616       << Ptr->getType() << Ptr->getSourceRange();
3617     return ExprError();
3618   }
3619 
3620   switch (ValType.getObjCLifetime()) {
3621   case Qualifiers::OCL_None:
3622   case Qualifiers::OCL_ExplicitNone:
3623     // okay
3624     break;
3625 
3626   case Qualifiers::OCL_Weak:
3627   case Qualifiers::OCL_Strong:
3628   case Qualifiers::OCL_Autoreleasing:
3629     // FIXME: Can this happen? By this point, ValType should be known
3630     // to be trivially copyable.
3631     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3632       << ValType << Ptr->getSourceRange();
3633     return ExprError();
3634   }
3635 
3636   // All atomic operations have an overload which takes a pointer to a volatile
3637   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
3638   // into the result or the other operands. Similarly atomic_load takes a
3639   // pointer to a const 'A'.
3640   ValType.removeLocalVolatile();
3641   ValType.removeLocalConst();
3642   QualType ResultType = ValType;
3643   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
3644       Form == Init)
3645     ResultType = Context.VoidTy;
3646   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
3647     ResultType = Context.BoolTy;
3648 
3649   // The type of a parameter passed 'by value'. In the GNU atomics, such
3650   // arguments are actually passed as pointers.
3651   QualType ByValType = ValType; // 'CP'
3652   bool IsPassedByAddress = false;
3653   if (!IsC11 && !IsN) {
3654     ByValType = Ptr->getType();
3655     IsPassedByAddress = true;
3656   }
3657 
3658   // The first argument's non-CV pointer type is used to deduce the type of
3659   // subsequent arguments, except for:
3660   //  - weak flag (always converted to bool)
3661   //  - memory order (always converted to int)
3662   //  - scope  (always converted to int)
3663   for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
3664     QualType Ty;
3665     if (i < NumVals[Form] + 1) {
3666       switch (i) {
3667       case 0:
3668         // The first argument is always a pointer. It has a fixed type.
3669         // It is always dereferenced, a nullptr is undefined.
3670         CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart());
3671         // Nothing else to do: we already know all we want about this pointer.
3672         continue;
3673       case 1:
3674         // The second argument is the non-atomic operand. For arithmetic, this
3675         // is always passed by value, and for a compare_exchange it is always
3676         // passed by address. For the rest, GNU uses by-address and C11 uses
3677         // by-value.
3678         assert(Form != Load);
3679         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
3680           Ty = ValType;
3681         else if (Form == Copy || Form == Xchg) {
3682           if (IsPassedByAddress)
3683             // The value pointer is always dereferenced, a nullptr is undefined.
3684             CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart());
3685           Ty = ByValType;
3686         } else if (Form == Arithmetic)
3687           Ty = Context.getPointerDiffType();
3688         else {
3689           Expr *ValArg = TheCall->getArg(i);
3690           // The value pointer is always dereferenced, a nullptr is undefined.
3691           CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
3692           LangAS AS = LangAS::Default;
3693           // Keep address space of non-atomic pointer type.
3694           if (const PointerType *PtrTy =
3695                   ValArg->getType()->getAs<PointerType>()) {
3696             AS = PtrTy->getPointeeType().getAddressSpace();
3697           }
3698           Ty = Context.getPointerType(
3699               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
3700         }
3701         break;
3702       case 2:
3703         // The third argument to compare_exchange / GNU exchange is the desired
3704         // value, either by-value (for the C11 and *_n variant) or as a pointer.
3705         if (IsPassedByAddress)
3706           CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart());
3707         Ty = ByValType;
3708         break;
3709       case 3:
3710         // The fourth argument to GNU compare_exchange is a 'weak' flag.
3711         Ty = Context.BoolTy;
3712         break;
3713       }
3714     } else {
3715       // The order(s) and scope are always converted to int.
3716       Ty = Context.IntTy;
3717     }
3718 
3719     InitializedEntity Entity =
3720         InitializedEntity::InitializeParameter(Context, Ty, false);
3721     ExprResult Arg = TheCall->getArg(i);
3722     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3723     if (Arg.isInvalid())
3724       return true;
3725     TheCall->setArg(i, Arg.get());
3726   }
3727 
3728   // Permute the arguments into a 'consistent' order.
3729   SmallVector<Expr*, 5> SubExprs;
3730   SubExprs.push_back(Ptr);
3731   switch (Form) {
3732   case Init:
3733     // Note, AtomicExpr::getVal1() has a special case for this atomic.
3734     SubExprs.push_back(TheCall->getArg(1)); // Val1
3735     break;
3736   case Load:
3737     SubExprs.push_back(TheCall->getArg(1)); // Order
3738     break;
3739   case LoadCopy:
3740   case Copy:
3741   case Arithmetic:
3742   case Xchg:
3743     SubExprs.push_back(TheCall->getArg(2)); // Order
3744     SubExprs.push_back(TheCall->getArg(1)); // Val1
3745     break;
3746   case GNUXchg:
3747     // Note, AtomicExpr::getVal2() has a special case for this atomic.
3748     SubExprs.push_back(TheCall->getArg(3)); // Order
3749     SubExprs.push_back(TheCall->getArg(1)); // Val1
3750     SubExprs.push_back(TheCall->getArg(2)); // Val2
3751     break;
3752   case C11CmpXchg:
3753     SubExprs.push_back(TheCall->getArg(3)); // Order
3754     SubExprs.push_back(TheCall->getArg(1)); // Val1
3755     SubExprs.push_back(TheCall->getArg(4)); // OrderFail
3756     SubExprs.push_back(TheCall->getArg(2)); // Val2
3757     break;
3758   case GNUCmpXchg:
3759     SubExprs.push_back(TheCall->getArg(4)); // Order
3760     SubExprs.push_back(TheCall->getArg(1)); // Val1
3761     SubExprs.push_back(TheCall->getArg(5)); // OrderFail
3762     SubExprs.push_back(TheCall->getArg(2)); // Val2
3763     SubExprs.push_back(TheCall->getArg(3)); // Weak
3764     break;
3765   }
3766 
3767   if (SubExprs.size() >= 2 && Form != Init) {
3768     llvm::APSInt Result(32);
3769     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
3770         !isValidOrderingForOp(Result.getSExtValue(), Op))
3771       Diag(SubExprs[1]->getLocStart(),
3772            diag::warn_atomic_op_has_invalid_memory_order)
3773           << SubExprs[1]->getSourceRange();
3774   }
3775 
3776   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
3777     auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
3778     llvm::APSInt Result(32);
3779     if (Scope->isIntegerConstantExpr(Result, Context) &&
3780         !ScopeModel->isValid(Result.getZExtValue())) {
3781       Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope)
3782           << Scope->getSourceRange();
3783     }
3784     SubExprs.push_back(Scope);
3785   }
3786 
3787   AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
3788                                             SubExprs, ResultType, Op,
3789                                             TheCall->getRParenLoc());
3790 
3791   if ((Op == AtomicExpr::AO__c11_atomic_load ||
3792        Op == AtomicExpr::AO__c11_atomic_store ||
3793        Op == AtomicExpr::AO__opencl_atomic_load ||
3794        Op == AtomicExpr::AO__opencl_atomic_store ) &&
3795       Context.AtomicUsesUnsupportedLibcall(AE))
3796     Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib)
3797         << ((Op == AtomicExpr::AO__c11_atomic_load ||
3798             Op == AtomicExpr::AO__opencl_atomic_load)
3799                 ? 0 : 1);
3800 
3801   return AE;
3802 }
3803 
3804 /// checkBuiltinArgument - Given a call to a builtin function, perform
3805 /// normal type-checking on the given argument, updating the call in
3806 /// place.  This is useful when a builtin function requires custom
3807 /// type-checking for some of its arguments but not necessarily all of
3808 /// them.
3809 ///
3810 /// Returns true on error.
3811 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
3812   FunctionDecl *Fn = E->getDirectCallee();
3813   assert(Fn && "builtin call without direct callee!");
3814 
3815   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
3816   InitializedEntity Entity =
3817     InitializedEntity::InitializeParameter(S.Context, Param);
3818 
3819   ExprResult Arg = E->getArg(0);
3820   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3821   if (Arg.isInvalid())
3822     return true;
3823 
3824   E->setArg(ArgIndex, Arg.get());
3825   return false;
3826 }
3827 
3828 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
3829 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
3830 /// type of its first argument.  The main ActOnCallExpr routines have already
3831 /// promoted the types of arguments because all of these calls are prototyped as
3832 /// void(...).
3833 ///
3834 /// This function goes through and does final semantic checking for these
3835 /// builtins,
3836 ExprResult
3837 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
3838   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3839   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3840   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3841 
3842   // Ensure that we have at least one argument to do type inference from.
3843   if (TheCall->getNumArgs() < 1) {
3844     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3845       << 0 << 1 << TheCall->getNumArgs()
3846       << TheCall->getCallee()->getSourceRange();
3847     return ExprError();
3848   }
3849 
3850   // Inspect the first argument of the atomic builtin.  This should always be
3851   // a pointer type, whose element is an integral scalar or pointer type.
3852   // Because it is a pointer type, we don't have to worry about any implicit
3853   // casts here.
3854   // FIXME: We don't allow floating point scalars as input.
3855   Expr *FirstArg = TheCall->getArg(0);
3856   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3857   if (FirstArgResult.isInvalid())
3858     return ExprError();
3859   FirstArg = FirstArgResult.get();
3860   TheCall->setArg(0, FirstArg);
3861 
3862   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3863   if (!pointerType) {
3864     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3865       << FirstArg->getType() << FirstArg->getSourceRange();
3866     return ExprError();
3867   }
3868 
3869   QualType ValType = pointerType->getPointeeType();
3870   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3871       !ValType->isBlockPointerType()) {
3872     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3873       << FirstArg->getType() << FirstArg->getSourceRange();
3874     return ExprError();
3875   }
3876 
3877   if (ValType.isConstQualified()) {
3878     Diag(DRE->getLocStart(), diag::err_atomic_builtin_cannot_be_const)
3879         << FirstArg->getType() << FirstArg->getSourceRange();
3880     return ExprError();
3881   }
3882 
3883   switch (ValType.getObjCLifetime()) {
3884   case Qualifiers::OCL_None:
3885   case Qualifiers::OCL_ExplicitNone:
3886     // okay
3887     break;
3888 
3889   case Qualifiers::OCL_Weak:
3890   case Qualifiers::OCL_Strong:
3891   case Qualifiers::OCL_Autoreleasing:
3892     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3893       << ValType << FirstArg->getSourceRange();
3894     return ExprError();
3895   }
3896 
3897   // Strip any qualifiers off ValType.
3898   ValType = ValType.getUnqualifiedType();
3899 
3900   // The majority of builtins return a value, but a few have special return
3901   // types, so allow them to override appropriately below.
3902   QualType ResultType = ValType;
3903 
3904   // We need to figure out which concrete builtin this maps onto.  For example,
3905   // __sync_fetch_and_add with a 2 byte object turns into
3906   // __sync_fetch_and_add_2.
3907 #define BUILTIN_ROW(x) \
3908   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3909     Builtin::BI##x##_8, Builtin::BI##x##_16 }
3910 
3911   static const unsigned BuiltinIndices[][5] = {
3912     BUILTIN_ROW(__sync_fetch_and_add),
3913     BUILTIN_ROW(__sync_fetch_and_sub),
3914     BUILTIN_ROW(__sync_fetch_and_or),
3915     BUILTIN_ROW(__sync_fetch_and_and),
3916     BUILTIN_ROW(__sync_fetch_and_xor),
3917     BUILTIN_ROW(__sync_fetch_and_nand),
3918 
3919     BUILTIN_ROW(__sync_add_and_fetch),
3920     BUILTIN_ROW(__sync_sub_and_fetch),
3921     BUILTIN_ROW(__sync_and_and_fetch),
3922     BUILTIN_ROW(__sync_or_and_fetch),
3923     BUILTIN_ROW(__sync_xor_and_fetch),
3924     BUILTIN_ROW(__sync_nand_and_fetch),
3925 
3926     BUILTIN_ROW(__sync_val_compare_and_swap),
3927     BUILTIN_ROW(__sync_bool_compare_and_swap),
3928     BUILTIN_ROW(__sync_lock_test_and_set),
3929     BUILTIN_ROW(__sync_lock_release),
3930     BUILTIN_ROW(__sync_swap)
3931   };
3932 #undef BUILTIN_ROW
3933 
3934   // Determine the index of the size.
3935   unsigned SizeIndex;
3936   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
3937   case 1: SizeIndex = 0; break;
3938   case 2: SizeIndex = 1; break;
3939   case 4: SizeIndex = 2; break;
3940   case 8: SizeIndex = 3; break;
3941   case 16: SizeIndex = 4; break;
3942   default:
3943     Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3944       << FirstArg->getType() << FirstArg->getSourceRange();
3945     return ExprError();
3946   }
3947 
3948   // Each of these builtins has one pointer argument, followed by some number of
3949   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3950   // that we ignore.  Find out which row of BuiltinIndices to read from as well
3951   // as the number of fixed args.
3952   unsigned BuiltinID = FDecl->getBuiltinID();
3953   unsigned BuiltinIndex, NumFixed = 1;
3954   bool WarnAboutSemanticsChange = false;
3955   switch (BuiltinID) {
3956   default: llvm_unreachable("Unknown overloaded atomic builtin!");
3957   case Builtin::BI__sync_fetch_and_add:
3958   case Builtin::BI__sync_fetch_and_add_1:
3959   case Builtin::BI__sync_fetch_and_add_2:
3960   case Builtin::BI__sync_fetch_and_add_4:
3961   case Builtin::BI__sync_fetch_and_add_8:
3962   case Builtin::BI__sync_fetch_and_add_16:
3963     BuiltinIndex = 0;
3964     break;
3965 
3966   case Builtin::BI__sync_fetch_and_sub:
3967   case Builtin::BI__sync_fetch_and_sub_1:
3968   case Builtin::BI__sync_fetch_and_sub_2:
3969   case Builtin::BI__sync_fetch_and_sub_4:
3970   case Builtin::BI__sync_fetch_and_sub_8:
3971   case Builtin::BI__sync_fetch_and_sub_16:
3972     BuiltinIndex = 1;
3973     break;
3974 
3975   case Builtin::BI__sync_fetch_and_or:
3976   case Builtin::BI__sync_fetch_and_or_1:
3977   case Builtin::BI__sync_fetch_and_or_2:
3978   case Builtin::BI__sync_fetch_and_or_4:
3979   case Builtin::BI__sync_fetch_and_or_8:
3980   case Builtin::BI__sync_fetch_and_or_16:
3981     BuiltinIndex = 2;
3982     break;
3983 
3984   case Builtin::BI__sync_fetch_and_and:
3985   case Builtin::BI__sync_fetch_and_and_1:
3986   case Builtin::BI__sync_fetch_and_and_2:
3987   case Builtin::BI__sync_fetch_and_and_4:
3988   case Builtin::BI__sync_fetch_and_and_8:
3989   case Builtin::BI__sync_fetch_and_and_16:
3990     BuiltinIndex = 3;
3991     break;
3992 
3993   case Builtin::BI__sync_fetch_and_xor:
3994   case Builtin::BI__sync_fetch_and_xor_1:
3995   case Builtin::BI__sync_fetch_and_xor_2:
3996   case Builtin::BI__sync_fetch_and_xor_4:
3997   case Builtin::BI__sync_fetch_and_xor_8:
3998   case Builtin::BI__sync_fetch_and_xor_16:
3999     BuiltinIndex = 4;
4000     break;
4001 
4002   case Builtin::BI__sync_fetch_and_nand:
4003   case Builtin::BI__sync_fetch_and_nand_1:
4004   case Builtin::BI__sync_fetch_and_nand_2:
4005   case Builtin::BI__sync_fetch_and_nand_4:
4006   case Builtin::BI__sync_fetch_and_nand_8:
4007   case Builtin::BI__sync_fetch_and_nand_16:
4008     BuiltinIndex = 5;
4009     WarnAboutSemanticsChange = true;
4010     break;
4011 
4012   case Builtin::BI__sync_add_and_fetch:
4013   case Builtin::BI__sync_add_and_fetch_1:
4014   case Builtin::BI__sync_add_and_fetch_2:
4015   case Builtin::BI__sync_add_and_fetch_4:
4016   case Builtin::BI__sync_add_and_fetch_8:
4017   case Builtin::BI__sync_add_and_fetch_16:
4018     BuiltinIndex = 6;
4019     break;
4020 
4021   case Builtin::BI__sync_sub_and_fetch:
4022   case Builtin::BI__sync_sub_and_fetch_1:
4023   case Builtin::BI__sync_sub_and_fetch_2:
4024   case Builtin::BI__sync_sub_and_fetch_4:
4025   case Builtin::BI__sync_sub_and_fetch_8:
4026   case Builtin::BI__sync_sub_and_fetch_16:
4027     BuiltinIndex = 7;
4028     break;
4029 
4030   case Builtin::BI__sync_and_and_fetch:
4031   case Builtin::BI__sync_and_and_fetch_1:
4032   case Builtin::BI__sync_and_and_fetch_2:
4033   case Builtin::BI__sync_and_and_fetch_4:
4034   case Builtin::BI__sync_and_and_fetch_8:
4035   case Builtin::BI__sync_and_and_fetch_16:
4036     BuiltinIndex = 8;
4037     break;
4038 
4039   case Builtin::BI__sync_or_and_fetch:
4040   case Builtin::BI__sync_or_and_fetch_1:
4041   case Builtin::BI__sync_or_and_fetch_2:
4042   case Builtin::BI__sync_or_and_fetch_4:
4043   case Builtin::BI__sync_or_and_fetch_8:
4044   case Builtin::BI__sync_or_and_fetch_16:
4045     BuiltinIndex = 9;
4046     break;
4047 
4048   case Builtin::BI__sync_xor_and_fetch:
4049   case Builtin::BI__sync_xor_and_fetch_1:
4050   case Builtin::BI__sync_xor_and_fetch_2:
4051   case Builtin::BI__sync_xor_and_fetch_4:
4052   case Builtin::BI__sync_xor_and_fetch_8:
4053   case Builtin::BI__sync_xor_and_fetch_16:
4054     BuiltinIndex = 10;
4055     break;
4056 
4057   case Builtin::BI__sync_nand_and_fetch:
4058   case Builtin::BI__sync_nand_and_fetch_1:
4059   case Builtin::BI__sync_nand_and_fetch_2:
4060   case Builtin::BI__sync_nand_and_fetch_4:
4061   case Builtin::BI__sync_nand_and_fetch_8:
4062   case Builtin::BI__sync_nand_and_fetch_16:
4063     BuiltinIndex = 11;
4064     WarnAboutSemanticsChange = true;
4065     break;
4066 
4067   case Builtin::BI__sync_val_compare_and_swap:
4068   case Builtin::BI__sync_val_compare_and_swap_1:
4069   case Builtin::BI__sync_val_compare_and_swap_2:
4070   case Builtin::BI__sync_val_compare_and_swap_4:
4071   case Builtin::BI__sync_val_compare_and_swap_8:
4072   case Builtin::BI__sync_val_compare_and_swap_16:
4073     BuiltinIndex = 12;
4074     NumFixed = 2;
4075     break;
4076 
4077   case Builtin::BI__sync_bool_compare_and_swap:
4078   case Builtin::BI__sync_bool_compare_and_swap_1:
4079   case Builtin::BI__sync_bool_compare_and_swap_2:
4080   case Builtin::BI__sync_bool_compare_and_swap_4:
4081   case Builtin::BI__sync_bool_compare_and_swap_8:
4082   case Builtin::BI__sync_bool_compare_and_swap_16:
4083     BuiltinIndex = 13;
4084     NumFixed = 2;
4085     ResultType = Context.BoolTy;
4086     break;
4087 
4088   case Builtin::BI__sync_lock_test_and_set:
4089   case Builtin::BI__sync_lock_test_and_set_1:
4090   case Builtin::BI__sync_lock_test_and_set_2:
4091   case Builtin::BI__sync_lock_test_and_set_4:
4092   case Builtin::BI__sync_lock_test_and_set_8:
4093   case Builtin::BI__sync_lock_test_and_set_16:
4094     BuiltinIndex = 14;
4095     break;
4096 
4097   case Builtin::BI__sync_lock_release:
4098   case Builtin::BI__sync_lock_release_1:
4099   case Builtin::BI__sync_lock_release_2:
4100   case Builtin::BI__sync_lock_release_4:
4101   case Builtin::BI__sync_lock_release_8:
4102   case Builtin::BI__sync_lock_release_16:
4103     BuiltinIndex = 15;
4104     NumFixed = 0;
4105     ResultType = Context.VoidTy;
4106     break;
4107 
4108   case Builtin::BI__sync_swap:
4109   case Builtin::BI__sync_swap_1:
4110   case Builtin::BI__sync_swap_2:
4111   case Builtin::BI__sync_swap_4:
4112   case Builtin::BI__sync_swap_8:
4113   case Builtin::BI__sync_swap_16:
4114     BuiltinIndex = 16;
4115     break;
4116   }
4117 
4118   // Now that we know how many fixed arguments we expect, first check that we
4119   // have at least that many.
4120   if (TheCall->getNumArgs() < 1+NumFixed) {
4121     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
4122       << 0 << 1+NumFixed << TheCall->getNumArgs()
4123       << TheCall->getCallee()->getSourceRange();
4124     return ExprError();
4125   }
4126 
4127   if (WarnAboutSemanticsChange) {
4128     Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
4129       << TheCall->getCallee()->getSourceRange();
4130   }
4131 
4132   // Get the decl for the concrete builtin from this, we can tell what the
4133   // concrete integer type we should convert to is.
4134   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
4135   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
4136   FunctionDecl *NewBuiltinDecl;
4137   if (NewBuiltinID == BuiltinID)
4138     NewBuiltinDecl = FDecl;
4139   else {
4140     // Perform builtin lookup to avoid redeclaring it.
4141     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
4142     LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
4143     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
4144     assert(Res.getFoundDecl());
4145     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
4146     if (!NewBuiltinDecl)
4147       return ExprError();
4148   }
4149 
4150   // The first argument --- the pointer --- has a fixed type; we
4151   // deduce the types of the rest of the arguments accordingly.  Walk
4152   // the remaining arguments, converting them to the deduced value type.
4153   for (unsigned i = 0; i != NumFixed; ++i) {
4154     ExprResult Arg = TheCall->getArg(i+1);
4155 
4156     // GCC does an implicit conversion to the pointer or integer ValType.  This
4157     // can fail in some cases (1i -> int**), check for this error case now.
4158     // Initialize the argument.
4159     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4160                                                    ValType, /*consume*/ false);
4161     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4162     if (Arg.isInvalid())
4163       return ExprError();
4164 
4165     // Okay, we have something that *can* be converted to the right type.  Check
4166     // to see if there is a potentially weird extension going on here.  This can
4167     // happen when you do an atomic operation on something like an char* and
4168     // pass in 42.  The 42 gets converted to char.  This is even more strange
4169     // for things like 45.123 -> char, etc.
4170     // FIXME: Do this check.
4171     TheCall->setArg(i+1, Arg.get());
4172   }
4173 
4174   ASTContext& Context = this->getASTContext();
4175 
4176   // Create a new DeclRefExpr to refer to the new decl.
4177   DeclRefExpr* NewDRE = DeclRefExpr::Create(
4178       Context,
4179       DRE->getQualifierLoc(),
4180       SourceLocation(),
4181       NewBuiltinDecl,
4182       /*enclosing*/ false,
4183       DRE->getLocation(),
4184       Context.BuiltinFnTy,
4185       DRE->getValueKind());
4186 
4187   // Set the callee in the CallExpr.
4188   // FIXME: This loses syntactic information.
4189   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
4190   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
4191                                               CK_BuiltinFnToFnPtr);
4192   TheCall->setCallee(PromotedCall.get());
4193 
4194   // Change the result type of the call to match the original value type. This
4195   // is arbitrary, but the codegen for these builtins ins design to handle it
4196   // gracefully.
4197   TheCall->setType(ResultType);
4198 
4199   return TheCallResult;
4200 }
4201 
4202 /// SemaBuiltinNontemporalOverloaded - We have a call to
4203 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
4204 /// overloaded function based on the pointer type of its last argument.
4205 ///
4206 /// This function goes through and does final semantic checking for these
4207 /// builtins.
4208 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
4209   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
4210   DeclRefExpr *DRE =
4211       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4212   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4213   unsigned BuiltinID = FDecl->getBuiltinID();
4214   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
4215           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
4216          "Unexpected nontemporal load/store builtin!");
4217   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
4218   unsigned numArgs = isStore ? 2 : 1;
4219 
4220   // Ensure that we have the proper number of arguments.
4221   if (checkArgCount(*this, TheCall, numArgs))
4222     return ExprError();
4223 
4224   // Inspect the last argument of the nontemporal builtin.  This should always
4225   // be a pointer type, from which we imply the type of the memory access.
4226   // Because it is a pointer type, we don't have to worry about any implicit
4227   // casts here.
4228   Expr *PointerArg = TheCall->getArg(numArgs - 1);
4229   ExprResult PointerArgResult =
4230       DefaultFunctionArrayLvalueConversion(PointerArg);
4231 
4232   if (PointerArgResult.isInvalid())
4233     return ExprError();
4234   PointerArg = PointerArgResult.get();
4235   TheCall->setArg(numArgs - 1, PointerArg);
4236 
4237   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
4238   if (!pointerType) {
4239     Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
4240         << PointerArg->getType() << PointerArg->getSourceRange();
4241     return ExprError();
4242   }
4243 
4244   QualType ValType = pointerType->getPointeeType();
4245 
4246   // Strip any qualifiers off ValType.
4247   ValType = ValType.getUnqualifiedType();
4248   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4249       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
4250       !ValType->isVectorType()) {
4251     Diag(DRE->getLocStart(),
4252          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
4253         << PointerArg->getType() << PointerArg->getSourceRange();
4254     return ExprError();
4255   }
4256 
4257   if (!isStore) {
4258     TheCall->setType(ValType);
4259     return TheCallResult;
4260   }
4261 
4262   ExprResult ValArg = TheCall->getArg(0);
4263   InitializedEntity Entity = InitializedEntity::InitializeParameter(
4264       Context, ValType, /*consume*/ false);
4265   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
4266   if (ValArg.isInvalid())
4267     return ExprError();
4268 
4269   TheCall->setArg(0, ValArg.get());
4270   TheCall->setType(Context.VoidTy);
4271   return TheCallResult;
4272 }
4273 
4274 /// CheckObjCString - Checks that the argument to the builtin
4275 /// CFString constructor is correct
4276 /// Note: It might also make sense to do the UTF-16 conversion here (would
4277 /// simplify the backend).
4278 bool Sema::CheckObjCString(Expr *Arg) {
4279   Arg = Arg->IgnoreParenCasts();
4280   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
4281 
4282   if (!Literal || !Literal->isAscii()) {
4283     Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
4284       << Arg->getSourceRange();
4285     return true;
4286   }
4287 
4288   if (Literal->containsNonAsciiOrNull()) {
4289     StringRef String = Literal->getString();
4290     unsigned NumBytes = String.size();
4291     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
4292     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
4293     llvm::UTF16 *ToPtr = &ToBuf[0];
4294 
4295     llvm::ConversionResult Result =
4296         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
4297                                  ToPtr + NumBytes, llvm::strictConversion);
4298     // Check for conversion failure.
4299     if (Result != llvm::conversionOK)
4300       Diag(Arg->getLocStart(),
4301            diag::warn_cfstring_truncated) << Arg->getSourceRange();
4302   }
4303   return false;
4304 }
4305 
4306 /// CheckObjCString - Checks that the format string argument to the os_log()
4307 /// and os_trace() functions is correct, and converts it to const char *.
4308 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
4309   Arg = Arg->IgnoreParenCasts();
4310   auto *Literal = dyn_cast<StringLiteral>(Arg);
4311   if (!Literal) {
4312     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
4313       Literal = ObjcLiteral->getString();
4314     }
4315   }
4316 
4317   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
4318     return ExprError(
4319         Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
4320         << Arg->getSourceRange());
4321   }
4322 
4323   ExprResult Result(Literal);
4324   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
4325   InitializedEntity Entity =
4326       InitializedEntity::InitializeParameter(Context, ResultTy, false);
4327   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
4328   return Result;
4329 }
4330 
4331 /// Check that the user is calling the appropriate va_start builtin for the
4332 /// target and calling convention.
4333 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
4334   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
4335   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
4336   bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
4337   bool IsWindows = TT.isOSWindows();
4338   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
4339   if (IsX64 || IsAArch64) {
4340     CallingConv CC = CC_C;
4341     if (const FunctionDecl *FD = S.getCurFunctionDecl())
4342       CC = FD->getType()->getAs<FunctionType>()->getCallConv();
4343     if (IsMSVAStart) {
4344       // Don't allow this in System V ABI functions.
4345       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
4346         return S.Diag(Fn->getLocStart(),
4347                       diag::err_ms_va_start_used_in_sysv_function);
4348     } else {
4349       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
4350       // On x64 Windows, don't allow this in System V ABI functions.
4351       // (Yes, that means there's no corresponding way to support variadic
4352       // System V ABI functions on Windows.)
4353       if ((IsWindows && CC == CC_X86_64SysV) ||
4354           (!IsWindows && CC == CC_Win64))
4355         return S.Diag(Fn->getLocStart(),
4356                       diag::err_va_start_used_in_wrong_abi_function)
4357                << !IsWindows;
4358     }
4359     return false;
4360   }
4361 
4362   if (IsMSVAStart)
4363     return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only);
4364   return false;
4365 }
4366 
4367 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
4368                                              ParmVarDecl **LastParam = nullptr) {
4369   // Determine whether the current function, block, or obj-c method is variadic
4370   // and get its parameter list.
4371   bool IsVariadic = false;
4372   ArrayRef<ParmVarDecl *> Params;
4373   DeclContext *Caller = S.CurContext;
4374   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
4375     IsVariadic = Block->isVariadic();
4376     Params = Block->parameters();
4377   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
4378     IsVariadic = FD->isVariadic();
4379     Params = FD->parameters();
4380   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
4381     IsVariadic = MD->isVariadic();
4382     // FIXME: This isn't correct for methods (results in bogus warning).
4383     Params = MD->parameters();
4384   } else if (isa<CapturedDecl>(Caller)) {
4385     // We don't support va_start in a CapturedDecl.
4386     S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
4387     return true;
4388   } else {
4389     // This must be some other declcontext that parses exprs.
4390     S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
4391     return true;
4392   }
4393 
4394   if (!IsVariadic) {
4395     S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
4396     return true;
4397   }
4398 
4399   if (LastParam)
4400     *LastParam = Params.empty() ? nullptr : Params.back();
4401 
4402   return false;
4403 }
4404 
4405 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
4406 /// for validity.  Emit an error and return true on failure; return false
4407 /// on success.
4408 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
4409   Expr *Fn = TheCall->getCallee();
4410 
4411   if (checkVAStartABI(*this, BuiltinID, Fn))
4412     return true;
4413 
4414   if (TheCall->getNumArgs() > 2) {
4415     Diag(TheCall->getArg(2)->getLocStart(),
4416          diag::err_typecheck_call_too_many_args)
4417       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4418       << Fn->getSourceRange()
4419       << SourceRange(TheCall->getArg(2)->getLocStart(),
4420                      (*(TheCall->arg_end()-1))->getLocEnd());
4421     return true;
4422   }
4423 
4424   if (TheCall->getNumArgs() < 2) {
4425     return Diag(TheCall->getLocEnd(),
4426       diag::err_typecheck_call_too_few_args_at_least)
4427       << 0 /*function call*/ << 2 << TheCall->getNumArgs();
4428   }
4429 
4430   // Type-check the first argument normally.
4431   if (checkBuiltinArgument(*this, TheCall, 0))
4432     return true;
4433 
4434   // Check that the current function is variadic, and get its last parameter.
4435   ParmVarDecl *LastParam;
4436   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
4437     return true;
4438 
4439   // Verify that the second argument to the builtin is the last argument of the
4440   // current function or method.
4441   bool SecondArgIsLastNamedArgument = false;
4442   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
4443 
4444   // These are valid if SecondArgIsLastNamedArgument is false after the next
4445   // block.
4446   QualType Type;
4447   SourceLocation ParamLoc;
4448   bool IsCRegister = false;
4449 
4450   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
4451     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
4452       SecondArgIsLastNamedArgument = PV == LastParam;
4453 
4454       Type = PV->getType();
4455       ParamLoc = PV->getLocation();
4456       IsCRegister =
4457           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
4458     }
4459   }
4460 
4461   if (!SecondArgIsLastNamedArgument)
4462     Diag(TheCall->getArg(1)->getLocStart(),
4463          diag::warn_second_arg_of_va_start_not_last_named_param);
4464   else if (IsCRegister || Type->isReferenceType() ||
4465            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
4466              // Promotable integers are UB, but enumerations need a bit of
4467              // extra checking to see what their promotable type actually is.
4468              if (!Type->isPromotableIntegerType())
4469                return false;
4470              if (!Type->isEnumeralType())
4471                return true;
4472              const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
4473              return !(ED &&
4474                       Context.typesAreCompatible(ED->getPromotionType(), Type));
4475            }()) {
4476     unsigned Reason = 0;
4477     if (Type->isReferenceType())  Reason = 1;
4478     else if (IsCRegister)         Reason = 2;
4479     Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
4480     Diag(ParamLoc, diag::note_parameter_type) << Type;
4481   }
4482 
4483   TheCall->setType(Context.VoidTy);
4484   return false;
4485 }
4486 
4487 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
4488   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
4489   //                 const char *named_addr);
4490 
4491   Expr *Func = Call->getCallee();
4492 
4493   if (Call->getNumArgs() < 3)
4494     return Diag(Call->getLocEnd(),
4495                 diag::err_typecheck_call_too_few_args_at_least)
4496            << 0 /*function call*/ << 3 << Call->getNumArgs();
4497 
4498   // Type-check the first argument normally.
4499   if (checkBuiltinArgument(*this, Call, 0))
4500     return true;
4501 
4502   // Check that the current function is variadic.
4503   if (checkVAStartIsInVariadicFunction(*this, Func))
4504     return true;
4505 
4506   // __va_start on Windows does not validate the parameter qualifiers
4507 
4508   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
4509   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
4510 
4511   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
4512   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
4513 
4514   const QualType &ConstCharPtrTy =
4515       Context.getPointerType(Context.CharTy.withConst());
4516   if (!Arg1Ty->isPointerType() ||
4517       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
4518     Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible)
4519         << Arg1->getType() << ConstCharPtrTy
4520         << 1 /* different class */
4521         << 0 /* qualifier difference */
4522         << 3 /* parameter mismatch */
4523         << 2 << Arg1->getType() << ConstCharPtrTy;
4524 
4525   const QualType SizeTy = Context.getSizeType();
4526   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
4527     Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible)
4528         << Arg2->getType() << SizeTy
4529         << 1 /* different class */
4530         << 0 /* qualifier difference */
4531         << 3 /* parameter mismatch */
4532         << 3 << Arg2->getType() << SizeTy;
4533 
4534   return false;
4535 }
4536 
4537 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
4538 /// friends.  This is declared to take (...), so we have to check everything.
4539 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
4540   if (TheCall->getNumArgs() < 2)
4541     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4542       << 0 << 2 << TheCall->getNumArgs()/*function call*/;
4543   if (TheCall->getNumArgs() > 2)
4544     return Diag(TheCall->getArg(2)->getLocStart(),
4545                 diag::err_typecheck_call_too_many_args)
4546       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4547       << SourceRange(TheCall->getArg(2)->getLocStart(),
4548                      (*(TheCall->arg_end()-1))->getLocEnd());
4549 
4550   ExprResult OrigArg0 = TheCall->getArg(0);
4551   ExprResult OrigArg1 = TheCall->getArg(1);
4552 
4553   // Do standard promotions between the two arguments, returning their common
4554   // type.
4555   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
4556   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
4557     return true;
4558 
4559   // Make sure any conversions are pushed back into the call; this is
4560   // type safe since unordered compare builtins are declared as "_Bool
4561   // foo(...)".
4562   TheCall->setArg(0, OrigArg0.get());
4563   TheCall->setArg(1, OrigArg1.get());
4564 
4565   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
4566     return false;
4567 
4568   // If the common type isn't a real floating type, then the arguments were
4569   // invalid for this operation.
4570   if (Res.isNull() || !Res->isRealFloatingType())
4571     return Diag(OrigArg0.get()->getLocStart(),
4572                 diag::err_typecheck_call_invalid_ordered_compare)
4573       << OrigArg0.get()->getType() << OrigArg1.get()->getType()
4574       << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
4575 
4576   return false;
4577 }
4578 
4579 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
4580 /// __builtin_isnan and friends.  This is declared to take (...), so we have
4581 /// to check everything. We expect the last argument to be a floating point
4582 /// value.
4583 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
4584   if (TheCall->getNumArgs() < NumArgs)
4585     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4586       << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
4587   if (TheCall->getNumArgs() > NumArgs)
4588     return Diag(TheCall->getArg(NumArgs)->getLocStart(),
4589                 diag::err_typecheck_call_too_many_args)
4590       << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
4591       << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
4592                      (*(TheCall->arg_end()-1))->getLocEnd());
4593 
4594   Expr *OrigArg = TheCall->getArg(NumArgs-1);
4595 
4596   if (OrigArg->isTypeDependent())
4597     return false;
4598 
4599   // This operation requires a non-_Complex floating-point number.
4600   if (!OrigArg->getType()->isRealFloatingType())
4601     return Diag(OrigArg->getLocStart(),
4602                 diag::err_typecheck_call_invalid_unary_fp)
4603       << OrigArg->getType() << OrigArg->getSourceRange();
4604 
4605   // If this is an implicit conversion from float -> float, double, or
4606   // long double, remove it.
4607   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
4608     // Only remove standard FloatCasts, leaving other casts inplace
4609     if (Cast->getCastKind() == CK_FloatingCast) {
4610       Expr *CastArg = Cast->getSubExpr();
4611       if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
4612         assert(
4613             (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
4614              Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) ||
4615              Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) &&
4616             "promotion from float to either float, double, or long double is "
4617             "the only expected cast here");
4618         Cast->setSubExpr(nullptr);
4619         TheCall->setArg(NumArgs-1, CastArg);
4620       }
4621     }
4622   }
4623 
4624   return false;
4625 }
4626 
4627 // Customized Sema Checking for VSX builtins that have the following signature:
4628 // vector [...] builtinName(vector [...], vector [...], const int);
4629 // Which takes the same type of vectors (any legal vector type) for the first
4630 // two arguments and takes compile time constant for the third argument.
4631 // Example builtins are :
4632 // vector double vec_xxpermdi(vector double, vector double, int);
4633 // vector short vec_xxsldwi(vector short, vector short, int);
4634 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
4635   unsigned ExpectedNumArgs = 3;
4636   if (TheCall->getNumArgs() < ExpectedNumArgs)
4637     return Diag(TheCall->getLocEnd(),
4638                 diag::err_typecheck_call_too_few_args_at_least)
4639            << 0 /*function call*/ <<  ExpectedNumArgs << TheCall->getNumArgs()
4640            << TheCall->getSourceRange();
4641 
4642   if (TheCall->getNumArgs() > ExpectedNumArgs)
4643     return Diag(TheCall->getLocEnd(),
4644                 diag::err_typecheck_call_too_many_args_at_most)
4645            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4646            << TheCall->getSourceRange();
4647 
4648   // Check the third argument is a compile time constant
4649   llvm::APSInt Value;
4650   if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
4651     return Diag(TheCall->getLocStart(),
4652                 diag::err_vsx_builtin_nonconstant_argument)
4653            << 3 /* argument index */ << TheCall->getDirectCallee()
4654            << SourceRange(TheCall->getArg(2)->getLocStart(),
4655                           TheCall->getArg(2)->getLocEnd());
4656 
4657   QualType Arg1Ty = TheCall->getArg(0)->getType();
4658   QualType Arg2Ty = TheCall->getArg(1)->getType();
4659 
4660   // Check the type of argument 1 and argument 2 are vectors.
4661   SourceLocation BuiltinLoc = TheCall->getLocStart();
4662   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
4663       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
4664     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
4665            << TheCall->getDirectCallee()
4666            << SourceRange(TheCall->getArg(0)->getLocStart(),
4667                           TheCall->getArg(1)->getLocEnd());
4668   }
4669 
4670   // Check the first two arguments are the same type.
4671   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
4672     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
4673            << TheCall->getDirectCallee()
4674            << SourceRange(TheCall->getArg(0)->getLocStart(),
4675                           TheCall->getArg(1)->getLocEnd());
4676   }
4677 
4678   // When default clang type checking is turned off and the customized type
4679   // checking is used, the returning type of the function must be explicitly
4680   // set. Otherwise it is _Bool by default.
4681   TheCall->setType(Arg1Ty);
4682 
4683   return false;
4684 }
4685 
4686 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
4687 // This is declared to take (...), so we have to check everything.
4688 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
4689   if (TheCall->getNumArgs() < 2)
4690     return ExprError(Diag(TheCall->getLocEnd(),
4691                           diag::err_typecheck_call_too_few_args_at_least)
4692                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4693                      << TheCall->getSourceRange());
4694 
4695   // Determine which of the following types of shufflevector we're checking:
4696   // 1) unary, vector mask: (lhs, mask)
4697   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
4698   QualType resType = TheCall->getArg(0)->getType();
4699   unsigned numElements = 0;
4700 
4701   if (!TheCall->getArg(0)->isTypeDependent() &&
4702       !TheCall->getArg(1)->isTypeDependent()) {
4703     QualType LHSType = TheCall->getArg(0)->getType();
4704     QualType RHSType = TheCall->getArg(1)->getType();
4705 
4706     if (!LHSType->isVectorType() || !RHSType->isVectorType())
4707       return ExprError(Diag(TheCall->getLocStart(),
4708                             diag::err_vec_builtin_non_vector)
4709                        << TheCall->getDirectCallee()
4710                        << SourceRange(TheCall->getArg(0)->getLocStart(),
4711                                       TheCall->getArg(1)->getLocEnd()));
4712 
4713     numElements = LHSType->getAs<VectorType>()->getNumElements();
4714     unsigned numResElements = TheCall->getNumArgs() - 2;
4715 
4716     // Check to see if we have a call with 2 vector arguments, the unary shuffle
4717     // with mask.  If so, verify that RHS is an integer vector type with the
4718     // same number of elts as lhs.
4719     if (TheCall->getNumArgs() == 2) {
4720       if (!RHSType->hasIntegerRepresentation() ||
4721           RHSType->getAs<VectorType>()->getNumElements() != numElements)
4722         return ExprError(Diag(TheCall->getLocStart(),
4723                               diag::err_vec_builtin_incompatible_vector)
4724                          << TheCall->getDirectCallee()
4725                          << SourceRange(TheCall->getArg(1)->getLocStart(),
4726                                         TheCall->getArg(1)->getLocEnd()));
4727     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
4728       return ExprError(Diag(TheCall->getLocStart(),
4729                             diag::err_vec_builtin_incompatible_vector)
4730                        << TheCall->getDirectCallee()
4731                        << SourceRange(TheCall->getArg(0)->getLocStart(),
4732                                       TheCall->getArg(1)->getLocEnd()));
4733     } else if (numElements != numResElements) {
4734       QualType eltType = LHSType->getAs<VectorType>()->getElementType();
4735       resType = Context.getVectorType(eltType, numResElements,
4736                                       VectorType::GenericVector);
4737     }
4738   }
4739 
4740   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
4741     if (TheCall->getArg(i)->isTypeDependent() ||
4742         TheCall->getArg(i)->isValueDependent())
4743       continue;
4744 
4745     llvm::APSInt Result(32);
4746     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
4747       return ExprError(Diag(TheCall->getLocStart(),
4748                             diag::err_shufflevector_nonconstant_argument)
4749                        << TheCall->getArg(i)->getSourceRange());
4750 
4751     // Allow -1 which will be translated to undef in the IR.
4752     if (Result.isSigned() && Result.isAllOnesValue())
4753       continue;
4754 
4755     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
4756       return ExprError(Diag(TheCall->getLocStart(),
4757                             diag::err_shufflevector_argument_too_large)
4758                        << TheCall->getArg(i)->getSourceRange());
4759   }
4760 
4761   SmallVector<Expr*, 32> exprs;
4762 
4763   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
4764     exprs.push_back(TheCall->getArg(i));
4765     TheCall->setArg(i, nullptr);
4766   }
4767 
4768   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
4769                                          TheCall->getCallee()->getLocStart(),
4770                                          TheCall->getRParenLoc());
4771 }
4772 
4773 /// SemaConvertVectorExpr - Handle __builtin_convertvector
4774 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
4775                                        SourceLocation BuiltinLoc,
4776                                        SourceLocation RParenLoc) {
4777   ExprValueKind VK = VK_RValue;
4778   ExprObjectKind OK = OK_Ordinary;
4779   QualType DstTy = TInfo->getType();
4780   QualType SrcTy = E->getType();
4781 
4782   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
4783     return ExprError(Diag(BuiltinLoc,
4784                           diag::err_convertvector_non_vector)
4785                      << E->getSourceRange());
4786   if (!DstTy->isVectorType() && !DstTy->isDependentType())
4787     return ExprError(Diag(BuiltinLoc,
4788                           diag::err_convertvector_non_vector_type));
4789 
4790   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
4791     unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
4792     unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
4793     if (SrcElts != DstElts)
4794       return ExprError(Diag(BuiltinLoc,
4795                             diag::err_convertvector_incompatible_vector)
4796                        << E->getSourceRange());
4797   }
4798 
4799   return new (Context)
4800       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
4801 }
4802 
4803 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
4804 // This is declared to take (const void*, ...) and can take two
4805 // optional constant int args.
4806 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
4807   unsigned NumArgs = TheCall->getNumArgs();
4808 
4809   if (NumArgs > 3)
4810     return Diag(TheCall->getLocEnd(),
4811              diag::err_typecheck_call_too_many_args_at_most)
4812              << 0 /*function call*/ << 3 << NumArgs
4813              << TheCall->getSourceRange();
4814 
4815   // Argument 0 is checked for us and the remaining arguments must be
4816   // constant integers.
4817   for (unsigned i = 1; i != NumArgs; ++i)
4818     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
4819       return true;
4820 
4821   return false;
4822 }
4823 
4824 /// SemaBuiltinAssume - Handle __assume (MS Extension).
4825 // __assume does not evaluate its arguments, and should warn if its argument
4826 // has side effects.
4827 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
4828   Expr *Arg = TheCall->getArg(0);
4829   if (Arg->isInstantiationDependent()) return false;
4830 
4831   if (Arg->HasSideEffects(Context))
4832     Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
4833       << Arg->getSourceRange()
4834       << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
4835 
4836   return false;
4837 }
4838 
4839 /// Handle __builtin_alloca_with_align. This is declared
4840 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
4841 /// than 8.
4842 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
4843   // The alignment must be a constant integer.
4844   Expr *Arg = TheCall->getArg(1);
4845 
4846   // We can't check the value of a dependent argument.
4847   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4848     if (const auto *UE =
4849             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
4850       if (UE->getKind() == UETT_AlignOf)
4851         Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
4852           << Arg->getSourceRange();
4853 
4854     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
4855 
4856     if (!Result.isPowerOf2())
4857       return Diag(TheCall->getLocStart(),
4858                   diag::err_alignment_not_power_of_two)
4859            << Arg->getSourceRange();
4860 
4861     if (Result < Context.getCharWidth())
4862       return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
4863            << (unsigned)Context.getCharWidth()
4864            << Arg->getSourceRange();
4865 
4866     if (Result > std::numeric_limits<int32_t>::max())
4867       return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
4868            << std::numeric_limits<int32_t>::max()
4869            << Arg->getSourceRange();
4870   }
4871 
4872   return false;
4873 }
4874 
4875 /// Handle __builtin_assume_aligned. This is declared
4876 /// as (const void*, size_t, ...) and can take one optional constant int arg.
4877 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
4878   unsigned NumArgs = TheCall->getNumArgs();
4879 
4880   if (NumArgs > 3)
4881     return Diag(TheCall->getLocEnd(),
4882              diag::err_typecheck_call_too_many_args_at_most)
4883              << 0 /*function call*/ << 3 << NumArgs
4884              << TheCall->getSourceRange();
4885 
4886   // The alignment must be a constant integer.
4887   Expr *Arg = TheCall->getArg(1);
4888 
4889   // We can't check the value of a dependent argument.
4890   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4891     llvm::APSInt Result;
4892     if (SemaBuiltinConstantArg(TheCall, 1, Result))
4893       return true;
4894 
4895     if (!Result.isPowerOf2())
4896       return Diag(TheCall->getLocStart(),
4897                   diag::err_alignment_not_power_of_two)
4898            << Arg->getSourceRange();
4899   }
4900 
4901   if (NumArgs > 2) {
4902     ExprResult Arg(TheCall->getArg(2));
4903     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4904       Context.getSizeType(), false);
4905     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4906     if (Arg.isInvalid()) return true;
4907     TheCall->setArg(2, Arg.get());
4908   }
4909 
4910   return false;
4911 }
4912 
4913 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4914   unsigned BuiltinID =
4915       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4916   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4917 
4918   unsigned NumArgs = TheCall->getNumArgs();
4919   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4920   if (NumArgs < NumRequiredArgs) {
4921     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4922            << 0 /* function call */ << NumRequiredArgs << NumArgs
4923            << TheCall->getSourceRange();
4924   }
4925   if (NumArgs >= NumRequiredArgs + 0x100) {
4926     return Diag(TheCall->getLocEnd(),
4927                 diag::err_typecheck_call_too_many_args_at_most)
4928            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4929            << TheCall->getSourceRange();
4930   }
4931   unsigned i = 0;
4932 
4933   // For formatting call, check buffer arg.
4934   if (!IsSizeCall) {
4935     ExprResult Arg(TheCall->getArg(i));
4936     InitializedEntity Entity = InitializedEntity::InitializeParameter(
4937         Context, Context.VoidPtrTy, false);
4938     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4939     if (Arg.isInvalid())
4940       return true;
4941     TheCall->setArg(i, Arg.get());
4942     i++;
4943   }
4944 
4945   // Check string literal arg.
4946   unsigned FormatIdx = i;
4947   {
4948     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4949     if (Arg.isInvalid())
4950       return true;
4951     TheCall->setArg(i, Arg.get());
4952     i++;
4953   }
4954 
4955   // Make sure variadic args are scalar.
4956   unsigned FirstDataArg = i;
4957   while (i < NumArgs) {
4958     ExprResult Arg = DefaultVariadicArgumentPromotion(
4959         TheCall->getArg(i), VariadicFunction, nullptr);
4960     if (Arg.isInvalid())
4961       return true;
4962     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4963     if (ArgSize.getQuantity() >= 0x100) {
4964       return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4965              << i << (int)ArgSize.getQuantity() << 0xff
4966              << TheCall->getSourceRange();
4967     }
4968     TheCall->setArg(i, Arg.get());
4969     i++;
4970   }
4971 
4972   // Check formatting specifiers. NOTE: We're only doing this for the non-size
4973   // call to avoid duplicate diagnostics.
4974   if (!IsSizeCall) {
4975     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4976     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4977     bool Success = CheckFormatArguments(
4978         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4979         VariadicFunction, TheCall->getLocStart(), SourceRange(),
4980         CheckedVarArgs);
4981     if (!Success)
4982       return true;
4983   }
4984 
4985   if (IsSizeCall) {
4986     TheCall->setType(Context.getSizeType());
4987   } else {
4988     TheCall->setType(Context.VoidPtrTy);
4989   }
4990   return false;
4991 }
4992 
4993 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4994 /// TheCall is a constant expression.
4995 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4996                                   llvm::APSInt &Result) {
4997   Expr *Arg = TheCall->getArg(ArgNum);
4998   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4999   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5000 
5001   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
5002 
5003   if (!Arg->isIntegerConstantExpr(Result, Context))
5004     return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
5005                 << FDecl->getDeclName() <<  Arg->getSourceRange();
5006 
5007   return false;
5008 }
5009 
5010 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
5011 /// TheCall is a constant expression in the range [Low, High].
5012 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
5013                                        int Low, int High, bool RangeIsError) {
5014   llvm::APSInt Result;
5015 
5016   // We can't check the value of a dependent argument.
5017   Expr *Arg = TheCall->getArg(ArgNum);
5018   if (Arg->isTypeDependent() || Arg->isValueDependent())
5019     return false;
5020 
5021   // Check constant-ness first.
5022   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
5023     return true;
5024 
5025   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
5026     if (RangeIsError)
5027       return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
5028              << Result.toString(10) << Low << High << Arg->getSourceRange();
5029     else
5030       // Defer the warning until we know if the code will be emitted so that
5031       // dead code can ignore this.
5032       DiagRuntimeBehavior(TheCall->getLocStart(), TheCall,
5033                             PDiag(diag::warn_argument_invalid_range)
5034                                 << Result.toString(10) << Low << High
5035                                 << Arg->getSourceRange());
5036   }
5037 
5038   return false;
5039 }
5040 
5041 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
5042 /// TheCall is a constant expression is a multiple of Num..
5043 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
5044                                           unsigned Num) {
5045   llvm::APSInt Result;
5046 
5047   // We can't check the value of a dependent argument.
5048   Expr *Arg = TheCall->getArg(ArgNum);
5049   if (Arg->isTypeDependent() || Arg->isValueDependent())
5050     return false;
5051 
5052   // Check constant-ness first.
5053   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
5054     return true;
5055 
5056   if (Result.getSExtValue() % Num != 0)
5057     return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
5058       << Num << Arg->getSourceRange();
5059 
5060   return false;
5061 }
5062 
5063 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
5064 /// TheCall is an ARM/AArch64 special register string literal.
5065 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
5066                                     int ArgNum, unsigned ExpectedFieldNum,
5067                                     bool AllowName) {
5068   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
5069                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
5070                       BuiltinID == ARM::BI__builtin_arm_rsr ||
5071                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
5072                       BuiltinID == ARM::BI__builtin_arm_wsr ||
5073                       BuiltinID == ARM::BI__builtin_arm_wsrp;
5074   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
5075                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
5076                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
5077                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
5078                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
5079                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
5080   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
5081 
5082   // We can't check the value of a dependent argument.
5083   Expr *Arg = TheCall->getArg(ArgNum);
5084   if (Arg->isTypeDependent() || Arg->isValueDependent())
5085     return false;
5086 
5087   // Check if the argument is a string literal.
5088   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
5089     return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
5090            << Arg->getSourceRange();
5091 
5092   // Check the type of special register given.
5093   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
5094   SmallVector<StringRef, 6> Fields;
5095   Reg.split(Fields, ":");
5096 
5097   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
5098     return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
5099            << Arg->getSourceRange();
5100 
5101   // If the string is the name of a register then we cannot check that it is
5102   // valid here but if the string is of one the forms described in ACLE then we
5103   // can check that the supplied fields are integers and within the valid
5104   // ranges.
5105   if (Fields.size() > 1) {
5106     bool FiveFields = Fields.size() == 5;
5107 
5108     bool ValidString = true;
5109     if (IsARMBuiltin) {
5110       ValidString &= Fields[0].startswith_lower("cp") ||
5111                      Fields[0].startswith_lower("p");
5112       if (ValidString)
5113         Fields[0] =
5114           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
5115 
5116       ValidString &= Fields[2].startswith_lower("c");
5117       if (ValidString)
5118         Fields[2] = Fields[2].drop_front(1);
5119 
5120       if (FiveFields) {
5121         ValidString &= Fields[3].startswith_lower("c");
5122         if (ValidString)
5123           Fields[3] = Fields[3].drop_front(1);
5124       }
5125     }
5126 
5127     SmallVector<int, 5> Ranges;
5128     if (FiveFields)
5129       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
5130     else
5131       Ranges.append({15, 7, 15});
5132 
5133     for (unsigned i=0; i<Fields.size(); ++i) {
5134       int IntField;
5135       ValidString &= !Fields[i].getAsInteger(10, IntField);
5136       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
5137     }
5138 
5139     if (!ValidString)
5140       return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
5141              << Arg->getSourceRange();
5142   } else if (IsAArch64Builtin && Fields.size() == 1) {
5143     // If the register name is one of those that appear in the condition below
5144     // and the special register builtin being used is one of the write builtins,
5145     // then we require that the argument provided for writing to the register
5146     // is an integer constant expression. This is because it will be lowered to
5147     // an MSR (immediate) instruction, so we need to know the immediate at
5148     // compile time.
5149     if (TheCall->getNumArgs() != 2)
5150       return false;
5151 
5152     std::string RegLower = Reg.lower();
5153     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
5154         RegLower != "pan" && RegLower != "uao")
5155       return false;
5156 
5157     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
5158   }
5159 
5160   return false;
5161 }
5162 
5163 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
5164 /// This checks that the target supports __builtin_longjmp and
5165 /// that val is a constant 1.
5166 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
5167   if (!Context.getTargetInfo().hasSjLjLowering())
5168     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
5169              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
5170 
5171   Expr *Arg = TheCall->getArg(1);
5172   llvm::APSInt Result;
5173 
5174   // TODO: This is less than ideal. Overload this to take a value.
5175   if (SemaBuiltinConstantArg(TheCall, 1, Result))
5176     return true;
5177 
5178   if (Result != 1)
5179     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
5180              << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
5181 
5182   return false;
5183 }
5184 
5185 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
5186 /// This checks that the target supports __builtin_setjmp.
5187 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
5188   if (!Context.getTargetInfo().hasSjLjLowering())
5189     return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
5190              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
5191   return false;
5192 }
5193 
5194 namespace {
5195 
5196 class UncoveredArgHandler {
5197   enum { Unknown = -1, AllCovered = -2 };
5198 
5199   signed FirstUncoveredArg = Unknown;
5200   SmallVector<const Expr *, 4> DiagnosticExprs;
5201 
5202 public:
5203   UncoveredArgHandler() = default;
5204 
5205   bool hasUncoveredArg() const {
5206     return (FirstUncoveredArg >= 0);
5207   }
5208 
5209   unsigned getUncoveredArg() const {
5210     assert(hasUncoveredArg() && "no uncovered argument");
5211     return FirstUncoveredArg;
5212   }
5213 
5214   void setAllCovered() {
5215     // A string has been found with all arguments covered, so clear out
5216     // the diagnostics.
5217     DiagnosticExprs.clear();
5218     FirstUncoveredArg = AllCovered;
5219   }
5220 
5221   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
5222     assert(NewFirstUncoveredArg >= 0 && "Outside range");
5223 
5224     // Don't update if a previous string covers all arguments.
5225     if (FirstUncoveredArg == AllCovered)
5226       return;
5227 
5228     // UncoveredArgHandler tracks the highest uncovered argument index
5229     // and with it all the strings that match this index.
5230     if (NewFirstUncoveredArg == FirstUncoveredArg)
5231       DiagnosticExprs.push_back(StrExpr);
5232     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
5233       DiagnosticExprs.clear();
5234       DiagnosticExprs.push_back(StrExpr);
5235       FirstUncoveredArg = NewFirstUncoveredArg;
5236     }
5237   }
5238 
5239   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
5240 };
5241 
5242 enum StringLiteralCheckType {
5243   SLCT_NotALiteral,
5244   SLCT_UncheckedLiteral,
5245   SLCT_CheckedLiteral
5246 };
5247 
5248 } // namespace
5249 
5250 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
5251                                      BinaryOperatorKind BinOpKind,
5252                                      bool AddendIsRight) {
5253   unsigned BitWidth = Offset.getBitWidth();
5254   unsigned AddendBitWidth = Addend.getBitWidth();
5255   // There might be negative interim results.
5256   if (Addend.isUnsigned()) {
5257     Addend = Addend.zext(++AddendBitWidth);
5258     Addend.setIsSigned(true);
5259   }
5260   // Adjust the bit width of the APSInts.
5261   if (AddendBitWidth > BitWidth) {
5262     Offset = Offset.sext(AddendBitWidth);
5263     BitWidth = AddendBitWidth;
5264   } else if (BitWidth > AddendBitWidth) {
5265     Addend = Addend.sext(BitWidth);
5266   }
5267 
5268   bool Ov = false;
5269   llvm::APSInt ResOffset = Offset;
5270   if (BinOpKind == BO_Add)
5271     ResOffset = Offset.sadd_ov(Addend, Ov);
5272   else {
5273     assert(AddendIsRight && BinOpKind == BO_Sub &&
5274            "operator must be add or sub with addend on the right");
5275     ResOffset = Offset.ssub_ov(Addend, Ov);
5276   }
5277 
5278   // We add an offset to a pointer here so we should support an offset as big as
5279   // possible.
5280   if (Ov) {
5281     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
5282            "index (intermediate) result too big");
5283     Offset = Offset.sext(2 * BitWidth);
5284     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
5285     return;
5286   }
5287 
5288   Offset = ResOffset;
5289 }
5290 
5291 namespace {
5292 
5293 // This is a wrapper class around StringLiteral to support offsetted string
5294 // literals as format strings. It takes the offset into account when returning
5295 // the string and its length or the source locations to display notes correctly.
5296 class FormatStringLiteral {
5297   const StringLiteral *FExpr;
5298   int64_t Offset;
5299 
5300  public:
5301   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
5302       : FExpr(fexpr), Offset(Offset) {}
5303 
5304   StringRef getString() const {
5305     return FExpr->getString().drop_front(Offset);
5306   }
5307 
5308   unsigned getByteLength() const {
5309     return FExpr->getByteLength() - getCharByteWidth() * Offset;
5310   }
5311 
5312   unsigned getLength() const { return FExpr->getLength() - Offset; }
5313   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
5314 
5315   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
5316 
5317   QualType getType() const { return FExpr->getType(); }
5318 
5319   bool isAscii() const { return FExpr->isAscii(); }
5320   bool isWide() const { return FExpr->isWide(); }
5321   bool isUTF8() const { return FExpr->isUTF8(); }
5322   bool isUTF16() const { return FExpr->isUTF16(); }
5323   bool isUTF32() const { return FExpr->isUTF32(); }
5324   bool isPascal() const { return FExpr->isPascal(); }
5325 
5326   SourceLocation getLocationOfByte(
5327       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
5328       const TargetInfo &Target, unsigned *StartToken = nullptr,
5329       unsigned *StartTokenByteOffset = nullptr) const {
5330     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
5331                                     StartToken, StartTokenByteOffset);
5332   }
5333 
5334   SourceLocation getLocStart() const LLVM_READONLY {
5335     return FExpr->getLocStart().getLocWithOffset(Offset);
5336   }
5337 
5338   SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
5339 };
5340 
5341 }  // namespace
5342 
5343 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
5344                               const Expr *OrigFormatExpr,
5345                               ArrayRef<const Expr *> Args,
5346                               bool HasVAListArg, unsigned format_idx,
5347                               unsigned firstDataArg,
5348                               Sema::FormatStringType Type,
5349                               bool inFunctionCall,
5350                               Sema::VariadicCallType CallType,
5351                               llvm::SmallBitVector &CheckedVarArgs,
5352                               UncoveredArgHandler &UncoveredArg);
5353 
5354 // Determine if an expression is a string literal or constant string.
5355 // If this function returns false on the arguments to a function expecting a
5356 // format string, we will usually need to emit a warning.
5357 // True string literals are then checked by CheckFormatString.
5358 static StringLiteralCheckType
5359 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
5360                       bool HasVAListArg, unsigned format_idx,
5361                       unsigned firstDataArg, Sema::FormatStringType Type,
5362                       Sema::VariadicCallType CallType, bool InFunctionCall,
5363                       llvm::SmallBitVector &CheckedVarArgs,
5364                       UncoveredArgHandler &UncoveredArg,
5365                       llvm::APSInt Offset) {
5366  tryAgain:
5367   assert(Offset.isSigned() && "invalid offset");
5368 
5369   if (E->isTypeDependent() || E->isValueDependent())
5370     return SLCT_NotALiteral;
5371 
5372   E = E->IgnoreParenCasts();
5373 
5374   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
5375     // Technically -Wformat-nonliteral does not warn about this case.
5376     // The behavior of printf and friends in this case is implementation
5377     // dependent.  Ideally if the format string cannot be null then
5378     // it should have a 'nonnull' attribute in the function prototype.
5379     return SLCT_UncheckedLiteral;
5380 
5381   switch (E->getStmtClass()) {
5382   case Stmt::BinaryConditionalOperatorClass:
5383   case Stmt::ConditionalOperatorClass: {
5384     // The expression is a literal if both sub-expressions were, and it was
5385     // completely checked only if both sub-expressions were checked.
5386     const AbstractConditionalOperator *C =
5387         cast<AbstractConditionalOperator>(E);
5388 
5389     // Determine whether it is necessary to check both sub-expressions, for
5390     // example, because the condition expression is a constant that can be
5391     // evaluated at compile time.
5392     bool CheckLeft = true, CheckRight = true;
5393 
5394     bool Cond;
5395     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
5396       if (Cond)
5397         CheckRight = false;
5398       else
5399         CheckLeft = false;
5400     }
5401 
5402     // We need to maintain the offsets for the right and the left hand side
5403     // separately to check if every possible indexed expression is a valid
5404     // string literal. They might have different offsets for different string
5405     // literals in the end.
5406     StringLiteralCheckType Left;
5407     if (!CheckLeft)
5408       Left = SLCT_UncheckedLiteral;
5409     else {
5410       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
5411                                    HasVAListArg, format_idx, firstDataArg,
5412                                    Type, CallType, InFunctionCall,
5413                                    CheckedVarArgs, UncoveredArg, Offset);
5414       if (Left == SLCT_NotALiteral || !CheckRight) {
5415         return Left;
5416       }
5417     }
5418 
5419     StringLiteralCheckType Right =
5420         checkFormatStringExpr(S, C->getFalseExpr(), Args,
5421                               HasVAListArg, format_idx, firstDataArg,
5422                               Type, CallType, InFunctionCall, CheckedVarArgs,
5423                               UncoveredArg, Offset);
5424 
5425     return (CheckLeft && Left < Right) ? Left : Right;
5426   }
5427 
5428   case Stmt::ImplicitCastExprClass:
5429     E = cast<ImplicitCastExpr>(E)->getSubExpr();
5430     goto tryAgain;
5431 
5432   case Stmt::OpaqueValueExprClass:
5433     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
5434       E = src;
5435       goto tryAgain;
5436     }
5437     return SLCT_NotALiteral;
5438 
5439   case Stmt::PredefinedExprClass:
5440     // While __func__, etc., are technically not string literals, they
5441     // cannot contain format specifiers and thus are not a security
5442     // liability.
5443     return SLCT_UncheckedLiteral;
5444 
5445   case Stmt::DeclRefExprClass: {
5446     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
5447 
5448     // As an exception, do not flag errors for variables binding to
5449     // const string literals.
5450     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
5451       bool isConstant = false;
5452       QualType T = DR->getType();
5453 
5454       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
5455         isConstant = AT->getElementType().isConstant(S.Context);
5456       } else if (const PointerType *PT = T->getAs<PointerType>()) {
5457         isConstant = T.isConstant(S.Context) &&
5458                      PT->getPointeeType().isConstant(S.Context);
5459       } else if (T->isObjCObjectPointerType()) {
5460         // In ObjC, there is usually no "const ObjectPointer" type,
5461         // so don't check if the pointee type is constant.
5462         isConstant = T.isConstant(S.Context);
5463       }
5464 
5465       if (isConstant) {
5466         if (const Expr *Init = VD->getAnyInitializer()) {
5467           // Look through initializers like const char c[] = { "foo" }
5468           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
5469             if (InitList->isStringLiteralInit())
5470               Init = InitList->getInit(0)->IgnoreParenImpCasts();
5471           }
5472           return checkFormatStringExpr(S, Init, Args,
5473                                        HasVAListArg, format_idx,
5474                                        firstDataArg, Type, CallType,
5475                                        /*InFunctionCall*/ false, CheckedVarArgs,
5476                                        UncoveredArg, Offset);
5477         }
5478       }
5479 
5480       // For vprintf* functions (i.e., HasVAListArg==true), we add a
5481       // special check to see if the format string is a function parameter
5482       // of the function calling the printf function.  If the function
5483       // has an attribute indicating it is a printf-like function, then we
5484       // should suppress warnings concerning non-literals being used in a call
5485       // to a vprintf function.  For example:
5486       //
5487       // void
5488       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
5489       //      va_list ap;
5490       //      va_start(ap, fmt);
5491       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
5492       //      ...
5493       // }
5494       if (HasVAListArg) {
5495         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
5496           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
5497             int PVIndex = PV->getFunctionScopeIndex() + 1;
5498             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
5499               // adjust for implicit parameter
5500               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5501                 if (MD->isInstance())
5502                   ++PVIndex;
5503               // We also check if the formats are compatible.
5504               // We can't pass a 'scanf' string to a 'printf' function.
5505               if (PVIndex == PVFormat->getFormatIdx() &&
5506                   Type == S.GetFormatStringType(PVFormat))
5507                 return SLCT_UncheckedLiteral;
5508             }
5509           }
5510         }
5511       }
5512     }
5513 
5514     return SLCT_NotALiteral;
5515   }
5516 
5517   case Stmt::CallExprClass:
5518   case Stmt::CXXMemberCallExprClass: {
5519     const CallExpr *CE = cast<CallExpr>(E);
5520     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
5521       bool IsFirst = true;
5522       StringLiteralCheckType CommonResult;
5523       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
5524         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
5525         StringLiteralCheckType Result = checkFormatStringExpr(
5526             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
5527             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
5528         if (IsFirst) {
5529           CommonResult = Result;
5530           IsFirst = false;
5531         }
5532       }
5533       if (!IsFirst)
5534         return CommonResult;
5535 
5536       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
5537         unsigned BuiltinID = FD->getBuiltinID();
5538         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
5539             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
5540           const Expr *Arg = CE->getArg(0);
5541           return checkFormatStringExpr(S, Arg, Args,
5542                                        HasVAListArg, format_idx,
5543                                        firstDataArg, Type, CallType,
5544                                        InFunctionCall, CheckedVarArgs,
5545                                        UncoveredArg, Offset);
5546         }
5547       }
5548     }
5549 
5550     return SLCT_NotALiteral;
5551   }
5552   case Stmt::ObjCMessageExprClass: {
5553     const auto *ME = cast<ObjCMessageExpr>(E);
5554     if (const auto *ND = ME->getMethodDecl()) {
5555       if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
5556         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
5557         return checkFormatStringExpr(
5558             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
5559             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
5560       }
5561     }
5562 
5563     return SLCT_NotALiteral;
5564   }
5565   case Stmt::ObjCStringLiteralClass:
5566   case Stmt::StringLiteralClass: {
5567     const StringLiteral *StrE = nullptr;
5568 
5569     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
5570       StrE = ObjCFExpr->getString();
5571     else
5572       StrE = cast<StringLiteral>(E);
5573 
5574     if (StrE) {
5575       if (Offset.isNegative() || Offset > StrE->getLength()) {
5576         // TODO: It would be better to have an explicit warning for out of
5577         // bounds literals.
5578         return SLCT_NotALiteral;
5579       }
5580       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
5581       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
5582                         firstDataArg, Type, InFunctionCall, CallType,
5583                         CheckedVarArgs, UncoveredArg);
5584       return SLCT_CheckedLiteral;
5585     }
5586 
5587     return SLCT_NotALiteral;
5588   }
5589   case Stmt::BinaryOperatorClass: {
5590     llvm::APSInt LResult;
5591     llvm::APSInt RResult;
5592 
5593     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
5594 
5595     // A string literal + an int offset is still a string literal.
5596     if (BinOp->isAdditiveOp()) {
5597       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
5598       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
5599 
5600       if (LIsInt != RIsInt) {
5601         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
5602 
5603         if (LIsInt) {
5604           if (BinOpKind == BO_Add) {
5605             sumOffsets(Offset, LResult, BinOpKind, RIsInt);
5606             E = BinOp->getRHS();
5607             goto tryAgain;
5608           }
5609         } else {
5610           sumOffsets(Offset, RResult, BinOpKind, RIsInt);
5611           E = BinOp->getLHS();
5612           goto tryAgain;
5613         }
5614       }
5615     }
5616 
5617     return SLCT_NotALiteral;
5618   }
5619   case Stmt::UnaryOperatorClass: {
5620     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
5621     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
5622     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
5623       llvm::APSInt IndexResult;
5624       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
5625         sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
5626         E = ASE->getBase();
5627         goto tryAgain;
5628       }
5629     }
5630 
5631     return SLCT_NotALiteral;
5632   }
5633 
5634   default:
5635     return SLCT_NotALiteral;
5636   }
5637 }
5638 
5639 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
5640   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
5641       .Case("scanf", FST_Scanf)
5642       .Cases("printf", "printf0", FST_Printf)
5643       .Cases("NSString", "CFString", FST_NSString)
5644       .Case("strftime", FST_Strftime)
5645       .Case("strfmon", FST_Strfmon)
5646       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
5647       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
5648       .Case("os_trace", FST_OSLog)
5649       .Case("os_log", FST_OSLog)
5650       .Default(FST_Unknown);
5651 }
5652 
5653 /// CheckFormatArguments - Check calls to printf and scanf (and similar
5654 /// functions) for correct use of format strings.
5655 /// Returns true if a format string has been fully checked.
5656 bool Sema::CheckFormatArguments(const FormatAttr *Format,
5657                                 ArrayRef<const Expr *> Args,
5658                                 bool IsCXXMember,
5659                                 VariadicCallType CallType,
5660                                 SourceLocation Loc, SourceRange Range,
5661                                 llvm::SmallBitVector &CheckedVarArgs) {
5662   FormatStringInfo FSI;
5663   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
5664     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
5665                                 FSI.FirstDataArg, GetFormatStringType(Format),
5666                                 CallType, Loc, Range, CheckedVarArgs);
5667   return false;
5668 }
5669 
5670 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
5671                                 bool HasVAListArg, unsigned format_idx,
5672                                 unsigned firstDataArg, FormatStringType Type,
5673                                 VariadicCallType CallType,
5674                                 SourceLocation Loc, SourceRange Range,
5675                                 llvm::SmallBitVector &CheckedVarArgs) {
5676   // CHECK: printf/scanf-like function is called with no format string.
5677   if (format_idx >= Args.size()) {
5678     Diag(Loc, diag::warn_missing_format_string) << Range;
5679     return false;
5680   }
5681 
5682   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
5683 
5684   // CHECK: format string is not a string literal.
5685   //
5686   // Dynamically generated format strings are difficult to
5687   // automatically vet at compile time.  Requiring that format strings
5688   // are string literals: (1) permits the checking of format strings by
5689   // the compiler and thereby (2) can practically remove the source of
5690   // many format string exploits.
5691 
5692   // Format string can be either ObjC string (e.g. @"%d") or
5693   // C string (e.g. "%d")
5694   // ObjC string uses the same format specifiers as C string, so we can use
5695   // the same format string checking logic for both ObjC and C strings.
5696   UncoveredArgHandler UncoveredArg;
5697   StringLiteralCheckType CT =
5698       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
5699                             format_idx, firstDataArg, Type, CallType,
5700                             /*IsFunctionCall*/ true, CheckedVarArgs,
5701                             UncoveredArg,
5702                             /*no string offset*/ llvm::APSInt(64, false) = 0);
5703 
5704   // Generate a diagnostic where an uncovered argument is detected.
5705   if (UncoveredArg.hasUncoveredArg()) {
5706     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
5707     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
5708     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
5709   }
5710 
5711   if (CT != SLCT_NotALiteral)
5712     // Literal format string found, check done!
5713     return CT == SLCT_CheckedLiteral;
5714 
5715   // Strftime is particular as it always uses a single 'time' argument,
5716   // so it is safe to pass a non-literal string.
5717   if (Type == FST_Strftime)
5718     return false;
5719 
5720   // Do not emit diag when the string param is a macro expansion and the
5721   // format is either NSString or CFString. This is a hack to prevent
5722   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
5723   // which are usually used in place of NS and CF string literals.
5724   SourceLocation FormatLoc = Args[format_idx]->getLocStart();
5725   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
5726     return false;
5727 
5728   // If there are no arguments specified, warn with -Wformat-security, otherwise
5729   // warn only with -Wformat-nonliteral.
5730   if (Args.size() == firstDataArg) {
5731     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
5732       << OrigFormatExpr->getSourceRange();
5733     switch (Type) {
5734     default:
5735       break;
5736     case FST_Kprintf:
5737     case FST_FreeBSDKPrintf:
5738     case FST_Printf:
5739       Diag(FormatLoc, diag::note_format_security_fixit)
5740         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
5741       break;
5742     case FST_NSString:
5743       Diag(FormatLoc, diag::note_format_security_fixit)
5744         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
5745       break;
5746     }
5747   } else {
5748     Diag(FormatLoc, diag::warn_format_nonliteral)
5749       << OrigFormatExpr->getSourceRange();
5750   }
5751   return false;
5752 }
5753 
5754 namespace {
5755 
5756 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
5757 protected:
5758   Sema &S;
5759   const FormatStringLiteral *FExpr;
5760   const Expr *OrigFormatExpr;
5761   const Sema::FormatStringType FSType;
5762   const unsigned FirstDataArg;
5763   const unsigned NumDataArgs;
5764   const char *Beg; // Start of format string.
5765   const bool HasVAListArg;
5766   ArrayRef<const Expr *> Args;
5767   unsigned FormatIdx;
5768   llvm::SmallBitVector CoveredArgs;
5769   bool usesPositionalArgs = false;
5770   bool atFirstArg = true;
5771   bool inFunctionCall;
5772   Sema::VariadicCallType CallType;
5773   llvm::SmallBitVector &CheckedVarArgs;
5774   UncoveredArgHandler &UncoveredArg;
5775 
5776 public:
5777   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
5778                      const Expr *origFormatExpr,
5779                      const Sema::FormatStringType type, unsigned firstDataArg,
5780                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
5781                      ArrayRef<const Expr *> Args, unsigned formatIdx,
5782                      bool inFunctionCall, Sema::VariadicCallType callType,
5783                      llvm::SmallBitVector &CheckedVarArgs,
5784                      UncoveredArgHandler &UncoveredArg)
5785       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
5786         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
5787         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
5788         inFunctionCall(inFunctionCall), CallType(callType),
5789         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
5790     CoveredArgs.resize(numDataArgs);
5791     CoveredArgs.reset();
5792   }
5793 
5794   void DoneProcessing();
5795 
5796   void HandleIncompleteSpecifier(const char *startSpecifier,
5797                                  unsigned specifierLen) override;
5798 
5799   void HandleInvalidLengthModifier(
5800                            const analyze_format_string::FormatSpecifier &FS,
5801                            const analyze_format_string::ConversionSpecifier &CS,
5802                            const char *startSpecifier, unsigned specifierLen,
5803                            unsigned DiagID);
5804 
5805   void HandleNonStandardLengthModifier(
5806                     const analyze_format_string::FormatSpecifier &FS,
5807                     const char *startSpecifier, unsigned specifierLen);
5808 
5809   void HandleNonStandardConversionSpecifier(
5810                     const analyze_format_string::ConversionSpecifier &CS,
5811                     const char *startSpecifier, unsigned specifierLen);
5812 
5813   void HandlePosition(const char *startPos, unsigned posLen) override;
5814 
5815   void HandleInvalidPosition(const char *startSpecifier,
5816                              unsigned specifierLen,
5817                              analyze_format_string::PositionContext p) override;
5818 
5819   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
5820 
5821   void HandleNullChar(const char *nullCharacter) override;
5822 
5823   template <typename Range>
5824   static void
5825   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
5826                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
5827                        bool IsStringLocation, Range StringRange,
5828                        ArrayRef<FixItHint> Fixit = None);
5829 
5830 protected:
5831   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
5832                                         const char *startSpec,
5833                                         unsigned specifierLen,
5834                                         const char *csStart, unsigned csLen);
5835 
5836   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
5837                                          const char *startSpec,
5838                                          unsigned specifierLen);
5839 
5840   SourceRange getFormatStringRange();
5841   CharSourceRange getSpecifierRange(const char *startSpecifier,
5842                                     unsigned specifierLen);
5843   SourceLocation getLocationOfByte(const char *x);
5844 
5845   const Expr *getDataArg(unsigned i) const;
5846 
5847   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
5848                     const analyze_format_string::ConversionSpecifier &CS,
5849                     const char *startSpecifier, unsigned specifierLen,
5850                     unsigned argIndex);
5851 
5852   template <typename Range>
5853   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5854                             bool IsStringLocation, Range StringRange,
5855                             ArrayRef<FixItHint> Fixit = None);
5856 };
5857 
5858 } // namespace
5859 
5860 SourceRange CheckFormatHandler::getFormatStringRange() {
5861   return OrigFormatExpr->getSourceRange();
5862 }
5863 
5864 CharSourceRange CheckFormatHandler::
5865 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
5866   SourceLocation Start = getLocationOfByte(startSpecifier);
5867   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
5868 
5869   // Advance the end SourceLocation by one due to half-open ranges.
5870   End = End.getLocWithOffset(1);
5871 
5872   return CharSourceRange::getCharRange(Start, End);
5873 }
5874 
5875 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
5876   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
5877                                   S.getLangOpts(), S.Context.getTargetInfo());
5878 }
5879 
5880 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
5881                                                    unsigned specifierLen){
5882   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
5883                        getLocationOfByte(startSpecifier),
5884                        /*IsStringLocation*/true,
5885                        getSpecifierRange(startSpecifier, specifierLen));
5886 }
5887 
5888 void CheckFormatHandler::HandleInvalidLengthModifier(
5889     const analyze_format_string::FormatSpecifier &FS,
5890     const analyze_format_string::ConversionSpecifier &CS,
5891     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
5892   using namespace analyze_format_string;
5893 
5894   const LengthModifier &LM = FS.getLengthModifier();
5895   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5896 
5897   // See if we know how to fix this length modifier.
5898   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
5899   if (FixedLM) {
5900     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
5901                          getLocationOfByte(LM.getStart()),
5902                          /*IsStringLocation*/true,
5903                          getSpecifierRange(startSpecifier, specifierLen));
5904 
5905     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5906       << FixedLM->toString()
5907       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5908 
5909   } else {
5910     FixItHint Hint;
5911     if (DiagID == diag::warn_format_nonsensical_length)
5912       Hint = FixItHint::CreateRemoval(LMRange);
5913 
5914     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
5915                          getLocationOfByte(LM.getStart()),
5916                          /*IsStringLocation*/true,
5917                          getSpecifierRange(startSpecifier, specifierLen),
5918                          Hint);
5919   }
5920 }
5921 
5922 void CheckFormatHandler::HandleNonStandardLengthModifier(
5923     const analyze_format_string::FormatSpecifier &FS,
5924     const char *startSpecifier, unsigned specifierLen) {
5925   using namespace analyze_format_string;
5926 
5927   const LengthModifier &LM = FS.getLengthModifier();
5928   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5929 
5930   // See if we know how to fix this length modifier.
5931   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
5932   if (FixedLM) {
5933     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5934                            << LM.toString() << 0,
5935                          getLocationOfByte(LM.getStart()),
5936                          /*IsStringLocation*/true,
5937                          getSpecifierRange(startSpecifier, specifierLen));
5938 
5939     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5940       << FixedLM->toString()
5941       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5942 
5943   } else {
5944     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5945                            << LM.toString() << 0,
5946                          getLocationOfByte(LM.getStart()),
5947                          /*IsStringLocation*/true,
5948                          getSpecifierRange(startSpecifier, specifierLen));
5949   }
5950 }
5951 
5952 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5953     const analyze_format_string::ConversionSpecifier &CS,
5954     const char *startSpecifier, unsigned specifierLen) {
5955   using namespace analyze_format_string;
5956 
5957   // See if we know how to fix this conversion specifier.
5958   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
5959   if (FixedCS) {
5960     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5961                           << CS.toString() << /*conversion specifier*/1,
5962                          getLocationOfByte(CS.getStart()),
5963                          /*IsStringLocation*/true,
5964                          getSpecifierRange(startSpecifier, specifierLen));
5965 
5966     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5967     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5968       << FixedCS->toString()
5969       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5970   } else {
5971     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5972                           << CS.toString() << /*conversion specifier*/1,
5973                          getLocationOfByte(CS.getStart()),
5974                          /*IsStringLocation*/true,
5975                          getSpecifierRange(startSpecifier, specifierLen));
5976   }
5977 }
5978 
5979 void CheckFormatHandler::HandlePosition(const char *startPos,
5980                                         unsigned posLen) {
5981   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5982                                getLocationOfByte(startPos),
5983                                /*IsStringLocation*/true,
5984                                getSpecifierRange(startPos, posLen));
5985 }
5986 
5987 void
5988 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5989                                      analyze_format_string::PositionContext p) {
5990   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5991                          << (unsigned) p,
5992                        getLocationOfByte(startPos), /*IsStringLocation*/true,
5993                        getSpecifierRange(startPos, posLen));
5994 }
5995 
5996 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
5997                                             unsigned posLen) {
5998   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5999                                getLocationOfByte(startPos),
6000                                /*IsStringLocation*/true,
6001                                getSpecifierRange(startPos, posLen));
6002 }
6003 
6004 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
6005   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
6006     // The presence of a null character is likely an error.
6007     EmitFormatDiagnostic(
6008       S.PDiag(diag::warn_printf_format_string_contains_null_char),
6009       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
6010       getFormatStringRange());
6011   }
6012 }
6013 
6014 // Note that this may return NULL if there was an error parsing or building
6015 // one of the argument expressions.
6016 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
6017   return Args[FirstDataArg + i];
6018 }
6019 
6020 void CheckFormatHandler::DoneProcessing() {
6021   // Does the number of data arguments exceed the number of
6022   // format conversions in the format string?
6023   if (!HasVAListArg) {
6024       // Find any arguments that weren't covered.
6025     CoveredArgs.flip();
6026     signed notCoveredArg = CoveredArgs.find_first();
6027     if (notCoveredArg >= 0) {
6028       assert((unsigned)notCoveredArg < NumDataArgs);
6029       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
6030     } else {
6031       UncoveredArg.setAllCovered();
6032     }
6033   }
6034 }
6035 
6036 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
6037                                    const Expr *ArgExpr) {
6038   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
6039          "Invalid state");
6040 
6041   if (!ArgExpr)
6042     return;
6043 
6044   SourceLocation Loc = ArgExpr->getLocStart();
6045 
6046   if (S.getSourceManager().isInSystemMacro(Loc))
6047     return;
6048 
6049   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
6050   for (auto E : DiagnosticExprs)
6051     PDiag << E->getSourceRange();
6052 
6053   CheckFormatHandler::EmitFormatDiagnostic(
6054                                   S, IsFunctionCall, DiagnosticExprs[0],
6055                                   PDiag, Loc, /*IsStringLocation*/false,
6056                                   DiagnosticExprs[0]->getSourceRange());
6057 }
6058 
6059 bool
6060 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
6061                                                      SourceLocation Loc,
6062                                                      const char *startSpec,
6063                                                      unsigned specifierLen,
6064                                                      const char *csStart,
6065                                                      unsigned csLen) {
6066   bool keepGoing = true;
6067   if (argIndex < NumDataArgs) {
6068     // Consider the argument coverered, even though the specifier doesn't
6069     // make sense.
6070     CoveredArgs.set(argIndex);
6071   }
6072   else {
6073     // If argIndex exceeds the number of data arguments we
6074     // don't issue a warning because that is just a cascade of warnings (and
6075     // they may have intended '%%' anyway). We don't want to continue processing
6076     // the format string after this point, however, as we will like just get
6077     // gibberish when trying to match arguments.
6078     keepGoing = false;
6079   }
6080 
6081   StringRef Specifier(csStart, csLen);
6082 
6083   // If the specifier in non-printable, it could be the first byte of a UTF-8
6084   // sequence. In that case, print the UTF-8 code point. If not, print the byte
6085   // hex value.
6086   std::string CodePointStr;
6087   if (!llvm::sys::locale::isPrint(*csStart)) {
6088     llvm::UTF32 CodePoint;
6089     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
6090     const llvm::UTF8 *E =
6091         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
6092     llvm::ConversionResult Result =
6093         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
6094 
6095     if (Result != llvm::conversionOK) {
6096       unsigned char FirstChar = *csStart;
6097       CodePoint = (llvm::UTF32)FirstChar;
6098     }
6099 
6100     llvm::raw_string_ostream OS(CodePointStr);
6101     if (CodePoint < 256)
6102       OS << "\\x" << llvm::format("%02x", CodePoint);
6103     else if (CodePoint <= 0xFFFF)
6104       OS << "\\u" << llvm::format("%04x", CodePoint);
6105     else
6106       OS << "\\U" << llvm::format("%08x", CodePoint);
6107     OS.flush();
6108     Specifier = CodePointStr;
6109   }
6110 
6111   EmitFormatDiagnostic(
6112       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
6113       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
6114 
6115   return keepGoing;
6116 }
6117 
6118 void
6119 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
6120                                                       const char *startSpec,
6121                                                       unsigned specifierLen) {
6122   EmitFormatDiagnostic(
6123     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
6124     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
6125 }
6126 
6127 bool
6128 CheckFormatHandler::CheckNumArgs(
6129   const analyze_format_string::FormatSpecifier &FS,
6130   const analyze_format_string::ConversionSpecifier &CS,
6131   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
6132 
6133   if (argIndex >= NumDataArgs) {
6134     PartialDiagnostic PDiag = FS.usesPositionalArg()
6135       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
6136            << (argIndex+1) << NumDataArgs)
6137       : S.PDiag(diag::warn_printf_insufficient_data_args);
6138     EmitFormatDiagnostic(
6139       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
6140       getSpecifierRange(startSpecifier, specifierLen));
6141 
6142     // Since more arguments than conversion tokens are given, by extension
6143     // all arguments are covered, so mark this as so.
6144     UncoveredArg.setAllCovered();
6145     return false;
6146   }
6147   return true;
6148 }
6149 
6150 template<typename Range>
6151 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
6152                                               SourceLocation Loc,
6153                                               bool IsStringLocation,
6154                                               Range StringRange,
6155                                               ArrayRef<FixItHint> FixIt) {
6156   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
6157                        Loc, IsStringLocation, StringRange, FixIt);
6158 }
6159 
6160 /// If the format string is not within the function call, emit a note
6161 /// so that the function call and string are in diagnostic messages.
6162 ///
6163 /// \param InFunctionCall if true, the format string is within the function
6164 /// call and only one diagnostic message will be produced.  Otherwise, an
6165 /// extra note will be emitted pointing to location of the format string.
6166 ///
6167 /// \param ArgumentExpr the expression that is passed as the format string
6168 /// argument in the function call.  Used for getting locations when two
6169 /// diagnostics are emitted.
6170 ///
6171 /// \param PDiag the callee should already have provided any strings for the
6172 /// diagnostic message.  This function only adds locations and fixits
6173 /// to diagnostics.
6174 ///
6175 /// \param Loc primary location for diagnostic.  If two diagnostics are
6176 /// required, one will be at Loc and a new SourceLocation will be created for
6177 /// the other one.
6178 ///
6179 /// \param IsStringLocation if true, Loc points to the format string should be
6180 /// used for the note.  Otherwise, Loc points to the argument list and will
6181 /// be used with PDiag.
6182 ///
6183 /// \param StringRange some or all of the string to highlight.  This is
6184 /// templated so it can accept either a CharSourceRange or a SourceRange.
6185 ///
6186 /// \param FixIt optional fix it hint for the format string.
6187 template <typename Range>
6188 void CheckFormatHandler::EmitFormatDiagnostic(
6189     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
6190     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
6191     Range StringRange, ArrayRef<FixItHint> FixIt) {
6192   if (InFunctionCall) {
6193     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
6194     D << StringRange;
6195     D << FixIt;
6196   } else {
6197     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
6198       << ArgumentExpr->getSourceRange();
6199 
6200     const Sema::SemaDiagnosticBuilder &Note =
6201       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
6202              diag::note_format_string_defined);
6203 
6204     Note << StringRange;
6205     Note << FixIt;
6206   }
6207 }
6208 
6209 //===--- CHECK: Printf format string checking ------------------------------===//
6210 
6211 namespace {
6212 
6213 class CheckPrintfHandler : public CheckFormatHandler {
6214 public:
6215   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
6216                      const Expr *origFormatExpr,
6217                      const Sema::FormatStringType type, unsigned firstDataArg,
6218                      unsigned numDataArgs, bool isObjC, const char *beg,
6219                      bool hasVAListArg, ArrayRef<const Expr *> Args,
6220                      unsigned formatIdx, bool inFunctionCall,
6221                      Sema::VariadicCallType CallType,
6222                      llvm::SmallBitVector &CheckedVarArgs,
6223                      UncoveredArgHandler &UncoveredArg)
6224       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6225                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
6226                            inFunctionCall, CallType, CheckedVarArgs,
6227                            UncoveredArg) {}
6228 
6229   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
6230 
6231   /// Returns true if '%@' specifiers are allowed in the format string.
6232   bool allowsObjCArg() const {
6233     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
6234            FSType == Sema::FST_OSTrace;
6235   }
6236 
6237   bool HandleInvalidPrintfConversionSpecifier(
6238                                       const analyze_printf::PrintfSpecifier &FS,
6239                                       const char *startSpecifier,
6240                                       unsigned specifierLen) override;
6241 
6242   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
6243                              const char *startSpecifier,
6244                              unsigned specifierLen) override;
6245   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6246                        const char *StartSpecifier,
6247                        unsigned SpecifierLen,
6248                        const Expr *E);
6249 
6250   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
6251                     const char *startSpecifier, unsigned specifierLen);
6252   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
6253                            const analyze_printf::OptionalAmount &Amt,
6254                            unsigned type,
6255                            const char *startSpecifier, unsigned specifierLen);
6256   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
6257                   const analyze_printf::OptionalFlag &flag,
6258                   const char *startSpecifier, unsigned specifierLen);
6259   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
6260                          const analyze_printf::OptionalFlag &ignoredFlag,
6261                          const analyze_printf::OptionalFlag &flag,
6262                          const char *startSpecifier, unsigned specifierLen);
6263   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
6264                            const Expr *E);
6265 
6266   void HandleEmptyObjCModifierFlag(const char *startFlag,
6267                                    unsigned flagLen) override;
6268 
6269   void HandleInvalidObjCModifierFlag(const char *startFlag,
6270                                             unsigned flagLen) override;
6271 
6272   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
6273                                            const char *flagsEnd,
6274                                            const char *conversionPosition)
6275                                              override;
6276 };
6277 
6278 } // namespace
6279 
6280 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
6281                                       const analyze_printf::PrintfSpecifier &FS,
6282                                       const char *startSpecifier,
6283                                       unsigned specifierLen) {
6284   const analyze_printf::PrintfConversionSpecifier &CS =
6285     FS.getConversionSpecifier();
6286 
6287   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6288                                           getLocationOfByte(CS.getStart()),
6289                                           startSpecifier, specifierLen,
6290                                           CS.getStart(), CS.getLength());
6291 }
6292 
6293 bool CheckPrintfHandler::HandleAmount(
6294                                const analyze_format_string::OptionalAmount &Amt,
6295                                unsigned k, const char *startSpecifier,
6296                                unsigned specifierLen) {
6297   if (Amt.hasDataArgument()) {
6298     if (!HasVAListArg) {
6299       unsigned argIndex = Amt.getArgIndex();
6300       if (argIndex >= NumDataArgs) {
6301         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
6302                                << k,
6303                              getLocationOfByte(Amt.getStart()),
6304                              /*IsStringLocation*/true,
6305                              getSpecifierRange(startSpecifier, specifierLen));
6306         // Don't do any more checking.  We will just emit
6307         // spurious errors.
6308         return false;
6309       }
6310 
6311       // Type check the data argument.  It should be an 'int'.
6312       // Although not in conformance with C99, we also allow the argument to be
6313       // an 'unsigned int' as that is a reasonably safe case.  GCC also
6314       // doesn't emit a warning for that case.
6315       CoveredArgs.set(argIndex);
6316       const Expr *Arg = getDataArg(argIndex);
6317       if (!Arg)
6318         return false;
6319 
6320       QualType T = Arg->getType();
6321 
6322       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
6323       assert(AT.isValid());
6324 
6325       if (!AT.matchesType(S.Context, T)) {
6326         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
6327                                << k << AT.getRepresentativeTypeName(S.Context)
6328                                << T << Arg->getSourceRange(),
6329                              getLocationOfByte(Amt.getStart()),
6330                              /*IsStringLocation*/true,
6331                              getSpecifierRange(startSpecifier, specifierLen));
6332         // Don't do any more checking.  We will just emit
6333         // spurious errors.
6334         return false;
6335       }
6336     }
6337   }
6338   return true;
6339 }
6340 
6341 void CheckPrintfHandler::HandleInvalidAmount(
6342                                       const analyze_printf::PrintfSpecifier &FS,
6343                                       const analyze_printf::OptionalAmount &Amt,
6344                                       unsigned type,
6345                                       const char *startSpecifier,
6346                                       unsigned specifierLen) {
6347   const analyze_printf::PrintfConversionSpecifier &CS =
6348     FS.getConversionSpecifier();
6349 
6350   FixItHint fixit =
6351     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
6352       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
6353                                  Amt.getConstantLength()))
6354       : FixItHint();
6355 
6356   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
6357                          << type << CS.toString(),
6358                        getLocationOfByte(Amt.getStart()),
6359                        /*IsStringLocation*/true,
6360                        getSpecifierRange(startSpecifier, specifierLen),
6361                        fixit);
6362 }
6363 
6364 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
6365                                     const analyze_printf::OptionalFlag &flag,
6366                                     const char *startSpecifier,
6367                                     unsigned specifierLen) {
6368   // Warn about pointless flag with a fixit removal.
6369   const analyze_printf::PrintfConversionSpecifier &CS =
6370     FS.getConversionSpecifier();
6371   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
6372                          << flag.toString() << CS.toString(),
6373                        getLocationOfByte(flag.getPosition()),
6374                        /*IsStringLocation*/true,
6375                        getSpecifierRange(startSpecifier, specifierLen),
6376                        FixItHint::CreateRemoval(
6377                          getSpecifierRange(flag.getPosition(), 1)));
6378 }
6379 
6380 void CheckPrintfHandler::HandleIgnoredFlag(
6381                                 const analyze_printf::PrintfSpecifier &FS,
6382                                 const analyze_printf::OptionalFlag &ignoredFlag,
6383                                 const analyze_printf::OptionalFlag &flag,
6384                                 const char *startSpecifier,
6385                                 unsigned specifierLen) {
6386   // Warn about ignored flag with a fixit removal.
6387   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
6388                          << ignoredFlag.toString() << flag.toString(),
6389                        getLocationOfByte(ignoredFlag.getPosition()),
6390                        /*IsStringLocation*/true,
6391                        getSpecifierRange(startSpecifier, specifierLen),
6392                        FixItHint::CreateRemoval(
6393                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
6394 }
6395 
6396 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
6397                                                      unsigned flagLen) {
6398   // Warn about an empty flag.
6399   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
6400                        getLocationOfByte(startFlag),
6401                        /*IsStringLocation*/true,
6402                        getSpecifierRange(startFlag, flagLen));
6403 }
6404 
6405 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
6406                                                        unsigned flagLen) {
6407   // Warn about an invalid flag.
6408   auto Range = getSpecifierRange(startFlag, flagLen);
6409   StringRef flag(startFlag, flagLen);
6410   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
6411                       getLocationOfByte(startFlag),
6412                       /*IsStringLocation*/true,
6413                       Range, FixItHint::CreateRemoval(Range));
6414 }
6415 
6416 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
6417     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
6418     // Warn about using '[...]' without a '@' conversion.
6419     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
6420     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
6421     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
6422                          getLocationOfByte(conversionPosition),
6423                          /*IsStringLocation*/true,
6424                          Range, FixItHint::CreateRemoval(Range));
6425 }
6426 
6427 // Determines if the specified is a C++ class or struct containing
6428 // a member with the specified name and kind (e.g. a CXXMethodDecl named
6429 // "c_str()").
6430 template<typename MemberKind>
6431 static llvm::SmallPtrSet<MemberKind*, 1>
6432 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
6433   const RecordType *RT = Ty->getAs<RecordType>();
6434   llvm::SmallPtrSet<MemberKind*, 1> Results;
6435 
6436   if (!RT)
6437     return Results;
6438   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
6439   if (!RD || !RD->getDefinition())
6440     return Results;
6441 
6442   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
6443                  Sema::LookupMemberName);
6444   R.suppressDiagnostics();
6445 
6446   // We just need to include all members of the right kind turned up by the
6447   // filter, at this point.
6448   if (S.LookupQualifiedName(R, RT->getDecl()))
6449     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6450       NamedDecl *decl = (*I)->getUnderlyingDecl();
6451       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
6452         Results.insert(FK);
6453     }
6454   return Results;
6455 }
6456 
6457 /// Check if we could call '.c_str()' on an object.
6458 ///
6459 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
6460 /// allow the call, or if it would be ambiguous).
6461 bool Sema::hasCStrMethod(const Expr *E) {
6462   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
6463 
6464   MethodSet Results =
6465       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
6466   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
6467        MI != ME; ++MI)
6468     if ((*MI)->getMinRequiredArguments() == 0)
6469       return true;
6470   return false;
6471 }
6472 
6473 // Check if a (w)string was passed when a (w)char* was needed, and offer a
6474 // better diagnostic if so. AT is assumed to be valid.
6475 // Returns true when a c_str() conversion method is found.
6476 bool CheckPrintfHandler::checkForCStrMembers(
6477     const analyze_printf::ArgType &AT, const Expr *E) {
6478   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
6479 
6480   MethodSet Results =
6481       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
6482 
6483   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
6484        MI != ME; ++MI) {
6485     const CXXMethodDecl *Method = *MI;
6486     if (Method->getMinRequiredArguments() == 0 &&
6487         AT.matchesType(S.Context, Method->getReturnType())) {
6488       // FIXME: Suggest parens if the expression needs them.
6489       SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
6490       S.Diag(E->getLocStart(), diag::note_printf_c_str)
6491           << "c_str()"
6492           << FixItHint::CreateInsertion(EndLoc, ".c_str()");
6493       return true;
6494     }
6495   }
6496 
6497   return false;
6498 }
6499 
6500 bool
6501 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
6502                                             &FS,
6503                                           const char *startSpecifier,
6504                                           unsigned specifierLen) {
6505   using namespace analyze_format_string;
6506   using namespace analyze_printf;
6507 
6508   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
6509 
6510   if (FS.consumesDataArgument()) {
6511     if (atFirstArg) {
6512         atFirstArg = false;
6513         usesPositionalArgs = FS.usesPositionalArg();
6514     }
6515     else if (usesPositionalArgs != FS.usesPositionalArg()) {
6516       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6517                                         startSpecifier, specifierLen);
6518       return false;
6519     }
6520   }
6521 
6522   // First check if the field width, precision, and conversion specifier
6523   // have matching data arguments.
6524   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
6525                     startSpecifier, specifierLen)) {
6526     return false;
6527   }
6528 
6529   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
6530                     startSpecifier, specifierLen)) {
6531     return false;
6532   }
6533 
6534   if (!CS.consumesDataArgument()) {
6535     // FIXME: Technically specifying a precision or field width here
6536     // makes no sense.  Worth issuing a warning at some point.
6537     return true;
6538   }
6539 
6540   // Consume the argument.
6541   unsigned argIndex = FS.getArgIndex();
6542   if (argIndex < NumDataArgs) {
6543     // The check to see if the argIndex is valid will come later.
6544     // We set the bit here because we may exit early from this
6545     // function if we encounter some other error.
6546     CoveredArgs.set(argIndex);
6547   }
6548 
6549   // FreeBSD kernel extensions.
6550   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
6551       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
6552     // We need at least two arguments.
6553     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
6554       return false;
6555 
6556     // Claim the second argument.
6557     CoveredArgs.set(argIndex + 1);
6558 
6559     // Type check the first argument (int for %b, pointer for %D)
6560     const Expr *Ex = getDataArg(argIndex);
6561     const analyze_printf::ArgType &AT =
6562       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
6563         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
6564     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
6565       EmitFormatDiagnostic(
6566         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6567         << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
6568         << false << Ex->getSourceRange(),
6569         Ex->getLocStart(), /*IsStringLocation*/false,
6570         getSpecifierRange(startSpecifier, specifierLen));
6571 
6572     // Type check the second argument (char * for both %b and %D)
6573     Ex = getDataArg(argIndex + 1);
6574     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
6575     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
6576       EmitFormatDiagnostic(
6577         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6578         << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
6579         << false << Ex->getSourceRange(),
6580         Ex->getLocStart(), /*IsStringLocation*/false,
6581         getSpecifierRange(startSpecifier, specifierLen));
6582 
6583      return true;
6584   }
6585 
6586   // Check for using an Objective-C specific conversion specifier
6587   // in a non-ObjC literal.
6588   if (!allowsObjCArg() && CS.isObjCArg()) {
6589     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6590                                                   specifierLen);
6591   }
6592 
6593   // %P can only be used with os_log.
6594   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
6595     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6596                                                   specifierLen);
6597   }
6598 
6599   // %n is not allowed with os_log.
6600   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
6601     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
6602                          getLocationOfByte(CS.getStart()),
6603                          /*IsStringLocation*/ false,
6604                          getSpecifierRange(startSpecifier, specifierLen));
6605 
6606     return true;
6607   }
6608 
6609   // Only scalars are allowed for os_trace.
6610   if (FSType == Sema::FST_OSTrace &&
6611       (CS.getKind() == ConversionSpecifier::PArg ||
6612        CS.getKind() == ConversionSpecifier::sArg ||
6613        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
6614     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6615                                                   specifierLen);
6616   }
6617 
6618   // Check for use of public/private annotation outside of os_log().
6619   if (FSType != Sema::FST_OSLog) {
6620     if (FS.isPublic().isSet()) {
6621       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6622                                << "public",
6623                            getLocationOfByte(FS.isPublic().getPosition()),
6624                            /*IsStringLocation*/ false,
6625                            getSpecifierRange(startSpecifier, specifierLen));
6626     }
6627     if (FS.isPrivate().isSet()) {
6628       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6629                                << "private",
6630                            getLocationOfByte(FS.isPrivate().getPosition()),
6631                            /*IsStringLocation*/ false,
6632                            getSpecifierRange(startSpecifier, specifierLen));
6633     }
6634   }
6635 
6636   // Check for invalid use of field width
6637   if (!FS.hasValidFieldWidth()) {
6638     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
6639         startSpecifier, specifierLen);
6640   }
6641 
6642   // Check for invalid use of precision
6643   if (!FS.hasValidPrecision()) {
6644     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
6645         startSpecifier, specifierLen);
6646   }
6647 
6648   // Precision is mandatory for %P specifier.
6649   if (CS.getKind() == ConversionSpecifier::PArg &&
6650       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
6651     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
6652                          getLocationOfByte(startSpecifier),
6653                          /*IsStringLocation*/ false,
6654                          getSpecifierRange(startSpecifier, specifierLen));
6655   }
6656 
6657   // Check each flag does not conflict with any other component.
6658   if (!FS.hasValidThousandsGroupingPrefix())
6659     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
6660   if (!FS.hasValidLeadingZeros())
6661     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
6662   if (!FS.hasValidPlusPrefix())
6663     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
6664   if (!FS.hasValidSpacePrefix())
6665     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
6666   if (!FS.hasValidAlternativeForm())
6667     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
6668   if (!FS.hasValidLeftJustified())
6669     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
6670 
6671   // Check that flags are not ignored by another flag
6672   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
6673     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
6674         startSpecifier, specifierLen);
6675   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
6676     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
6677             startSpecifier, specifierLen);
6678 
6679   // Check the length modifier is valid with the given conversion specifier.
6680   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
6681     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6682                                 diag::warn_format_nonsensical_length);
6683   else if (!FS.hasStandardLengthModifier())
6684     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
6685   else if (!FS.hasStandardLengthConversionCombination())
6686     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6687                                 diag::warn_format_non_standard_conversion_spec);
6688 
6689   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6690     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6691 
6692   // The remaining checks depend on the data arguments.
6693   if (HasVAListArg)
6694     return true;
6695 
6696   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
6697     return false;
6698 
6699   const Expr *Arg = getDataArg(argIndex);
6700   if (!Arg)
6701     return true;
6702 
6703   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
6704 }
6705 
6706 static bool requiresParensToAddCast(const Expr *E) {
6707   // FIXME: We should have a general way to reason about operator
6708   // precedence and whether parens are actually needed here.
6709   // Take care of a few common cases where they aren't.
6710   const Expr *Inside = E->IgnoreImpCasts();
6711   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
6712     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
6713 
6714   switch (Inside->getStmtClass()) {
6715   case Stmt::ArraySubscriptExprClass:
6716   case Stmt::CallExprClass:
6717   case Stmt::CharacterLiteralClass:
6718   case Stmt::CXXBoolLiteralExprClass:
6719   case Stmt::DeclRefExprClass:
6720   case Stmt::FloatingLiteralClass:
6721   case Stmt::IntegerLiteralClass:
6722   case Stmt::MemberExprClass:
6723   case Stmt::ObjCArrayLiteralClass:
6724   case Stmt::ObjCBoolLiteralExprClass:
6725   case Stmt::ObjCBoxedExprClass:
6726   case Stmt::ObjCDictionaryLiteralClass:
6727   case Stmt::ObjCEncodeExprClass:
6728   case Stmt::ObjCIvarRefExprClass:
6729   case Stmt::ObjCMessageExprClass:
6730   case Stmt::ObjCPropertyRefExprClass:
6731   case Stmt::ObjCStringLiteralClass:
6732   case Stmt::ObjCSubscriptRefExprClass:
6733   case Stmt::ParenExprClass:
6734   case Stmt::StringLiteralClass:
6735   case Stmt::UnaryOperatorClass:
6736     return false;
6737   default:
6738     return true;
6739   }
6740 }
6741 
6742 static std::pair<QualType, StringRef>
6743 shouldNotPrintDirectly(const ASTContext &Context,
6744                        QualType IntendedTy,
6745                        const Expr *E) {
6746   // Use a 'while' to peel off layers of typedefs.
6747   QualType TyTy = IntendedTy;
6748   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
6749     StringRef Name = UserTy->getDecl()->getName();
6750     QualType CastTy = llvm::StringSwitch<QualType>(Name)
6751       .Case("CFIndex", Context.getNSIntegerType())
6752       .Case("NSInteger", Context.getNSIntegerType())
6753       .Case("NSUInteger", Context.getNSUIntegerType())
6754       .Case("SInt32", Context.IntTy)
6755       .Case("UInt32", Context.UnsignedIntTy)
6756       .Default(QualType());
6757 
6758     if (!CastTy.isNull())
6759       return std::make_pair(CastTy, Name);
6760 
6761     TyTy = UserTy->desugar();
6762   }
6763 
6764   // Strip parens if necessary.
6765   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
6766     return shouldNotPrintDirectly(Context,
6767                                   PE->getSubExpr()->getType(),
6768                                   PE->getSubExpr());
6769 
6770   // If this is a conditional expression, then its result type is constructed
6771   // via usual arithmetic conversions and thus there might be no necessary
6772   // typedef sugar there.  Recurse to operands to check for NSInteger &
6773   // Co. usage condition.
6774   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6775     QualType TrueTy, FalseTy;
6776     StringRef TrueName, FalseName;
6777 
6778     std::tie(TrueTy, TrueName) =
6779       shouldNotPrintDirectly(Context,
6780                              CO->getTrueExpr()->getType(),
6781                              CO->getTrueExpr());
6782     std::tie(FalseTy, FalseName) =
6783       shouldNotPrintDirectly(Context,
6784                              CO->getFalseExpr()->getType(),
6785                              CO->getFalseExpr());
6786 
6787     if (TrueTy == FalseTy)
6788       return std::make_pair(TrueTy, TrueName);
6789     else if (TrueTy.isNull())
6790       return std::make_pair(FalseTy, FalseName);
6791     else if (FalseTy.isNull())
6792       return std::make_pair(TrueTy, TrueName);
6793   }
6794 
6795   return std::make_pair(QualType(), StringRef());
6796 }
6797 
6798 bool
6799 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6800                                     const char *StartSpecifier,
6801                                     unsigned SpecifierLen,
6802                                     const Expr *E) {
6803   using namespace analyze_format_string;
6804   using namespace analyze_printf;
6805 
6806   // Now type check the data expression that matches the
6807   // format specifier.
6808   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
6809   if (!AT.isValid())
6810     return true;
6811 
6812   QualType ExprTy = E->getType();
6813   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
6814     ExprTy = TET->getUnderlyingExpr()->getType();
6815   }
6816 
6817   const analyze_printf::ArgType::MatchKind Match =
6818       AT.matchesType(S.Context, ExprTy);
6819   bool Pedantic = Match == analyze_printf::ArgType::NoMatchPedantic;
6820   if (Match == analyze_printf::ArgType::Match)
6821     return true;
6822 
6823   // Look through argument promotions for our error message's reported type.
6824   // This includes the integral and floating promotions, but excludes array
6825   // and function pointer decay; seeing that an argument intended to be a
6826   // string has type 'char [6]' is probably more confusing than 'char *'.
6827   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6828     if (ICE->getCastKind() == CK_IntegralCast ||
6829         ICE->getCastKind() == CK_FloatingCast) {
6830       E = ICE->getSubExpr();
6831       ExprTy = E->getType();
6832 
6833       // Check if we didn't match because of an implicit cast from a 'char'
6834       // or 'short' to an 'int'.  This is done because printf is a varargs
6835       // function.
6836       if (ICE->getType() == S.Context.IntTy ||
6837           ICE->getType() == S.Context.UnsignedIntTy) {
6838         // All further checking is done on the subexpression.
6839         if (AT.matchesType(S.Context, ExprTy))
6840           return true;
6841       }
6842     }
6843   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
6844     // Special case for 'a', which has type 'int' in C.
6845     // Note, however, that we do /not/ want to treat multibyte constants like
6846     // 'MooV' as characters! This form is deprecated but still exists.
6847     if (ExprTy == S.Context.IntTy)
6848       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6849         ExprTy = S.Context.CharTy;
6850   }
6851 
6852   // Look through enums to their underlying type.
6853   bool IsEnum = false;
6854   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
6855     ExprTy = EnumTy->getDecl()->getIntegerType();
6856     IsEnum = true;
6857   }
6858 
6859   // %C in an Objective-C context prints a unichar, not a wchar_t.
6860   // If the argument is an integer of some kind, believe the %C and suggest
6861   // a cast instead of changing the conversion specifier.
6862   QualType IntendedTy = ExprTy;
6863   if (isObjCContext() &&
6864       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
6865     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6866         !ExprTy->isCharType()) {
6867       // 'unichar' is defined as a typedef of unsigned short, but we should
6868       // prefer using the typedef if it is visible.
6869       IntendedTy = S.Context.UnsignedShortTy;
6870 
6871       // While we are here, check if the value is an IntegerLiteral that happens
6872       // to be within the valid range.
6873       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
6874         const llvm::APInt &V = IL->getValue();
6875         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6876           return true;
6877       }
6878 
6879       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
6880                           Sema::LookupOrdinaryName);
6881       if (S.LookupName(Result, S.getCurScope())) {
6882         NamedDecl *ND = Result.getFoundDecl();
6883         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
6884           if (TD->getUnderlyingType() == IntendedTy)
6885             IntendedTy = S.Context.getTypedefType(TD);
6886       }
6887     }
6888   }
6889 
6890   // Special-case some of Darwin's platform-independence types by suggesting
6891   // casts to primitive types that are known to be large enough.
6892   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
6893   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
6894     QualType CastTy;
6895     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
6896     if (!CastTy.isNull()) {
6897       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
6898       // (long in ASTContext). Only complain to pedants.
6899       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
6900           (AT.isSizeT() || AT.isPtrdiffT()) &&
6901           AT.matchesType(S.Context, CastTy))
6902         Pedantic = true;
6903       IntendedTy = CastTy;
6904       ShouldNotPrintDirectly = true;
6905     }
6906   }
6907 
6908   // We may be able to offer a FixItHint if it is a supported type.
6909   PrintfSpecifier fixedFS = FS;
6910   bool Success =
6911       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
6912 
6913   if (Success) {
6914     // Get the fix string from the fixed format specifier
6915     SmallString<16> buf;
6916     llvm::raw_svector_ostream os(buf);
6917     fixedFS.toString(os);
6918 
6919     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6920 
6921     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
6922       unsigned Diag =
6923           Pedantic
6924               ? diag::warn_format_conversion_argument_type_mismatch_pedantic
6925               : diag::warn_format_conversion_argument_type_mismatch;
6926       // In this case, the specifier is wrong and should be changed to match
6927       // the argument.
6928       EmitFormatDiagnostic(S.PDiag(Diag)
6929                                << AT.getRepresentativeTypeName(S.Context)
6930                                << IntendedTy << IsEnum << E->getSourceRange(),
6931                            E->getLocStart(),
6932                            /*IsStringLocation*/ false, SpecRange,
6933                            FixItHint::CreateReplacement(SpecRange, os.str()));
6934     } else {
6935       // The canonical type for formatting this value is different from the
6936       // actual type of the expression. (This occurs, for example, with Darwin's
6937       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6938       // should be printed as 'long' for 64-bit compatibility.)
6939       // Rather than emitting a normal format/argument mismatch, we want to
6940       // add a cast to the recommended type (and correct the format string
6941       // if necessary).
6942       SmallString<16> CastBuf;
6943       llvm::raw_svector_ostream CastFix(CastBuf);
6944       CastFix << "(";
6945       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6946       CastFix << ")";
6947 
6948       SmallVector<FixItHint,4> Hints;
6949       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
6950         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6951 
6952       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6953         // If there's already a cast present, just replace it.
6954         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6955         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6956 
6957       } else if (!requiresParensToAddCast(E)) {
6958         // If the expression has high enough precedence,
6959         // just write the C-style cast.
6960         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6961                                                    CastFix.str()));
6962       } else {
6963         // Otherwise, add parens around the expression as well as the cast.
6964         CastFix << "(";
6965         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6966                                                    CastFix.str()));
6967 
6968         SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
6969         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6970       }
6971 
6972       if (ShouldNotPrintDirectly) {
6973         // The expression has a type that should not be printed directly.
6974         // We extract the name from the typedef because we don't want to show
6975         // the underlying type in the diagnostic.
6976         StringRef Name;
6977         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6978           Name = TypedefTy->getDecl()->getName();
6979         else
6980           Name = CastTyName;
6981         unsigned Diag = Pedantic
6982                             ? diag::warn_format_argument_needs_cast_pedantic
6983                             : diag::warn_format_argument_needs_cast;
6984         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
6985                                            << E->getSourceRange(),
6986                              E->getLocStart(), /*IsStringLocation=*/false,
6987                              SpecRange, Hints);
6988       } else {
6989         // In this case, the expression could be printed using a different
6990         // specifier, but we've decided that the specifier is probably correct
6991         // and we should cast instead. Just use the normal warning message.
6992         EmitFormatDiagnostic(
6993           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6994             << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
6995             << E->getSourceRange(),
6996           E->getLocStart(), /*IsStringLocation*/false,
6997           SpecRange, Hints);
6998       }
6999     }
7000   } else {
7001     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
7002                                                    SpecifierLen);
7003     // Since the warning for passing non-POD types to variadic functions
7004     // was deferred until now, we emit a warning for non-POD
7005     // arguments here.
7006     switch (S.isValidVarArgType(ExprTy)) {
7007     case Sema::VAK_Valid:
7008     case Sema::VAK_ValidInCXX11: {
7009       unsigned Diag =
7010           Pedantic
7011               ? diag::warn_format_conversion_argument_type_mismatch_pedantic
7012               : diag::warn_format_conversion_argument_type_mismatch;
7013 
7014       EmitFormatDiagnostic(
7015           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
7016                         << IsEnum << CSR << E->getSourceRange(),
7017           E->getLocStart(), /*IsStringLocation*/ false, CSR);
7018       break;
7019     }
7020     case Sema::VAK_Undefined:
7021     case Sema::VAK_MSVCUndefined:
7022       EmitFormatDiagnostic(
7023         S.PDiag(diag::warn_non_pod_vararg_with_format_string)
7024           << S.getLangOpts().CPlusPlus11
7025           << ExprTy
7026           << CallType
7027           << AT.getRepresentativeTypeName(S.Context)
7028           << CSR
7029           << E->getSourceRange(),
7030         E->getLocStart(), /*IsStringLocation*/false, CSR);
7031       checkForCStrMembers(AT, E);
7032       break;
7033 
7034     case Sema::VAK_Invalid:
7035       if (ExprTy->isObjCObjectType())
7036         EmitFormatDiagnostic(
7037           S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
7038             << S.getLangOpts().CPlusPlus11
7039             << ExprTy
7040             << CallType
7041             << AT.getRepresentativeTypeName(S.Context)
7042             << CSR
7043             << E->getSourceRange(),
7044           E->getLocStart(), /*IsStringLocation*/false, CSR);
7045       else
7046         // FIXME: If this is an initializer list, suggest removing the braces
7047         // or inserting a cast to the target type.
7048         S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
7049           << isa<InitListExpr>(E) << ExprTy << CallType
7050           << AT.getRepresentativeTypeName(S.Context)
7051           << E->getSourceRange();
7052       break;
7053     }
7054 
7055     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
7056            "format string specifier index out of range");
7057     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
7058   }
7059 
7060   return true;
7061 }
7062 
7063 //===--- CHECK: Scanf format string checking ------------------------------===//
7064 
7065 namespace {
7066 
7067 class CheckScanfHandler : public CheckFormatHandler {
7068 public:
7069   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
7070                     const Expr *origFormatExpr, Sema::FormatStringType type,
7071                     unsigned firstDataArg, unsigned numDataArgs,
7072                     const char *beg, bool hasVAListArg,
7073                     ArrayRef<const Expr *> Args, unsigned formatIdx,
7074                     bool inFunctionCall, Sema::VariadicCallType CallType,
7075                     llvm::SmallBitVector &CheckedVarArgs,
7076                     UncoveredArgHandler &UncoveredArg)
7077       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7078                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
7079                            inFunctionCall, CallType, CheckedVarArgs,
7080                            UncoveredArg) {}
7081 
7082   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
7083                             const char *startSpecifier,
7084                             unsigned specifierLen) override;
7085 
7086   bool HandleInvalidScanfConversionSpecifier(
7087           const analyze_scanf::ScanfSpecifier &FS,
7088           const char *startSpecifier,
7089           unsigned specifierLen) override;
7090 
7091   void HandleIncompleteScanList(const char *start, const char *end) override;
7092 };
7093 
7094 } // namespace
7095 
7096 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
7097                                                  const char *end) {
7098   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
7099                        getLocationOfByte(end), /*IsStringLocation*/true,
7100                        getSpecifierRange(start, end - start));
7101 }
7102 
7103 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
7104                                         const analyze_scanf::ScanfSpecifier &FS,
7105                                         const char *startSpecifier,
7106                                         unsigned specifierLen) {
7107   const analyze_scanf::ScanfConversionSpecifier &CS =
7108     FS.getConversionSpecifier();
7109 
7110   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7111                                           getLocationOfByte(CS.getStart()),
7112                                           startSpecifier, specifierLen,
7113                                           CS.getStart(), CS.getLength());
7114 }
7115 
7116 bool CheckScanfHandler::HandleScanfSpecifier(
7117                                        const analyze_scanf::ScanfSpecifier &FS,
7118                                        const char *startSpecifier,
7119                                        unsigned specifierLen) {
7120   using namespace analyze_scanf;
7121   using namespace analyze_format_string;
7122 
7123   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
7124 
7125   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
7126   // be used to decide if we are using positional arguments consistently.
7127   if (FS.consumesDataArgument()) {
7128     if (atFirstArg) {
7129       atFirstArg = false;
7130       usesPositionalArgs = FS.usesPositionalArg();
7131     }
7132     else if (usesPositionalArgs != FS.usesPositionalArg()) {
7133       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7134                                         startSpecifier, specifierLen);
7135       return false;
7136     }
7137   }
7138 
7139   // Check if the field with is non-zero.
7140   const OptionalAmount &Amt = FS.getFieldWidth();
7141   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
7142     if (Amt.getConstantAmount() == 0) {
7143       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
7144                                                    Amt.getConstantLength());
7145       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
7146                            getLocationOfByte(Amt.getStart()),
7147                            /*IsStringLocation*/true, R,
7148                            FixItHint::CreateRemoval(R));
7149     }
7150   }
7151 
7152   if (!FS.consumesDataArgument()) {
7153     // FIXME: Technically specifying a precision or field width here
7154     // makes no sense.  Worth issuing a warning at some point.
7155     return true;
7156   }
7157 
7158   // Consume the argument.
7159   unsigned argIndex = FS.getArgIndex();
7160   if (argIndex < NumDataArgs) {
7161       // The check to see if the argIndex is valid will come later.
7162       // We set the bit here because we may exit early from this
7163       // function if we encounter some other error.
7164     CoveredArgs.set(argIndex);
7165   }
7166 
7167   // Check the length modifier is valid with the given conversion specifier.
7168   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
7169     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7170                                 diag::warn_format_nonsensical_length);
7171   else if (!FS.hasStandardLengthModifier())
7172     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
7173   else if (!FS.hasStandardLengthConversionCombination())
7174     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7175                                 diag::warn_format_non_standard_conversion_spec);
7176 
7177   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
7178     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
7179 
7180   // The remaining checks depend on the data arguments.
7181   if (HasVAListArg)
7182     return true;
7183 
7184   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
7185     return false;
7186 
7187   // Check that the argument type matches the format specifier.
7188   const Expr *Ex = getDataArg(argIndex);
7189   if (!Ex)
7190     return true;
7191 
7192   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
7193 
7194   if (!AT.isValid()) {
7195     return true;
7196   }
7197 
7198   analyze_format_string::ArgType::MatchKind Match =
7199       AT.matchesType(S.Context, Ex->getType());
7200   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
7201   if (Match == analyze_format_string::ArgType::Match)
7202     return true;
7203 
7204   ScanfSpecifier fixedFS = FS;
7205   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
7206                                  S.getLangOpts(), S.Context);
7207 
7208   unsigned Diag =
7209       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
7210                : diag::warn_format_conversion_argument_type_mismatch;
7211 
7212   if (Success) {
7213     // Get the fix string from the fixed format specifier.
7214     SmallString<128> buf;
7215     llvm::raw_svector_ostream os(buf);
7216     fixedFS.toString(os);
7217 
7218     EmitFormatDiagnostic(
7219         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
7220                       << Ex->getType() << false << Ex->getSourceRange(),
7221         Ex->getLocStart(),
7222         /*IsStringLocation*/ false,
7223         getSpecifierRange(startSpecifier, specifierLen),
7224         FixItHint::CreateReplacement(
7225             getSpecifierRange(startSpecifier, specifierLen), os.str()));
7226   } else {
7227     EmitFormatDiagnostic(S.PDiag(Diag)
7228                              << AT.getRepresentativeTypeName(S.Context)
7229                              << Ex->getType() << false << Ex->getSourceRange(),
7230                          Ex->getLocStart(),
7231                          /*IsStringLocation*/ false,
7232                          getSpecifierRange(startSpecifier, specifierLen));
7233   }
7234 
7235   return true;
7236 }
7237 
7238 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
7239                               const Expr *OrigFormatExpr,
7240                               ArrayRef<const Expr *> Args,
7241                               bool HasVAListArg, unsigned format_idx,
7242                               unsigned firstDataArg,
7243                               Sema::FormatStringType Type,
7244                               bool inFunctionCall,
7245                               Sema::VariadicCallType CallType,
7246                               llvm::SmallBitVector &CheckedVarArgs,
7247                               UncoveredArgHandler &UncoveredArg) {
7248   // CHECK: is the format string a wide literal?
7249   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
7250     CheckFormatHandler::EmitFormatDiagnostic(
7251       S, inFunctionCall, Args[format_idx],
7252       S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
7253       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
7254     return;
7255   }
7256 
7257   // Str - The format string.  NOTE: this is NOT null-terminated!
7258   StringRef StrRef = FExpr->getString();
7259   const char *Str = StrRef.data();
7260   // Account for cases where the string literal is truncated in a declaration.
7261   const ConstantArrayType *T =
7262     S.Context.getAsConstantArrayType(FExpr->getType());
7263   assert(T && "String literal not of constant array type!");
7264   size_t TypeSize = T->getSize().getZExtValue();
7265   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
7266   const unsigned numDataArgs = Args.size() - firstDataArg;
7267 
7268   // Emit a warning if the string literal is truncated and does not contain an
7269   // embedded null character.
7270   if (TypeSize <= StrRef.size() &&
7271       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
7272     CheckFormatHandler::EmitFormatDiagnostic(
7273         S, inFunctionCall, Args[format_idx],
7274         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
7275         FExpr->getLocStart(),
7276         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
7277     return;
7278   }
7279 
7280   // CHECK: empty format string?
7281   if (StrLen == 0 && numDataArgs > 0) {
7282     CheckFormatHandler::EmitFormatDiagnostic(
7283       S, inFunctionCall, Args[format_idx],
7284       S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
7285       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
7286     return;
7287   }
7288 
7289   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
7290       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
7291       Type == Sema::FST_OSTrace) {
7292     CheckPrintfHandler H(
7293         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
7294         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
7295         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
7296         CheckedVarArgs, UncoveredArg);
7297 
7298     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
7299                                                   S.getLangOpts(),
7300                                                   S.Context.getTargetInfo(),
7301                                             Type == Sema::FST_FreeBSDKPrintf))
7302       H.DoneProcessing();
7303   } else if (Type == Sema::FST_Scanf) {
7304     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
7305                         numDataArgs, Str, HasVAListArg, Args, format_idx,
7306                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
7307 
7308     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
7309                                                  S.getLangOpts(),
7310                                                  S.Context.getTargetInfo()))
7311       H.DoneProcessing();
7312   } // TODO: handle other formats
7313 }
7314 
7315 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
7316   // Str - The format string.  NOTE: this is NOT null-terminated!
7317   StringRef StrRef = FExpr->getString();
7318   const char *Str = StrRef.data();
7319   // Account for cases where the string literal is truncated in a declaration.
7320   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
7321   assert(T && "String literal not of constant array type!");
7322   size_t TypeSize = T->getSize().getZExtValue();
7323   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
7324   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
7325                                                          getLangOpts(),
7326                                                          Context.getTargetInfo());
7327 }
7328 
7329 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
7330 
7331 // Returns the related absolute value function that is larger, of 0 if one
7332 // does not exist.
7333 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
7334   switch (AbsFunction) {
7335   default:
7336     return 0;
7337 
7338   case Builtin::BI__builtin_abs:
7339     return Builtin::BI__builtin_labs;
7340   case Builtin::BI__builtin_labs:
7341     return Builtin::BI__builtin_llabs;
7342   case Builtin::BI__builtin_llabs:
7343     return 0;
7344 
7345   case Builtin::BI__builtin_fabsf:
7346     return Builtin::BI__builtin_fabs;
7347   case Builtin::BI__builtin_fabs:
7348     return Builtin::BI__builtin_fabsl;
7349   case Builtin::BI__builtin_fabsl:
7350     return 0;
7351 
7352   case Builtin::BI__builtin_cabsf:
7353     return Builtin::BI__builtin_cabs;
7354   case Builtin::BI__builtin_cabs:
7355     return Builtin::BI__builtin_cabsl;
7356   case Builtin::BI__builtin_cabsl:
7357     return 0;
7358 
7359   case Builtin::BIabs:
7360     return Builtin::BIlabs;
7361   case Builtin::BIlabs:
7362     return Builtin::BIllabs;
7363   case Builtin::BIllabs:
7364     return 0;
7365 
7366   case Builtin::BIfabsf:
7367     return Builtin::BIfabs;
7368   case Builtin::BIfabs:
7369     return Builtin::BIfabsl;
7370   case Builtin::BIfabsl:
7371     return 0;
7372 
7373   case Builtin::BIcabsf:
7374    return Builtin::BIcabs;
7375   case Builtin::BIcabs:
7376     return Builtin::BIcabsl;
7377   case Builtin::BIcabsl:
7378     return 0;
7379   }
7380 }
7381 
7382 // Returns the argument type of the absolute value function.
7383 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
7384                                              unsigned AbsType) {
7385   if (AbsType == 0)
7386     return QualType();
7387 
7388   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
7389   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
7390   if (Error != ASTContext::GE_None)
7391     return QualType();
7392 
7393   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
7394   if (!FT)
7395     return QualType();
7396 
7397   if (FT->getNumParams() != 1)
7398     return QualType();
7399 
7400   return FT->getParamType(0);
7401 }
7402 
7403 // Returns the best absolute value function, or zero, based on type and
7404 // current absolute value function.
7405 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
7406                                    unsigned AbsFunctionKind) {
7407   unsigned BestKind = 0;
7408   uint64_t ArgSize = Context.getTypeSize(ArgType);
7409   for (unsigned Kind = AbsFunctionKind; Kind != 0;
7410        Kind = getLargerAbsoluteValueFunction(Kind)) {
7411     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
7412     if (Context.getTypeSize(ParamType) >= ArgSize) {
7413       if (BestKind == 0)
7414         BestKind = Kind;
7415       else if (Context.hasSameType(ParamType, ArgType)) {
7416         BestKind = Kind;
7417         break;
7418       }
7419     }
7420   }
7421   return BestKind;
7422 }
7423 
7424 enum AbsoluteValueKind {
7425   AVK_Integer,
7426   AVK_Floating,
7427   AVK_Complex
7428 };
7429 
7430 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
7431   if (T->isIntegralOrEnumerationType())
7432     return AVK_Integer;
7433   if (T->isRealFloatingType())
7434     return AVK_Floating;
7435   if (T->isAnyComplexType())
7436     return AVK_Complex;
7437 
7438   llvm_unreachable("Type not integer, floating, or complex");
7439 }
7440 
7441 // Changes the absolute value function to a different type.  Preserves whether
7442 // the function is a builtin.
7443 static unsigned changeAbsFunction(unsigned AbsKind,
7444                                   AbsoluteValueKind ValueKind) {
7445   switch (ValueKind) {
7446   case AVK_Integer:
7447     switch (AbsKind) {
7448     default:
7449       return 0;
7450     case Builtin::BI__builtin_fabsf:
7451     case Builtin::BI__builtin_fabs:
7452     case Builtin::BI__builtin_fabsl:
7453     case Builtin::BI__builtin_cabsf:
7454     case Builtin::BI__builtin_cabs:
7455     case Builtin::BI__builtin_cabsl:
7456       return Builtin::BI__builtin_abs;
7457     case Builtin::BIfabsf:
7458     case Builtin::BIfabs:
7459     case Builtin::BIfabsl:
7460     case Builtin::BIcabsf:
7461     case Builtin::BIcabs:
7462     case Builtin::BIcabsl:
7463       return Builtin::BIabs;
7464     }
7465   case AVK_Floating:
7466     switch (AbsKind) {
7467     default:
7468       return 0;
7469     case Builtin::BI__builtin_abs:
7470     case Builtin::BI__builtin_labs:
7471     case Builtin::BI__builtin_llabs:
7472     case Builtin::BI__builtin_cabsf:
7473     case Builtin::BI__builtin_cabs:
7474     case Builtin::BI__builtin_cabsl:
7475       return Builtin::BI__builtin_fabsf;
7476     case Builtin::BIabs:
7477     case Builtin::BIlabs:
7478     case Builtin::BIllabs:
7479     case Builtin::BIcabsf:
7480     case Builtin::BIcabs:
7481     case Builtin::BIcabsl:
7482       return Builtin::BIfabsf;
7483     }
7484   case AVK_Complex:
7485     switch (AbsKind) {
7486     default:
7487       return 0;
7488     case Builtin::BI__builtin_abs:
7489     case Builtin::BI__builtin_labs:
7490     case Builtin::BI__builtin_llabs:
7491     case Builtin::BI__builtin_fabsf:
7492     case Builtin::BI__builtin_fabs:
7493     case Builtin::BI__builtin_fabsl:
7494       return Builtin::BI__builtin_cabsf;
7495     case Builtin::BIabs:
7496     case Builtin::BIlabs:
7497     case Builtin::BIllabs:
7498     case Builtin::BIfabsf:
7499     case Builtin::BIfabs:
7500     case Builtin::BIfabsl:
7501       return Builtin::BIcabsf;
7502     }
7503   }
7504   llvm_unreachable("Unable to convert function");
7505 }
7506 
7507 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
7508   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
7509   if (!FnInfo)
7510     return 0;
7511 
7512   switch (FDecl->getBuiltinID()) {
7513   default:
7514     return 0;
7515   case Builtin::BI__builtin_abs:
7516   case Builtin::BI__builtin_fabs:
7517   case Builtin::BI__builtin_fabsf:
7518   case Builtin::BI__builtin_fabsl:
7519   case Builtin::BI__builtin_labs:
7520   case Builtin::BI__builtin_llabs:
7521   case Builtin::BI__builtin_cabs:
7522   case Builtin::BI__builtin_cabsf:
7523   case Builtin::BI__builtin_cabsl:
7524   case Builtin::BIabs:
7525   case Builtin::BIlabs:
7526   case Builtin::BIllabs:
7527   case Builtin::BIfabs:
7528   case Builtin::BIfabsf:
7529   case Builtin::BIfabsl:
7530   case Builtin::BIcabs:
7531   case Builtin::BIcabsf:
7532   case Builtin::BIcabsl:
7533     return FDecl->getBuiltinID();
7534   }
7535   llvm_unreachable("Unknown Builtin type");
7536 }
7537 
7538 // If the replacement is valid, emit a note with replacement function.
7539 // Additionally, suggest including the proper header if not already included.
7540 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
7541                             unsigned AbsKind, QualType ArgType) {
7542   bool EmitHeaderHint = true;
7543   const char *HeaderName = nullptr;
7544   const char *FunctionName = nullptr;
7545   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
7546     FunctionName = "std::abs";
7547     if (ArgType->isIntegralOrEnumerationType()) {
7548       HeaderName = "cstdlib";
7549     } else if (ArgType->isRealFloatingType()) {
7550       HeaderName = "cmath";
7551     } else {
7552       llvm_unreachable("Invalid Type");
7553     }
7554 
7555     // Lookup all std::abs
7556     if (NamespaceDecl *Std = S.getStdNamespace()) {
7557       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
7558       R.suppressDiagnostics();
7559       S.LookupQualifiedName(R, Std);
7560 
7561       for (const auto *I : R) {
7562         const FunctionDecl *FDecl = nullptr;
7563         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
7564           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
7565         } else {
7566           FDecl = dyn_cast<FunctionDecl>(I);
7567         }
7568         if (!FDecl)
7569           continue;
7570 
7571         // Found std::abs(), check that they are the right ones.
7572         if (FDecl->getNumParams() != 1)
7573           continue;
7574 
7575         // Check that the parameter type can handle the argument.
7576         QualType ParamType = FDecl->getParamDecl(0)->getType();
7577         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
7578             S.Context.getTypeSize(ArgType) <=
7579                 S.Context.getTypeSize(ParamType)) {
7580           // Found a function, don't need the header hint.
7581           EmitHeaderHint = false;
7582           break;
7583         }
7584       }
7585     }
7586   } else {
7587     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
7588     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
7589 
7590     if (HeaderName) {
7591       DeclarationName DN(&S.Context.Idents.get(FunctionName));
7592       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
7593       R.suppressDiagnostics();
7594       S.LookupName(R, S.getCurScope());
7595 
7596       if (R.isSingleResult()) {
7597         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
7598         if (FD && FD->getBuiltinID() == AbsKind) {
7599           EmitHeaderHint = false;
7600         } else {
7601           return;
7602         }
7603       } else if (!R.empty()) {
7604         return;
7605       }
7606     }
7607   }
7608 
7609   S.Diag(Loc, diag::note_replace_abs_function)
7610       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
7611 
7612   if (!HeaderName)
7613     return;
7614 
7615   if (!EmitHeaderHint)
7616     return;
7617 
7618   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
7619                                                     << FunctionName;
7620 }
7621 
7622 template <std::size_t StrLen>
7623 static bool IsStdFunction(const FunctionDecl *FDecl,
7624                           const char (&Str)[StrLen]) {
7625   if (!FDecl)
7626     return false;
7627   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
7628     return false;
7629   if (!FDecl->isInStdNamespace())
7630     return false;
7631 
7632   return true;
7633 }
7634 
7635 // Warn when using the wrong abs() function.
7636 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
7637                                       const FunctionDecl *FDecl) {
7638   if (Call->getNumArgs() != 1)
7639     return;
7640 
7641   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
7642   bool IsStdAbs = IsStdFunction(FDecl, "abs");
7643   if (AbsKind == 0 && !IsStdAbs)
7644     return;
7645 
7646   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7647   QualType ParamType = Call->getArg(0)->getType();
7648 
7649   // Unsigned types cannot be negative.  Suggest removing the absolute value
7650   // function call.
7651   if (ArgType->isUnsignedIntegerType()) {
7652     const char *FunctionName =
7653         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
7654     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
7655     Diag(Call->getExprLoc(), diag::note_remove_abs)
7656         << FunctionName
7657         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
7658     return;
7659   }
7660 
7661   // Taking the absolute value of a pointer is very suspicious, they probably
7662   // wanted to index into an array, dereference a pointer, call a function, etc.
7663   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
7664     unsigned DiagType = 0;
7665     if (ArgType->isFunctionType())
7666       DiagType = 1;
7667     else if (ArgType->isArrayType())
7668       DiagType = 2;
7669 
7670     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
7671     return;
7672   }
7673 
7674   // std::abs has overloads which prevent most of the absolute value problems
7675   // from occurring.
7676   if (IsStdAbs)
7677     return;
7678 
7679   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
7680   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
7681 
7682   // The argument and parameter are the same kind.  Check if they are the right
7683   // size.
7684   if (ArgValueKind == ParamValueKind) {
7685     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
7686       return;
7687 
7688     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
7689     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
7690         << FDecl << ArgType << ParamType;
7691 
7692     if (NewAbsKind == 0)
7693       return;
7694 
7695     emitReplacement(*this, Call->getExprLoc(),
7696                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
7697     return;
7698   }
7699 
7700   // ArgValueKind != ParamValueKind
7701   // The wrong type of absolute value function was used.  Attempt to find the
7702   // proper one.
7703   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
7704   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
7705   if (NewAbsKind == 0)
7706     return;
7707 
7708   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
7709       << FDecl << ParamValueKind << ArgValueKind;
7710 
7711   emitReplacement(*this, Call->getExprLoc(),
7712                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
7713 }
7714 
7715 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
7716 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
7717                                 const FunctionDecl *FDecl) {
7718   if (!Call || !FDecl) return;
7719 
7720   // Ignore template specializations and macros.
7721   if (inTemplateInstantiation()) return;
7722   if (Call->getExprLoc().isMacroID()) return;
7723 
7724   // Only care about the one template argument, two function parameter std::max
7725   if (Call->getNumArgs() != 2) return;
7726   if (!IsStdFunction(FDecl, "max")) return;
7727   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
7728   if (!ArgList) return;
7729   if (ArgList->size() != 1) return;
7730 
7731   // Check that template type argument is unsigned integer.
7732   const auto& TA = ArgList->get(0);
7733   if (TA.getKind() != TemplateArgument::Type) return;
7734   QualType ArgType = TA.getAsType();
7735   if (!ArgType->isUnsignedIntegerType()) return;
7736 
7737   // See if either argument is a literal zero.
7738   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
7739     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
7740     if (!MTE) return false;
7741     const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
7742     if (!Num) return false;
7743     if (Num->getValue() != 0) return false;
7744     return true;
7745   };
7746 
7747   const Expr *FirstArg = Call->getArg(0);
7748   const Expr *SecondArg = Call->getArg(1);
7749   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
7750   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
7751 
7752   // Only warn when exactly one argument is zero.
7753   if (IsFirstArgZero == IsSecondArgZero) return;
7754 
7755   SourceRange FirstRange = FirstArg->getSourceRange();
7756   SourceRange SecondRange = SecondArg->getSourceRange();
7757 
7758   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
7759 
7760   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
7761       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
7762 
7763   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
7764   SourceRange RemovalRange;
7765   if (IsFirstArgZero) {
7766     RemovalRange = SourceRange(FirstRange.getBegin(),
7767                                SecondRange.getBegin().getLocWithOffset(-1));
7768   } else {
7769     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
7770                                SecondRange.getEnd());
7771   }
7772 
7773   Diag(Call->getExprLoc(), diag::note_remove_max_call)
7774         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
7775         << FixItHint::CreateRemoval(RemovalRange);
7776 }
7777 
7778 //===--- CHECK: Standard memory functions ---------------------------------===//
7779 
7780 /// Takes the expression passed to the size_t parameter of functions
7781 /// such as memcmp, strncat, etc and warns if it's a comparison.
7782 ///
7783 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
7784 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
7785                                            IdentifierInfo *FnName,
7786                                            SourceLocation FnLoc,
7787                                            SourceLocation RParenLoc) {
7788   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
7789   if (!Size)
7790     return false;
7791 
7792   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
7793   if (!Size->isComparisonOp() && !Size->isLogicalOp())
7794     return false;
7795 
7796   SourceRange SizeRange = Size->getSourceRange();
7797   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
7798       << SizeRange << FnName;
7799   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
7800       << FnName << FixItHint::CreateInsertion(
7801                        S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
7802       << FixItHint::CreateRemoval(RParenLoc);
7803   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
7804       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
7805       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
7806                                     ")");
7807 
7808   return true;
7809 }
7810 
7811 /// Determine whether the given type is or contains a dynamic class type
7812 /// (e.g., whether it has a vtable).
7813 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
7814                                                      bool &IsContained) {
7815   // Look through array types while ignoring qualifiers.
7816   const Type *Ty = T->getBaseElementTypeUnsafe();
7817   IsContained = false;
7818 
7819   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
7820   RD = RD ? RD->getDefinition() : nullptr;
7821   if (!RD || RD->isInvalidDecl())
7822     return nullptr;
7823 
7824   if (RD->isDynamicClass())
7825     return RD;
7826 
7827   // Check all the fields.  If any bases were dynamic, the class is dynamic.
7828   // It's impossible for a class to transitively contain itself by value, so
7829   // infinite recursion is impossible.
7830   for (auto *FD : RD->fields()) {
7831     bool SubContained;
7832     if (const CXXRecordDecl *ContainedRD =
7833             getContainedDynamicClass(FD->getType(), SubContained)) {
7834       IsContained = true;
7835       return ContainedRD;
7836     }
7837   }
7838 
7839   return nullptr;
7840 }
7841 
7842 /// If E is a sizeof expression, returns its argument expression,
7843 /// otherwise returns NULL.
7844 static const Expr *getSizeOfExprArg(const Expr *E) {
7845   if (const UnaryExprOrTypeTraitExpr *SizeOf =
7846       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7847     if (SizeOf->getKind() == UETT_SizeOf && !SizeOf->isArgumentType())
7848       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
7849 
7850   return nullptr;
7851 }
7852 
7853 /// If E is a sizeof expression, returns its argument type.
7854 static QualType getSizeOfArgType(const Expr *E) {
7855   if (const UnaryExprOrTypeTraitExpr *SizeOf =
7856       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7857     if (SizeOf->getKind() == UETT_SizeOf)
7858       return SizeOf->getTypeOfArgument();
7859 
7860   return QualType();
7861 }
7862 
7863 namespace {
7864 
7865 struct SearchNonTrivialToInitializeField
7866     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
7867   using Super =
7868       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
7869 
7870   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
7871 
7872   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
7873                      SourceLocation SL) {
7874     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
7875       asDerived().visitArray(PDIK, AT, SL);
7876       return;
7877     }
7878 
7879     Super::visitWithKind(PDIK, FT, SL);
7880   }
7881 
7882   void visitARCStrong(QualType FT, SourceLocation SL) {
7883     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
7884   }
7885   void visitARCWeak(QualType FT, SourceLocation SL) {
7886     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
7887   }
7888   void visitStruct(QualType FT, SourceLocation SL) {
7889     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
7890       visit(FD->getType(), FD->getLocation());
7891   }
7892   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
7893                   const ArrayType *AT, SourceLocation SL) {
7894     visit(getContext().getBaseElementType(AT), SL);
7895   }
7896   void visitTrivial(QualType FT, SourceLocation SL) {}
7897 
7898   static void diag(QualType RT, const Expr *E, Sema &S) {
7899     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
7900   }
7901 
7902   ASTContext &getContext() { return S.getASTContext(); }
7903 
7904   const Expr *E;
7905   Sema &S;
7906 };
7907 
7908 struct SearchNonTrivialToCopyField
7909     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
7910   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
7911 
7912   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
7913 
7914   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
7915                      SourceLocation SL) {
7916     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
7917       asDerived().visitArray(PCK, AT, SL);
7918       return;
7919     }
7920 
7921     Super::visitWithKind(PCK, FT, SL);
7922   }
7923 
7924   void visitARCStrong(QualType FT, SourceLocation SL) {
7925     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
7926   }
7927   void visitARCWeak(QualType FT, SourceLocation SL) {
7928     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
7929   }
7930   void visitStruct(QualType FT, SourceLocation SL) {
7931     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
7932       visit(FD->getType(), FD->getLocation());
7933   }
7934   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
7935                   SourceLocation SL) {
7936     visit(getContext().getBaseElementType(AT), SL);
7937   }
7938   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
7939                 SourceLocation SL) {}
7940   void visitTrivial(QualType FT, SourceLocation SL) {}
7941   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
7942 
7943   static void diag(QualType RT, const Expr *E, Sema &S) {
7944     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
7945   }
7946 
7947   ASTContext &getContext() { return S.getASTContext(); }
7948 
7949   const Expr *E;
7950   Sema &S;
7951 };
7952 
7953 }
7954 
7955 /// Check for dangerous or invalid arguments to memset().
7956 ///
7957 /// This issues warnings on known problematic, dangerous or unspecified
7958 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
7959 /// function calls.
7960 ///
7961 /// \param Call The call expression to diagnose.
7962 void Sema::CheckMemaccessArguments(const CallExpr *Call,
7963                                    unsigned BId,
7964                                    IdentifierInfo *FnName) {
7965   assert(BId != 0);
7966 
7967   // It is possible to have a non-standard definition of memset.  Validate
7968   // we have enough arguments, and if not, abort further checking.
7969   unsigned ExpectedNumArgs =
7970       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
7971   if (Call->getNumArgs() < ExpectedNumArgs)
7972     return;
7973 
7974   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
7975                       BId == Builtin::BIstrndup ? 1 : 2);
7976   unsigned LenArg =
7977       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
7978   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
7979 
7980   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
7981                                      Call->getLocStart(), Call->getRParenLoc()))
7982     return;
7983 
7984   // We have special checking when the length is a sizeof expression.
7985   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
7986   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
7987   llvm::FoldingSetNodeID SizeOfArgID;
7988 
7989   // Although widely used, 'bzero' is not a standard function. Be more strict
7990   // with the argument types before allowing diagnostics and only allow the
7991   // form bzero(ptr, sizeof(...)).
7992   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7993   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
7994     return;
7995 
7996   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7997     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
7998     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
7999 
8000     QualType DestTy = Dest->getType();
8001     QualType PointeeTy;
8002     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
8003       PointeeTy = DestPtrTy->getPointeeType();
8004 
8005       // Never warn about void type pointers. This can be used to suppress
8006       // false positives.
8007       if (PointeeTy->isVoidType())
8008         continue;
8009 
8010       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
8011       // actually comparing the expressions for equality. Because computing the
8012       // expression IDs can be expensive, we only do this if the diagnostic is
8013       // enabled.
8014       if (SizeOfArg &&
8015           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
8016                            SizeOfArg->getExprLoc())) {
8017         // We only compute IDs for expressions if the warning is enabled, and
8018         // cache the sizeof arg's ID.
8019         if (SizeOfArgID == llvm::FoldingSetNodeID())
8020           SizeOfArg->Profile(SizeOfArgID, Context, true);
8021         llvm::FoldingSetNodeID DestID;
8022         Dest->Profile(DestID, Context, true);
8023         if (DestID == SizeOfArgID) {
8024           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
8025           //       over sizeof(src) as well.
8026           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
8027           StringRef ReadableName = FnName->getName();
8028 
8029           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
8030             if (UnaryOp->getOpcode() == UO_AddrOf)
8031               ActionIdx = 1; // If its an address-of operator, just remove it.
8032           if (!PointeeTy->isIncompleteType() &&
8033               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
8034             ActionIdx = 2; // If the pointee's size is sizeof(char),
8035                            // suggest an explicit length.
8036 
8037           // If the function is defined as a builtin macro, do not show macro
8038           // expansion.
8039           SourceLocation SL = SizeOfArg->getExprLoc();
8040           SourceRange DSR = Dest->getSourceRange();
8041           SourceRange SSR = SizeOfArg->getSourceRange();
8042           SourceManager &SM = getSourceManager();
8043 
8044           if (SM.isMacroArgExpansion(SL)) {
8045             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
8046             SL = SM.getSpellingLoc(SL);
8047             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
8048                              SM.getSpellingLoc(DSR.getEnd()));
8049             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
8050                              SM.getSpellingLoc(SSR.getEnd()));
8051           }
8052 
8053           DiagRuntimeBehavior(SL, SizeOfArg,
8054                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
8055                                 << ReadableName
8056                                 << PointeeTy
8057                                 << DestTy
8058                                 << DSR
8059                                 << SSR);
8060           DiagRuntimeBehavior(SL, SizeOfArg,
8061                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
8062                                 << ActionIdx
8063                                 << SSR);
8064 
8065           break;
8066         }
8067       }
8068 
8069       // Also check for cases where the sizeof argument is the exact same
8070       // type as the memory argument, and where it points to a user-defined
8071       // record type.
8072       if (SizeOfArgTy != QualType()) {
8073         if (PointeeTy->isRecordType() &&
8074             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
8075           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
8076                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
8077                                 << FnName << SizeOfArgTy << ArgIdx
8078                                 << PointeeTy << Dest->getSourceRange()
8079                                 << LenExpr->getSourceRange());
8080           break;
8081         }
8082       }
8083     } else if (DestTy->isArrayType()) {
8084       PointeeTy = DestTy;
8085     }
8086 
8087     if (PointeeTy == QualType())
8088       continue;
8089 
8090     // Always complain about dynamic classes.
8091     bool IsContained;
8092     if (const CXXRecordDecl *ContainedRD =
8093             getContainedDynamicClass(PointeeTy, IsContained)) {
8094 
8095       unsigned OperationType = 0;
8096       // "overwritten" if we're warning about the destination for any call
8097       // but memcmp; otherwise a verb appropriate to the call.
8098       if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
8099         if (BId == Builtin::BImemcpy)
8100           OperationType = 1;
8101         else if(BId == Builtin::BImemmove)
8102           OperationType = 2;
8103         else if (BId == Builtin::BImemcmp)
8104           OperationType = 3;
8105       }
8106 
8107       DiagRuntimeBehavior(
8108         Dest->getExprLoc(), Dest,
8109         PDiag(diag::warn_dyn_class_memaccess)
8110           << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
8111           << FnName << IsContained << ContainedRD << OperationType
8112           << Call->getCallee()->getSourceRange());
8113     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
8114              BId != Builtin::BImemset)
8115       DiagRuntimeBehavior(
8116         Dest->getExprLoc(), Dest,
8117         PDiag(diag::warn_arc_object_memaccess)
8118           << ArgIdx << FnName << PointeeTy
8119           << Call->getCallee()->getSourceRange());
8120     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
8121       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
8122           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
8123         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
8124                             PDiag(diag::warn_cstruct_memaccess)
8125                                 << ArgIdx << FnName << PointeeTy << 0);
8126         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
8127       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
8128                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
8129         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
8130                             PDiag(diag::warn_cstruct_memaccess)
8131                                 << ArgIdx << FnName << PointeeTy << 1);
8132         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
8133       } else {
8134         continue;
8135       }
8136     } else
8137       continue;
8138 
8139     DiagRuntimeBehavior(
8140       Dest->getExprLoc(), Dest,
8141       PDiag(diag::note_bad_memaccess_silence)
8142         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
8143     break;
8144   }
8145 }
8146 
8147 // A little helper routine: ignore addition and subtraction of integer literals.
8148 // This intentionally does not ignore all integer constant expressions because
8149 // we don't want to remove sizeof().
8150 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
8151   Ex = Ex->IgnoreParenCasts();
8152 
8153   while (true) {
8154     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
8155     if (!BO || !BO->isAdditiveOp())
8156       break;
8157 
8158     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
8159     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
8160 
8161     if (isa<IntegerLiteral>(RHS))
8162       Ex = LHS;
8163     else if (isa<IntegerLiteral>(LHS))
8164       Ex = RHS;
8165     else
8166       break;
8167   }
8168 
8169   return Ex;
8170 }
8171 
8172 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
8173                                                       ASTContext &Context) {
8174   // Only handle constant-sized or VLAs, but not flexible members.
8175   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
8176     // Only issue the FIXIT for arrays of size > 1.
8177     if (CAT->getSize().getSExtValue() <= 1)
8178       return false;
8179   } else if (!Ty->isVariableArrayType()) {
8180     return false;
8181   }
8182   return true;
8183 }
8184 
8185 // Warn if the user has made the 'size' argument to strlcpy or strlcat
8186 // be the size of the source, instead of the destination.
8187 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
8188                                     IdentifierInfo *FnName) {
8189 
8190   // Don't crash if the user has the wrong number of arguments
8191   unsigned NumArgs = Call->getNumArgs();
8192   if ((NumArgs != 3) && (NumArgs != 4))
8193     return;
8194 
8195   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
8196   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
8197   const Expr *CompareWithSrc = nullptr;
8198 
8199   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
8200                                      Call->getLocStart(), Call->getRParenLoc()))
8201     return;
8202 
8203   // Look for 'strlcpy(dst, x, sizeof(x))'
8204   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
8205     CompareWithSrc = Ex;
8206   else {
8207     // Look for 'strlcpy(dst, x, strlen(x))'
8208     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
8209       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
8210           SizeCall->getNumArgs() == 1)
8211         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
8212     }
8213   }
8214 
8215   if (!CompareWithSrc)
8216     return;
8217 
8218   // Determine if the argument to sizeof/strlen is equal to the source
8219   // argument.  In principle there's all kinds of things you could do
8220   // here, for instance creating an == expression and evaluating it with
8221   // EvaluateAsBooleanCondition, but this uses a more direct technique:
8222   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
8223   if (!SrcArgDRE)
8224     return;
8225 
8226   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
8227   if (!CompareWithSrcDRE ||
8228       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
8229     return;
8230 
8231   const Expr *OriginalSizeArg = Call->getArg(2);
8232   Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
8233     << OriginalSizeArg->getSourceRange() << FnName;
8234 
8235   // Output a FIXIT hint if the destination is an array (rather than a
8236   // pointer to an array).  This could be enhanced to handle some
8237   // pointers if we know the actual size, like if DstArg is 'array+2'
8238   // we could say 'sizeof(array)-2'.
8239   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
8240   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
8241     return;
8242 
8243   SmallString<128> sizeString;
8244   llvm::raw_svector_ostream OS(sizeString);
8245   OS << "sizeof(";
8246   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
8247   OS << ")";
8248 
8249   Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
8250     << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
8251                                     OS.str());
8252 }
8253 
8254 /// Check if two expressions refer to the same declaration.
8255 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
8256   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
8257     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
8258       return D1->getDecl() == D2->getDecl();
8259   return false;
8260 }
8261 
8262 static const Expr *getStrlenExprArg(const Expr *E) {
8263   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8264     const FunctionDecl *FD = CE->getDirectCallee();
8265     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
8266       return nullptr;
8267     return CE->getArg(0)->IgnoreParenCasts();
8268   }
8269   return nullptr;
8270 }
8271 
8272 // Warn on anti-patterns as the 'size' argument to strncat.
8273 // The correct size argument should look like following:
8274 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
8275 void Sema::CheckStrncatArguments(const CallExpr *CE,
8276                                  IdentifierInfo *FnName) {
8277   // Don't crash if the user has the wrong number of arguments.
8278   if (CE->getNumArgs() < 3)
8279     return;
8280   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
8281   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
8282   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
8283 
8284   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
8285                                      CE->getRParenLoc()))
8286     return;
8287 
8288   // Identify common expressions, which are wrongly used as the size argument
8289   // to strncat and may lead to buffer overflows.
8290   unsigned PatternType = 0;
8291   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
8292     // - sizeof(dst)
8293     if (referToTheSameDecl(SizeOfArg, DstArg))
8294       PatternType = 1;
8295     // - sizeof(src)
8296     else if (referToTheSameDecl(SizeOfArg, SrcArg))
8297       PatternType = 2;
8298   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
8299     if (BE->getOpcode() == BO_Sub) {
8300       const Expr *L = BE->getLHS()->IgnoreParenCasts();
8301       const Expr *R = BE->getRHS()->IgnoreParenCasts();
8302       // - sizeof(dst) - strlen(dst)
8303       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
8304           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
8305         PatternType = 1;
8306       // - sizeof(src) - (anything)
8307       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
8308         PatternType = 2;
8309     }
8310   }
8311 
8312   if (PatternType == 0)
8313     return;
8314 
8315   // Generate the diagnostic.
8316   SourceLocation SL = LenArg->getLocStart();
8317   SourceRange SR = LenArg->getSourceRange();
8318   SourceManager &SM = getSourceManager();
8319 
8320   // If the function is defined as a builtin macro, do not show macro expansion.
8321   if (SM.isMacroArgExpansion(SL)) {
8322     SL = SM.getSpellingLoc(SL);
8323     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
8324                      SM.getSpellingLoc(SR.getEnd()));
8325   }
8326 
8327   // Check if the destination is an array (rather than a pointer to an array).
8328   QualType DstTy = DstArg->getType();
8329   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
8330                                                                     Context);
8331   if (!isKnownSizeArray) {
8332     if (PatternType == 1)
8333       Diag(SL, diag::warn_strncat_wrong_size) << SR;
8334     else
8335       Diag(SL, diag::warn_strncat_src_size) << SR;
8336     return;
8337   }
8338 
8339   if (PatternType == 1)
8340     Diag(SL, diag::warn_strncat_large_size) << SR;
8341   else
8342     Diag(SL, diag::warn_strncat_src_size) << SR;
8343 
8344   SmallString<128> sizeString;
8345   llvm::raw_svector_ostream OS(sizeString);
8346   OS << "sizeof(";
8347   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
8348   OS << ") - ";
8349   OS << "strlen(";
8350   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
8351   OS << ") - 1";
8352 
8353   Diag(SL, diag::note_strncat_wrong_size)
8354     << FixItHint::CreateReplacement(SR, OS.str());
8355 }
8356 
8357 //===--- CHECK: Return Address of Stack Variable --------------------------===//
8358 
8359 static const Expr *EvalVal(const Expr *E,
8360                            SmallVectorImpl<const DeclRefExpr *> &refVars,
8361                            const Decl *ParentDecl);
8362 static const Expr *EvalAddr(const Expr *E,
8363                             SmallVectorImpl<const DeclRefExpr *> &refVars,
8364                             const Decl *ParentDecl);
8365 
8366 /// CheckReturnStackAddr - Check if a return statement returns the address
8367 ///   of a stack variable.
8368 static void
8369 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
8370                      SourceLocation ReturnLoc) {
8371   const Expr *stackE = nullptr;
8372   SmallVector<const DeclRefExpr *, 8> refVars;
8373 
8374   // Perform checking for returned stack addresses, local blocks,
8375   // label addresses or references to temporaries.
8376   if (lhsType->isPointerType() ||
8377       (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
8378     stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
8379   } else if (lhsType->isReferenceType()) {
8380     stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
8381   }
8382 
8383   if (!stackE)
8384     return; // Nothing suspicious was found.
8385 
8386   // Parameters are initialized in the calling scope, so taking the address
8387   // of a parameter reference doesn't need a warning.
8388   for (auto *DRE : refVars)
8389     if (isa<ParmVarDecl>(DRE->getDecl()))
8390       return;
8391 
8392   SourceLocation diagLoc;
8393   SourceRange diagRange;
8394   if (refVars.empty()) {
8395     diagLoc = stackE->getLocStart();
8396     diagRange = stackE->getSourceRange();
8397   } else {
8398     // We followed through a reference variable. 'stackE' contains the
8399     // problematic expression but we will warn at the return statement pointing
8400     // at the reference variable. We will later display the "trail" of
8401     // reference variables using notes.
8402     diagLoc = refVars[0]->getLocStart();
8403     diagRange = refVars[0]->getSourceRange();
8404   }
8405 
8406   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
8407     // address of local var
8408     S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
8409      << DR->getDecl()->getDeclName() << diagRange;
8410   } else if (isa<BlockExpr>(stackE)) { // local block.
8411     S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
8412   } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
8413     S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
8414   } else { // local temporary.
8415     // If there is an LValue->RValue conversion, then the value of the
8416     // reference type is used, not the reference.
8417     if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
8418       if (ICE->getCastKind() == CK_LValueToRValue) {
8419         return;
8420       }
8421     }
8422     S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
8423      << lhsType->isReferenceType() << diagRange;
8424   }
8425 
8426   // Display the "trail" of reference variables that we followed until we
8427   // found the problematic expression using notes.
8428   for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
8429     const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
8430     // If this var binds to another reference var, show the range of the next
8431     // var, otherwise the var binds to the problematic expression, in which case
8432     // show the range of the expression.
8433     SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
8434                                     : stackE->getSourceRange();
8435     S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
8436         << VD->getDeclName() << range;
8437   }
8438 }
8439 
8440 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
8441 ///  check if the expression in a return statement evaluates to an address
8442 ///  to a location on the stack, a local block, an address of a label, or a
8443 ///  reference to local temporary. The recursion is used to traverse the
8444 ///  AST of the return expression, with recursion backtracking when we
8445 ///  encounter a subexpression that (1) clearly does not lead to one of the
8446 ///  above problematic expressions (2) is something we cannot determine leads to
8447 ///  a problematic expression based on such local checking.
8448 ///
8449 ///  Both EvalAddr and EvalVal follow through reference variables to evaluate
8450 ///  the expression that they point to. Such variables are added to the
8451 ///  'refVars' vector so that we know what the reference variable "trail" was.
8452 ///
8453 ///  EvalAddr processes expressions that are pointers that are used as
8454 ///  references (and not L-values).  EvalVal handles all other values.
8455 ///  At the base case of the recursion is a check for the above problematic
8456 ///  expressions.
8457 ///
8458 ///  This implementation handles:
8459 ///
8460 ///   * pointer-to-pointer casts
8461 ///   * implicit conversions from array references to pointers
8462 ///   * taking the address of fields
8463 ///   * arbitrary interplay between "&" and "*" operators
8464 ///   * pointer arithmetic from an address of a stack variable
8465 ///   * taking the address of an array element where the array is on the stack
8466 static const Expr *EvalAddr(const Expr *E,
8467                             SmallVectorImpl<const DeclRefExpr *> &refVars,
8468                             const Decl *ParentDecl) {
8469   if (E->isTypeDependent())
8470     return nullptr;
8471 
8472   // We should only be called for evaluating pointer expressions.
8473   assert((E->getType()->isAnyPointerType() ||
8474           E->getType()->isBlockPointerType() ||
8475           E->getType()->isObjCQualifiedIdType()) &&
8476          "EvalAddr only works on pointers");
8477 
8478   E = E->IgnoreParens();
8479 
8480   // Our "symbolic interpreter" is just a dispatch off the currently
8481   // viewed AST node.  We then recursively traverse the AST by calling
8482   // EvalAddr and EvalVal appropriately.
8483   switch (E->getStmtClass()) {
8484   case Stmt::DeclRefExprClass: {
8485     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
8486 
8487     // If we leave the immediate function, the lifetime isn't about to end.
8488     if (DR->refersToEnclosingVariableOrCapture())
8489       return nullptr;
8490 
8491     if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
8492       // If this is a reference variable, follow through to the expression that
8493       // it points to.
8494       if (V->hasLocalStorage() &&
8495           V->getType()->isReferenceType() && V->hasInit()) {
8496         // Add the reference variable to the "trail".
8497         refVars.push_back(DR);
8498         return EvalAddr(V->getInit(), refVars, ParentDecl);
8499       }
8500 
8501     return nullptr;
8502   }
8503 
8504   case Stmt::UnaryOperatorClass: {
8505     // The only unary operator that make sense to handle here
8506     // is AddrOf.  All others don't make sense as pointers.
8507     const UnaryOperator *U = cast<UnaryOperator>(E);
8508 
8509     if (U->getOpcode() == UO_AddrOf)
8510       return EvalVal(U->getSubExpr(), refVars, ParentDecl);
8511     return nullptr;
8512   }
8513 
8514   case Stmt::BinaryOperatorClass: {
8515     // Handle pointer arithmetic.  All other binary operators are not valid
8516     // in this context.
8517     const BinaryOperator *B = cast<BinaryOperator>(E);
8518     BinaryOperatorKind op = B->getOpcode();
8519 
8520     if (op != BO_Add && op != BO_Sub)
8521       return nullptr;
8522 
8523     const Expr *Base = B->getLHS();
8524 
8525     // Determine which argument is the real pointer base.  It could be
8526     // the RHS argument instead of the LHS.
8527     if (!Base->getType()->isPointerType())
8528       Base = B->getRHS();
8529 
8530     assert(Base->getType()->isPointerType());
8531     return EvalAddr(Base, refVars, ParentDecl);
8532   }
8533 
8534   // For conditional operators we need to see if either the LHS or RHS are
8535   // valid DeclRefExpr*s.  If one of them is valid, we return it.
8536   case Stmt::ConditionalOperatorClass: {
8537     const ConditionalOperator *C = cast<ConditionalOperator>(E);
8538 
8539     // Handle the GNU extension for missing LHS.
8540     // FIXME: That isn't a ConditionalOperator, so doesn't get here.
8541     if (const Expr *LHSExpr = C->getLHS()) {
8542       // In C++, we can have a throw-expression, which has 'void' type.
8543       if (!LHSExpr->getType()->isVoidType())
8544         if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
8545           return LHS;
8546     }
8547 
8548     // In C++, we can have a throw-expression, which has 'void' type.
8549     if (C->getRHS()->getType()->isVoidType())
8550       return nullptr;
8551 
8552     return EvalAddr(C->getRHS(), refVars, ParentDecl);
8553   }
8554 
8555   case Stmt::BlockExprClass:
8556     if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
8557       return E; // local block.
8558     return nullptr;
8559 
8560   case Stmt::AddrLabelExprClass:
8561     return E; // address of label.
8562 
8563   case Stmt::ExprWithCleanupsClass:
8564     return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
8565                     ParentDecl);
8566 
8567   // For casts, we need to handle conversions from arrays to
8568   // pointer values, and pointer-to-pointer conversions.
8569   case Stmt::ImplicitCastExprClass:
8570   case Stmt::CStyleCastExprClass:
8571   case Stmt::CXXFunctionalCastExprClass:
8572   case Stmt::ObjCBridgedCastExprClass:
8573   case Stmt::CXXStaticCastExprClass:
8574   case Stmt::CXXDynamicCastExprClass:
8575   case Stmt::CXXConstCastExprClass:
8576   case Stmt::CXXReinterpretCastExprClass: {
8577     const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
8578     switch (cast<CastExpr>(E)->getCastKind()) {
8579     case CK_LValueToRValue:
8580     case CK_NoOp:
8581     case CK_BaseToDerived:
8582     case CK_DerivedToBase:
8583     case CK_UncheckedDerivedToBase:
8584     case CK_Dynamic:
8585     case CK_CPointerToObjCPointerCast:
8586     case CK_BlockPointerToObjCPointerCast:
8587     case CK_AnyPointerToBlockPointerCast:
8588       return EvalAddr(SubExpr, refVars, ParentDecl);
8589 
8590     case CK_ArrayToPointerDecay:
8591       return EvalVal(SubExpr, refVars, ParentDecl);
8592 
8593     case CK_BitCast:
8594       if (SubExpr->getType()->isAnyPointerType() ||
8595           SubExpr->getType()->isBlockPointerType() ||
8596           SubExpr->getType()->isObjCQualifiedIdType())
8597         return EvalAddr(SubExpr, refVars, ParentDecl);
8598       else
8599         return nullptr;
8600 
8601     default:
8602       return nullptr;
8603     }
8604   }
8605 
8606   case Stmt::MaterializeTemporaryExprClass:
8607     if (const Expr *Result =
8608             EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8609                      refVars, ParentDecl))
8610       return Result;
8611     return E;
8612 
8613   // Everything else: we simply don't reason about them.
8614   default:
8615     return nullptr;
8616   }
8617 }
8618 
8619 ///  EvalVal - This function is complements EvalAddr in the mutual recursion.
8620 ///   See the comments for EvalAddr for more details.
8621 static const Expr *EvalVal(const Expr *E,
8622                            SmallVectorImpl<const DeclRefExpr *> &refVars,
8623                            const Decl *ParentDecl) {
8624   do {
8625     // We should only be called for evaluating non-pointer expressions, or
8626     // expressions with a pointer type that are not used as references but
8627     // instead
8628     // are l-values (e.g., DeclRefExpr with a pointer type).
8629 
8630     // Our "symbolic interpreter" is just a dispatch off the currently
8631     // viewed AST node.  We then recursively traverse the AST by calling
8632     // EvalAddr and EvalVal appropriately.
8633 
8634     E = E->IgnoreParens();
8635     switch (E->getStmtClass()) {
8636     case Stmt::ImplicitCastExprClass: {
8637       const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
8638       if (IE->getValueKind() == VK_LValue) {
8639         E = IE->getSubExpr();
8640         continue;
8641       }
8642       return nullptr;
8643     }
8644 
8645     case Stmt::ExprWithCleanupsClass:
8646       return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
8647                      ParentDecl);
8648 
8649     case Stmt::DeclRefExprClass: {
8650       // When we hit a DeclRefExpr we are looking at code that refers to a
8651       // variable's name. If it's not a reference variable we check if it has
8652       // local storage within the function, and if so, return the expression.
8653       const DeclRefExpr *DR = cast<DeclRefExpr>(E);
8654 
8655       // If we leave the immediate function, the lifetime isn't about to end.
8656       if (DR->refersToEnclosingVariableOrCapture())
8657         return nullptr;
8658 
8659       if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
8660         // Check if it refers to itself, e.g. "int& i = i;".
8661         if (V == ParentDecl)
8662           return DR;
8663 
8664         if (V->hasLocalStorage()) {
8665           if (!V->getType()->isReferenceType())
8666             return DR;
8667 
8668           // Reference variable, follow through to the expression that
8669           // it points to.
8670           if (V->hasInit()) {
8671             // Add the reference variable to the "trail".
8672             refVars.push_back(DR);
8673             return EvalVal(V->getInit(), refVars, V);
8674           }
8675         }
8676       }
8677 
8678       return nullptr;
8679     }
8680 
8681     case Stmt::UnaryOperatorClass: {
8682       // The only unary operator that make sense to handle here
8683       // is Deref.  All others don't resolve to a "name."  This includes
8684       // handling all sorts of rvalues passed to a unary operator.
8685       const UnaryOperator *U = cast<UnaryOperator>(E);
8686 
8687       if (U->getOpcode() == UO_Deref)
8688         return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
8689 
8690       return nullptr;
8691     }
8692 
8693     case Stmt::ArraySubscriptExprClass: {
8694       // Array subscripts are potential references to data on the stack.  We
8695       // retrieve the DeclRefExpr* for the array variable if it indeed
8696       // has local storage.
8697       const auto *ASE = cast<ArraySubscriptExpr>(E);
8698       if (ASE->isTypeDependent())
8699         return nullptr;
8700       return EvalAddr(ASE->getBase(), refVars, ParentDecl);
8701     }
8702 
8703     case Stmt::OMPArraySectionExprClass: {
8704       return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
8705                       ParentDecl);
8706     }
8707 
8708     case Stmt::ConditionalOperatorClass: {
8709       // For conditional operators we need to see if either the LHS or RHS are
8710       // non-NULL Expr's.  If one is non-NULL, we return it.
8711       const ConditionalOperator *C = cast<ConditionalOperator>(E);
8712 
8713       // Handle the GNU extension for missing LHS.
8714       if (const Expr *LHSExpr = C->getLHS()) {
8715         // In C++, we can have a throw-expression, which has 'void' type.
8716         if (!LHSExpr->getType()->isVoidType())
8717           if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
8718             return LHS;
8719       }
8720 
8721       // In C++, we can have a throw-expression, which has 'void' type.
8722       if (C->getRHS()->getType()->isVoidType())
8723         return nullptr;
8724 
8725       return EvalVal(C->getRHS(), refVars, ParentDecl);
8726     }
8727 
8728     // Accesses to members are potential references to data on the stack.
8729     case Stmt::MemberExprClass: {
8730       const MemberExpr *M = cast<MemberExpr>(E);
8731 
8732       // Check for indirect access.  We only want direct field accesses.
8733       if (M->isArrow())
8734         return nullptr;
8735 
8736       // Check whether the member type is itself a reference, in which case
8737       // we're not going to refer to the member, but to what the member refers
8738       // to.
8739       if (M->getMemberDecl()->getType()->isReferenceType())
8740         return nullptr;
8741 
8742       return EvalVal(M->getBase(), refVars, ParentDecl);
8743     }
8744 
8745     case Stmt::MaterializeTemporaryExprClass:
8746       if (const Expr *Result =
8747               EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8748                       refVars, ParentDecl))
8749         return Result;
8750       return E;
8751 
8752     default:
8753       // Check that we don't return or take the address of a reference to a
8754       // temporary. This is only useful in C++.
8755       if (!E->isTypeDependent() && E->isRValue())
8756         return E;
8757 
8758       // Everything else: we simply don't reason about them.
8759       return nullptr;
8760     }
8761   } while (true);
8762 }
8763 
8764 void
8765 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
8766                          SourceLocation ReturnLoc,
8767                          bool isObjCMethod,
8768                          const AttrVec *Attrs,
8769                          const FunctionDecl *FD) {
8770   CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
8771 
8772   // Check if the return value is null but should not be.
8773   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
8774        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
8775       CheckNonNullExpr(*this, RetValExp))
8776     Diag(ReturnLoc, diag::warn_null_ret)
8777       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
8778 
8779   // C++11 [basic.stc.dynamic.allocation]p4:
8780   //   If an allocation function declared with a non-throwing
8781   //   exception-specification fails to allocate storage, it shall return
8782   //   a null pointer. Any other allocation function that fails to allocate
8783   //   storage shall indicate failure only by throwing an exception [...]
8784   if (FD) {
8785     OverloadedOperatorKind Op = FD->getOverloadedOperator();
8786     if (Op == OO_New || Op == OO_Array_New) {
8787       const FunctionProtoType *Proto
8788         = FD->getType()->castAs<FunctionProtoType>();
8789       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
8790           CheckNonNullExpr(*this, RetValExp))
8791         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
8792           << FD << getLangOpts().CPlusPlus11;
8793     }
8794   }
8795 }
8796 
8797 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
8798 
8799 /// Check for comparisons of floating point operands using != and ==.
8800 /// Issue a warning if these are no self-comparisons, as they are not likely
8801 /// to do what the programmer intended.
8802 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
8803   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
8804   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
8805 
8806   // Special case: check for x == x (which is OK).
8807   // Do not emit warnings for such cases.
8808   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
8809     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
8810       if (DRL->getDecl() == DRR->getDecl())
8811         return;
8812 
8813   // Special case: check for comparisons against literals that can be exactly
8814   //  represented by APFloat.  In such cases, do not emit a warning.  This
8815   //  is a heuristic: often comparison against such literals are used to
8816   //  detect if a value in a variable has not changed.  This clearly can
8817   //  lead to false negatives.
8818   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
8819     if (FLL->isExact())
8820       return;
8821   } else
8822     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
8823       if (FLR->isExact())
8824         return;
8825 
8826   // Check for comparisons with builtin types.
8827   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
8828     if (CL->getBuiltinCallee())
8829       return;
8830 
8831   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
8832     if (CR->getBuiltinCallee())
8833       return;
8834 
8835   // Emit the diagnostic.
8836   Diag(Loc, diag::warn_floatingpoint_eq)
8837     << LHS->getSourceRange() << RHS->getSourceRange();
8838 }
8839 
8840 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
8841 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
8842 
8843 namespace {
8844 
8845 /// Structure recording the 'active' range of an integer-valued
8846 /// expression.
8847 struct IntRange {
8848   /// The number of bits active in the int.
8849   unsigned Width;
8850 
8851   /// True if the int is known not to have negative values.
8852   bool NonNegative;
8853 
8854   IntRange(unsigned Width, bool NonNegative)
8855       : Width(Width), NonNegative(NonNegative) {}
8856 
8857   /// Returns the range of the bool type.
8858   static IntRange forBoolType() {
8859     return IntRange(1, true);
8860   }
8861 
8862   /// Returns the range of an opaque value of the given integral type.
8863   static IntRange forValueOfType(ASTContext &C, QualType T) {
8864     return forValueOfCanonicalType(C,
8865                           T->getCanonicalTypeInternal().getTypePtr());
8866   }
8867 
8868   /// Returns the range of an opaque value of a canonical integral type.
8869   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
8870     assert(T->isCanonicalUnqualified());
8871 
8872     if (const VectorType *VT = dyn_cast<VectorType>(T))
8873       T = VT->getElementType().getTypePtr();
8874     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8875       T = CT->getElementType().getTypePtr();
8876     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8877       T = AT->getValueType().getTypePtr();
8878 
8879     if (!C.getLangOpts().CPlusPlus) {
8880       // For enum types in C code, use the underlying datatype.
8881       if (const EnumType *ET = dyn_cast<EnumType>(T))
8882         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
8883     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
8884       // For enum types in C++, use the known bit width of the enumerators.
8885       EnumDecl *Enum = ET->getDecl();
8886       // In C++11, enums can have a fixed underlying type. Use this type to
8887       // compute the range.
8888       if (Enum->isFixed()) {
8889         return IntRange(C.getIntWidth(QualType(T, 0)),
8890                         !ET->isSignedIntegerOrEnumerationType());
8891       }
8892 
8893       unsigned NumPositive = Enum->getNumPositiveBits();
8894       unsigned NumNegative = Enum->getNumNegativeBits();
8895 
8896       if (NumNegative == 0)
8897         return IntRange(NumPositive, true/*NonNegative*/);
8898       else
8899         return IntRange(std::max(NumPositive + 1, NumNegative),
8900                         false/*NonNegative*/);
8901     }
8902 
8903     const BuiltinType *BT = cast<BuiltinType>(T);
8904     assert(BT->isInteger());
8905 
8906     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8907   }
8908 
8909   /// Returns the "target" range of a canonical integral type, i.e.
8910   /// the range of values expressible in the type.
8911   ///
8912   /// This matches forValueOfCanonicalType except that enums have the
8913   /// full range of their type, not the range of their enumerators.
8914   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
8915     assert(T->isCanonicalUnqualified());
8916 
8917     if (const VectorType *VT = dyn_cast<VectorType>(T))
8918       T = VT->getElementType().getTypePtr();
8919     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8920       T = CT->getElementType().getTypePtr();
8921     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8922       T = AT->getValueType().getTypePtr();
8923     if (const EnumType *ET = dyn_cast<EnumType>(T))
8924       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
8925 
8926     const BuiltinType *BT = cast<BuiltinType>(T);
8927     assert(BT->isInteger());
8928 
8929     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8930   }
8931 
8932   /// Returns the supremum of two ranges: i.e. their conservative merge.
8933   static IntRange join(IntRange L, IntRange R) {
8934     return IntRange(std::max(L.Width, R.Width),
8935                     L.NonNegative && R.NonNegative);
8936   }
8937 
8938   /// Returns the infinum of two ranges: i.e. their aggressive merge.
8939   static IntRange meet(IntRange L, IntRange R) {
8940     return IntRange(std::min(L.Width, R.Width),
8941                     L.NonNegative || R.NonNegative);
8942   }
8943 };
8944 
8945 } // namespace
8946 
8947 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
8948                               unsigned MaxWidth) {
8949   if (value.isSigned() && value.isNegative())
8950     return IntRange(value.getMinSignedBits(), false);
8951 
8952   if (value.getBitWidth() > MaxWidth)
8953     value = value.trunc(MaxWidth);
8954 
8955   // isNonNegative() just checks the sign bit without considering
8956   // signedness.
8957   return IntRange(value.getActiveBits(), true);
8958 }
8959 
8960 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
8961                               unsigned MaxWidth) {
8962   if (result.isInt())
8963     return GetValueRange(C, result.getInt(), MaxWidth);
8964 
8965   if (result.isVector()) {
8966     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
8967     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
8968       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
8969       R = IntRange::join(R, El);
8970     }
8971     return R;
8972   }
8973 
8974   if (result.isComplexInt()) {
8975     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
8976     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
8977     return IntRange::join(R, I);
8978   }
8979 
8980   // This can happen with lossless casts to intptr_t of "based" lvalues.
8981   // Assume it might use arbitrary bits.
8982   // FIXME: The only reason we need to pass the type in here is to get
8983   // the sign right on this one case.  It would be nice if APValue
8984   // preserved this.
8985   assert(result.isLValue() || result.isAddrLabelDiff());
8986   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
8987 }
8988 
8989 static QualType GetExprType(const Expr *E) {
8990   QualType Ty = E->getType();
8991   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
8992     Ty = AtomicRHS->getValueType();
8993   return Ty;
8994 }
8995 
8996 /// Pseudo-evaluate the given integer expression, estimating the
8997 /// range of values it might take.
8998 ///
8999 /// \param MaxWidth - the width to which the value will be truncated
9000 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
9001   E = E->IgnoreParens();
9002 
9003   // Try a full evaluation first.
9004   Expr::EvalResult result;
9005   if (E->EvaluateAsRValue(result, C))
9006     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
9007 
9008   // I think we only want to look through implicit casts here; if the
9009   // user has an explicit widening cast, we should treat the value as
9010   // being of the new, wider type.
9011   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
9012     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
9013       return GetExprRange(C, CE->getSubExpr(), MaxWidth);
9014 
9015     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
9016 
9017     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
9018                          CE->getCastKind() == CK_BooleanToSignedIntegral;
9019 
9020     // Assume that non-integer casts can span the full range of the type.
9021     if (!isIntegerCast)
9022       return OutputTypeRange;
9023 
9024     IntRange SubRange
9025       = GetExprRange(C, CE->getSubExpr(),
9026                      std::min(MaxWidth, OutputTypeRange.Width));
9027 
9028     // Bail out if the subexpr's range is as wide as the cast type.
9029     if (SubRange.Width >= OutputTypeRange.Width)
9030       return OutputTypeRange;
9031 
9032     // Otherwise, we take the smaller width, and we're non-negative if
9033     // either the output type or the subexpr is.
9034     return IntRange(SubRange.Width,
9035                     SubRange.NonNegative || OutputTypeRange.NonNegative);
9036   }
9037 
9038   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
9039     // If we can fold the condition, just take that operand.
9040     bool CondResult;
9041     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
9042       return GetExprRange(C, CondResult ? CO->getTrueExpr()
9043                                         : CO->getFalseExpr(),
9044                           MaxWidth);
9045 
9046     // Otherwise, conservatively merge.
9047     IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
9048     IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
9049     return IntRange::join(L, R);
9050   }
9051 
9052   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
9053     switch (BO->getOpcode()) {
9054     case BO_Cmp:
9055       llvm_unreachable("builtin <=> should have class type");
9056 
9057     // Boolean-valued operations are single-bit and positive.
9058     case BO_LAnd:
9059     case BO_LOr:
9060     case BO_LT:
9061     case BO_GT:
9062     case BO_LE:
9063     case BO_GE:
9064     case BO_EQ:
9065     case BO_NE:
9066       return IntRange::forBoolType();
9067 
9068     // The type of the assignments is the type of the LHS, so the RHS
9069     // is not necessarily the same type.
9070     case BO_MulAssign:
9071     case BO_DivAssign:
9072     case BO_RemAssign:
9073     case BO_AddAssign:
9074     case BO_SubAssign:
9075     case BO_XorAssign:
9076     case BO_OrAssign:
9077       // TODO: bitfields?
9078       return IntRange::forValueOfType(C, GetExprType(E));
9079 
9080     // Simple assignments just pass through the RHS, which will have
9081     // been coerced to the LHS type.
9082     case BO_Assign:
9083       // TODO: bitfields?
9084       return GetExprRange(C, BO->getRHS(), MaxWidth);
9085 
9086     // Operations with opaque sources are black-listed.
9087     case BO_PtrMemD:
9088     case BO_PtrMemI:
9089       return IntRange::forValueOfType(C, GetExprType(E));
9090 
9091     // Bitwise-and uses the *infinum* of the two source ranges.
9092     case BO_And:
9093     case BO_AndAssign:
9094       return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
9095                             GetExprRange(C, BO->getRHS(), MaxWidth));
9096 
9097     // Left shift gets black-listed based on a judgement call.
9098     case BO_Shl:
9099       // ...except that we want to treat '1 << (blah)' as logically
9100       // positive.  It's an important idiom.
9101       if (IntegerLiteral *I
9102             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
9103         if (I->getValue() == 1) {
9104           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
9105           return IntRange(R.Width, /*NonNegative*/ true);
9106         }
9107       }
9108       LLVM_FALLTHROUGH;
9109 
9110     case BO_ShlAssign:
9111       return IntRange::forValueOfType(C, GetExprType(E));
9112 
9113     // Right shift by a constant can narrow its left argument.
9114     case BO_Shr:
9115     case BO_ShrAssign: {
9116       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
9117 
9118       // If the shift amount is a positive constant, drop the width by
9119       // that much.
9120       llvm::APSInt shift;
9121       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
9122           shift.isNonNegative()) {
9123         unsigned zext = shift.getZExtValue();
9124         if (zext >= L.Width)
9125           L.Width = (L.NonNegative ? 0 : 1);
9126         else
9127           L.Width -= zext;
9128       }
9129 
9130       return L;
9131     }
9132 
9133     // Comma acts as its right operand.
9134     case BO_Comma:
9135       return GetExprRange(C, BO->getRHS(), MaxWidth);
9136 
9137     // Black-list pointer subtractions.
9138     case BO_Sub:
9139       if (BO->getLHS()->getType()->isPointerType())
9140         return IntRange::forValueOfType(C, GetExprType(E));
9141       break;
9142 
9143     // The width of a division result is mostly determined by the size
9144     // of the LHS.
9145     case BO_Div: {
9146       // Don't 'pre-truncate' the operands.
9147       unsigned opWidth = C.getIntWidth(GetExprType(E));
9148       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
9149 
9150       // If the divisor is constant, use that.
9151       llvm::APSInt divisor;
9152       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
9153         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
9154         if (log2 >= L.Width)
9155           L.Width = (L.NonNegative ? 0 : 1);
9156         else
9157           L.Width = std::min(L.Width - log2, MaxWidth);
9158         return L;
9159       }
9160 
9161       // Otherwise, just use the LHS's width.
9162       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
9163       return IntRange(L.Width, L.NonNegative && R.NonNegative);
9164     }
9165 
9166     // The result of a remainder can't be larger than the result of
9167     // either side.
9168     case BO_Rem: {
9169       // Don't 'pre-truncate' the operands.
9170       unsigned opWidth = C.getIntWidth(GetExprType(E));
9171       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
9172       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
9173 
9174       IntRange meet = IntRange::meet(L, R);
9175       meet.Width = std::min(meet.Width, MaxWidth);
9176       return meet;
9177     }
9178 
9179     // The default behavior is okay for these.
9180     case BO_Mul:
9181     case BO_Add:
9182     case BO_Xor:
9183     case BO_Or:
9184       break;
9185     }
9186 
9187     // The default case is to treat the operation as if it were closed
9188     // on the narrowest type that encompasses both operands.
9189     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
9190     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
9191     return IntRange::join(L, R);
9192   }
9193 
9194   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
9195     switch (UO->getOpcode()) {
9196     // Boolean-valued operations are white-listed.
9197     case UO_LNot:
9198       return IntRange::forBoolType();
9199 
9200     // Operations with opaque sources are black-listed.
9201     case UO_Deref:
9202     case UO_AddrOf: // should be impossible
9203       return IntRange::forValueOfType(C, GetExprType(E));
9204 
9205     default:
9206       return GetExprRange(C, UO->getSubExpr(), MaxWidth);
9207     }
9208   }
9209 
9210   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
9211     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
9212 
9213   if (const auto *BitField = E->getSourceBitField())
9214     return IntRange(BitField->getBitWidthValue(C),
9215                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
9216 
9217   return IntRange::forValueOfType(C, GetExprType(E));
9218 }
9219 
9220 static IntRange GetExprRange(ASTContext &C, const Expr *E) {
9221   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
9222 }
9223 
9224 /// Checks whether the given value, which currently has the given
9225 /// source semantics, has the same value when coerced through the
9226 /// target semantics.
9227 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
9228                                  const llvm::fltSemantics &Src,
9229                                  const llvm::fltSemantics &Tgt) {
9230   llvm::APFloat truncated = value;
9231 
9232   bool ignored;
9233   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
9234   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
9235 
9236   return truncated.bitwiseIsEqual(value);
9237 }
9238 
9239 /// Checks whether the given value, which currently has the given
9240 /// source semantics, has the same value when coerced through the
9241 /// target semantics.
9242 ///
9243 /// The value might be a vector of floats (or a complex number).
9244 static bool IsSameFloatAfterCast(const APValue &value,
9245                                  const llvm::fltSemantics &Src,
9246                                  const llvm::fltSemantics &Tgt) {
9247   if (value.isFloat())
9248     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
9249 
9250   if (value.isVector()) {
9251     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
9252       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
9253         return false;
9254     return true;
9255   }
9256 
9257   assert(value.isComplexFloat());
9258   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
9259           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
9260 }
9261 
9262 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
9263 
9264 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
9265   // Suppress cases where we are comparing against an enum constant.
9266   if (const DeclRefExpr *DR =
9267       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
9268     if (isa<EnumConstantDecl>(DR->getDecl()))
9269       return true;
9270 
9271   // Suppress cases where the '0' value is expanded from a macro.
9272   if (E->getLocStart().isMacroID())
9273     return true;
9274 
9275   return false;
9276 }
9277 
9278 static bool isKnownToHaveUnsignedValue(Expr *E) {
9279   return E->getType()->isIntegerType() &&
9280          (!E->getType()->isSignedIntegerType() ||
9281           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
9282 }
9283 
9284 namespace {
9285 /// The promoted range of values of a type. In general this has the
9286 /// following structure:
9287 ///
9288 ///     |-----------| . . . |-----------|
9289 ///     ^           ^       ^           ^
9290 ///    Min       HoleMin  HoleMax      Max
9291 ///
9292 /// ... where there is only a hole if a signed type is promoted to unsigned
9293 /// (in which case Min and Max are the smallest and largest representable
9294 /// values).
9295 struct PromotedRange {
9296   // Min, or HoleMax if there is a hole.
9297   llvm::APSInt PromotedMin;
9298   // Max, or HoleMin if there is a hole.
9299   llvm::APSInt PromotedMax;
9300 
9301   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
9302     if (R.Width == 0)
9303       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
9304     else if (R.Width >= BitWidth && !Unsigned) {
9305       // Promotion made the type *narrower*. This happens when promoting
9306       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
9307       // Treat all values of 'signed int' as being in range for now.
9308       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
9309       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
9310     } else {
9311       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
9312                         .extOrTrunc(BitWidth);
9313       PromotedMin.setIsUnsigned(Unsigned);
9314 
9315       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
9316                         .extOrTrunc(BitWidth);
9317       PromotedMax.setIsUnsigned(Unsigned);
9318     }
9319   }
9320 
9321   // Determine whether this range is contiguous (has no hole).
9322   bool isContiguous() const { return PromotedMin <= PromotedMax; }
9323 
9324   // Where a constant value is within the range.
9325   enum ComparisonResult {
9326     LT = 0x1,
9327     LE = 0x2,
9328     GT = 0x4,
9329     GE = 0x8,
9330     EQ = 0x10,
9331     NE = 0x20,
9332     InRangeFlag = 0x40,
9333 
9334     Less = LE | LT | NE,
9335     Min = LE | InRangeFlag,
9336     InRange = InRangeFlag,
9337     Max = GE | InRangeFlag,
9338     Greater = GE | GT | NE,
9339 
9340     OnlyValue = LE | GE | EQ | InRangeFlag,
9341     InHole = NE
9342   };
9343 
9344   ComparisonResult compare(const llvm::APSInt &Value) const {
9345     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
9346            Value.isUnsigned() == PromotedMin.isUnsigned());
9347     if (!isContiguous()) {
9348       assert(Value.isUnsigned() && "discontiguous range for signed compare");
9349       if (Value.isMinValue()) return Min;
9350       if (Value.isMaxValue()) return Max;
9351       if (Value >= PromotedMin) return InRange;
9352       if (Value <= PromotedMax) return InRange;
9353       return InHole;
9354     }
9355 
9356     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
9357     case -1: return Less;
9358     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
9359     case 1:
9360       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
9361       case -1: return InRange;
9362       case 0: return Max;
9363       case 1: return Greater;
9364       }
9365     }
9366 
9367     llvm_unreachable("impossible compare result");
9368   }
9369 
9370   static llvm::Optional<StringRef>
9371   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
9372     if (Op == BO_Cmp) {
9373       ComparisonResult LTFlag = LT, GTFlag = GT;
9374       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
9375 
9376       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
9377       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
9378       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
9379       return llvm::None;
9380     }
9381 
9382     ComparisonResult TrueFlag, FalseFlag;
9383     if (Op == BO_EQ) {
9384       TrueFlag = EQ;
9385       FalseFlag = NE;
9386     } else if (Op == BO_NE) {
9387       TrueFlag = NE;
9388       FalseFlag = EQ;
9389     } else {
9390       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
9391         TrueFlag = LT;
9392         FalseFlag = GE;
9393       } else {
9394         TrueFlag = GT;
9395         FalseFlag = LE;
9396       }
9397       if (Op == BO_GE || Op == BO_LE)
9398         std::swap(TrueFlag, FalseFlag);
9399     }
9400     if (R & TrueFlag)
9401       return StringRef("true");
9402     if (R & FalseFlag)
9403       return StringRef("false");
9404     return llvm::None;
9405   }
9406 };
9407 }
9408 
9409 static bool HasEnumType(Expr *E) {
9410   // Strip off implicit integral promotions.
9411   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9412     if (ICE->getCastKind() != CK_IntegralCast &&
9413         ICE->getCastKind() != CK_NoOp)
9414       break;
9415     E = ICE->getSubExpr();
9416   }
9417 
9418   return E->getType()->isEnumeralType();
9419 }
9420 
9421 static int classifyConstantValue(Expr *Constant) {
9422   // The values of this enumeration are used in the diagnostics
9423   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
9424   enum ConstantValueKind {
9425     Miscellaneous = 0,
9426     LiteralTrue,
9427     LiteralFalse
9428   };
9429   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
9430     return BL->getValue() ? ConstantValueKind::LiteralTrue
9431                           : ConstantValueKind::LiteralFalse;
9432   return ConstantValueKind::Miscellaneous;
9433 }
9434 
9435 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
9436                                         Expr *Constant, Expr *Other,
9437                                         const llvm::APSInt &Value,
9438                                         bool RhsConstant) {
9439   if (S.inTemplateInstantiation())
9440     return false;
9441 
9442   Expr *OriginalOther = Other;
9443 
9444   Constant = Constant->IgnoreParenImpCasts();
9445   Other = Other->IgnoreParenImpCasts();
9446 
9447   // Suppress warnings on tautological comparisons between values of the same
9448   // enumeration type. There are only two ways we could warn on this:
9449   //  - If the constant is outside the range of representable values of
9450   //    the enumeration. In such a case, we should warn about the cast
9451   //    to enumeration type, not about the comparison.
9452   //  - If the constant is the maximum / minimum in-range value. For an
9453   //    enumeratin type, such comparisons can be meaningful and useful.
9454   if (Constant->getType()->isEnumeralType() &&
9455       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
9456     return false;
9457 
9458   // TODO: Investigate using GetExprRange() to get tighter bounds
9459   // on the bit ranges.
9460   QualType OtherT = Other->getType();
9461   if (const auto *AT = OtherT->getAs<AtomicType>())
9462     OtherT = AT->getValueType();
9463   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
9464 
9465   // Whether we're treating Other as being a bool because of the form of
9466   // expression despite it having another type (typically 'int' in C).
9467   bool OtherIsBooleanDespiteType =
9468       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
9469   if (OtherIsBooleanDespiteType)
9470     OtherRange = IntRange::forBoolType();
9471 
9472   // Determine the promoted range of the other type and see if a comparison of
9473   // the constant against that range is tautological.
9474   PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
9475                                    Value.isUnsigned());
9476   auto Cmp = OtherPromotedRange.compare(Value);
9477   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
9478   if (!Result)
9479     return false;
9480 
9481   // Suppress the diagnostic for an in-range comparison if the constant comes
9482   // from a macro or enumerator. We don't want to diagnose
9483   //
9484   //   some_long_value <= INT_MAX
9485   //
9486   // when sizeof(int) == sizeof(long).
9487   bool InRange = Cmp & PromotedRange::InRangeFlag;
9488   if (InRange && IsEnumConstOrFromMacro(S, Constant))
9489     return false;
9490 
9491   // If this is a comparison to an enum constant, include that
9492   // constant in the diagnostic.
9493   const EnumConstantDecl *ED = nullptr;
9494   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
9495     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
9496 
9497   // Should be enough for uint128 (39 decimal digits)
9498   SmallString<64> PrettySourceValue;
9499   llvm::raw_svector_ostream OS(PrettySourceValue);
9500   if (ED)
9501     OS << '\'' << *ED << "' (" << Value << ")";
9502   else
9503     OS << Value;
9504 
9505   // FIXME: We use a somewhat different formatting for the in-range cases and
9506   // cases involving boolean values for historical reasons. We should pick a
9507   // consistent way of presenting these diagnostics.
9508   if (!InRange || Other->isKnownToHaveBooleanValue()) {
9509     S.DiagRuntimeBehavior(
9510       E->getOperatorLoc(), E,
9511       S.PDiag(!InRange ? diag::warn_out_of_range_compare
9512                        : diag::warn_tautological_bool_compare)
9513           << OS.str() << classifyConstantValue(Constant)
9514           << OtherT << OtherIsBooleanDespiteType << *Result
9515           << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
9516   } else {
9517     unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
9518                         ? (HasEnumType(OriginalOther)
9519                                ? diag::warn_unsigned_enum_always_true_comparison
9520                                : diag::warn_unsigned_always_true_comparison)
9521                         : diag::warn_tautological_constant_compare;
9522 
9523     S.Diag(E->getOperatorLoc(), Diag)
9524         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
9525         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
9526   }
9527 
9528   return true;
9529 }
9530 
9531 /// Analyze the operands of the given comparison.  Implements the
9532 /// fallback case from AnalyzeComparison.
9533 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
9534   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9535   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9536 }
9537 
9538 /// Implements -Wsign-compare.
9539 ///
9540 /// \param E the binary operator to check for warnings
9541 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
9542   // The type the comparison is being performed in.
9543   QualType T = E->getLHS()->getType();
9544 
9545   // Only analyze comparison operators where both sides have been converted to
9546   // the same type.
9547   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
9548     return AnalyzeImpConvsInComparison(S, E);
9549 
9550   // Don't analyze value-dependent comparisons directly.
9551   if (E->isValueDependent())
9552     return AnalyzeImpConvsInComparison(S, E);
9553 
9554   Expr *LHS = E->getLHS();
9555   Expr *RHS = E->getRHS();
9556 
9557   if (T->isIntegralType(S.Context)) {
9558     llvm::APSInt RHSValue;
9559     llvm::APSInt LHSValue;
9560 
9561     bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
9562     bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
9563 
9564     // We don't care about expressions whose result is a constant.
9565     if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
9566       return AnalyzeImpConvsInComparison(S, E);
9567 
9568     // We only care about expressions where just one side is literal
9569     if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
9570       // Is the constant on the RHS or LHS?
9571       const bool RhsConstant = IsRHSIntegralLiteral;
9572       Expr *Const = RhsConstant ? RHS : LHS;
9573       Expr *Other = RhsConstant ? LHS : RHS;
9574       const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
9575 
9576       // Check whether an integer constant comparison results in a value
9577       // of 'true' or 'false'.
9578       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
9579         return AnalyzeImpConvsInComparison(S, E);
9580     }
9581   }
9582 
9583   if (!T->hasUnsignedIntegerRepresentation()) {
9584     // We don't do anything special if this isn't an unsigned integral
9585     // comparison:  we're only interested in integral comparisons, and
9586     // signed comparisons only happen in cases we don't care to warn about.
9587     return AnalyzeImpConvsInComparison(S, E);
9588   }
9589 
9590   LHS = LHS->IgnoreParenImpCasts();
9591   RHS = RHS->IgnoreParenImpCasts();
9592 
9593   if (!S.getLangOpts().CPlusPlus) {
9594     // Avoid warning about comparison of integers with different signs when
9595     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
9596     // the type of `E`.
9597     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
9598       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
9599     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
9600       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
9601   }
9602 
9603   // Check to see if one of the (unmodified) operands is of different
9604   // signedness.
9605   Expr *signedOperand, *unsignedOperand;
9606   if (LHS->getType()->hasSignedIntegerRepresentation()) {
9607     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
9608            "unsigned comparison between two signed integer expressions?");
9609     signedOperand = LHS;
9610     unsignedOperand = RHS;
9611   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
9612     signedOperand = RHS;
9613     unsignedOperand = LHS;
9614   } else {
9615     return AnalyzeImpConvsInComparison(S, E);
9616   }
9617 
9618   // Otherwise, calculate the effective range of the signed operand.
9619   IntRange signedRange = GetExprRange(S.Context, signedOperand);
9620 
9621   // Go ahead and analyze implicit conversions in the operands.  Note
9622   // that we skip the implicit conversions on both sides.
9623   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
9624   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
9625 
9626   // If the signed range is non-negative, -Wsign-compare won't fire.
9627   if (signedRange.NonNegative)
9628     return;
9629 
9630   // For (in)equality comparisons, if the unsigned operand is a
9631   // constant which cannot collide with a overflowed signed operand,
9632   // then reinterpreting the signed operand as unsigned will not
9633   // change the result of the comparison.
9634   if (E->isEqualityOp()) {
9635     unsigned comparisonWidth = S.Context.getIntWidth(T);
9636     IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
9637 
9638     // We should never be unable to prove that the unsigned operand is
9639     // non-negative.
9640     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
9641 
9642     if (unsignedRange.Width < comparisonWidth)
9643       return;
9644   }
9645 
9646   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
9647     S.PDiag(diag::warn_mixed_sign_comparison)
9648       << LHS->getType() << RHS->getType()
9649       << LHS->getSourceRange() << RHS->getSourceRange());
9650 }
9651 
9652 /// Analyzes an attempt to assign the given value to a bitfield.
9653 ///
9654 /// Returns true if there was something fishy about the attempt.
9655 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
9656                                       SourceLocation InitLoc) {
9657   assert(Bitfield->isBitField());
9658   if (Bitfield->isInvalidDecl())
9659     return false;
9660 
9661   // White-list bool bitfields.
9662   QualType BitfieldType = Bitfield->getType();
9663   if (BitfieldType->isBooleanType())
9664      return false;
9665 
9666   if (BitfieldType->isEnumeralType()) {
9667     EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
9668     // If the underlying enum type was not explicitly specified as an unsigned
9669     // type and the enum contain only positive values, MSVC++ will cause an
9670     // inconsistency by storing this as a signed type.
9671     if (S.getLangOpts().CPlusPlus11 &&
9672         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
9673         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
9674         BitfieldEnumDecl->getNumNegativeBits() == 0) {
9675       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
9676         << BitfieldEnumDecl->getNameAsString();
9677     }
9678   }
9679 
9680   if (Bitfield->getType()->isBooleanType())
9681     return false;
9682 
9683   // Ignore value- or type-dependent expressions.
9684   if (Bitfield->getBitWidth()->isValueDependent() ||
9685       Bitfield->getBitWidth()->isTypeDependent() ||
9686       Init->isValueDependent() ||
9687       Init->isTypeDependent())
9688     return false;
9689 
9690   Expr *OriginalInit = Init->IgnoreParenImpCasts();
9691   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
9692 
9693   llvm::APSInt Value;
9694   if (!OriginalInit->EvaluateAsInt(Value, S.Context,
9695                                    Expr::SE_AllowSideEffects)) {
9696     // The RHS is not constant.  If the RHS has an enum type, make sure the
9697     // bitfield is wide enough to hold all the values of the enum without
9698     // truncation.
9699     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
9700       EnumDecl *ED = EnumTy->getDecl();
9701       bool SignedBitfield = BitfieldType->isSignedIntegerType();
9702 
9703       // Enum types are implicitly signed on Windows, so check if there are any
9704       // negative enumerators to see if the enum was intended to be signed or
9705       // not.
9706       bool SignedEnum = ED->getNumNegativeBits() > 0;
9707 
9708       // Check for surprising sign changes when assigning enum values to a
9709       // bitfield of different signedness.  If the bitfield is signed and we
9710       // have exactly the right number of bits to store this unsigned enum,
9711       // suggest changing the enum to an unsigned type. This typically happens
9712       // on Windows where unfixed enums always use an underlying type of 'int'.
9713       unsigned DiagID = 0;
9714       if (SignedEnum && !SignedBitfield) {
9715         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
9716       } else if (SignedBitfield && !SignedEnum &&
9717                  ED->getNumPositiveBits() == FieldWidth) {
9718         DiagID = diag::warn_signed_bitfield_enum_conversion;
9719       }
9720 
9721       if (DiagID) {
9722         S.Diag(InitLoc, DiagID) << Bitfield << ED;
9723         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
9724         SourceRange TypeRange =
9725             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
9726         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
9727             << SignedEnum << TypeRange;
9728       }
9729 
9730       // Compute the required bitwidth. If the enum has negative values, we need
9731       // one more bit than the normal number of positive bits to represent the
9732       // sign bit.
9733       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
9734                                                   ED->getNumNegativeBits())
9735                                        : ED->getNumPositiveBits();
9736 
9737       // Check the bitwidth.
9738       if (BitsNeeded > FieldWidth) {
9739         Expr *WidthExpr = Bitfield->getBitWidth();
9740         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
9741             << Bitfield << ED;
9742         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
9743             << BitsNeeded << ED << WidthExpr->getSourceRange();
9744       }
9745     }
9746 
9747     return false;
9748   }
9749 
9750   unsigned OriginalWidth = Value.getBitWidth();
9751 
9752   if (!Value.isSigned() || Value.isNegative())
9753     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
9754       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
9755         OriginalWidth = Value.getMinSignedBits();
9756 
9757   if (OriginalWidth <= FieldWidth)
9758     return false;
9759 
9760   // Compute the value which the bitfield will contain.
9761   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
9762   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
9763 
9764   // Check whether the stored value is equal to the original value.
9765   TruncatedValue = TruncatedValue.extend(OriginalWidth);
9766   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
9767     return false;
9768 
9769   // Special-case bitfields of width 1: booleans are naturally 0/1, and
9770   // therefore don't strictly fit into a signed bitfield of width 1.
9771   if (FieldWidth == 1 && Value == 1)
9772     return false;
9773 
9774   std::string PrettyValue = Value.toString(10);
9775   std::string PrettyTrunc = TruncatedValue.toString(10);
9776 
9777   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
9778     << PrettyValue << PrettyTrunc << OriginalInit->getType()
9779     << Init->getSourceRange();
9780 
9781   return true;
9782 }
9783 
9784 /// Analyze the given simple or compound assignment for warning-worthy
9785 /// operations.
9786 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
9787   // Just recurse on the LHS.
9788   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9789 
9790   // We want to recurse on the RHS as normal unless we're assigning to
9791   // a bitfield.
9792   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
9793     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
9794                                   E->getOperatorLoc())) {
9795       // Recurse, ignoring any implicit conversions on the RHS.
9796       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
9797                                         E->getOperatorLoc());
9798     }
9799   }
9800 
9801   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9802 }
9803 
9804 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
9805 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
9806                             SourceLocation CContext, unsigned diag,
9807                             bool pruneControlFlow = false) {
9808   if (pruneControlFlow) {
9809     S.DiagRuntimeBehavior(E->getExprLoc(), E,
9810                           S.PDiag(diag)
9811                             << SourceType << T << E->getSourceRange()
9812                             << SourceRange(CContext));
9813     return;
9814   }
9815   S.Diag(E->getExprLoc(), diag)
9816     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
9817 }
9818 
9819 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
9820 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
9821                             SourceLocation CContext,
9822                             unsigned diag, bool pruneControlFlow = false) {
9823   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
9824 }
9825 
9826 /// Analyze the given compound assignment for the possible losing of
9827 /// floating-point precision.
9828 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
9829   assert(isa<CompoundAssignOperator>(E) &&
9830          "Must be compound assignment operation");
9831   // Recurse on the LHS and RHS in here
9832   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9833   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9834 
9835   // Now check the outermost expression
9836   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
9837   const auto *RBT = cast<CompoundAssignOperator>(E)
9838                         ->getComputationResultType()
9839                         ->getAs<BuiltinType>();
9840 
9841   // If both source and target are floating points.
9842   if (ResultBT && ResultBT->isFloatingPoint() && RBT && RBT->isFloatingPoint())
9843     // Builtin FP kinds are ordered by increasing FP rank.
9844     if (ResultBT->getKind() < RBT->getKind())
9845       // We don't want to warn for system macro.
9846       if (!S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
9847         // warn about dropping FP rank.
9848         DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(),
9849                         E->getOperatorLoc(),
9850                         diag::warn_impcast_float_result_precision);
9851 }
9852 
9853 /// Diagnose an implicit cast from a floating point value to an integer value.
9854 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
9855                                     SourceLocation CContext) {
9856   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
9857   const bool PruneWarnings = S.inTemplateInstantiation();
9858 
9859   Expr *InnerE = E->IgnoreParenImpCasts();
9860   // We also want to warn on, e.g., "int i = -1.234"
9861   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
9862     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
9863       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
9864 
9865   const bool IsLiteral =
9866       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
9867 
9868   llvm::APFloat Value(0.0);
9869   bool IsConstant =
9870     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
9871   if (!IsConstant) {
9872     return DiagnoseImpCast(S, E, T, CContext,
9873                            diag::warn_impcast_float_integer, PruneWarnings);
9874   }
9875 
9876   bool isExact = false;
9877 
9878   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
9879                             T->hasUnsignedIntegerRepresentation());
9880   llvm::APFloat::opStatus Result = Value.convertToInteger(
9881       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
9882 
9883   if (Result == llvm::APFloat::opOK && isExact) {
9884     if (IsLiteral) return;
9885     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
9886                            PruneWarnings);
9887   }
9888 
9889   // Conversion of a floating-point value to a non-bool integer where the
9890   // integral part cannot be represented by the integer type is undefined.
9891   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
9892     return DiagnoseImpCast(
9893         S, E, T, CContext,
9894         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
9895                   : diag::warn_impcast_float_to_integer_out_of_range,
9896         PruneWarnings);
9897 
9898   unsigned DiagID = 0;
9899   if (IsLiteral) {
9900     // Warn on floating point literal to integer.
9901     DiagID = diag::warn_impcast_literal_float_to_integer;
9902   } else if (IntegerValue == 0) {
9903     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
9904       return DiagnoseImpCast(S, E, T, CContext,
9905                              diag::warn_impcast_float_integer, PruneWarnings);
9906     }
9907     // Warn on non-zero to zero conversion.
9908     DiagID = diag::warn_impcast_float_to_integer_zero;
9909   } else {
9910     if (IntegerValue.isUnsigned()) {
9911       if (!IntegerValue.isMaxValue()) {
9912         return DiagnoseImpCast(S, E, T, CContext,
9913                                diag::warn_impcast_float_integer, PruneWarnings);
9914       }
9915     } else {  // IntegerValue.isSigned()
9916       if (!IntegerValue.isMaxSignedValue() &&
9917           !IntegerValue.isMinSignedValue()) {
9918         return DiagnoseImpCast(S, E, T, CContext,
9919                                diag::warn_impcast_float_integer, PruneWarnings);
9920       }
9921     }
9922     // Warn on evaluatable floating point expression to integer conversion.
9923     DiagID = diag::warn_impcast_float_to_integer;
9924   }
9925 
9926   // FIXME: Force the precision of the source value down so we don't print
9927   // digits which are usually useless (we don't really care here if we
9928   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
9929   // would automatically print the shortest representation, but it's a bit
9930   // tricky to implement.
9931   SmallString<16> PrettySourceValue;
9932   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
9933   precision = (precision * 59 + 195) / 196;
9934   Value.toString(PrettySourceValue, precision);
9935 
9936   SmallString<16> PrettyTargetValue;
9937   if (IsBool)
9938     PrettyTargetValue = Value.isZero() ? "false" : "true";
9939   else
9940     IntegerValue.toString(PrettyTargetValue);
9941 
9942   if (PruneWarnings) {
9943     S.DiagRuntimeBehavior(E->getExprLoc(), E,
9944                           S.PDiag(DiagID)
9945                               << E->getType() << T.getUnqualifiedType()
9946                               << PrettySourceValue << PrettyTargetValue
9947                               << E->getSourceRange() << SourceRange(CContext));
9948   } else {
9949     S.Diag(E->getExprLoc(), DiagID)
9950         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
9951         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
9952   }
9953 }
9954 
9955 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
9956                                       IntRange Range) {
9957   if (!Range.Width) return "0";
9958 
9959   llvm::APSInt ValueInRange = Value;
9960   ValueInRange.setIsSigned(!Range.NonNegative);
9961   ValueInRange = ValueInRange.trunc(Range.Width);
9962   return ValueInRange.toString(10);
9963 }
9964 
9965 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
9966   if (!isa<ImplicitCastExpr>(Ex))
9967     return false;
9968 
9969   Expr *InnerE = Ex->IgnoreParenImpCasts();
9970   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
9971   const Type *Source =
9972     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
9973   if (Target->isDependentType())
9974     return false;
9975 
9976   const BuiltinType *FloatCandidateBT =
9977     dyn_cast<BuiltinType>(ToBool ? Source : Target);
9978   const Type *BoolCandidateType = ToBool ? Target : Source;
9979 
9980   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
9981           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
9982 }
9983 
9984 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
9985                                              SourceLocation CC) {
9986   unsigned NumArgs = TheCall->getNumArgs();
9987   for (unsigned i = 0; i < NumArgs; ++i) {
9988     Expr *CurrA = TheCall->getArg(i);
9989     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
9990       continue;
9991 
9992     bool IsSwapped = ((i > 0) &&
9993         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
9994     IsSwapped |= ((i < (NumArgs - 1)) &&
9995         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
9996     if (IsSwapped) {
9997       // Warn on this floating-point to bool conversion.
9998       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
9999                       CurrA->getType(), CC,
10000                       diag::warn_impcast_floating_point_to_bool);
10001     }
10002   }
10003 }
10004 
10005 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
10006                                    SourceLocation CC) {
10007   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
10008                         E->getExprLoc()))
10009     return;
10010 
10011   // Don't warn on functions which have return type nullptr_t.
10012   if (isa<CallExpr>(E))
10013     return;
10014 
10015   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
10016   const Expr::NullPointerConstantKind NullKind =
10017       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
10018   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
10019     return;
10020 
10021   // Return if target type is a safe conversion.
10022   if (T->isAnyPointerType() || T->isBlockPointerType() ||
10023       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
10024     return;
10025 
10026   SourceLocation Loc = E->getSourceRange().getBegin();
10027 
10028   // Venture through the macro stacks to get to the source of macro arguments.
10029   // The new location is a better location than the complete location that was
10030   // passed in.
10031   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
10032   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
10033 
10034   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
10035   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
10036     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
10037         Loc, S.SourceMgr, S.getLangOpts());
10038     if (MacroName == "NULL")
10039       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
10040   }
10041 
10042   // Only warn if the null and context location are in the same macro expansion.
10043   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
10044     return;
10045 
10046   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
10047       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
10048       << FixItHint::CreateReplacement(Loc,
10049                                       S.getFixItZeroLiteralForType(T, Loc));
10050 }
10051 
10052 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
10053                                   ObjCArrayLiteral *ArrayLiteral);
10054 
10055 static void
10056 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
10057                            ObjCDictionaryLiteral *DictionaryLiteral);
10058 
10059 /// Check a single element within a collection literal against the
10060 /// target element type.
10061 static void checkObjCCollectionLiteralElement(Sema &S,
10062                                               QualType TargetElementType,
10063                                               Expr *Element,
10064                                               unsigned ElementKind) {
10065   // Skip a bitcast to 'id' or qualified 'id'.
10066   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
10067     if (ICE->getCastKind() == CK_BitCast &&
10068         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
10069       Element = ICE->getSubExpr();
10070   }
10071 
10072   QualType ElementType = Element->getType();
10073   ExprResult ElementResult(Element);
10074   if (ElementType->getAs<ObjCObjectPointerType>() &&
10075       S.CheckSingleAssignmentConstraints(TargetElementType,
10076                                          ElementResult,
10077                                          false, false)
10078         != Sema::Compatible) {
10079     S.Diag(Element->getLocStart(),
10080            diag::warn_objc_collection_literal_element)
10081       << ElementType << ElementKind << TargetElementType
10082       << Element->getSourceRange();
10083   }
10084 
10085   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
10086     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
10087   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
10088     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
10089 }
10090 
10091 /// Check an Objective-C array literal being converted to the given
10092 /// target type.
10093 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
10094                                   ObjCArrayLiteral *ArrayLiteral) {
10095   if (!S.NSArrayDecl)
10096     return;
10097 
10098   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
10099   if (!TargetObjCPtr)
10100     return;
10101 
10102   if (TargetObjCPtr->isUnspecialized() ||
10103       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
10104         != S.NSArrayDecl->getCanonicalDecl())
10105     return;
10106 
10107   auto TypeArgs = TargetObjCPtr->getTypeArgs();
10108   if (TypeArgs.size() != 1)
10109     return;
10110 
10111   QualType TargetElementType = TypeArgs[0];
10112   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
10113     checkObjCCollectionLiteralElement(S, TargetElementType,
10114                                       ArrayLiteral->getElement(I),
10115                                       0);
10116   }
10117 }
10118 
10119 /// Check an Objective-C dictionary literal being converted to the given
10120 /// target type.
10121 static void
10122 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
10123                            ObjCDictionaryLiteral *DictionaryLiteral) {
10124   if (!S.NSDictionaryDecl)
10125     return;
10126 
10127   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
10128   if (!TargetObjCPtr)
10129     return;
10130 
10131   if (TargetObjCPtr->isUnspecialized() ||
10132       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
10133         != S.NSDictionaryDecl->getCanonicalDecl())
10134     return;
10135 
10136   auto TypeArgs = TargetObjCPtr->getTypeArgs();
10137   if (TypeArgs.size() != 2)
10138     return;
10139 
10140   QualType TargetKeyType = TypeArgs[0];
10141   QualType TargetObjectType = TypeArgs[1];
10142   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
10143     auto Element = DictionaryLiteral->getKeyValueElement(I);
10144     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
10145     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
10146   }
10147 }
10148 
10149 // Helper function to filter out cases for constant width constant conversion.
10150 // Don't warn on char array initialization or for non-decimal values.
10151 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
10152                                           SourceLocation CC) {
10153   // If initializing from a constant, and the constant starts with '0',
10154   // then it is a binary, octal, or hexadecimal.  Allow these constants
10155   // to fill all the bits, even if there is a sign change.
10156   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
10157     const char FirstLiteralCharacter =
10158         S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
10159     if (FirstLiteralCharacter == '0')
10160       return false;
10161   }
10162 
10163   // If the CC location points to a '{', and the type is char, then assume
10164   // assume it is an array initialization.
10165   if (CC.isValid() && T->isCharType()) {
10166     const char FirstContextCharacter =
10167         S.getSourceManager().getCharacterData(CC)[0];
10168     if (FirstContextCharacter == '{')
10169       return false;
10170   }
10171 
10172   return true;
10173 }
10174 
10175 static void
10176 CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
10177                         bool *ICContext = nullptr) {
10178   if (E->isTypeDependent() || E->isValueDependent()) return;
10179 
10180   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
10181   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
10182   if (Source == Target) return;
10183   if (Target->isDependentType()) return;
10184 
10185   // If the conversion context location is invalid don't complain. We also
10186   // don't want to emit a warning if the issue occurs from the expansion of
10187   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
10188   // delay this check as long as possible. Once we detect we are in that
10189   // scenario, we just return.
10190   if (CC.isInvalid())
10191     return;
10192 
10193   // Diagnose implicit casts to bool.
10194   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
10195     if (isa<StringLiteral>(E))
10196       // Warn on string literal to bool.  Checks for string literals in logical
10197       // and expressions, for instance, assert(0 && "error here"), are
10198       // prevented by a check in AnalyzeImplicitConversions().
10199       return DiagnoseImpCast(S, E, T, CC,
10200                              diag::warn_impcast_string_literal_to_bool);
10201     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
10202         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
10203       // This covers the literal expressions that evaluate to Objective-C
10204       // objects.
10205       return DiagnoseImpCast(S, E, T, CC,
10206                              diag::warn_impcast_objective_c_literal_to_bool);
10207     }
10208     if (Source->isPointerType() || Source->canDecayToPointerType()) {
10209       // Warn on pointer to bool conversion that is always true.
10210       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
10211                                      SourceRange(CC));
10212     }
10213   }
10214 
10215   // Check implicit casts from Objective-C collection literals to specialized
10216   // collection types, e.g., NSArray<NSString *> *.
10217   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
10218     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
10219   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
10220     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
10221 
10222   // Strip vector types.
10223   if (isa<VectorType>(Source)) {
10224     if (!isa<VectorType>(Target)) {
10225       if (S.SourceMgr.isInSystemMacro(CC))
10226         return;
10227       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
10228     }
10229 
10230     // If the vector cast is cast between two vectors of the same size, it is
10231     // a bitcast, not a conversion.
10232     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
10233       return;
10234 
10235     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
10236     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
10237   }
10238   if (auto VecTy = dyn_cast<VectorType>(Target))
10239     Target = VecTy->getElementType().getTypePtr();
10240 
10241   // Strip complex types.
10242   if (isa<ComplexType>(Source)) {
10243     if (!isa<ComplexType>(Target)) {
10244       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
10245         return;
10246 
10247       return DiagnoseImpCast(S, E, T, CC,
10248                              S.getLangOpts().CPlusPlus
10249                                  ? diag::err_impcast_complex_scalar
10250                                  : diag::warn_impcast_complex_scalar);
10251     }
10252 
10253     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
10254     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
10255   }
10256 
10257   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
10258   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
10259 
10260   // If the source is floating point...
10261   if (SourceBT && SourceBT->isFloatingPoint()) {
10262     // ...and the target is floating point...
10263     if (TargetBT && TargetBT->isFloatingPoint()) {
10264       // ...then warn if we're dropping FP rank.
10265 
10266       // Builtin FP kinds are ordered by increasing FP rank.
10267       if (SourceBT->getKind() > TargetBT->getKind()) {
10268         // Don't warn about float constants that are precisely
10269         // representable in the target type.
10270         Expr::EvalResult result;
10271         if (E->EvaluateAsRValue(result, S.Context)) {
10272           // Value might be a float, a float vector, or a float complex.
10273           if (IsSameFloatAfterCast(result.Val,
10274                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
10275                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
10276             return;
10277         }
10278 
10279         if (S.SourceMgr.isInSystemMacro(CC))
10280           return;
10281 
10282         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
10283       }
10284       // ... or possibly if we're increasing rank, too
10285       else if (TargetBT->getKind() > SourceBT->getKind()) {
10286         if (S.SourceMgr.isInSystemMacro(CC))
10287           return;
10288 
10289         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
10290       }
10291       return;
10292     }
10293 
10294     // If the target is integral, always warn.
10295     if (TargetBT && TargetBT->isInteger()) {
10296       if (S.SourceMgr.isInSystemMacro(CC))
10297         return;
10298 
10299       DiagnoseFloatingImpCast(S, E, T, CC);
10300     }
10301 
10302     // Detect the case where a call result is converted from floating-point to
10303     // to bool, and the final argument to the call is converted from bool, to
10304     // discover this typo:
10305     //
10306     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
10307     //
10308     // FIXME: This is an incredibly special case; is there some more general
10309     // way to detect this class of misplaced-parentheses bug?
10310     if (Target->isBooleanType() && isa<CallExpr>(E)) {
10311       // Check last argument of function call to see if it is an
10312       // implicit cast from a type matching the type the result
10313       // is being cast to.
10314       CallExpr *CEx = cast<CallExpr>(E);
10315       if (unsigned NumArgs = CEx->getNumArgs()) {
10316         Expr *LastA = CEx->getArg(NumArgs - 1);
10317         Expr *InnerE = LastA->IgnoreParenImpCasts();
10318         if (isa<ImplicitCastExpr>(LastA) &&
10319             InnerE->getType()->isBooleanType()) {
10320           // Warn on this floating-point to bool conversion
10321           DiagnoseImpCast(S, E, T, CC,
10322                           diag::warn_impcast_floating_point_to_bool);
10323         }
10324       }
10325     }
10326     return;
10327   }
10328 
10329   DiagnoseNullConversion(S, E, T, CC);
10330 
10331   S.DiscardMisalignedMemberAddress(Target, E);
10332 
10333   if (!Source->isIntegerType() || !Target->isIntegerType())
10334     return;
10335 
10336   // TODO: remove this early return once the false positives for constant->bool
10337   // in templates, macros, etc, are reduced or removed.
10338   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
10339     return;
10340 
10341   IntRange SourceRange = GetExprRange(S.Context, E);
10342   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
10343 
10344   if (SourceRange.Width > TargetRange.Width) {
10345     // If the source is a constant, use a default-on diagnostic.
10346     // TODO: this should happen for bitfield stores, too.
10347     llvm::APSInt Value(32);
10348     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
10349       if (S.SourceMgr.isInSystemMacro(CC))
10350         return;
10351 
10352       std::string PrettySourceValue = Value.toString(10);
10353       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
10354 
10355       S.DiagRuntimeBehavior(E->getExprLoc(), E,
10356         S.PDiag(diag::warn_impcast_integer_precision_constant)
10357             << PrettySourceValue << PrettyTargetValue
10358             << E->getType() << T << E->getSourceRange()
10359             << clang::SourceRange(CC));
10360       return;
10361     }
10362 
10363     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
10364     if (S.SourceMgr.isInSystemMacro(CC))
10365       return;
10366 
10367     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
10368       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
10369                              /* pruneControlFlow */ true);
10370     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
10371   }
10372 
10373   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
10374       SourceRange.NonNegative && Source->isSignedIntegerType()) {
10375     // Warn when doing a signed to signed conversion, warn if the positive
10376     // source value is exactly the width of the target type, which will
10377     // cause a negative value to be stored.
10378 
10379     llvm::APSInt Value;
10380     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
10381         !S.SourceMgr.isInSystemMacro(CC)) {
10382       if (isSameWidthConstantConversion(S, E, T, CC)) {
10383         std::string PrettySourceValue = Value.toString(10);
10384         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
10385 
10386         S.DiagRuntimeBehavior(
10387             E->getExprLoc(), E,
10388             S.PDiag(diag::warn_impcast_integer_precision_constant)
10389                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
10390                 << E->getSourceRange() << clang::SourceRange(CC));
10391         return;
10392       }
10393     }
10394 
10395     // Fall through for non-constants to give a sign conversion warning.
10396   }
10397 
10398   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
10399       (!TargetRange.NonNegative && SourceRange.NonNegative &&
10400        SourceRange.Width == TargetRange.Width)) {
10401     if (S.SourceMgr.isInSystemMacro(CC))
10402       return;
10403 
10404     unsigned DiagID = diag::warn_impcast_integer_sign;
10405 
10406     // Traditionally, gcc has warned about this under -Wsign-compare.
10407     // We also want to warn about it in -Wconversion.
10408     // So if -Wconversion is off, use a completely identical diagnostic
10409     // in the sign-compare group.
10410     // The conditional-checking code will
10411     if (ICContext) {
10412       DiagID = diag::warn_impcast_integer_sign_conditional;
10413       *ICContext = true;
10414     }
10415 
10416     return DiagnoseImpCast(S, E, T, CC, DiagID);
10417   }
10418 
10419   // Diagnose conversions between different enumeration types.
10420   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
10421   // type, to give us better diagnostics.
10422   QualType SourceType = E->getType();
10423   if (!S.getLangOpts().CPlusPlus) {
10424     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10425       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
10426         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
10427         SourceType = S.Context.getTypeDeclType(Enum);
10428         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
10429       }
10430   }
10431 
10432   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
10433     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
10434       if (SourceEnum->getDecl()->hasNameForLinkage() &&
10435           TargetEnum->getDecl()->hasNameForLinkage() &&
10436           SourceEnum != TargetEnum) {
10437         if (S.SourceMgr.isInSystemMacro(CC))
10438           return;
10439 
10440         return DiagnoseImpCast(S, E, SourceType, T, CC,
10441                                diag::warn_impcast_different_enum_types);
10442       }
10443 }
10444 
10445 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
10446                                      SourceLocation CC, QualType T);
10447 
10448 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
10449                                     SourceLocation CC, bool &ICContext) {
10450   E = E->IgnoreParenImpCasts();
10451 
10452   if (isa<ConditionalOperator>(E))
10453     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
10454 
10455   AnalyzeImplicitConversions(S, E, CC);
10456   if (E->getType() != T)
10457     return CheckImplicitConversion(S, E, T, CC, &ICContext);
10458 }
10459 
10460 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
10461                                      SourceLocation CC, QualType T) {
10462   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
10463 
10464   bool Suspicious = false;
10465   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
10466   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
10467 
10468   // If -Wconversion would have warned about either of the candidates
10469   // for a signedness conversion to the context type...
10470   if (!Suspicious) return;
10471 
10472   // ...but it's currently ignored...
10473   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
10474     return;
10475 
10476   // ...then check whether it would have warned about either of the
10477   // candidates for a signedness conversion to the condition type.
10478   if (E->getType() == T) return;
10479 
10480   Suspicious = false;
10481   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
10482                           E->getType(), CC, &Suspicious);
10483   if (!Suspicious)
10484     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
10485                             E->getType(), CC, &Suspicious);
10486 }
10487 
10488 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10489 /// Input argument E is a logical expression.
10490 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
10491   if (S.getLangOpts().Bool)
10492     return;
10493   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
10494 }
10495 
10496 /// AnalyzeImplicitConversions - Find and report any interesting
10497 /// implicit conversions in the given expression.  There are a couple
10498 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
10499 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
10500                                        SourceLocation CC) {
10501   QualType T = OrigE->getType();
10502   Expr *E = OrigE->IgnoreParenImpCasts();
10503 
10504   if (E->isTypeDependent() || E->isValueDependent())
10505     return;
10506 
10507   // For conditional operators, we analyze the arguments as if they
10508   // were being fed directly into the output.
10509   if (isa<ConditionalOperator>(E)) {
10510     ConditionalOperator *CO = cast<ConditionalOperator>(E);
10511     CheckConditionalOperator(S, CO, CC, T);
10512     return;
10513   }
10514 
10515   // Check implicit argument conversions for function calls.
10516   if (CallExpr *Call = dyn_cast<CallExpr>(E))
10517     CheckImplicitArgumentConversions(S, Call, CC);
10518 
10519   // Go ahead and check any implicit conversions we might have skipped.
10520   // The non-canonical typecheck is just an optimization;
10521   // CheckImplicitConversion will filter out dead implicit conversions.
10522   if (E->getType() != T)
10523     CheckImplicitConversion(S, E, T, CC);
10524 
10525   // Now continue drilling into this expression.
10526 
10527   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
10528     // The bound subexpressions in a PseudoObjectExpr are not reachable
10529     // as transitive children.
10530     // FIXME: Use a more uniform representation for this.
10531     for (auto *SE : POE->semantics())
10532       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
10533         AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
10534   }
10535 
10536   // Skip past explicit casts.
10537   if (isa<ExplicitCastExpr>(E)) {
10538     E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
10539     return AnalyzeImplicitConversions(S, E, CC);
10540   }
10541 
10542   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10543     // Do a somewhat different check with comparison operators.
10544     if (BO->isComparisonOp())
10545       return AnalyzeComparison(S, BO);
10546 
10547     // And with simple assignments.
10548     if (BO->getOpcode() == BO_Assign)
10549       return AnalyzeAssignment(S, BO);
10550     // And with compound assignments.
10551     if (BO->isAssignmentOp())
10552       return AnalyzeCompoundAssignment(S, BO);
10553   }
10554 
10555   // These break the otherwise-useful invariant below.  Fortunately,
10556   // we don't really need to recurse into them, because any internal
10557   // expressions should have been analyzed already when they were
10558   // built into statements.
10559   if (isa<StmtExpr>(E)) return;
10560 
10561   // Don't descend into unevaluated contexts.
10562   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
10563 
10564   // Now just recurse over the expression's children.
10565   CC = E->getExprLoc();
10566   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
10567   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
10568   for (Stmt *SubStmt : E->children()) {
10569     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
10570     if (!ChildExpr)
10571       continue;
10572 
10573     if (IsLogicalAndOperator &&
10574         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
10575       // Ignore checking string literals that are in logical and operators.
10576       // This is a common pattern for asserts.
10577       continue;
10578     AnalyzeImplicitConversions(S, ChildExpr, CC);
10579   }
10580 
10581   if (BO && BO->isLogicalOp()) {
10582     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
10583     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
10584       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
10585 
10586     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
10587     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
10588       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
10589   }
10590 
10591   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
10592     if (U->getOpcode() == UO_LNot)
10593       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
10594 }
10595 
10596 /// Diagnose integer type and any valid implicit conversion to it.
10597 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
10598   // Taking into account implicit conversions,
10599   // allow any integer.
10600   if (!E->getType()->isIntegerType()) {
10601     S.Diag(E->getLocStart(),
10602            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
10603     return true;
10604   }
10605   // Potentially emit standard warnings for implicit conversions if enabled
10606   // using -Wconversion.
10607   CheckImplicitConversion(S, E, IntT, E->getLocStart());
10608   return false;
10609 }
10610 
10611 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
10612 // Returns true when emitting a warning about taking the address of a reference.
10613 static bool CheckForReference(Sema &SemaRef, const Expr *E,
10614                               const PartialDiagnostic &PD) {
10615   E = E->IgnoreParenImpCasts();
10616 
10617   const FunctionDecl *FD = nullptr;
10618 
10619   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10620     if (!DRE->getDecl()->getType()->isReferenceType())
10621       return false;
10622   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10623     if (!M->getMemberDecl()->getType()->isReferenceType())
10624       return false;
10625   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
10626     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
10627       return false;
10628     FD = Call->getDirectCallee();
10629   } else {
10630     return false;
10631   }
10632 
10633   SemaRef.Diag(E->getExprLoc(), PD);
10634 
10635   // If possible, point to location of function.
10636   if (FD) {
10637     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
10638   }
10639 
10640   return true;
10641 }
10642 
10643 // Returns true if the SourceLocation is expanded from any macro body.
10644 // Returns false if the SourceLocation is invalid, is from not in a macro
10645 // expansion, or is from expanded from a top-level macro argument.
10646 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
10647   if (Loc.isInvalid())
10648     return false;
10649 
10650   while (Loc.isMacroID()) {
10651     if (SM.isMacroBodyExpansion(Loc))
10652       return true;
10653     Loc = SM.getImmediateMacroCallerLoc(Loc);
10654   }
10655 
10656   return false;
10657 }
10658 
10659 /// Diagnose pointers that are always non-null.
10660 /// \param E the expression containing the pointer
10661 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
10662 /// compared to a null pointer
10663 /// \param IsEqual True when the comparison is equal to a null pointer
10664 /// \param Range Extra SourceRange to highlight in the diagnostic
10665 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
10666                                         Expr::NullPointerConstantKind NullKind,
10667                                         bool IsEqual, SourceRange Range) {
10668   if (!E)
10669     return;
10670 
10671   // Don't warn inside macros.
10672   if (E->getExprLoc().isMacroID()) {
10673     const SourceManager &SM = getSourceManager();
10674     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
10675         IsInAnyMacroBody(SM, Range.getBegin()))
10676       return;
10677   }
10678   E = E->IgnoreImpCasts();
10679 
10680   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
10681 
10682   if (isa<CXXThisExpr>(E)) {
10683     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
10684                                 : diag::warn_this_bool_conversion;
10685     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
10686     return;
10687   }
10688 
10689   bool IsAddressOf = false;
10690 
10691   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10692     if (UO->getOpcode() != UO_AddrOf)
10693       return;
10694     IsAddressOf = true;
10695     E = UO->getSubExpr();
10696   }
10697 
10698   if (IsAddressOf) {
10699     unsigned DiagID = IsCompare
10700                           ? diag::warn_address_of_reference_null_compare
10701                           : diag::warn_address_of_reference_bool_conversion;
10702     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
10703                                          << IsEqual;
10704     if (CheckForReference(*this, E, PD)) {
10705       return;
10706     }
10707   }
10708 
10709   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
10710     bool IsParam = isa<NonNullAttr>(NonnullAttr);
10711     std::string Str;
10712     llvm::raw_string_ostream S(Str);
10713     E->printPretty(S, nullptr, getPrintingPolicy());
10714     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
10715                                 : diag::warn_cast_nonnull_to_bool;
10716     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
10717       << E->getSourceRange() << Range << IsEqual;
10718     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
10719   };
10720 
10721   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
10722   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
10723     if (auto *Callee = Call->getDirectCallee()) {
10724       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
10725         ComplainAboutNonnullParamOrCall(A);
10726         return;
10727       }
10728     }
10729   }
10730 
10731   // Expect to find a single Decl.  Skip anything more complicated.
10732   ValueDecl *D = nullptr;
10733   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
10734     D = R->getDecl();
10735   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10736     D = M->getMemberDecl();
10737   }
10738 
10739   // Weak Decls can be null.
10740   if (!D || D->isWeak())
10741     return;
10742 
10743   // Check for parameter decl with nonnull attribute
10744   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
10745     if (getCurFunction() &&
10746         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
10747       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
10748         ComplainAboutNonnullParamOrCall(A);
10749         return;
10750       }
10751 
10752       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
10753         auto ParamIter = llvm::find(FD->parameters(), PV);
10754         assert(ParamIter != FD->param_end());
10755         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
10756 
10757         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
10758           if (!NonNull->args_size()) {
10759               ComplainAboutNonnullParamOrCall(NonNull);
10760               return;
10761           }
10762 
10763           for (const ParamIdx &ArgNo : NonNull->args()) {
10764             if (ArgNo.getASTIndex() == ParamNo) {
10765               ComplainAboutNonnullParamOrCall(NonNull);
10766               return;
10767             }
10768           }
10769         }
10770       }
10771     }
10772   }
10773 
10774   QualType T = D->getType();
10775   const bool IsArray = T->isArrayType();
10776   const bool IsFunction = T->isFunctionType();
10777 
10778   // Address of function is used to silence the function warning.
10779   if (IsAddressOf && IsFunction) {
10780     return;
10781   }
10782 
10783   // Found nothing.
10784   if (!IsAddressOf && !IsFunction && !IsArray)
10785     return;
10786 
10787   // Pretty print the expression for the diagnostic.
10788   std::string Str;
10789   llvm::raw_string_ostream S(Str);
10790   E->printPretty(S, nullptr, getPrintingPolicy());
10791 
10792   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
10793                               : diag::warn_impcast_pointer_to_bool;
10794   enum {
10795     AddressOf,
10796     FunctionPointer,
10797     ArrayPointer
10798   } DiagType;
10799   if (IsAddressOf)
10800     DiagType = AddressOf;
10801   else if (IsFunction)
10802     DiagType = FunctionPointer;
10803   else if (IsArray)
10804     DiagType = ArrayPointer;
10805   else
10806     llvm_unreachable("Could not determine diagnostic.");
10807   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
10808                                 << Range << IsEqual;
10809 
10810   if (!IsFunction)
10811     return;
10812 
10813   // Suggest '&' to silence the function warning.
10814   Diag(E->getExprLoc(), diag::note_function_warning_silence)
10815       << FixItHint::CreateInsertion(E->getLocStart(), "&");
10816 
10817   // Check to see if '()' fixit should be emitted.
10818   QualType ReturnType;
10819   UnresolvedSet<4> NonTemplateOverloads;
10820   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
10821   if (ReturnType.isNull())
10822     return;
10823 
10824   if (IsCompare) {
10825     // There are two cases here.  If there is null constant, the only suggest
10826     // for a pointer return type.  If the null is 0, then suggest if the return
10827     // type is a pointer or an integer type.
10828     if (!ReturnType->isPointerType()) {
10829       if (NullKind == Expr::NPCK_ZeroExpression ||
10830           NullKind == Expr::NPCK_ZeroLiteral) {
10831         if (!ReturnType->isIntegerType())
10832           return;
10833       } else {
10834         return;
10835       }
10836     }
10837   } else { // !IsCompare
10838     // For function to bool, only suggest if the function pointer has bool
10839     // return type.
10840     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
10841       return;
10842   }
10843   Diag(E->getExprLoc(), diag::note_function_to_function_call)
10844       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
10845 }
10846 
10847 /// Diagnoses "dangerous" implicit conversions within the given
10848 /// expression (which is a full expression).  Implements -Wconversion
10849 /// and -Wsign-compare.
10850 ///
10851 /// \param CC the "context" location of the implicit conversion, i.e.
10852 ///   the most location of the syntactic entity requiring the implicit
10853 ///   conversion
10854 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
10855   // Don't diagnose in unevaluated contexts.
10856   if (isUnevaluatedContext())
10857     return;
10858 
10859   // Don't diagnose for value- or type-dependent expressions.
10860   if (E->isTypeDependent() || E->isValueDependent())
10861     return;
10862 
10863   // Check for array bounds violations in cases where the check isn't triggered
10864   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
10865   // ArraySubscriptExpr is on the RHS of a variable initialization.
10866   CheckArrayAccess(E);
10867 
10868   // This is not the right CC for (e.g.) a variable initialization.
10869   AnalyzeImplicitConversions(*this, E, CC);
10870 }
10871 
10872 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10873 /// Input argument E is a logical expression.
10874 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
10875   ::CheckBoolLikeConversion(*this, E, CC);
10876 }
10877 
10878 /// Diagnose when expression is an integer constant expression and its evaluation
10879 /// results in integer overflow
10880 void Sema::CheckForIntOverflow (Expr *E) {
10881   // Use a work list to deal with nested struct initializers.
10882   SmallVector<Expr *, 2> Exprs(1, E);
10883 
10884   do {
10885     Expr *OriginalE = Exprs.pop_back_val();
10886     Expr *E = OriginalE->IgnoreParenCasts();
10887 
10888     if (isa<BinaryOperator>(E)) {
10889       E->EvaluateForOverflow(Context);
10890       continue;
10891     }
10892 
10893     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
10894       Exprs.append(InitList->inits().begin(), InitList->inits().end());
10895     else if (isa<ObjCBoxedExpr>(OriginalE))
10896       E->EvaluateForOverflow(Context);
10897     else if (auto Call = dyn_cast<CallExpr>(E))
10898       Exprs.append(Call->arg_begin(), Call->arg_end());
10899     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
10900       Exprs.append(Message->arg_begin(), Message->arg_end());
10901   } while (!Exprs.empty());
10902 }
10903 
10904 namespace {
10905 
10906 /// Visitor for expressions which looks for unsequenced operations on the
10907 /// same object.
10908 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
10909   using Base = EvaluatedExprVisitor<SequenceChecker>;
10910 
10911   /// A tree of sequenced regions within an expression. Two regions are
10912   /// unsequenced if one is an ancestor or a descendent of the other. When we
10913   /// finish processing an expression with sequencing, such as a comma
10914   /// expression, we fold its tree nodes into its parent, since they are
10915   /// unsequenced with respect to nodes we will visit later.
10916   class SequenceTree {
10917     struct Value {
10918       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
10919       unsigned Parent : 31;
10920       unsigned Merged : 1;
10921     };
10922     SmallVector<Value, 8> Values;
10923 
10924   public:
10925     /// A region within an expression which may be sequenced with respect
10926     /// to some other region.
10927     class Seq {
10928       friend class SequenceTree;
10929 
10930       unsigned Index = 0;
10931 
10932       explicit Seq(unsigned N) : Index(N) {}
10933 
10934     public:
10935       Seq() = default;
10936     };
10937 
10938     SequenceTree() { Values.push_back(Value(0)); }
10939     Seq root() const { return Seq(0); }
10940 
10941     /// Create a new sequence of operations, which is an unsequenced
10942     /// subset of \p Parent. This sequence of operations is sequenced with
10943     /// respect to other children of \p Parent.
10944     Seq allocate(Seq Parent) {
10945       Values.push_back(Value(Parent.Index));
10946       return Seq(Values.size() - 1);
10947     }
10948 
10949     /// Merge a sequence of operations into its parent.
10950     void merge(Seq S) {
10951       Values[S.Index].Merged = true;
10952     }
10953 
10954     /// Determine whether two operations are unsequenced. This operation
10955     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
10956     /// should have been merged into its parent as appropriate.
10957     bool isUnsequenced(Seq Cur, Seq Old) {
10958       unsigned C = representative(Cur.Index);
10959       unsigned Target = representative(Old.Index);
10960       while (C >= Target) {
10961         if (C == Target)
10962           return true;
10963         C = Values[C].Parent;
10964       }
10965       return false;
10966     }
10967 
10968   private:
10969     /// Pick a representative for a sequence.
10970     unsigned representative(unsigned K) {
10971       if (Values[K].Merged)
10972         // Perform path compression as we go.
10973         return Values[K].Parent = representative(Values[K].Parent);
10974       return K;
10975     }
10976   };
10977 
10978   /// An object for which we can track unsequenced uses.
10979   using Object = NamedDecl *;
10980 
10981   /// Different flavors of object usage which we track. We only track the
10982   /// least-sequenced usage of each kind.
10983   enum UsageKind {
10984     /// A read of an object. Multiple unsequenced reads are OK.
10985     UK_Use,
10986 
10987     /// A modification of an object which is sequenced before the value
10988     /// computation of the expression, such as ++n in C++.
10989     UK_ModAsValue,
10990 
10991     /// A modification of an object which is not sequenced before the value
10992     /// computation of the expression, such as n++.
10993     UK_ModAsSideEffect,
10994 
10995     UK_Count = UK_ModAsSideEffect + 1
10996   };
10997 
10998   struct Usage {
10999     Expr *Use = nullptr;
11000     SequenceTree::Seq Seq;
11001 
11002     Usage() = default;
11003   };
11004 
11005   struct UsageInfo {
11006     Usage Uses[UK_Count];
11007 
11008     /// Have we issued a diagnostic for this variable already?
11009     bool Diagnosed = false;
11010 
11011     UsageInfo() = default;
11012   };
11013   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
11014 
11015   Sema &SemaRef;
11016 
11017   /// Sequenced regions within the expression.
11018   SequenceTree Tree;
11019 
11020   /// Declaration modifications and references which we have seen.
11021   UsageInfoMap UsageMap;
11022 
11023   /// The region we are currently within.
11024   SequenceTree::Seq Region;
11025 
11026   /// Filled in with declarations which were modified as a side-effect
11027   /// (that is, post-increment operations).
11028   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
11029 
11030   /// Expressions to check later. We defer checking these to reduce
11031   /// stack usage.
11032   SmallVectorImpl<Expr *> &WorkList;
11033 
11034   /// RAII object wrapping the visitation of a sequenced subexpression of an
11035   /// expression. At the end of this process, the side-effects of the evaluation
11036   /// become sequenced with respect to the value computation of the result, so
11037   /// we downgrade any UK_ModAsSideEffect within the evaluation to
11038   /// UK_ModAsValue.
11039   struct SequencedSubexpression {
11040     SequencedSubexpression(SequenceChecker &Self)
11041       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
11042       Self.ModAsSideEffect = &ModAsSideEffect;
11043     }
11044 
11045     ~SequencedSubexpression() {
11046       for (auto &M : llvm::reverse(ModAsSideEffect)) {
11047         UsageInfo &U = Self.UsageMap[M.first];
11048         auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
11049         Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
11050         SideEffectUsage = M.second;
11051       }
11052       Self.ModAsSideEffect = OldModAsSideEffect;
11053     }
11054 
11055     SequenceChecker &Self;
11056     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
11057     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
11058   };
11059 
11060   /// RAII object wrapping the visitation of a subexpression which we might
11061   /// choose to evaluate as a constant. If any subexpression is evaluated and
11062   /// found to be non-constant, this allows us to suppress the evaluation of
11063   /// the outer expression.
11064   class EvaluationTracker {
11065   public:
11066     EvaluationTracker(SequenceChecker &Self)
11067         : Self(Self), Prev(Self.EvalTracker) {
11068       Self.EvalTracker = this;
11069     }
11070 
11071     ~EvaluationTracker() {
11072       Self.EvalTracker = Prev;
11073       if (Prev)
11074         Prev->EvalOK &= EvalOK;
11075     }
11076 
11077     bool evaluate(const Expr *E, bool &Result) {
11078       if (!EvalOK || E->isValueDependent())
11079         return false;
11080       EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
11081       return EvalOK;
11082     }
11083 
11084   private:
11085     SequenceChecker &Self;
11086     EvaluationTracker *Prev;
11087     bool EvalOK = true;
11088   } *EvalTracker = nullptr;
11089 
11090   /// Find the object which is produced by the specified expression,
11091   /// if any.
11092   Object getObject(Expr *E, bool Mod) const {
11093     E = E->IgnoreParenCasts();
11094     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
11095       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
11096         return getObject(UO->getSubExpr(), Mod);
11097     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11098       if (BO->getOpcode() == BO_Comma)
11099         return getObject(BO->getRHS(), Mod);
11100       if (Mod && BO->isAssignmentOp())
11101         return getObject(BO->getLHS(), Mod);
11102     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
11103       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
11104       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
11105         return ME->getMemberDecl();
11106     } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11107       // FIXME: If this is a reference, map through to its value.
11108       return DRE->getDecl();
11109     return nullptr;
11110   }
11111 
11112   /// Note that an object was modified or used by an expression.
11113   void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
11114     Usage &U = UI.Uses[UK];
11115     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
11116       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
11117         ModAsSideEffect->push_back(std::make_pair(O, U));
11118       U.Use = Ref;
11119       U.Seq = Region;
11120     }
11121   }
11122 
11123   /// Check whether a modification or use conflicts with a prior usage.
11124   void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
11125                   bool IsModMod) {
11126     if (UI.Diagnosed)
11127       return;
11128 
11129     const Usage &U = UI.Uses[OtherKind];
11130     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
11131       return;
11132 
11133     Expr *Mod = U.Use;
11134     Expr *ModOrUse = Ref;
11135     if (OtherKind == UK_Use)
11136       std::swap(Mod, ModOrUse);
11137 
11138     SemaRef.Diag(Mod->getExprLoc(),
11139                  IsModMod ? diag::warn_unsequenced_mod_mod
11140                           : diag::warn_unsequenced_mod_use)
11141       << O << SourceRange(ModOrUse->getExprLoc());
11142     UI.Diagnosed = true;
11143   }
11144 
11145   void notePreUse(Object O, Expr *Use) {
11146     UsageInfo &U = UsageMap[O];
11147     // Uses conflict with other modifications.
11148     checkUsage(O, U, Use, UK_ModAsValue, false);
11149   }
11150 
11151   void notePostUse(Object O, Expr *Use) {
11152     UsageInfo &U = UsageMap[O];
11153     checkUsage(O, U, Use, UK_ModAsSideEffect, false);
11154     addUsage(U, O, Use, UK_Use);
11155   }
11156 
11157   void notePreMod(Object O, Expr *Mod) {
11158     UsageInfo &U = UsageMap[O];
11159     // Modifications conflict with other modifications and with uses.
11160     checkUsage(O, U, Mod, UK_ModAsValue, true);
11161     checkUsage(O, U, Mod, UK_Use, false);
11162   }
11163 
11164   void notePostMod(Object O, Expr *Use, UsageKind UK) {
11165     UsageInfo &U = UsageMap[O];
11166     checkUsage(O, U, Use, UK_ModAsSideEffect, true);
11167     addUsage(U, O, Use, UK);
11168   }
11169 
11170 public:
11171   SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
11172       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
11173     Visit(E);
11174   }
11175 
11176   void VisitStmt(Stmt *S) {
11177     // Skip all statements which aren't expressions for now.
11178   }
11179 
11180   void VisitExpr(Expr *E) {
11181     // By default, just recurse to evaluated subexpressions.
11182     Base::VisitStmt(E);
11183   }
11184 
11185   void VisitCastExpr(CastExpr *E) {
11186     Object O = Object();
11187     if (E->getCastKind() == CK_LValueToRValue)
11188       O = getObject(E->getSubExpr(), false);
11189 
11190     if (O)
11191       notePreUse(O, E);
11192     VisitExpr(E);
11193     if (O)
11194       notePostUse(O, E);
11195   }
11196 
11197   void VisitBinComma(BinaryOperator *BO) {
11198     // C++11 [expr.comma]p1:
11199     //   Every value computation and side effect associated with the left
11200     //   expression is sequenced before every value computation and side
11201     //   effect associated with the right expression.
11202     SequenceTree::Seq LHS = Tree.allocate(Region);
11203     SequenceTree::Seq RHS = Tree.allocate(Region);
11204     SequenceTree::Seq OldRegion = Region;
11205 
11206     {
11207       SequencedSubexpression SeqLHS(*this);
11208       Region = LHS;
11209       Visit(BO->getLHS());
11210     }
11211 
11212     Region = RHS;
11213     Visit(BO->getRHS());
11214 
11215     Region = OldRegion;
11216 
11217     // Forget that LHS and RHS are sequenced. They are both unsequenced
11218     // with respect to other stuff.
11219     Tree.merge(LHS);
11220     Tree.merge(RHS);
11221   }
11222 
11223   void VisitBinAssign(BinaryOperator *BO) {
11224     // The modification is sequenced after the value computation of the LHS
11225     // and RHS, so check it before inspecting the operands and update the
11226     // map afterwards.
11227     Object O = getObject(BO->getLHS(), true);
11228     if (!O)
11229       return VisitExpr(BO);
11230 
11231     notePreMod(O, BO);
11232 
11233     // C++11 [expr.ass]p7:
11234     //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
11235     //   only once.
11236     //
11237     // Therefore, for a compound assignment operator, O is considered used
11238     // everywhere except within the evaluation of E1 itself.
11239     if (isa<CompoundAssignOperator>(BO))
11240       notePreUse(O, BO);
11241 
11242     Visit(BO->getLHS());
11243 
11244     if (isa<CompoundAssignOperator>(BO))
11245       notePostUse(O, BO);
11246 
11247     Visit(BO->getRHS());
11248 
11249     // C++11 [expr.ass]p1:
11250     //   the assignment is sequenced [...] before the value computation of the
11251     //   assignment expression.
11252     // C11 6.5.16/3 has no such rule.
11253     notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
11254                                                        : UK_ModAsSideEffect);
11255   }
11256 
11257   void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
11258     VisitBinAssign(CAO);
11259   }
11260 
11261   void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
11262   void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
11263   void VisitUnaryPreIncDec(UnaryOperator *UO) {
11264     Object O = getObject(UO->getSubExpr(), true);
11265     if (!O)
11266       return VisitExpr(UO);
11267 
11268     notePreMod(O, UO);
11269     Visit(UO->getSubExpr());
11270     // C++11 [expr.pre.incr]p1:
11271     //   the expression ++x is equivalent to x+=1
11272     notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
11273                                                        : UK_ModAsSideEffect);
11274   }
11275 
11276   void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
11277   void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
11278   void VisitUnaryPostIncDec(UnaryOperator *UO) {
11279     Object O = getObject(UO->getSubExpr(), true);
11280     if (!O)
11281       return VisitExpr(UO);
11282 
11283     notePreMod(O, UO);
11284     Visit(UO->getSubExpr());
11285     notePostMod(O, UO, UK_ModAsSideEffect);
11286   }
11287 
11288   /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
11289   void VisitBinLOr(BinaryOperator *BO) {
11290     // The side-effects of the LHS of an '&&' are sequenced before the
11291     // value computation of the RHS, and hence before the value computation
11292     // of the '&&' itself, unless the LHS evaluates to zero. We treat them
11293     // as if they were unconditionally sequenced.
11294     EvaluationTracker Eval(*this);
11295     {
11296       SequencedSubexpression Sequenced(*this);
11297       Visit(BO->getLHS());
11298     }
11299 
11300     bool Result;
11301     if (Eval.evaluate(BO->getLHS(), Result)) {
11302       if (!Result)
11303         Visit(BO->getRHS());
11304     } else {
11305       // Check for unsequenced operations in the RHS, treating it as an
11306       // entirely separate evaluation.
11307       //
11308       // FIXME: If there are operations in the RHS which are unsequenced
11309       // with respect to operations outside the RHS, and those operations
11310       // are unconditionally evaluated, diagnose them.
11311       WorkList.push_back(BO->getRHS());
11312     }
11313   }
11314   void VisitBinLAnd(BinaryOperator *BO) {
11315     EvaluationTracker Eval(*this);
11316     {
11317       SequencedSubexpression Sequenced(*this);
11318       Visit(BO->getLHS());
11319     }
11320 
11321     bool Result;
11322     if (Eval.evaluate(BO->getLHS(), Result)) {
11323       if (Result)
11324         Visit(BO->getRHS());
11325     } else {
11326       WorkList.push_back(BO->getRHS());
11327     }
11328   }
11329 
11330   // Only visit the condition, unless we can be sure which subexpression will
11331   // be chosen.
11332   void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
11333     EvaluationTracker Eval(*this);
11334     {
11335       SequencedSubexpression Sequenced(*this);
11336       Visit(CO->getCond());
11337     }
11338 
11339     bool Result;
11340     if (Eval.evaluate(CO->getCond(), Result))
11341       Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
11342     else {
11343       WorkList.push_back(CO->getTrueExpr());
11344       WorkList.push_back(CO->getFalseExpr());
11345     }
11346   }
11347 
11348   void VisitCallExpr(CallExpr *CE) {
11349     // C++11 [intro.execution]p15:
11350     //   When calling a function [...], every value computation and side effect
11351     //   associated with any argument expression, or with the postfix expression
11352     //   designating the called function, is sequenced before execution of every
11353     //   expression or statement in the body of the function [and thus before
11354     //   the value computation of its result].
11355     SequencedSubexpression Sequenced(*this);
11356     Base::VisitCallExpr(CE);
11357 
11358     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
11359   }
11360 
11361   void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
11362     // This is a call, so all subexpressions are sequenced before the result.
11363     SequencedSubexpression Sequenced(*this);
11364 
11365     if (!CCE->isListInitialization())
11366       return VisitExpr(CCE);
11367 
11368     // In C++11, list initializations are sequenced.
11369     SmallVector<SequenceTree::Seq, 32> Elts;
11370     SequenceTree::Seq Parent = Region;
11371     for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
11372                                         E = CCE->arg_end();
11373          I != E; ++I) {
11374       Region = Tree.allocate(Parent);
11375       Elts.push_back(Region);
11376       Visit(*I);
11377     }
11378 
11379     // Forget that the initializers are sequenced.
11380     Region = Parent;
11381     for (unsigned I = 0; I < Elts.size(); ++I)
11382       Tree.merge(Elts[I]);
11383   }
11384 
11385   void VisitInitListExpr(InitListExpr *ILE) {
11386     if (!SemaRef.getLangOpts().CPlusPlus11)
11387       return VisitExpr(ILE);
11388 
11389     // In C++11, list initializations are sequenced.
11390     SmallVector<SequenceTree::Seq, 32> Elts;
11391     SequenceTree::Seq Parent = Region;
11392     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
11393       Expr *E = ILE->getInit(I);
11394       if (!E) continue;
11395       Region = Tree.allocate(Parent);
11396       Elts.push_back(Region);
11397       Visit(E);
11398     }
11399 
11400     // Forget that the initializers are sequenced.
11401     Region = Parent;
11402     for (unsigned I = 0; I < Elts.size(); ++I)
11403       Tree.merge(Elts[I]);
11404   }
11405 };
11406 
11407 } // namespace
11408 
11409 void Sema::CheckUnsequencedOperations(Expr *E) {
11410   SmallVector<Expr *, 8> WorkList;
11411   WorkList.push_back(E);
11412   while (!WorkList.empty()) {
11413     Expr *Item = WorkList.pop_back_val();
11414     SequenceChecker(*this, Item, WorkList);
11415   }
11416 }
11417 
11418 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
11419                               bool IsConstexpr) {
11420   CheckImplicitConversions(E, CheckLoc);
11421   if (!E->isInstantiationDependent())
11422     CheckUnsequencedOperations(E);
11423   if (!IsConstexpr && !E->isValueDependent())
11424     CheckForIntOverflow(E);
11425   DiagnoseMisalignedMembers();
11426 }
11427 
11428 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
11429                                        FieldDecl *BitField,
11430                                        Expr *Init) {
11431   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
11432 }
11433 
11434 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
11435                                          SourceLocation Loc) {
11436   if (!PType->isVariablyModifiedType())
11437     return;
11438   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
11439     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
11440     return;
11441   }
11442   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
11443     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
11444     return;
11445   }
11446   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
11447     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
11448     return;
11449   }
11450 
11451   const ArrayType *AT = S.Context.getAsArrayType(PType);
11452   if (!AT)
11453     return;
11454 
11455   if (AT->getSizeModifier() != ArrayType::Star) {
11456     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
11457     return;
11458   }
11459 
11460   S.Diag(Loc, diag::err_array_star_in_function_definition);
11461 }
11462 
11463 /// CheckParmsForFunctionDef - Check that the parameters of the given
11464 /// function are appropriate for the definition of a function. This
11465 /// takes care of any checks that cannot be performed on the
11466 /// declaration itself, e.g., that the types of each of the function
11467 /// parameters are complete.
11468 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
11469                                     bool CheckParameterNames) {
11470   bool HasInvalidParm = false;
11471   for (ParmVarDecl *Param : Parameters) {
11472     // C99 6.7.5.3p4: the parameters in a parameter type list in a
11473     // function declarator that is part of a function definition of
11474     // that function shall not have incomplete type.
11475     //
11476     // This is also C++ [dcl.fct]p6.
11477     if (!Param->isInvalidDecl() &&
11478         RequireCompleteType(Param->getLocation(), Param->getType(),
11479                             diag::err_typecheck_decl_incomplete_type)) {
11480       Param->setInvalidDecl();
11481       HasInvalidParm = true;
11482     }
11483 
11484     // C99 6.9.1p5: If the declarator includes a parameter type list, the
11485     // declaration of each parameter shall include an identifier.
11486     if (CheckParameterNames &&
11487         Param->getIdentifier() == nullptr &&
11488         !Param->isImplicit() &&
11489         !getLangOpts().CPlusPlus)
11490       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
11491 
11492     // C99 6.7.5.3p12:
11493     //   If the function declarator is not part of a definition of that
11494     //   function, parameters may have incomplete type and may use the [*]
11495     //   notation in their sequences of declarator specifiers to specify
11496     //   variable length array types.
11497     QualType PType = Param->getOriginalType();
11498     // FIXME: This diagnostic should point the '[*]' if source-location
11499     // information is added for it.
11500     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
11501 
11502     // If the parameter is a c++ class type and it has to be destructed in the
11503     // callee function, declare the destructor so that it can be called by the
11504     // callee function. Do not perform any direct access check on the dtor here.
11505     if (!Param->isInvalidDecl()) {
11506       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
11507         if (!ClassDecl->isInvalidDecl() &&
11508             !ClassDecl->hasIrrelevantDestructor() &&
11509             !ClassDecl->isDependentContext() &&
11510             ClassDecl->isParamDestroyedInCallee()) {
11511           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
11512           MarkFunctionReferenced(Param->getLocation(), Destructor);
11513           DiagnoseUseOfDecl(Destructor, Param->getLocation());
11514         }
11515       }
11516     }
11517 
11518     // Parameters with the pass_object_size attribute only need to be marked
11519     // constant at function definitions. Because we lack information about
11520     // whether we're on a declaration or definition when we're instantiating the
11521     // attribute, we need to check for constness here.
11522     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
11523       if (!Param->getType().isConstQualified())
11524         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
11525             << Attr->getSpelling() << 1;
11526   }
11527 
11528   return HasInvalidParm;
11529 }
11530 
11531 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
11532 /// or MemberExpr.
11533 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
11534                               ASTContext &Context) {
11535   if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
11536     return Context.getDeclAlign(DRE->getDecl());
11537 
11538   if (const auto *ME = dyn_cast<MemberExpr>(E))
11539     return Context.getDeclAlign(ME->getMemberDecl());
11540 
11541   return TypeAlign;
11542 }
11543 
11544 /// CheckCastAlign - Implements -Wcast-align, which warns when a
11545 /// pointer cast increases the alignment requirements.
11546 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
11547   // This is actually a lot of work to potentially be doing on every
11548   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
11549   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
11550     return;
11551 
11552   // Ignore dependent types.
11553   if (T->isDependentType() || Op->getType()->isDependentType())
11554     return;
11555 
11556   // Require that the destination be a pointer type.
11557   const PointerType *DestPtr = T->getAs<PointerType>();
11558   if (!DestPtr) return;
11559 
11560   // If the destination has alignment 1, we're done.
11561   QualType DestPointee = DestPtr->getPointeeType();
11562   if (DestPointee->isIncompleteType()) return;
11563   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
11564   if (DestAlign.isOne()) return;
11565 
11566   // Require that the source be a pointer type.
11567   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
11568   if (!SrcPtr) return;
11569   QualType SrcPointee = SrcPtr->getPointeeType();
11570 
11571   // Whitelist casts from cv void*.  We already implicitly
11572   // whitelisted casts to cv void*, since they have alignment 1.
11573   // Also whitelist casts involving incomplete types, which implicitly
11574   // includes 'void'.
11575   if (SrcPointee->isIncompleteType()) return;
11576 
11577   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
11578 
11579   if (auto *CE = dyn_cast<CastExpr>(Op)) {
11580     if (CE->getCastKind() == CK_ArrayToPointerDecay)
11581       SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
11582   } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
11583     if (UO->getOpcode() == UO_AddrOf)
11584       SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
11585   }
11586 
11587   if (SrcAlign >= DestAlign) return;
11588 
11589   Diag(TRange.getBegin(), diag::warn_cast_align)
11590     << Op->getType() << T
11591     << static_cast<unsigned>(SrcAlign.getQuantity())
11592     << static_cast<unsigned>(DestAlign.getQuantity())
11593     << TRange << Op->getSourceRange();
11594 }
11595 
11596 /// Check whether this array fits the idiom of a size-one tail padded
11597 /// array member of a struct.
11598 ///
11599 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
11600 /// commonly used to emulate flexible arrays in C89 code.
11601 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
11602                                     const NamedDecl *ND) {
11603   if (Size != 1 || !ND) return false;
11604 
11605   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
11606   if (!FD) return false;
11607 
11608   // Don't consider sizes resulting from macro expansions or template argument
11609   // substitution to form C89 tail-padded arrays.
11610 
11611   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
11612   while (TInfo) {
11613     TypeLoc TL = TInfo->getTypeLoc();
11614     // Look through typedefs.
11615     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
11616       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
11617       TInfo = TDL->getTypeSourceInfo();
11618       continue;
11619     }
11620     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
11621       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
11622       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
11623         return false;
11624     }
11625     break;
11626   }
11627 
11628   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
11629   if (!RD) return false;
11630   if (RD->isUnion()) return false;
11631   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
11632     if (!CRD->isStandardLayout()) return false;
11633   }
11634 
11635   // See if this is the last field decl in the record.
11636   const Decl *D = FD;
11637   while ((D = D->getNextDeclInContext()))
11638     if (isa<FieldDecl>(D))
11639       return false;
11640   return true;
11641 }
11642 
11643 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
11644                             const ArraySubscriptExpr *ASE,
11645                             bool AllowOnePastEnd, bool IndexNegated) {
11646   IndexExpr = IndexExpr->IgnoreParenImpCasts();
11647   if (IndexExpr->isValueDependent())
11648     return;
11649 
11650   const Type *EffectiveType =
11651       BaseExpr->getType()->getPointeeOrArrayElementType();
11652   BaseExpr = BaseExpr->IgnoreParenCasts();
11653   const ConstantArrayType *ArrayTy =
11654     Context.getAsConstantArrayType(BaseExpr->getType());
11655   if (!ArrayTy)
11656     return;
11657 
11658   llvm::APSInt index;
11659   if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
11660     return;
11661   if (IndexNegated)
11662     index = -index;
11663 
11664   const NamedDecl *ND = nullptr;
11665   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
11666     ND = DRE->getDecl();
11667   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
11668     ND = ME->getMemberDecl();
11669 
11670   if (index.isUnsigned() || !index.isNegative()) {
11671     llvm::APInt size = ArrayTy->getSize();
11672     if (!size.isStrictlyPositive())
11673       return;
11674 
11675     const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
11676     if (BaseType != EffectiveType) {
11677       // Make sure we're comparing apples to apples when comparing index to size
11678       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
11679       uint64_t array_typesize = Context.getTypeSize(BaseType);
11680       // Handle ptrarith_typesize being zero, such as when casting to void*
11681       if (!ptrarith_typesize) ptrarith_typesize = 1;
11682       if (ptrarith_typesize != array_typesize) {
11683         // There's a cast to a different size type involved
11684         uint64_t ratio = array_typesize / ptrarith_typesize;
11685         // TODO: Be smarter about handling cases where array_typesize is not a
11686         // multiple of ptrarith_typesize
11687         if (ptrarith_typesize * ratio == array_typesize)
11688           size *= llvm::APInt(size.getBitWidth(), ratio);
11689       }
11690     }
11691 
11692     if (size.getBitWidth() > index.getBitWidth())
11693       index = index.zext(size.getBitWidth());
11694     else if (size.getBitWidth() < index.getBitWidth())
11695       size = size.zext(index.getBitWidth());
11696 
11697     // For array subscripting the index must be less than size, but for pointer
11698     // arithmetic also allow the index (offset) to be equal to size since
11699     // computing the next address after the end of the array is legal and
11700     // commonly done e.g. in C++ iterators and range-based for loops.
11701     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
11702       return;
11703 
11704     // Also don't warn for arrays of size 1 which are members of some
11705     // structure. These are often used to approximate flexible arrays in C89
11706     // code.
11707     if (IsTailPaddedMemberArray(*this, size, ND))
11708       return;
11709 
11710     // Suppress the warning if the subscript expression (as identified by the
11711     // ']' location) and the index expression are both from macro expansions
11712     // within a system header.
11713     if (ASE) {
11714       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
11715           ASE->getRBracketLoc());
11716       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
11717         SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
11718             IndexExpr->getLocStart());
11719         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
11720           return;
11721       }
11722     }
11723 
11724     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
11725     if (ASE)
11726       DiagID = diag::warn_array_index_exceeds_bounds;
11727 
11728     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11729                         PDiag(DiagID) << index.toString(10, true)
11730                           << size.toString(10, true)
11731                           << (unsigned)size.getLimitedValue(~0U)
11732                           << IndexExpr->getSourceRange());
11733   } else {
11734     unsigned DiagID = diag::warn_array_index_precedes_bounds;
11735     if (!ASE) {
11736       DiagID = diag::warn_ptr_arith_precedes_bounds;
11737       if (index.isNegative()) index = -index;
11738     }
11739 
11740     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11741                         PDiag(DiagID) << index.toString(10, true)
11742                           << IndexExpr->getSourceRange());
11743   }
11744 
11745   if (!ND) {
11746     // Try harder to find a NamedDecl to point at in the note.
11747     while (const ArraySubscriptExpr *ASE =
11748            dyn_cast<ArraySubscriptExpr>(BaseExpr))
11749       BaseExpr = ASE->getBase()->IgnoreParenCasts();
11750     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
11751       ND = DRE->getDecl();
11752     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
11753       ND = ME->getMemberDecl();
11754   }
11755 
11756   if (ND)
11757     DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
11758                         PDiag(diag::note_array_index_out_of_bounds)
11759                           << ND->getDeclName());
11760 }
11761 
11762 void Sema::CheckArrayAccess(const Expr *expr) {
11763   int AllowOnePastEnd = 0;
11764   while (expr) {
11765     expr = expr->IgnoreParenImpCasts();
11766     switch (expr->getStmtClass()) {
11767       case Stmt::ArraySubscriptExprClass: {
11768         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
11769         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
11770                          AllowOnePastEnd > 0);
11771         expr = ASE->getBase();
11772         break;
11773       }
11774       case Stmt::MemberExprClass: {
11775         expr = cast<MemberExpr>(expr)->getBase();
11776         break;
11777       }
11778       case Stmt::OMPArraySectionExprClass: {
11779         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
11780         if (ASE->getLowerBound())
11781           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
11782                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
11783         return;
11784       }
11785       case Stmt::UnaryOperatorClass: {
11786         // Only unwrap the * and & unary operators
11787         const UnaryOperator *UO = cast<UnaryOperator>(expr);
11788         expr = UO->getSubExpr();
11789         switch (UO->getOpcode()) {
11790           case UO_AddrOf:
11791             AllowOnePastEnd++;
11792             break;
11793           case UO_Deref:
11794             AllowOnePastEnd--;
11795             break;
11796           default:
11797             return;
11798         }
11799         break;
11800       }
11801       case Stmt::ConditionalOperatorClass: {
11802         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
11803         if (const Expr *lhs = cond->getLHS())
11804           CheckArrayAccess(lhs);
11805         if (const Expr *rhs = cond->getRHS())
11806           CheckArrayAccess(rhs);
11807         return;
11808       }
11809       case Stmt::CXXOperatorCallExprClass: {
11810         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
11811         for (const auto *Arg : OCE->arguments())
11812           CheckArrayAccess(Arg);
11813         return;
11814       }
11815       default:
11816         return;
11817     }
11818   }
11819 }
11820 
11821 //===--- CHECK: Objective-C retain cycles ----------------------------------//
11822 
11823 namespace {
11824 
11825 struct RetainCycleOwner {
11826   VarDecl *Variable = nullptr;
11827   SourceRange Range;
11828   SourceLocation Loc;
11829   bool Indirect = false;
11830 
11831   RetainCycleOwner() = default;
11832 
11833   void setLocsFrom(Expr *e) {
11834     Loc = e->getExprLoc();
11835     Range = e->getSourceRange();
11836   }
11837 };
11838 
11839 } // namespace
11840 
11841 /// Consider whether capturing the given variable can possibly lead to
11842 /// a retain cycle.
11843 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
11844   // In ARC, it's captured strongly iff the variable has __strong
11845   // lifetime.  In MRR, it's captured strongly if the variable is
11846   // __block and has an appropriate type.
11847   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11848     return false;
11849 
11850   owner.Variable = var;
11851   if (ref)
11852     owner.setLocsFrom(ref);
11853   return true;
11854 }
11855 
11856 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
11857   while (true) {
11858     e = e->IgnoreParens();
11859     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
11860       switch (cast->getCastKind()) {
11861       case CK_BitCast:
11862       case CK_LValueBitCast:
11863       case CK_LValueToRValue:
11864       case CK_ARCReclaimReturnedObject:
11865         e = cast->getSubExpr();
11866         continue;
11867 
11868       default:
11869         return false;
11870       }
11871     }
11872 
11873     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
11874       ObjCIvarDecl *ivar = ref->getDecl();
11875       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11876         return false;
11877 
11878       // Try to find a retain cycle in the base.
11879       if (!findRetainCycleOwner(S, ref->getBase(), owner))
11880         return false;
11881 
11882       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
11883       owner.Indirect = true;
11884       return true;
11885     }
11886 
11887     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
11888       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
11889       if (!var) return false;
11890       return considerVariable(var, ref, owner);
11891     }
11892 
11893     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
11894       if (member->isArrow()) return false;
11895 
11896       // Don't count this as an indirect ownership.
11897       e = member->getBase();
11898       continue;
11899     }
11900 
11901     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
11902       // Only pay attention to pseudo-objects on property references.
11903       ObjCPropertyRefExpr *pre
11904         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
11905                                               ->IgnoreParens());
11906       if (!pre) return false;
11907       if (pre->isImplicitProperty()) return false;
11908       ObjCPropertyDecl *property = pre->getExplicitProperty();
11909       if (!property->isRetaining() &&
11910           !(property->getPropertyIvarDecl() &&
11911             property->getPropertyIvarDecl()->getType()
11912               .getObjCLifetime() == Qualifiers::OCL_Strong))
11913           return false;
11914 
11915       owner.Indirect = true;
11916       if (pre->isSuperReceiver()) {
11917         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
11918         if (!owner.Variable)
11919           return false;
11920         owner.Loc = pre->getLocation();
11921         owner.Range = pre->getSourceRange();
11922         return true;
11923       }
11924       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
11925                               ->getSourceExpr());
11926       continue;
11927     }
11928 
11929     // Array ivars?
11930 
11931     return false;
11932   }
11933 }
11934 
11935 namespace {
11936 
11937   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
11938     ASTContext &Context;
11939     VarDecl *Variable;
11940     Expr *Capturer = nullptr;
11941     bool VarWillBeReased = false;
11942 
11943     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
11944         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
11945           Context(Context), Variable(variable) {}
11946 
11947     void VisitDeclRefExpr(DeclRefExpr *ref) {
11948       if (ref->getDecl() == Variable && !Capturer)
11949         Capturer = ref;
11950     }
11951 
11952     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
11953       if (Capturer) return;
11954       Visit(ref->getBase());
11955       if (Capturer && ref->isFreeIvar())
11956         Capturer = ref;
11957     }
11958 
11959     void VisitBlockExpr(BlockExpr *block) {
11960       // Look inside nested blocks
11961       if (block->getBlockDecl()->capturesVariable(Variable))
11962         Visit(block->getBlockDecl()->getBody());
11963     }
11964 
11965     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
11966       if (Capturer) return;
11967       if (OVE->getSourceExpr())
11968         Visit(OVE->getSourceExpr());
11969     }
11970 
11971     void VisitBinaryOperator(BinaryOperator *BinOp) {
11972       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
11973         return;
11974       Expr *LHS = BinOp->getLHS();
11975       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
11976         if (DRE->getDecl() != Variable)
11977           return;
11978         if (Expr *RHS = BinOp->getRHS()) {
11979           RHS = RHS->IgnoreParenCasts();
11980           llvm::APSInt Value;
11981           VarWillBeReased =
11982             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
11983         }
11984       }
11985     }
11986   };
11987 
11988 } // namespace
11989 
11990 /// Check whether the given argument is a block which captures a
11991 /// variable.
11992 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
11993   assert(owner.Variable && owner.Loc.isValid());
11994 
11995   e = e->IgnoreParenCasts();
11996 
11997   // Look through [^{...} copy] and Block_copy(^{...}).
11998   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
11999     Selector Cmd = ME->getSelector();
12000     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
12001       e = ME->getInstanceReceiver();
12002       if (!e)
12003         return nullptr;
12004       e = e->IgnoreParenCasts();
12005     }
12006   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
12007     if (CE->getNumArgs() == 1) {
12008       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
12009       if (Fn) {
12010         const IdentifierInfo *FnI = Fn->getIdentifier();
12011         if (FnI && FnI->isStr("_Block_copy")) {
12012           e = CE->getArg(0)->IgnoreParenCasts();
12013         }
12014       }
12015     }
12016   }
12017 
12018   BlockExpr *block = dyn_cast<BlockExpr>(e);
12019   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
12020     return nullptr;
12021 
12022   FindCaptureVisitor visitor(S.Context, owner.Variable);
12023   visitor.Visit(block->getBlockDecl()->getBody());
12024   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
12025 }
12026 
12027 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
12028                                 RetainCycleOwner &owner) {
12029   assert(capturer);
12030   assert(owner.Variable && owner.Loc.isValid());
12031 
12032   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
12033     << owner.Variable << capturer->getSourceRange();
12034   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
12035     << owner.Indirect << owner.Range;
12036 }
12037 
12038 /// Check for a keyword selector that starts with the word 'add' or
12039 /// 'set'.
12040 static bool isSetterLikeSelector(Selector sel) {
12041   if (sel.isUnarySelector()) return false;
12042 
12043   StringRef str = sel.getNameForSlot(0);
12044   while (!str.empty() && str.front() == '_') str = str.substr(1);
12045   if (str.startswith("set"))
12046     str = str.substr(3);
12047   else if (str.startswith("add")) {
12048     // Specially whitelist 'addOperationWithBlock:'.
12049     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
12050       return false;
12051     str = str.substr(3);
12052   }
12053   else
12054     return false;
12055 
12056   if (str.empty()) return true;
12057   return !isLowercase(str.front());
12058 }
12059 
12060 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
12061                                                     ObjCMessageExpr *Message) {
12062   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
12063                                                 Message->getReceiverInterface(),
12064                                                 NSAPI::ClassId_NSMutableArray);
12065   if (!IsMutableArray) {
12066     return None;
12067   }
12068 
12069   Selector Sel = Message->getSelector();
12070 
12071   Optional<NSAPI::NSArrayMethodKind> MKOpt =
12072     S.NSAPIObj->getNSArrayMethodKind(Sel);
12073   if (!MKOpt) {
12074     return None;
12075   }
12076 
12077   NSAPI::NSArrayMethodKind MK = *MKOpt;
12078 
12079   switch (MK) {
12080     case NSAPI::NSMutableArr_addObject:
12081     case NSAPI::NSMutableArr_insertObjectAtIndex:
12082     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
12083       return 0;
12084     case NSAPI::NSMutableArr_replaceObjectAtIndex:
12085       return 1;
12086 
12087     default:
12088       return None;
12089   }
12090 
12091   return None;
12092 }
12093 
12094 static
12095 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
12096                                                   ObjCMessageExpr *Message) {
12097   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
12098                                             Message->getReceiverInterface(),
12099                                             NSAPI::ClassId_NSMutableDictionary);
12100   if (!IsMutableDictionary) {
12101     return None;
12102   }
12103 
12104   Selector Sel = Message->getSelector();
12105 
12106   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
12107     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
12108   if (!MKOpt) {
12109     return None;
12110   }
12111 
12112   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
12113 
12114   switch (MK) {
12115     case NSAPI::NSMutableDict_setObjectForKey:
12116     case NSAPI::NSMutableDict_setValueForKey:
12117     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
12118       return 0;
12119 
12120     default:
12121       return None;
12122   }
12123 
12124   return None;
12125 }
12126 
12127 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
12128   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
12129                                                 Message->getReceiverInterface(),
12130                                                 NSAPI::ClassId_NSMutableSet);
12131 
12132   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
12133                                             Message->getReceiverInterface(),
12134                                             NSAPI::ClassId_NSMutableOrderedSet);
12135   if (!IsMutableSet && !IsMutableOrderedSet) {
12136     return None;
12137   }
12138 
12139   Selector Sel = Message->getSelector();
12140 
12141   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
12142   if (!MKOpt) {
12143     return None;
12144   }
12145 
12146   NSAPI::NSSetMethodKind MK = *MKOpt;
12147 
12148   switch (MK) {
12149     case NSAPI::NSMutableSet_addObject:
12150     case NSAPI::NSOrderedSet_setObjectAtIndex:
12151     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
12152     case NSAPI::NSOrderedSet_insertObjectAtIndex:
12153       return 0;
12154     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
12155       return 1;
12156   }
12157 
12158   return None;
12159 }
12160 
12161 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
12162   if (!Message->isInstanceMessage()) {
12163     return;
12164   }
12165 
12166   Optional<int> ArgOpt;
12167 
12168   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
12169       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
12170       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
12171     return;
12172   }
12173 
12174   int ArgIndex = *ArgOpt;
12175 
12176   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
12177   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
12178     Arg = OE->getSourceExpr()->IgnoreImpCasts();
12179   }
12180 
12181   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
12182     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
12183       if (ArgRE->isObjCSelfExpr()) {
12184         Diag(Message->getSourceRange().getBegin(),
12185              diag::warn_objc_circular_container)
12186           << ArgRE->getDecl() << StringRef("'super'");
12187       }
12188     }
12189   } else {
12190     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
12191 
12192     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
12193       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
12194     }
12195 
12196     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
12197       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
12198         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
12199           ValueDecl *Decl = ReceiverRE->getDecl();
12200           Diag(Message->getSourceRange().getBegin(),
12201                diag::warn_objc_circular_container)
12202             << Decl << Decl;
12203           if (!ArgRE->isObjCSelfExpr()) {
12204             Diag(Decl->getLocation(),
12205                  diag::note_objc_circular_container_declared_here)
12206               << Decl;
12207           }
12208         }
12209       }
12210     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
12211       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
12212         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
12213           ObjCIvarDecl *Decl = IvarRE->getDecl();
12214           Diag(Message->getSourceRange().getBegin(),
12215                diag::warn_objc_circular_container)
12216             << Decl << Decl;
12217           Diag(Decl->getLocation(),
12218                diag::note_objc_circular_container_declared_here)
12219             << Decl;
12220         }
12221       }
12222     }
12223   }
12224 }
12225 
12226 /// Check a message send to see if it's likely to cause a retain cycle.
12227 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
12228   // Only check instance methods whose selector looks like a setter.
12229   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
12230     return;
12231 
12232   // Try to find a variable that the receiver is strongly owned by.
12233   RetainCycleOwner owner;
12234   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
12235     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
12236       return;
12237   } else {
12238     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
12239     owner.Variable = getCurMethodDecl()->getSelfDecl();
12240     owner.Loc = msg->getSuperLoc();
12241     owner.Range = msg->getSuperLoc();
12242   }
12243 
12244   // Check whether the receiver is captured by any of the arguments.
12245   const ObjCMethodDecl *MD = msg->getMethodDecl();
12246   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
12247     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
12248       // noescape blocks should not be retained by the method.
12249       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
12250         continue;
12251       return diagnoseRetainCycle(*this, capturer, owner);
12252     }
12253   }
12254 }
12255 
12256 /// Check a property assign to see if it's likely to cause a retain cycle.
12257 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
12258   RetainCycleOwner owner;
12259   if (!findRetainCycleOwner(*this, receiver, owner))
12260     return;
12261 
12262   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
12263     diagnoseRetainCycle(*this, capturer, owner);
12264 }
12265 
12266 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
12267   RetainCycleOwner Owner;
12268   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
12269     return;
12270 
12271   // Because we don't have an expression for the variable, we have to set the
12272   // location explicitly here.
12273   Owner.Loc = Var->getLocation();
12274   Owner.Range = Var->getSourceRange();
12275 
12276   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
12277     diagnoseRetainCycle(*this, Capturer, Owner);
12278 }
12279 
12280 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
12281                                      Expr *RHS, bool isProperty) {
12282   // Check if RHS is an Objective-C object literal, which also can get
12283   // immediately zapped in a weak reference.  Note that we explicitly
12284   // allow ObjCStringLiterals, since those are designed to never really die.
12285   RHS = RHS->IgnoreParenImpCasts();
12286 
12287   // This enum needs to match with the 'select' in
12288   // warn_objc_arc_literal_assign (off-by-1).
12289   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
12290   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
12291     return false;
12292 
12293   S.Diag(Loc, diag::warn_arc_literal_assign)
12294     << (unsigned) Kind
12295     << (isProperty ? 0 : 1)
12296     << RHS->getSourceRange();
12297 
12298   return true;
12299 }
12300 
12301 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
12302                                     Qualifiers::ObjCLifetime LT,
12303                                     Expr *RHS, bool isProperty) {
12304   // Strip off any implicit cast added to get to the one ARC-specific.
12305   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
12306     if (cast->getCastKind() == CK_ARCConsumeObject) {
12307       S.Diag(Loc, diag::warn_arc_retained_assign)
12308         << (LT == Qualifiers::OCL_ExplicitNone)
12309         << (isProperty ? 0 : 1)
12310         << RHS->getSourceRange();
12311       return true;
12312     }
12313     RHS = cast->getSubExpr();
12314   }
12315 
12316   if (LT == Qualifiers::OCL_Weak &&
12317       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
12318     return true;
12319 
12320   return false;
12321 }
12322 
12323 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
12324                               QualType LHS, Expr *RHS) {
12325   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
12326 
12327   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
12328     return false;
12329 
12330   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
12331     return true;
12332 
12333   return false;
12334 }
12335 
12336 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
12337                               Expr *LHS, Expr *RHS) {
12338   QualType LHSType;
12339   // PropertyRef on LHS type need be directly obtained from
12340   // its declaration as it has a PseudoType.
12341   ObjCPropertyRefExpr *PRE
12342     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
12343   if (PRE && !PRE->isImplicitProperty()) {
12344     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
12345     if (PD)
12346       LHSType = PD->getType();
12347   }
12348 
12349   if (LHSType.isNull())
12350     LHSType = LHS->getType();
12351 
12352   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
12353 
12354   if (LT == Qualifiers::OCL_Weak) {
12355     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
12356       getCurFunction()->markSafeWeakUse(LHS);
12357   }
12358 
12359   if (checkUnsafeAssigns(Loc, LHSType, RHS))
12360     return;
12361 
12362   // FIXME. Check for other life times.
12363   if (LT != Qualifiers::OCL_None)
12364     return;
12365 
12366   if (PRE) {
12367     if (PRE->isImplicitProperty())
12368       return;
12369     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
12370     if (!PD)
12371       return;
12372 
12373     unsigned Attributes = PD->getPropertyAttributes();
12374     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
12375       // when 'assign' attribute was not explicitly specified
12376       // by user, ignore it and rely on property type itself
12377       // for lifetime info.
12378       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
12379       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
12380           LHSType->isObjCRetainableType())
12381         return;
12382 
12383       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
12384         if (cast->getCastKind() == CK_ARCConsumeObject) {
12385           Diag(Loc, diag::warn_arc_retained_property_assign)
12386           << RHS->getSourceRange();
12387           return;
12388         }
12389         RHS = cast->getSubExpr();
12390       }
12391     }
12392     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
12393       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
12394         return;
12395     }
12396   }
12397 }
12398 
12399 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
12400 
12401 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
12402                                         SourceLocation StmtLoc,
12403                                         const NullStmt *Body) {
12404   // Do not warn if the body is a macro that expands to nothing, e.g:
12405   //
12406   // #define CALL(x)
12407   // if (condition)
12408   //   CALL(0);
12409   if (Body->hasLeadingEmptyMacro())
12410     return false;
12411 
12412   // Get line numbers of statement and body.
12413   bool StmtLineInvalid;
12414   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
12415                                                       &StmtLineInvalid);
12416   if (StmtLineInvalid)
12417     return false;
12418 
12419   bool BodyLineInvalid;
12420   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
12421                                                       &BodyLineInvalid);
12422   if (BodyLineInvalid)
12423     return false;
12424 
12425   // Warn if null statement and body are on the same line.
12426   if (StmtLine != BodyLine)
12427     return false;
12428 
12429   return true;
12430 }
12431 
12432 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
12433                                  const Stmt *Body,
12434                                  unsigned DiagID) {
12435   // Since this is a syntactic check, don't emit diagnostic for template
12436   // instantiations, this just adds noise.
12437   if (CurrentInstantiationScope)
12438     return;
12439 
12440   // The body should be a null statement.
12441   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
12442   if (!NBody)
12443     return;
12444 
12445   // Do the usual checks.
12446   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
12447     return;
12448 
12449   Diag(NBody->getSemiLoc(), DiagID);
12450   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
12451 }
12452 
12453 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
12454                                  const Stmt *PossibleBody) {
12455   assert(!CurrentInstantiationScope); // Ensured by caller
12456 
12457   SourceLocation StmtLoc;
12458   const Stmt *Body;
12459   unsigned DiagID;
12460   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
12461     StmtLoc = FS->getRParenLoc();
12462     Body = FS->getBody();
12463     DiagID = diag::warn_empty_for_body;
12464   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
12465     StmtLoc = WS->getCond()->getSourceRange().getEnd();
12466     Body = WS->getBody();
12467     DiagID = diag::warn_empty_while_body;
12468   } else
12469     return; // Neither `for' nor `while'.
12470 
12471   // The body should be a null statement.
12472   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
12473   if (!NBody)
12474     return;
12475 
12476   // Skip expensive checks if diagnostic is disabled.
12477   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
12478     return;
12479 
12480   // Do the usual checks.
12481   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
12482     return;
12483 
12484   // `for(...);' and `while(...);' are popular idioms, so in order to keep
12485   // noise level low, emit diagnostics only if for/while is followed by a
12486   // CompoundStmt, e.g.:
12487   //    for (int i = 0; i < n; i++);
12488   //    {
12489   //      a(i);
12490   //    }
12491   // or if for/while is followed by a statement with more indentation
12492   // than for/while itself:
12493   //    for (int i = 0; i < n; i++);
12494   //      a(i);
12495   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
12496   if (!ProbableTypo) {
12497     bool BodyColInvalid;
12498     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
12499                              PossibleBody->getLocStart(),
12500                              &BodyColInvalid);
12501     if (BodyColInvalid)
12502       return;
12503 
12504     bool StmtColInvalid;
12505     unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
12506                              S->getLocStart(),
12507                              &StmtColInvalid);
12508     if (StmtColInvalid)
12509       return;
12510 
12511     if (BodyCol > StmtCol)
12512       ProbableTypo = true;
12513   }
12514 
12515   if (ProbableTypo) {
12516     Diag(NBody->getSemiLoc(), DiagID);
12517     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
12518   }
12519 }
12520 
12521 //===--- CHECK: Warn on self move with std::move. -------------------------===//
12522 
12523 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
12524 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
12525                              SourceLocation OpLoc) {
12526   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
12527     return;
12528 
12529   if (inTemplateInstantiation())
12530     return;
12531 
12532   // Strip parens and casts away.
12533   LHSExpr = LHSExpr->IgnoreParenImpCasts();
12534   RHSExpr = RHSExpr->IgnoreParenImpCasts();
12535 
12536   // Check for a call expression
12537   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
12538   if (!CE || CE->getNumArgs() != 1)
12539     return;
12540 
12541   // Check for a call to std::move
12542   if (!CE->isCallToStdMove())
12543     return;
12544 
12545   // Get argument from std::move
12546   RHSExpr = CE->getArg(0);
12547 
12548   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
12549   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
12550 
12551   // Two DeclRefExpr's, check that the decls are the same.
12552   if (LHSDeclRef && RHSDeclRef) {
12553     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
12554       return;
12555     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
12556         RHSDeclRef->getDecl()->getCanonicalDecl())
12557       return;
12558 
12559     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12560                                         << LHSExpr->getSourceRange()
12561                                         << RHSExpr->getSourceRange();
12562     return;
12563   }
12564 
12565   // Member variables require a different approach to check for self moves.
12566   // MemberExpr's are the same if every nested MemberExpr refers to the same
12567   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
12568   // the base Expr's are CXXThisExpr's.
12569   const Expr *LHSBase = LHSExpr;
12570   const Expr *RHSBase = RHSExpr;
12571   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
12572   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
12573   if (!LHSME || !RHSME)
12574     return;
12575 
12576   while (LHSME && RHSME) {
12577     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
12578         RHSME->getMemberDecl()->getCanonicalDecl())
12579       return;
12580 
12581     LHSBase = LHSME->getBase();
12582     RHSBase = RHSME->getBase();
12583     LHSME = dyn_cast<MemberExpr>(LHSBase);
12584     RHSME = dyn_cast<MemberExpr>(RHSBase);
12585   }
12586 
12587   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
12588   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
12589   if (LHSDeclRef && RHSDeclRef) {
12590     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
12591       return;
12592     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
12593         RHSDeclRef->getDecl()->getCanonicalDecl())
12594       return;
12595 
12596     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12597                                         << LHSExpr->getSourceRange()
12598                                         << RHSExpr->getSourceRange();
12599     return;
12600   }
12601 
12602   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
12603     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12604                                         << LHSExpr->getSourceRange()
12605                                         << RHSExpr->getSourceRange();
12606 }
12607 
12608 //===--- Layout compatibility ----------------------------------------------//
12609 
12610 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
12611 
12612 /// Check if two enumeration types are layout-compatible.
12613 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
12614   // C++11 [dcl.enum] p8:
12615   // Two enumeration types are layout-compatible if they have the same
12616   // underlying type.
12617   return ED1->isComplete() && ED2->isComplete() &&
12618          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
12619 }
12620 
12621 /// Check if two fields are layout-compatible.
12622 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
12623                                FieldDecl *Field2) {
12624   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
12625     return false;
12626 
12627   if (Field1->isBitField() != Field2->isBitField())
12628     return false;
12629 
12630   if (Field1->isBitField()) {
12631     // Make sure that the bit-fields are the same length.
12632     unsigned Bits1 = Field1->getBitWidthValue(C);
12633     unsigned Bits2 = Field2->getBitWidthValue(C);
12634 
12635     if (Bits1 != Bits2)
12636       return false;
12637   }
12638 
12639   return true;
12640 }
12641 
12642 /// Check if two standard-layout structs are layout-compatible.
12643 /// (C++11 [class.mem] p17)
12644 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
12645                                      RecordDecl *RD2) {
12646   // If both records are C++ classes, check that base classes match.
12647   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
12648     // If one of records is a CXXRecordDecl we are in C++ mode,
12649     // thus the other one is a CXXRecordDecl, too.
12650     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
12651     // Check number of base classes.
12652     if (D1CXX->getNumBases() != D2CXX->getNumBases())
12653       return false;
12654 
12655     // Check the base classes.
12656     for (CXXRecordDecl::base_class_const_iterator
12657                Base1 = D1CXX->bases_begin(),
12658            BaseEnd1 = D1CXX->bases_end(),
12659               Base2 = D2CXX->bases_begin();
12660          Base1 != BaseEnd1;
12661          ++Base1, ++Base2) {
12662       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
12663         return false;
12664     }
12665   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
12666     // If only RD2 is a C++ class, it should have zero base classes.
12667     if (D2CXX->getNumBases() > 0)
12668       return false;
12669   }
12670 
12671   // Check the fields.
12672   RecordDecl::field_iterator Field2 = RD2->field_begin(),
12673                              Field2End = RD2->field_end(),
12674                              Field1 = RD1->field_begin(),
12675                              Field1End = RD1->field_end();
12676   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
12677     if (!isLayoutCompatible(C, *Field1, *Field2))
12678       return false;
12679   }
12680   if (Field1 != Field1End || Field2 != Field2End)
12681     return false;
12682 
12683   return true;
12684 }
12685 
12686 /// Check if two standard-layout unions are layout-compatible.
12687 /// (C++11 [class.mem] p18)
12688 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
12689                                     RecordDecl *RD2) {
12690   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
12691   for (auto *Field2 : RD2->fields())
12692     UnmatchedFields.insert(Field2);
12693 
12694   for (auto *Field1 : RD1->fields()) {
12695     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
12696         I = UnmatchedFields.begin(),
12697         E = UnmatchedFields.end();
12698 
12699     for ( ; I != E; ++I) {
12700       if (isLayoutCompatible(C, Field1, *I)) {
12701         bool Result = UnmatchedFields.erase(*I);
12702         (void) Result;
12703         assert(Result);
12704         break;
12705       }
12706     }
12707     if (I == E)
12708       return false;
12709   }
12710 
12711   return UnmatchedFields.empty();
12712 }
12713 
12714 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
12715                                RecordDecl *RD2) {
12716   if (RD1->isUnion() != RD2->isUnion())
12717     return false;
12718 
12719   if (RD1->isUnion())
12720     return isLayoutCompatibleUnion(C, RD1, RD2);
12721   else
12722     return isLayoutCompatibleStruct(C, RD1, RD2);
12723 }
12724 
12725 /// Check if two types are layout-compatible in C++11 sense.
12726 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
12727   if (T1.isNull() || T2.isNull())
12728     return false;
12729 
12730   // C++11 [basic.types] p11:
12731   // If two types T1 and T2 are the same type, then T1 and T2 are
12732   // layout-compatible types.
12733   if (C.hasSameType(T1, T2))
12734     return true;
12735 
12736   T1 = T1.getCanonicalType().getUnqualifiedType();
12737   T2 = T2.getCanonicalType().getUnqualifiedType();
12738 
12739   const Type::TypeClass TC1 = T1->getTypeClass();
12740   const Type::TypeClass TC2 = T2->getTypeClass();
12741 
12742   if (TC1 != TC2)
12743     return false;
12744 
12745   if (TC1 == Type::Enum) {
12746     return isLayoutCompatible(C,
12747                               cast<EnumType>(T1)->getDecl(),
12748                               cast<EnumType>(T2)->getDecl());
12749   } else if (TC1 == Type::Record) {
12750     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
12751       return false;
12752 
12753     return isLayoutCompatible(C,
12754                               cast<RecordType>(T1)->getDecl(),
12755                               cast<RecordType>(T2)->getDecl());
12756   }
12757 
12758   return false;
12759 }
12760 
12761 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
12762 
12763 /// Given a type tag expression find the type tag itself.
12764 ///
12765 /// \param TypeExpr Type tag expression, as it appears in user's code.
12766 ///
12767 /// \param VD Declaration of an identifier that appears in a type tag.
12768 ///
12769 /// \param MagicValue Type tag magic value.
12770 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
12771                             const ValueDecl **VD, uint64_t *MagicValue) {
12772   while(true) {
12773     if (!TypeExpr)
12774       return false;
12775 
12776     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
12777 
12778     switch (TypeExpr->getStmtClass()) {
12779     case Stmt::UnaryOperatorClass: {
12780       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
12781       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
12782         TypeExpr = UO->getSubExpr();
12783         continue;
12784       }
12785       return false;
12786     }
12787 
12788     case Stmt::DeclRefExprClass: {
12789       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
12790       *VD = DRE->getDecl();
12791       return true;
12792     }
12793 
12794     case Stmt::IntegerLiteralClass: {
12795       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
12796       llvm::APInt MagicValueAPInt = IL->getValue();
12797       if (MagicValueAPInt.getActiveBits() <= 64) {
12798         *MagicValue = MagicValueAPInt.getZExtValue();
12799         return true;
12800       } else
12801         return false;
12802     }
12803 
12804     case Stmt::BinaryConditionalOperatorClass:
12805     case Stmt::ConditionalOperatorClass: {
12806       const AbstractConditionalOperator *ACO =
12807           cast<AbstractConditionalOperator>(TypeExpr);
12808       bool Result;
12809       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
12810         if (Result)
12811           TypeExpr = ACO->getTrueExpr();
12812         else
12813           TypeExpr = ACO->getFalseExpr();
12814         continue;
12815       }
12816       return false;
12817     }
12818 
12819     case Stmt::BinaryOperatorClass: {
12820       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
12821       if (BO->getOpcode() == BO_Comma) {
12822         TypeExpr = BO->getRHS();
12823         continue;
12824       }
12825       return false;
12826     }
12827 
12828     default:
12829       return false;
12830     }
12831   }
12832 }
12833 
12834 /// Retrieve the C type corresponding to type tag TypeExpr.
12835 ///
12836 /// \param TypeExpr Expression that specifies a type tag.
12837 ///
12838 /// \param MagicValues Registered magic values.
12839 ///
12840 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
12841 ///        kind.
12842 ///
12843 /// \param TypeInfo Information about the corresponding C type.
12844 ///
12845 /// \returns true if the corresponding C type was found.
12846 static bool GetMatchingCType(
12847         const IdentifierInfo *ArgumentKind,
12848         const Expr *TypeExpr, const ASTContext &Ctx,
12849         const llvm::DenseMap<Sema::TypeTagMagicValue,
12850                              Sema::TypeTagData> *MagicValues,
12851         bool &FoundWrongKind,
12852         Sema::TypeTagData &TypeInfo) {
12853   FoundWrongKind = false;
12854 
12855   // Variable declaration that has type_tag_for_datatype attribute.
12856   const ValueDecl *VD = nullptr;
12857 
12858   uint64_t MagicValue;
12859 
12860   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
12861     return false;
12862 
12863   if (VD) {
12864     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
12865       if (I->getArgumentKind() != ArgumentKind) {
12866         FoundWrongKind = true;
12867         return false;
12868       }
12869       TypeInfo.Type = I->getMatchingCType();
12870       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
12871       TypeInfo.MustBeNull = I->getMustBeNull();
12872       return true;
12873     }
12874     return false;
12875   }
12876 
12877   if (!MagicValues)
12878     return false;
12879 
12880   llvm::DenseMap<Sema::TypeTagMagicValue,
12881                  Sema::TypeTagData>::const_iterator I =
12882       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
12883   if (I == MagicValues->end())
12884     return false;
12885 
12886   TypeInfo = I->second;
12887   return true;
12888 }
12889 
12890 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
12891                                       uint64_t MagicValue, QualType Type,
12892                                       bool LayoutCompatible,
12893                                       bool MustBeNull) {
12894   if (!TypeTagForDatatypeMagicValues)
12895     TypeTagForDatatypeMagicValues.reset(
12896         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
12897 
12898   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
12899   (*TypeTagForDatatypeMagicValues)[Magic] =
12900       TypeTagData(Type, LayoutCompatible, MustBeNull);
12901 }
12902 
12903 static bool IsSameCharType(QualType T1, QualType T2) {
12904   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
12905   if (!BT1)
12906     return false;
12907 
12908   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
12909   if (!BT2)
12910     return false;
12911 
12912   BuiltinType::Kind T1Kind = BT1->getKind();
12913   BuiltinType::Kind T2Kind = BT2->getKind();
12914 
12915   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
12916          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
12917          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
12918          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
12919 }
12920 
12921 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
12922                                     const ArrayRef<const Expr *> ExprArgs,
12923                                     SourceLocation CallSiteLoc) {
12924   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
12925   bool IsPointerAttr = Attr->getIsPointer();
12926 
12927   // Retrieve the argument representing the 'type_tag'.
12928   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
12929   if (TypeTagIdxAST >= ExprArgs.size()) {
12930     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
12931         << 0 << Attr->getTypeTagIdx().getSourceIndex();
12932     return;
12933   }
12934   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
12935   bool FoundWrongKind;
12936   TypeTagData TypeInfo;
12937   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
12938                         TypeTagForDatatypeMagicValues.get(),
12939                         FoundWrongKind, TypeInfo)) {
12940     if (FoundWrongKind)
12941       Diag(TypeTagExpr->getExprLoc(),
12942            diag::warn_type_tag_for_datatype_wrong_kind)
12943         << TypeTagExpr->getSourceRange();
12944     return;
12945   }
12946 
12947   // Retrieve the argument representing the 'arg_idx'.
12948   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
12949   if (ArgumentIdxAST >= ExprArgs.size()) {
12950     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
12951         << 1 << Attr->getArgumentIdx().getSourceIndex();
12952     return;
12953   }
12954   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
12955   if (IsPointerAttr) {
12956     // Skip implicit cast of pointer to `void *' (as a function argument).
12957     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
12958       if (ICE->getType()->isVoidPointerType() &&
12959           ICE->getCastKind() == CK_BitCast)
12960         ArgumentExpr = ICE->getSubExpr();
12961   }
12962   QualType ArgumentType = ArgumentExpr->getType();
12963 
12964   // Passing a `void*' pointer shouldn't trigger a warning.
12965   if (IsPointerAttr && ArgumentType->isVoidPointerType())
12966     return;
12967 
12968   if (TypeInfo.MustBeNull) {
12969     // Type tag with matching void type requires a null pointer.
12970     if (!ArgumentExpr->isNullPointerConstant(Context,
12971                                              Expr::NPC_ValueDependentIsNotNull)) {
12972       Diag(ArgumentExpr->getExprLoc(),
12973            diag::warn_type_safety_null_pointer_required)
12974           << ArgumentKind->getName()
12975           << ArgumentExpr->getSourceRange()
12976           << TypeTagExpr->getSourceRange();
12977     }
12978     return;
12979   }
12980 
12981   QualType RequiredType = TypeInfo.Type;
12982   if (IsPointerAttr)
12983     RequiredType = Context.getPointerType(RequiredType);
12984 
12985   bool mismatch = false;
12986   if (!TypeInfo.LayoutCompatible) {
12987     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
12988 
12989     // C++11 [basic.fundamental] p1:
12990     // Plain char, signed char, and unsigned char are three distinct types.
12991     //
12992     // But we treat plain `char' as equivalent to `signed char' or `unsigned
12993     // char' depending on the current char signedness mode.
12994     if (mismatch)
12995       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
12996                                            RequiredType->getPointeeType())) ||
12997           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
12998         mismatch = false;
12999   } else
13000     if (IsPointerAttr)
13001       mismatch = !isLayoutCompatible(Context,
13002                                      ArgumentType->getPointeeType(),
13003                                      RequiredType->getPointeeType());
13004     else
13005       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
13006 
13007   if (mismatch)
13008     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
13009         << ArgumentType << ArgumentKind
13010         << TypeInfo.LayoutCompatible << RequiredType
13011         << ArgumentExpr->getSourceRange()
13012         << TypeTagExpr->getSourceRange();
13013 }
13014 
13015 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
13016                                          CharUnits Alignment) {
13017   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
13018 }
13019 
13020 void Sema::DiagnoseMisalignedMembers() {
13021   for (MisalignedMember &m : MisalignedMembers) {
13022     const NamedDecl *ND = m.RD;
13023     if (ND->getName().empty()) {
13024       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
13025         ND = TD;
13026     }
13027     Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
13028         << m.MD << ND << m.E->getSourceRange();
13029   }
13030   MisalignedMembers.clear();
13031 }
13032 
13033 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
13034   E = E->IgnoreParens();
13035   if (!T->isPointerType() && !T->isIntegerType())
13036     return;
13037   if (isa<UnaryOperator>(E) &&
13038       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
13039     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
13040     if (isa<MemberExpr>(Op)) {
13041       auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
13042                           MisalignedMember(Op));
13043       if (MA != MisalignedMembers.end() &&
13044           (T->isIntegerType() ||
13045            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
13046                                    Context.getTypeAlignInChars(
13047                                        T->getPointeeType()) <= MA->Alignment))))
13048         MisalignedMembers.erase(MA);
13049     }
13050   }
13051 }
13052 
13053 void Sema::RefersToMemberWithReducedAlignment(
13054     Expr *E,
13055     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
13056         Action) {
13057   const auto *ME = dyn_cast<MemberExpr>(E);
13058   if (!ME)
13059     return;
13060 
13061   // No need to check expressions with an __unaligned-qualified type.
13062   if (E->getType().getQualifiers().hasUnaligned())
13063     return;
13064 
13065   // For a chain of MemberExpr like "a.b.c.d" this list
13066   // will keep FieldDecl's like [d, c, b].
13067   SmallVector<FieldDecl *, 4> ReverseMemberChain;
13068   const MemberExpr *TopME = nullptr;
13069   bool AnyIsPacked = false;
13070   do {
13071     QualType BaseType = ME->getBase()->getType();
13072     if (ME->isArrow())
13073       BaseType = BaseType->getPointeeType();
13074     RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
13075     if (RD->isInvalidDecl())
13076       return;
13077 
13078     ValueDecl *MD = ME->getMemberDecl();
13079     auto *FD = dyn_cast<FieldDecl>(MD);
13080     // We do not care about non-data members.
13081     if (!FD || FD->isInvalidDecl())
13082       return;
13083 
13084     AnyIsPacked =
13085         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
13086     ReverseMemberChain.push_back(FD);
13087 
13088     TopME = ME;
13089     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
13090   } while (ME);
13091   assert(TopME && "We did not compute a topmost MemberExpr!");
13092 
13093   // Not the scope of this diagnostic.
13094   if (!AnyIsPacked)
13095     return;
13096 
13097   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
13098   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
13099   // TODO: The innermost base of the member expression may be too complicated.
13100   // For now, just disregard these cases. This is left for future
13101   // improvement.
13102   if (!DRE && !isa<CXXThisExpr>(TopBase))
13103       return;
13104 
13105   // Alignment expected by the whole expression.
13106   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
13107 
13108   // No need to do anything else with this case.
13109   if (ExpectedAlignment.isOne())
13110     return;
13111 
13112   // Synthesize offset of the whole access.
13113   CharUnits Offset;
13114   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
13115        I++) {
13116     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
13117   }
13118 
13119   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
13120   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
13121       ReverseMemberChain.back()->getParent()->getTypeForDecl());
13122 
13123   // The base expression of the innermost MemberExpr may give
13124   // stronger guarantees than the class containing the member.
13125   if (DRE && !TopME->isArrow()) {
13126     const ValueDecl *VD = DRE->getDecl();
13127     if (!VD->getType()->isReferenceType())
13128       CompleteObjectAlignment =
13129           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
13130   }
13131 
13132   // Check if the synthesized offset fulfills the alignment.
13133   if (Offset % ExpectedAlignment != 0 ||
13134       // It may fulfill the offset it but the effective alignment may still be
13135       // lower than the expected expression alignment.
13136       CompleteObjectAlignment < ExpectedAlignment) {
13137     // If this happens, we want to determine a sensible culprit of this.
13138     // Intuitively, watching the chain of member expressions from right to
13139     // left, we start with the required alignment (as required by the field
13140     // type) but some packed attribute in that chain has reduced the alignment.
13141     // It may happen that another packed structure increases it again. But if
13142     // we are here such increase has not been enough. So pointing the first
13143     // FieldDecl that either is packed or else its RecordDecl is,
13144     // seems reasonable.
13145     FieldDecl *FD = nullptr;
13146     CharUnits Alignment;
13147     for (FieldDecl *FDI : ReverseMemberChain) {
13148       if (FDI->hasAttr<PackedAttr>() ||
13149           FDI->getParent()->hasAttr<PackedAttr>()) {
13150         FD = FDI;
13151         Alignment = std::min(
13152             Context.getTypeAlignInChars(FD->getType()),
13153             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
13154         break;
13155       }
13156     }
13157     assert(FD && "We did not find a packed FieldDecl!");
13158     Action(E, FD->getParent(), FD, Alignment);
13159   }
13160 }
13161 
13162 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
13163   using namespace std::placeholders;
13164 
13165   RefersToMemberWithReducedAlignment(
13166       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
13167                      _2, _3, _4));
13168 }
13169