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/OperationKinds.h"
32 #include "clang/AST/Stmt.h"
33 #include "clang/AST/TemplateBase.h"
34 #include "clang/AST/Type.h"
35 #include "clang/AST/TypeLoc.h"
36 #include "clang/AST/UnresolvedSet.h"
37 #include "clang/Analysis/Analyses/FormatString.h"
38 #include "clang/Basic/AddressSpaces.h"
39 #include "clang/Basic/CharInfo.h"
40 #include "clang/Basic/Diagnostic.h"
41 #include "clang/Basic/IdentifierTable.h"
42 #include "clang/Basic/LLVM.h"
43 #include "clang/Basic/LangOptions.h"
44 #include "clang/Basic/OpenCLOptions.h"
45 #include "clang/Basic/OperatorKinds.h"
46 #include "clang/Basic/PartialDiagnostic.h"
47 #include "clang/Basic/SourceLocation.h"
48 #include "clang/Basic/SourceManager.h"
49 #include "clang/Basic/Specifiers.h"
50 #include "clang/Basic/SyncScope.h"
51 #include "clang/Basic/TargetBuiltins.h"
52 #include "clang/Basic/TargetCXXABI.h"
53 #include "clang/Basic/TargetInfo.h"
54 #include "clang/Basic/TypeTraits.h"
55 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
56 #include "clang/Sema/Initialization.h"
57 #include "clang/Sema/Lookup.h"
58 #include "clang/Sema/Ownership.h"
59 #include "clang/Sema/Scope.h"
60 #include "clang/Sema/ScopeInfo.h"
61 #include "clang/Sema/Sema.h"
62 #include "clang/Sema/SemaInternal.h"
63 #include "llvm/ADT/APFloat.h"
64 #include "llvm/ADT/APInt.h"
65 #include "llvm/ADT/APSInt.h"
66 #include "llvm/ADT/ArrayRef.h"
67 #include "llvm/ADT/DenseMap.h"
68 #include "llvm/ADT/FoldingSet.h"
69 #include "llvm/ADT/None.h"
70 #include "llvm/ADT/Optional.h"
71 #include "llvm/ADT/STLExtras.h"
72 #include "llvm/ADT/SmallBitVector.h"
73 #include "llvm/ADT/SmallPtrSet.h"
74 #include "llvm/ADT/SmallString.h"
75 #include "llvm/ADT/SmallVector.h"
76 #include "llvm/ADT/StringRef.h"
77 #include "llvm/ADT/StringSwitch.h"
78 #include "llvm/ADT/Triple.h"
79 #include "llvm/Support/AtomicOrdering.h"
80 #include "llvm/Support/Casting.h"
81 #include "llvm/Support/Compiler.h"
82 #include "llvm/Support/ConvertUTF.h"
83 #include "llvm/Support/ErrorHandling.h"
84 #include "llvm/Support/Format.h"
85 #include "llvm/Support/Locale.h"
86 #include "llvm/Support/MathExtras.h"
87 #include "llvm/Support/raw_ostream.h"
88 #include <algorithm>
89 #include <cassert>
90 #include <cstddef>
91 #include <cstdint>
92 #include <functional>
93 #include <limits>
94 #include <string>
95 #include <tuple>
96 #include <utility>
97 
98 using namespace clang;
99 using namespace sema;
100 
101 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
102                                                     unsigned ByteNo) const {
103   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
104                                Context.getTargetInfo());
105 }
106 
107 /// Checks that a call expression's argument count is the desired number.
108 /// This is useful when doing custom type-checking.  Returns true on error.
109 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
110   unsigned argCount = call->getNumArgs();
111   if (argCount == desiredArgCount) return false;
112 
113   if (argCount < desiredArgCount)
114     return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
115         << 0 /*function call*/ << desiredArgCount << argCount
116         << call->getSourceRange();
117 
118   // Highlight all the excess arguments.
119   SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
120                     call->getArg(argCount - 1)->getLocEnd());
121 
122   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
123     << 0 /*function call*/ << desiredArgCount << argCount
124     << call->getArg(1)->getSourceRange();
125 }
126 
127 /// Check that the first argument to __builtin_annotation is an integer
128 /// and the second argument is a non-wide string literal.
129 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
130   if (checkArgCount(S, TheCall, 2))
131     return true;
132 
133   // First argument should be an integer.
134   Expr *ValArg = TheCall->getArg(0);
135   QualType Ty = ValArg->getType();
136   if (!Ty->isIntegerType()) {
137     S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
138       << ValArg->getSourceRange();
139     return true;
140   }
141 
142   // Second argument should be a constant string.
143   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
144   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
145   if (!Literal || !Literal->isAscii()) {
146     S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
147       << StrArg->getSourceRange();
148     return true;
149   }
150 
151   TheCall->setType(Ty);
152   return false;
153 }
154 
155 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
156   // We need at least one argument.
157   if (TheCall->getNumArgs() < 1) {
158     S.Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
159         << 0 << 1 << TheCall->getNumArgs()
160         << TheCall->getCallee()->getSourceRange();
161     return true;
162   }
163 
164   // All arguments should be wide string literals.
165   for (Expr *Arg : TheCall->arguments()) {
166     auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
167     if (!Literal || !Literal->isWide()) {
168       S.Diag(Arg->getLocStart(), diag::err_msvc_annotation_wide_str)
169           << Arg->getSourceRange();
170       return true;
171     }
172   }
173 
174   return false;
175 }
176 
177 /// Check that the argument to __builtin_addressof is a glvalue, and set the
178 /// result type to the corresponding pointer type.
179 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
180   if (checkArgCount(S, TheCall, 1))
181     return true;
182 
183   ExprResult Arg(TheCall->getArg(0));
184   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
185   if (ResultType.isNull())
186     return true;
187 
188   TheCall->setArg(0, Arg.get());
189   TheCall->setType(ResultType);
190   return false;
191 }
192 
193 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
194   if (checkArgCount(S, TheCall, 3))
195     return true;
196 
197   // First two arguments should be integers.
198   for (unsigned I = 0; I < 2; ++I) {
199     Expr *Arg = TheCall->getArg(I);
200     QualType Ty = Arg->getType();
201     if (!Ty->isIntegerType()) {
202       S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
203           << Ty << Arg->getSourceRange();
204       return true;
205     }
206   }
207 
208   // Third argument should be a pointer to a non-const integer.
209   // IRGen correctly handles volatile, restrict, and address spaces, and
210   // the other qualifiers aren't possible.
211   {
212     Expr *Arg = TheCall->getArg(2);
213     QualType Ty = Arg->getType();
214     const auto *PtrTy = Ty->getAs<PointerType>();
215     if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
216           !PtrTy->getPointeeType().isConstQualified())) {
217       S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
218           << Ty << Arg->getSourceRange();
219       return true;
220     }
221   }
222 
223   return false;
224 }
225 
226 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
227 		                  CallExpr *TheCall, unsigned SizeIdx,
228                                   unsigned DstSizeIdx) {
229   if (TheCall->getNumArgs() <= SizeIdx ||
230       TheCall->getNumArgs() <= DstSizeIdx)
231     return;
232 
233   const Expr *SizeArg = TheCall->getArg(SizeIdx);
234   const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
235 
236   llvm::APSInt Size, DstSize;
237 
238   // find out if both sizes are known at compile time
239   if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
240       !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
241     return;
242 
243   if (Size.ule(DstSize))
244     return;
245 
246   // confirmed overflow so generate the diagnostic.
247   IdentifierInfo *FnName = FDecl->getIdentifier();
248   SourceLocation SL = TheCall->getLocStart();
249   SourceRange SR = TheCall->getSourceRange();
250 
251   S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
252 }
253 
254 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
255   if (checkArgCount(S, BuiltinCall, 2))
256     return true;
257 
258   SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
259   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
260   Expr *Call = BuiltinCall->getArg(0);
261   Expr *Chain = BuiltinCall->getArg(1);
262 
263   if (Call->getStmtClass() != Stmt::CallExprClass) {
264     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
265         << Call->getSourceRange();
266     return true;
267   }
268 
269   auto CE = cast<CallExpr>(Call);
270   if (CE->getCallee()->getType()->isBlockPointerType()) {
271     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
272         << Call->getSourceRange();
273     return true;
274   }
275 
276   const Decl *TargetDecl = CE->getCalleeDecl();
277   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
278     if (FD->getBuiltinID()) {
279       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
280           << Call->getSourceRange();
281       return true;
282     }
283 
284   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
285     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
286         << Call->getSourceRange();
287     return true;
288   }
289 
290   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
291   if (ChainResult.isInvalid())
292     return true;
293   if (!ChainResult.get()->getType()->isPointerType()) {
294     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
295         << Chain->getSourceRange();
296     return true;
297   }
298 
299   QualType ReturnTy = CE->getCallReturnType(S.Context);
300   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
301   QualType BuiltinTy = S.Context.getFunctionType(
302       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
303   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
304 
305   Builtin =
306       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
307 
308   BuiltinCall->setType(CE->getType());
309   BuiltinCall->setValueKind(CE->getValueKind());
310   BuiltinCall->setObjectKind(CE->getObjectKind());
311   BuiltinCall->setCallee(Builtin);
312   BuiltinCall->setArg(1, ChainResult.get());
313 
314   return false;
315 }
316 
317 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
318                                      Scope::ScopeFlags NeededScopeFlags,
319                                      unsigned DiagID) {
320   // Scopes aren't available during instantiation. Fortunately, builtin
321   // functions cannot be template args so they cannot be formed through template
322   // instantiation. Therefore checking once during the parse is sufficient.
323   if (SemaRef.inTemplateInstantiation())
324     return false;
325 
326   Scope *S = SemaRef.getCurScope();
327   while (S && !S->isSEHExceptScope())
328     S = S->getParent();
329   if (!S || !(S->getFlags() & NeededScopeFlags)) {
330     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
331     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
332         << DRE->getDecl()->getIdentifier();
333     return true;
334   }
335 
336   return false;
337 }
338 
339 static inline bool isBlockPointer(Expr *Arg) {
340   return Arg->getType()->isBlockPointerType();
341 }
342 
343 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
344 /// void*, which is a requirement of device side enqueue.
345 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
346   const BlockPointerType *BPT =
347       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
348   ArrayRef<QualType> Params =
349       BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
350   unsigned ArgCounter = 0;
351   bool IllegalParams = false;
352   // Iterate through the block parameters until either one is found that is not
353   // a local void*, or the block is valid.
354   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
355        I != E; ++I, ++ArgCounter) {
356     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
357         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
358             LangAS::opencl_local) {
359       // Get the location of the error. If a block literal has been passed
360       // (BlockExpr) then we can point straight to the offending argument,
361       // else we just point to the variable reference.
362       SourceLocation ErrorLoc;
363       if (isa<BlockExpr>(BlockArg)) {
364         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
365         ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
366       } else if (isa<DeclRefExpr>(BlockArg)) {
367         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
368       }
369       S.Diag(ErrorLoc,
370              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
371       IllegalParams = true;
372     }
373   }
374 
375   return IllegalParams;
376 }
377 
378 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
379   if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
380     S.Diag(Call->getLocStart(), diag::err_opencl_requires_extension)
381           << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
382     return true;
383   }
384   return false;
385 }
386 
387 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
388   if (checkArgCount(S, TheCall, 2))
389     return true;
390 
391   if (checkOpenCLSubgroupExt(S, TheCall))
392     return true;
393 
394   // First argument is an ndrange_t type.
395   Expr *NDRangeArg = TheCall->getArg(0);
396   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
397     S.Diag(NDRangeArg->getLocStart(),
398            diag::err_opencl_builtin_expected_type)
399         << TheCall->getDirectCallee() << "'ndrange_t'";
400     return true;
401   }
402 
403   Expr *BlockArg = TheCall->getArg(1);
404   if (!isBlockPointer(BlockArg)) {
405     S.Diag(BlockArg->getLocStart(),
406            diag::err_opencl_builtin_expected_type)
407         << TheCall->getDirectCallee() << "block";
408     return true;
409   }
410   return checkOpenCLBlockArgs(S, BlockArg);
411 }
412 
413 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
414 /// get_kernel_work_group_size
415 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
416 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
417   if (checkArgCount(S, TheCall, 1))
418     return true;
419 
420   Expr *BlockArg = TheCall->getArg(0);
421   if (!isBlockPointer(BlockArg)) {
422     S.Diag(BlockArg->getLocStart(),
423            diag::err_opencl_builtin_expected_type)
424         << TheCall->getDirectCallee() << "block";
425     return true;
426   }
427   return checkOpenCLBlockArgs(S, BlockArg);
428 }
429 
430 /// Diagnose integer type and any valid implicit conversion to it.
431 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
432                                       const QualType &IntType);
433 
434 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
435                                             unsigned Start, unsigned End) {
436   bool IllegalParams = false;
437   for (unsigned I = Start; I <= End; ++I)
438     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
439                                               S.Context.getSizeType());
440   return IllegalParams;
441 }
442 
443 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
444 /// 'local void*' parameter of passed block.
445 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
446                                            Expr *BlockArg,
447                                            unsigned NumNonVarArgs) {
448   const BlockPointerType *BPT =
449       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
450   unsigned NumBlockParams =
451       BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
452   unsigned TotalNumArgs = TheCall->getNumArgs();
453 
454   // For each argument passed to the block, a corresponding uint needs to
455   // be passed to describe the size of the local memory.
456   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
457     S.Diag(TheCall->getLocStart(),
458            diag::err_opencl_enqueue_kernel_local_size_args);
459     return true;
460   }
461 
462   // Check that the sizes of the local memory are specified by integers.
463   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
464                                          TotalNumArgs - 1);
465 }
466 
467 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
468 /// overload formats specified in Table 6.13.17.1.
469 /// int enqueue_kernel(queue_t queue,
470 ///                    kernel_enqueue_flags_t flags,
471 ///                    const ndrange_t ndrange,
472 ///                    void (^block)(void))
473 /// int enqueue_kernel(queue_t queue,
474 ///                    kernel_enqueue_flags_t flags,
475 ///                    const ndrange_t ndrange,
476 ///                    uint num_events_in_wait_list,
477 ///                    clk_event_t *event_wait_list,
478 ///                    clk_event_t *event_ret,
479 ///                    void (^block)(void))
480 /// int enqueue_kernel(queue_t queue,
481 ///                    kernel_enqueue_flags_t flags,
482 ///                    const ndrange_t ndrange,
483 ///                    void (^block)(local void*, ...),
484 ///                    uint size0, ...)
485 /// int enqueue_kernel(queue_t queue,
486 ///                    kernel_enqueue_flags_t flags,
487 ///                    const ndrange_t ndrange,
488 ///                    uint num_events_in_wait_list,
489 ///                    clk_event_t *event_wait_list,
490 ///                    clk_event_t *event_ret,
491 ///                    void (^block)(local void*, ...),
492 ///                    uint size0, ...)
493 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
494   unsigned NumArgs = TheCall->getNumArgs();
495 
496   if (NumArgs < 4) {
497     S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
498     return true;
499   }
500 
501   Expr *Arg0 = TheCall->getArg(0);
502   Expr *Arg1 = TheCall->getArg(1);
503   Expr *Arg2 = TheCall->getArg(2);
504   Expr *Arg3 = TheCall->getArg(3);
505 
506   // First argument always needs to be a queue_t type.
507   if (!Arg0->getType()->isQueueT()) {
508     S.Diag(TheCall->getArg(0)->getLocStart(),
509            diag::err_opencl_builtin_expected_type)
510         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
511     return true;
512   }
513 
514   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
515   if (!Arg1->getType()->isIntegerType()) {
516     S.Diag(TheCall->getArg(1)->getLocStart(),
517            diag::err_opencl_builtin_expected_type)
518         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
519     return true;
520   }
521 
522   // Third argument is always an ndrange_t type.
523   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
524     S.Diag(TheCall->getArg(2)->getLocStart(),
525            diag::err_opencl_builtin_expected_type)
526         << TheCall->getDirectCallee() << "'ndrange_t'";
527     return true;
528   }
529 
530   // With four arguments, there is only one form that the function could be
531   // called in: no events and no variable arguments.
532   if (NumArgs == 4) {
533     // check that the last argument is the right block type.
534     if (!isBlockPointer(Arg3)) {
535       S.Diag(Arg3->getLocStart(), diag::err_opencl_builtin_expected_type)
536           << TheCall->getDirectCallee() << "block";
537       return true;
538     }
539     // we have a block type, check the prototype
540     const BlockPointerType *BPT =
541         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
542     if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
543       S.Diag(Arg3->getLocStart(),
544              diag::err_opencl_enqueue_kernel_blocks_no_args);
545       return true;
546     }
547     return false;
548   }
549   // we can have block + varargs.
550   if (isBlockPointer(Arg3))
551     return (checkOpenCLBlockArgs(S, Arg3) ||
552             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
553   // last two cases with either exactly 7 args or 7 args and varargs.
554   if (NumArgs >= 7) {
555     // check common block argument.
556     Expr *Arg6 = TheCall->getArg(6);
557     if (!isBlockPointer(Arg6)) {
558       S.Diag(Arg6->getLocStart(), diag::err_opencl_builtin_expected_type)
559           << TheCall->getDirectCallee() << "block";
560       return true;
561     }
562     if (checkOpenCLBlockArgs(S, Arg6))
563       return true;
564 
565     // Forth argument has to be any integer type.
566     if (!Arg3->getType()->isIntegerType()) {
567       S.Diag(TheCall->getArg(3)->getLocStart(),
568              diag::err_opencl_builtin_expected_type)
569           << TheCall->getDirectCallee() << "integer";
570       return true;
571     }
572     // check remaining common arguments.
573     Expr *Arg4 = TheCall->getArg(4);
574     Expr *Arg5 = TheCall->getArg(5);
575 
576     // Fifth argument is always passed as a pointer to clk_event_t.
577     if (!Arg4->isNullPointerConstant(S.Context,
578                                      Expr::NPC_ValueDependentIsNotNull) &&
579         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
580       S.Diag(TheCall->getArg(4)->getLocStart(),
581              diag::err_opencl_builtin_expected_type)
582           << TheCall->getDirectCallee()
583           << S.Context.getPointerType(S.Context.OCLClkEventTy);
584       return true;
585     }
586 
587     // Sixth argument is always passed as a pointer to clk_event_t.
588     if (!Arg5->isNullPointerConstant(S.Context,
589                                      Expr::NPC_ValueDependentIsNotNull) &&
590         !(Arg5->getType()->isPointerType() &&
591           Arg5->getType()->getPointeeType()->isClkEventT())) {
592       S.Diag(TheCall->getArg(5)->getLocStart(),
593              diag::err_opencl_builtin_expected_type)
594           << TheCall->getDirectCallee()
595           << S.Context.getPointerType(S.Context.OCLClkEventTy);
596       return true;
597     }
598 
599     if (NumArgs == 7)
600       return false;
601 
602     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
603   }
604 
605   // None of the specific case has been detected, give generic error
606   S.Diag(TheCall->getLocStart(),
607          diag::err_opencl_enqueue_kernel_incorrect_args);
608   return true;
609 }
610 
611 /// Returns OpenCL access qual.
612 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
613     return D->getAttr<OpenCLAccessAttr>();
614 }
615 
616 /// Returns true if pipe element type is different from the pointer.
617 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
618   const Expr *Arg0 = Call->getArg(0);
619   // First argument type should always be pipe.
620   if (!Arg0->getType()->isPipeType()) {
621     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
622         << Call->getDirectCallee() << Arg0->getSourceRange();
623     return true;
624   }
625   OpenCLAccessAttr *AccessQual =
626       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
627   // Validates the access qualifier is compatible with the call.
628   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
629   // read_only and write_only, and assumed to be read_only if no qualifier is
630   // specified.
631   switch (Call->getDirectCallee()->getBuiltinID()) {
632   case Builtin::BIread_pipe:
633   case Builtin::BIreserve_read_pipe:
634   case Builtin::BIcommit_read_pipe:
635   case Builtin::BIwork_group_reserve_read_pipe:
636   case Builtin::BIsub_group_reserve_read_pipe:
637   case Builtin::BIwork_group_commit_read_pipe:
638   case Builtin::BIsub_group_commit_read_pipe:
639     if (!(!AccessQual || AccessQual->isReadOnly())) {
640       S.Diag(Arg0->getLocStart(),
641              diag::err_opencl_builtin_pipe_invalid_access_modifier)
642           << "read_only" << Arg0->getSourceRange();
643       return true;
644     }
645     break;
646   case Builtin::BIwrite_pipe:
647   case Builtin::BIreserve_write_pipe:
648   case Builtin::BIcommit_write_pipe:
649   case Builtin::BIwork_group_reserve_write_pipe:
650   case Builtin::BIsub_group_reserve_write_pipe:
651   case Builtin::BIwork_group_commit_write_pipe:
652   case Builtin::BIsub_group_commit_write_pipe:
653     if (!(AccessQual && AccessQual->isWriteOnly())) {
654       S.Diag(Arg0->getLocStart(),
655              diag::err_opencl_builtin_pipe_invalid_access_modifier)
656           << "write_only" << Arg0->getSourceRange();
657       return true;
658     }
659     break;
660   default:
661     break;
662   }
663   return false;
664 }
665 
666 /// Returns true if pipe element type is different from the pointer.
667 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
668   const Expr *Arg0 = Call->getArg(0);
669   const Expr *ArgIdx = Call->getArg(Idx);
670   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
671   const QualType EltTy = PipeTy->getElementType();
672   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
673   // The Idx argument should be a pointer and the type of the pointer and
674   // the type of pipe element should also be the same.
675   if (!ArgTy ||
676       !S.Context.hasSameType(
677           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
678     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
679         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
680         << ArgIdx->getType() << ArgIdx->getSourceRange();
681     return true;
682   }
683   return false;
684 }
685 
686 // \brief Performs semantic analysis for the read/write_pipe call.
687 // \param S Reference to the semantic analyzer.
688 // \param Call A pointer to the builtin call.
689 // \return True if a semantic error has been found, false otherwise.
690 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
691   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
692   // functions have two forms.
693   switch (Call->getNumArgs()) {
694   case 2:
695     if (checkOpenCLPipeArg(S, Call))
696       return true;
697     // The call with 2 arguments should be
698     // read/write_pipe(pipe T, T*).
699     // Check packet type T.
700     if (checkOpenCLPipePacketType(S, Call, 1))
701       return true;
702     break;
703 
704   case 4: {
705     if (checkOpenCLPipeArg(S, Call))
706       return true;
707     // The call with 4 arguments should be
708     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
709     // Check reserve_id_t.
710     if (!Call->getArg(1)->getType()->isReserveIDT()) {
711       S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
712           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
713           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
714       return true;
715     }
716 
717     // Check the index.
718     const Expr *Arg2 = Call->getArg(2);
719     if (!Arg2->getType()->isIntegerType() &&
720         !Arg2->getType()->isUnsignedIntegerType()) {
721       S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
722           << Call->getDirectCallee() << S.Context.UnsignedIntTy
723           << Arg2->getType() << Arg2->getSourceRange();
724       return true;
725     }
726 
727     // Check packet type T.
728     if (checkOpenCLPipePacketType(S, Call, 3))
729       return true;
730   } break;
731   default:
732     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
733         << Call->getDirectCallee() << Call->getSourceRange();
734     return true;
735   }
736 
737   return false;
738 }
739 
740 // \brief Performs a semantic analysis on the {work_group_/sub_group_
741 //        /_}reserve_{read/write}_pipe
742 // \param S Reference to the semantic analyzer.
743 // \param Call The call to the builtin function to be analyzed.
744 // \return True if a semantic error was found, false otherwise.
745 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
746   if (checkArgCount(S, Call, 2))
747     return true;
748 
749   if (checkOpenCLPipeArg(S, Call))
750     return true;
751 
752   // Check the reserve size.
753   if (!Call->getArg(1)->getType()->isIntegerType() &&
754       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
755     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
756         << Call->getDirectCallee() << S.Context.UnsignedIntTy
757         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
758     return true;
759   }
760 
761   // Since return type of reserve_read/write_pipe built-in function is
762   // reserve_id_t, which is not defined in the builtin def file , we used int
763   // as return type and need to override the return type of these functions.
764   Call->setType(S.Context.OCLReserveIDTy);
765 
766   return false;
767 }
768 
769 // \brief Performs a semantic analysis on {work_group_/sub_group_
770 //        /_}commit_{read/write}_pipe
771 // \param S Reference to the semantic analyzer.
772 // \param Call The call to the builtin function to be analyzed.
773 // \return True if a semantic error was found, false otherwise.
774 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
775   if (checkArgCount(S, Call, 2))
776     return true;
777 
778   if (checkOpenCLPipeArg(S, Call))
779     return true;
780 
781   // Check reserve_id_t.
782   if (!Call->getArg(1)->getType()->isReserveIDT()) {
783     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
784         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
785         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
786     return true;
787   }
788 
789   return false;
790 }
791 
792 // \brief Performs a semantic analysis on the call to built-in Pipe
793 //        Query Functions.
794 // \param S Reference to the semantic analyzer.
795 // \param Call The call to the builtin function to be analyzed.
796 // \return True if a semantic error was found, false otherwise.
797 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
798   if (checkArgCount(S, Call, 1))
799     return true;
800 
801   if (!Call->getArg(0)->getType()->isPipeType()) {
802     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
803         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
804     return true;
805   }
806 
807   return false;
808 }
809 
810 // \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
811 // \brief Performs semantic analysis for the to_global/local/private call.
812 // \param S Reference to the semantic analyzer.
813 // \param BuiltinID ID of the builtin function.
814 // \param Call A pointer to the builtin call.
815 // \return True if a semantic error has been found, false otherwise.
816 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
817                                     CallExpr *Call) {
818   if (Call->getNumArgs() != 1) {
819     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
820         << Call->getDirectCallee() << Call->getSourceRange();
821     return true;
822   }
823 
824   auto RT = Call->getArg(0)->getType();
825   if (!RT->isPointerType() || RT->getPointeeType()
826       .getAddressSpace() == LangAS::opencl_constant) {
827     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
828         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
829     return true;
830   }
831 
832   RT = RT->getPointeeType();
833   auto Qual = RT.getQualifiers();
834   switch (BuiltinID) {
835   case Builtin::BIto_global:
836     Qual.setAddressSpace(LangAS::opencl_global);
837     break;
838   case Builtin::BIto_local:
839     Qual.setAddressSpace(LangAS::opencl_local);
840     break;
841   case Builtin::BIto_private:
842     Qual.setAddressSpace(LangAS::opencl_private);
843     break;
844   default:
845     llvm_unreachable("Invalid builtin function");
846   }
847   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
848       RT.getUnqualifiedType(), Qual)));
849 
850   return false;
851 }
852 
853 ExprResult
854 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
855                                CallExpr *TheCall) {
856   ExprResult TheCallResult(TheCall);
857 
858   // Find out if any arguments are required to be integer constant expressions.
859   unsigned ICEArguments = 0;
860   ASTContext::GetBuiltinTypeError Error;
861   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
862   if (Error != ASTContext::GE_None)
863     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
864 
865   // If any arguments are required to be ICE's, check and diagnose.
866   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
867     // Skip arguments not required to be ICE's.
868     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
869 
870     llvm::APSInt Result;
871     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
872       return true;
873     ICEArguments &= ~(1 << ArgNo);
874   }
875 
876   switch (BuiltinID) {
877   case Builtin::BI__builtin___CFStringMakeConstantString:
878     assert(TheCall->getNumArgs() == 1 &&
879            "Wrong # arguments to builtin CFStringMakeConstantString");
880     if (CheckObjCString(TheCall->getArg(0)))
881       return ExprError();
882     break;
883   case Builtin::BI__builtin_ms_va_start:
884   case Builtin::BI__builtin_stdarg_start:
885   case Builtin::BI__builtin_va_start:
886     if (SemaBuiltinVAStart(BuiltinID, TheCall))
887       return ExprError();
888     break;
889   case Builtin::BI__va_start: {
890     switch (Context.getTargetInfo().getTriple().getArch()) {
891     case llvm::Triple::arm:
892     case llvm::Triple::thumb:
893       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
894         return ExprError();
895       break;
896     default:
897       if (SemaBuiltinVAStart(BuiltinID, TheCall))
898         return ExprError();
899       break;
900     }
901     break;
902   }
903   case Builtin::BI__builtin_isgreater:
904   case Builtin::BI__builtin_isgreaterequal:
905   case Builtin::BI__builtin_isless:
906   case Builtin::BI__builtin_islessequal:
907   case Builtin::BI__builtin_islessgreater:
908   case Builtin::BI__builtin_isunordered:
909     if (SemaBuiltinUnorderedCompare(TheCall))
910       return ExprError();
911     break;
912   case Builtin::BI__builtin_fpclassify:
913     if (SemaBuiltinFPClassification(TheCall, 6))
914       return ExprError();
915     break;
916   case Builtin::BI__builtin_isfinite:
917   case Builtin::BI__builtin_isinf:
918   case Builtin::BI__builtin_isinf_sign:
919   case Builtin::BI__builtin_isnan:
920   case Builtin::BI__builtin_isnormal:
921     if (SemaBuiltinFPClassification(TheCall, 1))
922       return ExprError();
923     break;
924   case Builtin::BI__builtin_shufflevector:
925     return SemaBuiltinShuffleVector(TheCall);
926     // TheCall will be freed by the smart pointer here, but that's fine, since
927     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
928   case Builtin::BI__builtin_prefetch:
929     if (SemaBuiltinPrefetch(TheCall))
930       return ExprError();
931     break;
932   case Builtin::BI__builtin_alloca_with_align:
933     if (SemaBuiltinAllocaWithAlign(TheCall))
934       return ExprError();
935     break;
936   case Builtin::BI__assume:
937   case Builtin::BI__builtin_assume:
938     if (SemaBuiltinAssume(TheCall))
939       return ExprError();
940     break;
941   case Builtin::BI__builtin_assume_aligned:
942     if (SemaBuiltinAssumeAligned(TheCall))
943       return ExprError();
944     break;
945   case Builtin::BI__builtin_object_size:
946     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
947       return ExprError();
948     break;
949   case Builtin::BI__builtin_longjmp:
950     if (SemaBuiltinLongjmp(TheCall))
951       return ExprError();
952     break;
953   case Builtin::BI__builtin_setjmp:
954     if (SemaBuiltinSetjmp(TheCall))
955       return ExprError();
956     break;
957   case Builtin::BI_setjmp:
958   case Builtin::BI_setjmpex:
959     if (checkArgCount(*this, TheCall, 1))
960       return true;
961     break;
962   case Builtin::BI__builtin_classify_type:
963     if (checkArgCount(*this, TheCall, 1)) return true;
964     TheCall->setType(Context.IntTy);
965     break;
966   case Builtin::BI__builtin_constant_p:
967     if (checkArgCount(*this, TheCall, 1)) return true;
968     TheCall->setType(Context.IntTy);
969     break;
970   case Builtin::BI__sync_fetch_and_add:
971   case Builtin::BI__sync_fetch_and_add_1:
972   case Builtin::BI__sync_fetch_and_add_2:
973   case Builtin::BI__sync_fetch_and_add_4:
974   case Builtin::BI__sync_fetch_and_add_8:
975   case Builtin::BI__sync_fetch_and_add_16:
976   case Builtin::BI__sync_fetch_and_sub:
977   case Builtin::BI__sync_fetch_and_sub_1:
978   case Builtin::BI__sync_fetch_and_sub_2:
979   case Builtin::BI__sync_fetch_and_sub_4:
980   case Builtin::BI__sync_fetch_and_sub_8:
981   case Builtin::BI__sync_fetch_and_sub_16:
982   case Builtin::BI__sync_fetch_and_or:
983   case Builtin::BI__sync_fetch_and_or_1:
984   case Builtin::BI__sync_fetch_and_or_2:
985   case Builtin::BI__sync_fetch_and_or_4:
986   case Builtin::BI__sync_fetch_and_or_8:
987   case Builtin::BI__sync_fetch_and_or_16:
988   case Builtin::BI__sync_fetch_and_and:
989   case Builtin::BI__sync_fetch_and_and_1:
990   case Builtin::BI__sync_fetch_and_and_2:
991   case Builtin::BI__sync_fetch_and_and_4:
992   case Builtin::BI__sync_fetch_and_and_8:
993   case Builtin::BI__sync_fetch_and_and_16:
994   case Builtin::BI__sync_fetch_and_xor:
995   case Builtin::BI__sync_fetch_and_xor_1:
996   case Builtin::BI__sync_fetch_and_xor_2:
997   case Builtin::BI__sync_fetch_and_xor_4:
998   case Builtin::BI__sync_fetch_and_xor_8:
999   case Builtin::BI__sync_fetch_and_xor_16:
1000   case Builtin::BI__sync_fetch_and_nand:
1001   case Builtin::BI__sync_fetch_and_nand_1:
1002   case Builtin::BI__sync_fetch_and_nand_2:
1003   case Builtin::BI__sync_fetch_and_nand_4:
1004   case Builtin::BI__sync_fetch_and_nand_8:
1005   case Builtin::BI__sync_fetch_and_nand_16:
1006   case Builtin::BI__sync_add_and_fetch:
1007   case Builtin::BI__sync_add_and_fetch_1:
1008   case Builtin::BI__sync_add_and_fetch_2:
1009   case Builtin::BI__sync_add_and_fetch_4:
1010   case Builtin::BI__sync_add_and_fetch_8:
1011   case Builtin::BI__sync_add_and_fetch_16:
1012   case Builtin::BI__sync_sub_and_fetch:
1013   case Builtin::BI__sync_sub_and_fetch_1:
1014   case Builtin::BI__sync_sub_and_fetch_2:
1015   case Builtin::BI__sync_sub_and_fetch_4:
1016   case Builtin::BI__sync_sub_and_fetch_8:
1017   case Builtin::BI__sync_sub_and_fetch_16:
1018   case Builtin::BI__sync_and_and_fetch:
1019   case Builtin::BI__sync_and_and_fetch_1:
1020   case Builtin::BI__sync_and_and_fetch_2:
1021   case Builtin::BI__sync_and_and_fetch_4:
1022   case Builtin::BI__sync_and_and_fetch_8:
1023   case Builtin::BI__sync_and_and_fetch_16:
1024   case Builtin::BI__sync_or_and_fetch:
1025   case Builtin::BI__sync_or_and_fetch_1:
1026   case Builtin::BI__sync_or_and_fetch_2:
1027   case Builtin::BI__sync_or_and_fetch_4:
1028   case Builtin::BI__sync_or_and_fetch_8:
1029   case Builtin::BI__sync_or_and_fetch_16:
1030   case Builtin::BI__sync_xor_and_fetch:
1031   case Builtin::BI__sync_xor_and_fetch_1:
1032   case Builtin::BI__sync_xor_and_fetch_2:
1033   case Builtin::BI__sync_xor_and_fetch_4:
1034   case Builtin::BI__sync_xor_and_fetch_8:
1035   case Builtin::BI__sync_xor_and_fetch_16:
1036   case Builtin::BI__sync_nand_and_fetch:
1037   case Builtin::BI__sync_nand_and_fetch_1:
1038   case Builtin::BI__sync_nand_and_fetch_2:
1039   case Builtin::BI__sync_nand_and_fetch_4:
1040   case Builtin::BI__sync_nand_and_fetch_8:
1041   case Builtin::BI__sync_nand_and_fetch_16:
1042   case Builtin::BI__sync_val_compare_and_swap:
1043   case Builtin::BI__sync_val_compare_and_swap_1:
1044   case Builtin::BI__sync_val_compare_and_swap_2:
1045   case Builtin::BI__sync_val_compare_and_swap_4:
1046   case Builtin::BI__sync_val_compare_and_swap_8:
1047   case Builtin::BI__sync_val_compare_and_swap_16:
1048   case Builtin::BI__sync_bool_compare_and_swap:
1049   case Builtin::BI__sync_bool_compare_and_swap_1:
1050   case Builtin::BI__sync_bool_compare_and_swap_2:
1051   case Builtin::BI__sync_bool_compare_and_swap_4:
1052   case Builtin::BI__sync_bool_compare_and_swap_8:
1053   case Builtin::BI__sync_bool_compare_and_swap_16:
1054   case Builtin::BI__sync_lock_test_and_set:
1055   case Builtin::BI__sync_lock_test_and_set_1:
1056   case Builtin::BI__sync_lock_test_and_set_2:
1057   case Builtin::BI__sync_lock_test_and_set_4:
1058   case Builtin::BI__sync_lock_test_and_set_8:
1059   case Builtin::BI__sync_lock_test_and_set_16:
1060   case Builtin::BI__sync_lock_release:
1061   case Builtin::BI__sync_lock_release_1:
1062   case Builtin::BI__sync_lock_release_2:
1063   case Builtin::BI__sync_lock_release_4:
1064   case Builtin::BI__sync_lock_release_8:
1065   case Builtin::BI__sync_lock_release_16:
1066   case Builtin::BI__sync_swap:
1067   case Builtin::BI__sync_swap_1:
1068   case Builtin::BI__sync_swap_2:
1069   case Builtin::BI__sync_swap_4:
1070   case Builtin::BI__sync_swap_8:
1071   case Builtin::BI__sync_swap_16:
1072     return SemaBuiltinAtomicOverloaded(TheCallResult);
1073   case Builtin::BI__builtin_nontemporal_load:
1074   case Builtin::BI__builtin_nontemporal_store:
1075     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1076 #define BUILTIN(ID, TYPE, ATTRS)
1077 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1078   case Builtin::BI##ID: \
1079     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1080 #include "clang/Basic/Builtins.def"
1081   case Builtin::BI__annotation:
1082     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1083       return ExprError();
1084     break;
1085   case Builtin::BI__builtin_annotation:
1086     if (SemaBuiltinAnnotation(*this, TheCall))
1087       return ExprError();
1088     break;
1089   case Builtin::BI__builtin_addressof:
1090     if (SemaBuiltinAddressof(*this, TheCall))
1091       return ExprError();
1092     break;
1093   case Builtin::BI__builtin_add_overflow:
1094   case Builtin::BI__builtin_sub_overflow:
1095   case Builtin::BI__builtin_mul_overflow:
1096     if (SemaBuiltinOverflow(*this, TheCall))
1097       return ExprError();
1098     break;
1099   case Builtin::BI__builtin_operator_new:
1100   case Builtin::BI__builtin_operator_delete: {
1101     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1102     ExprResult Res =
1103         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1104     if (Res.isInvalid())
1105       CorrectDelayedTyposInExpr(TheCallResult.get());
1106     return Res;
1107   }
1108   case Builtin::BI__builtin_dump_struct: {
1109     // We first want to ensure we are called with 2 arguments
1110     if (checkArgCount(*this, TheCall, 2))
1111       return ExprError();
1112     // Ensure that the first argument is of type 'struct XX *'
1113     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1114     const QualType PtrArgType = PtrArg->getType();
1115     if (!PtrArgType->isPointerType() ||
1116         !PtrArgType->getPointeeType()->isRecordType()) {
1117       Diag(PtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1118           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1119           << "structure pointer";
1120       return ExprError();
1121     }
1122 
1123     // Ensure that the second argument is of type 'FunctionType'
1124     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1125     const QualType FnPtrArgType = FnPtrArg->getType();
1126     if (!FnPtrArgType->isPointerType()) {
1127       Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1128           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1129           << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1130       return ExprError();
1131     }
1132 
1133     const auto *FuncType =
1134         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1135 
1136     if (!FuncType) {
1137       Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1138           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1139           << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1140       return ExprError();
1141     }
1142 
1143     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1144       if (!FT->getNumParams()) {
1145         Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1146             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1147             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1148         return ExprError();
1149       }
1150       QualType PT = FT->getParamType(0);
1151       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1152           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1153           !PT->getPointeeType().isConstQualified()) {
1154         Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1155             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1156             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1157         return ExprError();
1158       }
1159     }
1160 
1161     TheCall->setType(Context.IntTy);
1162     break;
1163   }
1164 
1165   // check secure string manipulation functions where overflows
1166   // are detectable at compile time
1167   case Builtin::BI__builtin___memcpy_chk:
1168   case Builtin::BI__builtin___memmove_chk:
1169   case Builtin::BI__builtin___memset_chk:
1170   case Builtin::BI__builtin___strlcat_chk:
1171   case Builtin::BI__builtin___strlcpy_chk:
1172   case Builtin::BI__builtin___strncat_chk:
1173   case Builtin::BI__builtin___strncpy_chk:
1174   case Builtin::BI__builtin___stpncpy_chk:
1175     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
1176     break;
1177   case Builtin::BI__builtin___memccpy_chk:
1178     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
1179     break;
1180   case Builtin::BI__builtin___snprintf_chk:
1181   case Builtin::BI__builtin___vsnprintf_chk:
1182     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
1183     break;
1184   case Builtin::BI__builtin_call_with_static_chain:
1185     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1186       return ExprError();
1187     break;
1188   case Builtin::BI__exception_code:
1189   case Builtin::BI_exception_code:
1190     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1191                                  diag::err_seh___except_block))
1192       return ExprError();
1193     break;
1194   case Builtin::BI__exception_info:
1195   case Builtin::BI_exception_info:
1196     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1197                                  diag::err_seh___except_filter))
1198       return ExprError();
1199     break;
1200   case Builtin::BI__GetExceptionInfo:
1201     if (checkArgCount(*this, TheCall, 1))
1202       return ExprError();
1203 
1204     if (CheckCXXThrowOperand(
1205             TheCall->getLocStart(),
1206             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1207             TheCall))
1208       return ExprError();
1209 
1210     TheCall->setType(Context.VoidPtrTy);
1211     break;
1212   // OpenCL v2.0, s6.13.16 - Pipe functions
1213   case Builtin::BIread_pipe:
1214   case Builtin::BIwrite_pipe:
1215     // Since those two functions are declared with var args, we need a semantic
1216     // check for the argument.
1217     if (SemaBuiltinRWPipe(*this, TheCall))
1218       return ExprError();
1219     TheCall->setType(Context.IntTy);
1220     break;
1221   case Builtin::BIreserve_read_pipe:
1222   case Builtin::BIreserve_write_pipe:
1223   case Builtin::BIwork_group_reserve_read_pipe:
1224   case Builtin::BIwork_group_reserve_write_pipe:
1225     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1226       return ExprError();
1227     break;
1228   case Builtin::BIsub_group_reserve_read_pipe:
1229   case Builtin::BIsub_group_reserve_write_pipe:
1230     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1231         SemaBuiltinReserveRWPipe(*this, TheCall))
1232       return ExprError();
1233     break;
1234   case Builtin::BIcommit_read_pipe:
1235   case Builtin::BIcommit_write_pipe:
1236   case Builtin::BIwork_group_commit_read_pipe:
1237   case Builtin::BIwork_group_commit_write_pipe:
1238     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1239       return ExprError();
1240     break;
1241   case Builtin::BIsub_group_commit_read_pipe:
1242   case Builtin::BIsub_group_commit_write_pipe:
1243     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1244         SemaBuiltinCommitRWPipe(*this, TheCall))
1245       return ExprError();
1246     break;
1247   case Builtin::BIget_pipe_num_packets:
1248   case Builtin::BIget_pipe_max_packets:
1249     if (SemaBuiltinPipePackets(*this, TheCall))
1250       return ExprError();
1251     TheCall->setType(Context.UnsignedIntTy);
1252     break;
1253   case Builtin::BIto_global:
1254   case Builtin::BIto_local:
1255   case Builtin::BIto_private:
1256     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1257       return ExprError();
1258     break;
1259   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1260   case Builtin::BIenqueue_kernel:
1261     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1262       return ExprError();
1263     break;
1264   case Builtin::BIget_kernel_work_group_size:
1265   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1266     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1267       return ExprError();
1268     break;
1269   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1270   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1271     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1272       return ExprError();
1273     break;
1274   case Builtin::BI__builtin_os_log_format:
1275   case Builtin::BI__builtin_os_log_format_buffer_size:
1276     if (SemaBuiltinOSLogFormat(TheCall))
1277       return ExprError();
1278     break;
1279   }
1280 
1281   // Since the target specific builtins for each arch overlap, only check those
1282   // of the arch we are compiling for.
1283   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1284     switch (Context.getTargetInfo().getTriple().getArch()) {
1285       case llvm::Triple::arm:
1286       case llvm::Triple::armeb:
1287       case llvm::Triple::thumb:
1288       case llvm::Triple::thumbeb:
1289         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1290           return ExprError();
1291         break;
1292       case llvm::Triple::aarch64:
1293       case llvm::Triple::aarch64_be:
1294         if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1295           return ExprError();
1296         break;
1297       case llvm::Triple::mips:
1298       case llvm::Triple::mipsel:
1299       case llvm::Triple::mips64:
1300       case llvm::Triple::mips64el:
1301         if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1302           return ExprError();
1303         break;
1304       case llvm::Triple::systemz:
1305         if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1306           return ExprError();
1307         break;
1308       case llvm::Triple::x86:
1309       case llvm::Triple::x86_64:
1310         if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1311           return ExprError();
1312         break;
1313       case llvm::Triple::ppc:
1314       case llvm::Triple::ppc64:
1315       case llvm::Triple::ppc64le:
1316         if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1317           return ExprError();
1318         break;
1319       default:
1320         break;
1321     }
1322   }
1323 
1324   return TheCallResult;
1325 }
1326 
1327 // Get the valid immediate range for the specified NEON type code.
1328 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1329   NeonTypeFlags Type(t);
1330   int IsQuad = ForceQuad ? true : Type.isQuad();
1331   switch (Type.getEltType()) {
1332   case NeonTypeFlags::Int8:
1333   case NeonTypeFlags::Poly8:
1334     return shift ? 7 : (8 << IsQuad) - 1;
1335   case NeonTypeFlags::Int16:
1336   case NeonTypeFlags::Poly16:
1337     return shift ? 15 : (4 << IsQuad) - 1;
1338   case NeonTypeFlags::Int32:
1339     return shift ? 31 : (2 << IsQuad) - 1;
1340   case NeonTypeFlags::Int64:
1341   case NeonTypeFlags::Poly64:
1342     return shift ? 63 : (1 << IsQuad) - 1;
1343   case NeonTypeFlags::Poly128:
1344     return shift ? 127 : (1 << IsQuad) - 1;
1345   case NeonTypeFlags::Float16:
1346     assert(!shift && "cannot shift float types!");
1347     return (4 << IsQuad) - 1;
1348   case NeonTypeFlags::Float32:
1349     assert(!shift && "cannot shift float types!");
1350     return (2 << IsQuad) - 1;
1351   case NeonTypeFlags::Float64:
1352     assert(!shift && "cannot shift float types!");
1353     return (1 << IsQuad) - 1;
1354   }
1355   llvm_unreachable("Invalid NeonTypeFlag!");
1356 }
1357 
1358 /// getNeonEltType - Return the QualType corresponding to the elements of
1359 /// the vector type specified by the NeonTypeFlags.  This is used to check
1360 /// the pointer arguments for Neon load/store intrinsics.
1361 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1362                                bool IsPolyUnsigned, bool IsInt64Long) {
1363   switch (Flags.getEltType()) {
1364   case NeonTypeFlags::Int8:
1365     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1366   case NeonTypeFlags::Int16:
1367     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1368   case NeonTypeFlags::Int32:
1369     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1370   case NeonTypeFlags::Int64:
1371     if (IsInt64Long)
1372       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1373     else
1374       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1375                                 : Context.LongLongTy;
1376   case NeonTypeFlags::Poly8:
1377     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1378   case NeonTypeFlags::Poly16:
1379     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1380   case NeonTypeFlags::Poly64:
1381     if (IsInt64Long)
1382       return Context.UnsignedLongTy;
1383     else
1384       return Context.UnsignedLongLongTy;
1385   case NeonTypeFlags::Poly128:
1386     break;
1387   case NeonTypeFlags::Float16:
1388     return Context.HalfTy;
1389   case NeonTypeFlags::Float32:
1390     return Context.FloatTy;
1391   case NeonTypeFlags::Float64:
1392     return Context.DoubleTy;
1393   }
1394   llvm_unreachable("Invalid NeonTypeFlag!");
1395 }
1396 
1397 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1398   llvm::APSInt Result;
1399   uint64_t mask = 0;
1400   unsigned TV = 0;
1401   int PtrArgNum = -1;
1402   bool HasConstPtr = false;
1403   switch (BuiltinID) {
1404 #define GET_NEON_OVERLOAD_CHECK
1405 #include "clang/Basic/arm_neon.inc"
1406 #include "clang/Basic/arm_fp16.inc"
1407 #undef GET_NEON_OVERLOAD_CHECK
1408   }
1409 
1410   // For NEON intrinsics which are overloaded on vector element type, validate
1411   // the immediate which specifies which variant to emit.
1412   unsigned ImmArg = TheCall->getNumArgs()-1;
1413   if (mask) {
1414     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1415       return true;
1416 
1417     TV = Result.getLimitedValue(64);
1418     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1419       return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
1420         << TheCall->getArg(ImmArg)->getSourceRange();
1421   }
1422 
1423   if (PtrArgNum >= 0) {
1424     // Check that pointer arguments have the specified type.
1425     Expr *Arg = TheCall->getArg(PtrArgNum);
1426     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1427       Arg = ICE->getSubExpr();
1428     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1429     QualType RHSTy = RHS.get()->getType();
1430 
1431     llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
1432     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1433                           Arch == llvm::Triple::aarch64_be;
1434     bool IsInt64Long =
1435         Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1436     QualType EltTy =
1437         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
1438     if (HasConstPtr)
1439       EltTy = EltTy.withConst();
1440     QualType LHSTy = Context.getPointerType(EltTy);
1441     AssignConvertType ConvTy;
1442     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1443     if (RHS.isInvalid())
1444       return true;
1445     if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1446                                  RHS.get(), AA_Assigning))
1447       return true;
1448   }
1449 
1450   // For NEON intrinsics which take an immediate value as part of the
1451   // instruction, range check them here.
1452   unsigned i = 0, l = 0, u = 0;
1453   switch (BuiltinID) {
1454   default:
1455     return false;
1456 #define GET_NEON_IMMEDIATE_CHECK
1457 #include "clang/Basic/arm_neon.inc"
1458 #include "clang/Basic/arm_fp16.inc"
1459 #undef GET_NEON_IMMEDIATE_CHECK
1460   }
1461 
1462   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1463 }
1464 
1465 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1466                                         unsigned MaxWidth) {
1467   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1468           BuiltinID == ARM::BI__builtin_arm_ldaex ||
1469           BuiltinID == ARM::BI__builtin_arm_strex ||
1470           BuiltinID == ARM::BI__builtin_arm_stlex ||
1471           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1472           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1473           BuiltinID == AArch64::BI__builtin_arm_strex ||
1474           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1475          "unexpected ARM builtin");
1476   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1477                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1478                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1479                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
1480 
1481   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1482 
1483   // Ensure that we have the proper number of arguments.
1484   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1485     return true;
1486 
1487   // Inspect the pointer argument of the atomic builtin.  This should always be
1488   // a pointer type, whose element is an integral scalar or pointer type.
1489   // Because it is a pointer type, we don't have to worry about any implicit
1490   // casts here.
1491   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1492   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1493   if (PointerArgRes.isInvalid())
1494     return true;
1495   PointerArg = PointerArgRes.get();
1496 
1497   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1498   if (!pointerType) {
1499     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1500       << PointerArg->getType() << PointerArg->getSourceRange();
1501     return true;
1502   }
1503 
1504   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1505   // task is to insert the appropriate casts into the AST. First work out just
1506   // what the appropriate type is.
1507   QualType ValType = pointerType->getPointeeType();
1508   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1509   if (IsLdrex)
1510     AddrType.addConst();
1511 
1512   // Issue a warning if the cast is dodgy.
1513   CastKind CastNeeded = CK_NoOp;
1514   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1515     CastNeeded = CK_BitCast;
1516     Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1517       << PointerArg->getType()
1518       << Context.getPointerType(AddrType)
1519       << AA_Passing << PointerArg->getSourceRange();
1520   }
1521 
1522   // Finally, do the cast and replace the argument with the corrected version.
1523   AddrType = Context.getPointerType(AddrType);
1524   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1525   if (PointerArgRes.isInvalid())
1526     return true;
1527   PointerArg = PointerArgRes.get();
1528 
1529   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1530 
1531   // In general, we allow ints, floats and pointers to be loaded and stored.
1532   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1533       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1534     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1535       << PointerArg->getType() << PointerArg->getSourceRange();
1536     return true;
1537   }
1538 
1539   // But ARM doesn't have instructions to deal with 128-bit versions.
1540   if (Context.getTypeSize(ValType) > MaxWidth) {
1541     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
1542     Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1543       << PointerArg->getType() << PointerArg->getSourceRange();
1544     return true;
1545   }
1546 
1547   switch (ValType.getObjCLifetime()) {
1548   case Qualifiers::OCL_None:
1549   case Qualifiers::OCL_ExplicitNone:
1550     // okay
1551     break;
1552 
1553   case Qualifiers::OCL_Weak:
1554   case Qualifiers::OCL_Strong:
1555   case Qualifiers::OCL_Autoreleasing:
1556     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1557       << ValType << PointerArg->getSourceRange();
1558     return true;
1559   }
1560 
1561   if (IsLdrex) {
1562     TheCall->setType(ValType);
1563     return false;
1564   }
1565 
1566   // Initialize the argument to be stored.
1567   ExprResult ValArg = TheCall->getArg(0);
1568   InitializedEntity Entity = InitializedEntity::InitializeParameter(
1569       Context, ValType, /*consume*/ false);
1570   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1571   if (ValArg.isInvalid())
1572     return true;
1573   TheCall->setArg(0, ValArg.get());
1574 
1575   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1576   // but the custom checker bypasses all default analysis.
1577   TheCall->setType(Context.IntTy);
1578   return false;
1579 }
1580 
1581 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1582   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1583       BuiltinID == ARM::BI__builtin_arm_ldaex ||
1584       BuiltinID == ARM::BI__builtin_arm_strex ||
1585       BuiltinID == ARM::BI__builtin_arm_stlex) {
1586     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1587   }
1588 
1589   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1590     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1591       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1592   }
1593 
1594   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1595       BuiltinID == ARM::BI__builtin_arm_wsr64)
1596     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1597 
1598   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1599       BuiltinID == ARM::BI__builtin_arm_rsrp ||
1600       BuiltinID == ARM::BI__builtin_arm_wsr ||
1601       BuiltinID == ARM::BI__builtin_arm_wsrp)
1602     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1603 
1604   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1605     return true;
1606 
1607   // For intrinsics which take an immediate value as part of the instruction,
1608   // range check them here.
1609   // FIXME: VFP Intrinsics should error if VFP not present.
1610   switch (BuiltinID) {
1611   default: return false;
1612   case ARM::BI__builtin_arm_ssat:
1613     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
1614   case ARM::BI__builtin_arm_usat:
1615     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
1616   case ARM::BI__builtin_arm_ssat16:
1617     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
1618   case ARM::BI__builtin_arm_usat16:
1619     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
1620   case ARM::BI__builtin_arm_vcvtr_f:
1621   case ARM::BI__builtin_arm_vcvtr_d:
1622     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
1623   case ARM::BI__builtin_arm_dmb:
1624   case ARM::BI__builtin_arm_dsb:
1625   case ARM::BI__builtin_arm_isb:
1626   case ARM::BI__builtin_arm_dbg:
1627     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
1628   }
1629 }
1630 
1631 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1632                                          CallExpr *TheCall) {
1633   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1634       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1635       BuiltinID == AArch64::BI__builtin_arm_strex ||
1636       BuiltinID == AArch64::BI__builtin_arm_stlex) {
1637     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1638   }
1639 
1640   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1641     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1642       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1643       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1644       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1645   }
1646 
1647   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1648       BuiltinID == AArch64::BI__builtin_arm_wsr64)
1649     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1650 
1651   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1652       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1653       BuiltinID == AArch64::BI__builtin_arm_wsr ||
1654       BuiltinID == AArch64::BI__builtin_arm_wsrp)
1655     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1656 
1657   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1658     return true;
1659 
1660   // For intrinsics which take an immediate value as part of the instruction,
1661   // range check them here.
1662   unsigned i = 0, l = 0, u = 0;
1663   switch (BuiltinID) {
1664   default: return false;
1665   case AArch64::BI__builtin_arm_dmb:
1666   case AArch64::BI__builtin_arm_dsb:
1667   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1668   }
1669 
1670   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1671 }
1672 
1673 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1674 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1675 // ordering for DSP is unspecified. MSA is ordered by the data format used
1676 // by the underlying instruction i.e., df/m, df/n and then by size.
1677 //
1678 // FIXME: The size tests here should instead be tablegen'd along with the
1679 //        definitions from include/clang/Basic/BuiltinsMips.def.
1680 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
1681 //        be too.
1682 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1683   unsigned i = 0, l = 0, u = 0, m = 0;
1684   switch (BuiltinID) {
1685   default: return false;
1686   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1687   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
1688   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1689   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1690   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1691   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1692   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
1693   // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1694   // df/m field.
1695   // These intrinsics take an unsigned 3 bit immediate.
1696   case Mips::BI__builtin_msa_bclri_b:
1697   case Mips::BI__builtin_msa_bnegi_b:
1698   case Mips::BI__builtin_msa_bseti_b:
1699   case Mips::BI__builtin_msa_sat_s_b:
1700   case Mips::BI__builtin_msa_sat_u_b:
1701   case Mips::BI__builtin_msa_slli_b:
1702   case Mips::BI__builtin_msa_srai_b:
1703   case Mips::BI__builtin_msa_srari_b:
1704   case Mips::BI__builtin_msa_srli_b:
1705   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1706   case Mips::BI__builtin_msa_binsli_b:
1707   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1708   // These intrinsics take an unsigned 4 bit immediate.
1709   case Mips::BI__builtin_msa_bclri_h:
1710   case Mips::BI__builtin_msa_bnegi_h:
1711   case Mips::BI__builtin_msa_bseti_h:
1712   case Mips::BI__builtin_msa_sat_s_h:
1713   case Mips::BI__builtin_msa_sat_u_h:
1714   case Mips::BI__builtin_msa_slli_h:
1715   case Mips::BI__builtin_msa_srai_h:
1716   case Mips::BI__builtin_msa_srari_h:
1717   case Mips::BI__builtin_msa_srli_h:
1718   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1719   case Mips::BI__builtin_msa_binsli_h:
1720   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
1721   // These intrinsics take an unsigned 5 bit immediate.
1722   // The first block of intrinsics actually have an unsigned 5 bit field,
1723   // not a df/n field.
1724   case Mips::BI__builtin_msa_clei_u_b:
1725   case Mips::BI__builtin_msa_clei_u_h:
1726   case Mips::BI__builtin_msa_clei_u_w:
1727   case Mips::BI__builtin_msa_clei_u_d:
1728   case Mips::BI__builtin_msa_clti_u_b:
1729   case Mips::BI__builtin_msa_clti_u_h:
1730   case Mips::BI__builtin_msa_clti_u_w:
1731   case Mips::BI__builtin_msa_clti_u_d:
1732   case Mips::BI__builtin_msa_maxi_u_b:
1733   case Mips::BI__builtin_msa_maxi_u_h:
1734   case Mips::BI__builtin_msa_maxi_u_w:
1735   case Mips::BI__builtin_msa_maxi_u_d:
1736   case Mips::BI__builtin_msa_mini_u_b:
1737   case Mips::BI__builtin_msa_mini_u_h:
1738   case Mips::BI__builtin_msa_mini_u_w:
1739   case Mips::BI__builtin_msa_mini_u_d:
1740   case Mips::BI__builtin_msa_addvi_b:
1741   case Mips::BI__builtin_msa_addvi_h:
1742   case Mips::BI__builtin_msa_addvi_w:
1743   case Mips::BI__builtin_msa_addvi_d:
1744   case Mips::BI__builtin_msa_bclri_w:
1745   case Mips::BI__builtin_msa_bnegi_w:
1746   case Mips::BI__builtin_msa_bseti_w:
1747   case Mips::BI__builtin_msa_sat_s_w:
1748   case Mips::BI__builtin_msa_sat_u_w:
1749   case Mips::BI__builtin_msa_slli_w:
1750   case Mips::BI__builtin_msa_srai_w:
1751   case Mips::BI__builtin_msa_srari_w:
1752   case Mips::BI__builtin_msa_srli_w:
1753   case Mips::BI__builtin_msa_srlri_w:
1754   case Mips::BI__builtin_msa_subvi_b:
1755   case Mips::BI__builtin_msa_subvi_h:
1756   case Mips::BI__builtin_msa_subvi_w:
1757   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1758   case Mips::BI__builtin_msa_binsli_w:
1759   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1760   // These intrinsics take an unsigned 6 bit immediate.
1761   case Mips::BI__builtin_msa_bclri_d:
1762   case Mips::BI__builtin_msa_bnegi_d:
1763   case Mips::BI__builtin_msa_bseti_d:
1764   case Mips::BI__builtin_msa_sat_s_d:
1765   case Mips::BI__builtin_msa_sat_u_d:
1766   case Mips::BI__builtin_msa_slli_d:
1767   case Mips::BI__builtin_msa_srai_d:
1768   case Mips::BI__builtin_msa_srari_d:
1769   case Mips::BI__builtin_msa_srli_d:
1770   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1771   case Mips::BI__builtin_msa_binsli_d:
1772   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1773   // These intrinsics take a signed 5 bit immediate.
1774   case Mips::BI__builtin_msa_ceqi_b:
1775   case Mips::BI__builtin_msa_ceqi_h:
1776   case Mips::BI__builtin_msa_ceqi_w:
1777   case Mips::BI__builtin_msa_ceqi_d:
1778   case Mips::BI__builtin_msa_clti_s_b:
1779   case Mips::BI__builtin_msa_clti_s_h:
1780   case Mips::BI__builtin_msa_clti_s_w:
1781   case Mips::BI__builtin_msa_clti_s_d:
1782   case Mips::BI__builtin_msa_clei_s_b:
1783   case Mips::BI__builtin_msa_clei_s_h:
1784   case Mips::BI__builtin_msa_clei_s_w:
1785   case Mips::BI__builtin_msa_clei_s_d:
1786   case Mips::BI__builtin_msa_maxi_s_b:
1787   case Mips::BI__builtin_msa_maxi_s_h:
1788   case Mips::BI__builtin_msa_maxi_s_w:
1789   case Mips::BI__builtin_msa_maxi_s_d:
1790   case Mips::BI__builtin_msa_mini_s_b:
1791   case Mips::BI__builtin_msa_mini_s_h:
1792   case Mips::BI__builtin_msa_mini_s_w:
1793   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
1794   // These intrinsics take an unsigned 8 bit immediate.
1795   case Mips::BI__builtin_msa_andi_b:
1796   case Mips::BI__builtin_msa_nori_b:
1797   case Mips::BI__builtin_msa_ori_b:
1798   case Mips::BI__builtin_msa_shf_b:
1799   case Mips::BI__builtin_msa_shf_h:
1800   case Mips::BI__builtin_msa_shf_w:
1801   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
1802   case Mips::BI__builtin_msa_bseli_b:
1803   case Mips::BI__builtin_msa_bmnzi_b:
1804   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
1805   // df/n format
1806   // These intrinsics take an unsigned 4 bit immediate.
1807   case Mips::BI__builtin_msa_copy_s_b:
1808   case Mips::BI__builtin_msa_copy_u_b:
1809   case Mips::BI__builtin_msa_insve_b:
1810   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
1811   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
1812   // These intrinsics take an unsigned 3 bit immediate.
1813   case Mips::BI__builtin_msa_copy_s_h:
1814   case Mips::BI__builtin_msa_copy_u_h:
1815   case Mips::BI__builtin_msa_insve_h:
1816   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
1817   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1818   // These intrinsics take an unsigned 2 bit immediate.
1819   case Mips::BI__builtin_msa_copy_s_w:
1820   case Mips::BI__builtin_msa_copy_u_w:
1821   case Mips::BI__builtin_msa_insve_w:
1822   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
1823   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1824   // These intrinsics take an unsigned 1 bit immediate.
1825   case Mips::BI__builtin_msa_copy_s_d:
1826   case Mips::BI__builtin_msa_copy_u_d:
1827   case Mips::BI__builtin_msa_insve_d:
1828   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
1829   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1830   // Memory offsets and immediate loads.
1831   // These intrinsics take a signed 10 bit immediate.
1832   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
1833   case Mips::BI__builtin_msa_ldi_h:
1834   case Mips::BI__builtin_msa_ldi_w:
1835   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1836   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1837   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1838   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1839   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1840   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1841   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1842   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1843   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
1844   }
1845 
1846   if (!m)
1847     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1848 
1849   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1850          SemaBuiltinConstantArgMultiple(TheCall, i, m);
1851 }
1852 
1853 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1854   unsigned i = 0, l = 0, u = 0;
1855   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1856                       BuiltinID == PPC::BI__builtin_divdeu ||
1857                       BuiltinID == PPC::BI__builtin_bpermd;
1858   bool IsTarget64Bit = Context.getTargetInfo()
1859                               .getTypeWidth(Context
1860                                             .getTargetInfo()
1861                                             .getIntPtrType()) == 64;
1862   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1863                        BuiltinID == PPC::BI__builtin_divweu ||
1864                        BuiltinID == PPC::BI__builtin_divde ||
1865                        BuiltinID == PPC::BI__builtin_divdeu;
1866 
1867   if (Is64BitBltin && !IsTarget64Bit)
1868       return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1869              << TheCall->getSourceRange();
1870 
1871   if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1872       (BuiltinID == PPC::BI__builtin_bpermd &&
1873        !Context.getTargetInfo().hasFeature("bpermd")))
1874     return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1875            << TheCall->getSourceRange();
1876 
1877   switch (BuiltinID) {
1878   default: return false;
1879   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1880   case PPC::BI__builtin_altivec_crypto_vshasigmad:
1881     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1882            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1883   case PPC::BI__builtin_tbegin:
1884   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1885   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1886   case PPC::BI__builtin_tabortwc:
1887   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1888   case PPC::BI__builtin_tabortwci:
1889   case PPC::BI__builtin_tabortdci:
1890     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1891            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1892   case PPC::BI__builtin_vsx_xxpermdi:
1893   case PPC::BI__builtin_vsx_xxsldwi:
1894     return SemaBuiltinVSX(TheCall);
1895   }
1896   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1897 }
1898 
1899 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1900                                            CallExpr *TheCall) {
1901   if (BuiltinID == SystemZ::BI__builtin_tabort) {
1902     Expr *Arg = TheCall->getArg(0);
1903     llvm::APSInt AbortCode(32);
1904     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1905         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1906       return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1907              << Arg->getSourceRange();
1908   }
1909 
1910   // For intrinsics which take an immediate value as part of the instruction,
1911   // range check them here.
1912   unsigned i = 0, l = 0, u = 0;
1913   switch (BuiltinID) {
1914   default: return false;
1915   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1916   case SystemZ::BI__builtin_s390_verimb:
1917   case SystemZ::BI__builtin_s390_verimh:
1918   case SystemZ::BI__builtin_s390_verimf:
1919   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1920   case SystemZ::BI__builtin_s390_vfaeb:
1921   case SystemZ::BI__builtin_s390_vfaeh:
1922   case SystemZ::BI__builtin_s390_vfaef:
1923   case SystemZ::BI__builtin_s390_vfaebs:
1924   case SystemZ::BI__builtin_s390_vfaehs:
1925   case SystemZ::BI__builtin_s390_vfaefs:
1926   case SystemZ::BI__builtin_s390_vfaezb:
1927   case SystemZ::BI__builtin_s390_vfaezh:
1928   case SystemZ::BI__builtin_s390_vfaezf:
1929   case SystemZ::BI__builtin_s390_vfaezbs:
1930   case SystemZ::BI__builtin_s390_vfaezhs:
1931   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1932   case SystemZ::BI__builtin_s390_vfisb:
1933   case SystemZ::BI__builtin_s390_vfidb:
1934     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1935            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1936   case SystemZ::BI__builtin_s390_vftcisb:
1937   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1938   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1939   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1940   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1941   case SystemZ::BI__builtin_s390_vstrcb:
1942   case SystemZ::BI__builtin_s390_vstrch:
1943   case SystemZ::BI__builtin_s390_vstrcf:
1944   case SystemZ::BI__builtin_s390_vstrczb:
1945   case SystemZ::BI__builtin_s390_vstrczh:
1946   case SystemZ::BI__builtin_s390_vstrczf:
1947   case SystemZ::BI__builtin_s390_vstrcbs:
1948   case SystemZ::BI__builtin_s390_vstrchs:
1949   case SystemZ::BI__builtin_s390_vstrcfs:
1950   case SystemZ::BI__builtin_s390_vstrczbs:
1951   case SystemZ::BI__builtin_s390_vstrczhs:
1952   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1953   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
1954   case SystemZ::BI__builtin_s390_vfminsb:
1955   case SystemZ::BI__builtin_s390_vfmaxsb:
1956   case SystemZ::BI__builtin_s390_vfmindb:
1957   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
1958   }
1959   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1960 }
1961 
1962 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1963 /// This checks that the target supports __builtin_cpu_supports and
1964 /// that the string argument is constant and valid.
1965 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1966   Expr *Arg = TheCall->getArg(0);
1967 
1968   // Check if the argument is a string literal.
1969   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1970     return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1971            << Arg->getSourceRange();
1972 
1973   // Check the contents of the string.
1974   StringRef Feature =
1975       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1976   if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1977     return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1978            << Arg->getSourceRange();
1979   return false;
1980 }
1981 
1982 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
1983 /// This checks that the target supports __builtin_cpu_is and
1984 /// that the string argument is constant and valid.
1985 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
1986   Expr *Arg = TheCall->getArg(0);
1987 
1988   // Check if the argument is a string literal.
1989   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1990     return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1991            << Arg->getSourceRange();
1992 
1993   // Check the contents of the string.
1994   StringRef Feature =
1995       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1996   if (!S.Context.getTargetInfo().validateCpuIs(Feature))
1997     return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is)
1998            << Arg->getSourceRange();
1999   return false;
2000 }
2001 
2002 // Check if the rounding mode is legal.
2003 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
2004   // Indicates if this instruction has rounding control or just SAE.
2005   bool HasRC = false;
2006 
2007   unsigned ArgNum = 0;
2008   switch (BuiltinID) {
2009   default:
2010     return false;
2011   case X86::BI__builtin_ia32_vcvttsd2si32:
2012   case X86::BI__builtin_ia32_vcvttsd2si64:
2013   case X86::BI__builtin_ia32_vcvttsd2usi32:
2014   case X86::BI__builtin_ia32_vcvttsd2usi64:
2015   case X86::BI__builtin_ia32_vcvttss2si32:
2016   case X86::BI__builtin_ia32_vcvttss2si64:
2017   case X86::BI__builtin_ia32_vcvttss2usi32:
2018   case X86::BI__builtin_ia32_vcvttss2usi64:
2019     ArgNum = 1;
2020     break;
2021   case X86::BI__builtin_ia32_cvtps2pd512_mask:
2022   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
2023   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
2024   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
2025   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
2026   case X86::BI__builtin_ia32_cvttps2dq512_mask:
2027   case X86::BI__builtin_ia32_cvttps2qq512_mask:
2028   case X86::BI__builtin_ia32_cvttps2udq512_mask:
2029   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
2030   case X86::BI__builtin_ia32_exp2pd_mask:
2031   case X86::BI__builtin_ia32_exp2ps_mask:
2032   case X86::BI__builtin_ia32_getexppd512_mask:
2033   case X86::BI__builtin_ia32_getexpps512_mask:
2034   case X86::BI__builtin_ia32_rcp28pd_mask:
2035   case X86::BI__builtin_ia32_rcp28ps_mask:
2036   case X86::BI__builtin_ia32_rsqrt28pd_mask:
2037   case X86::BI__builtin_ia32_rsqrt28ps_mask:
2038   case X86::BI__builtin_ia32_vcomisd:
2039   case X86::BI__builtin_ia32_vcomiss:
2040   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
2041     ArgNum = 3;
2042     break;
2043   case X86::BI__builtin_ia32_cmppd512_mask:
2044   case X86::BI__builtin_ia32_cmpps512_mask:
2045   case X86::BI__builtin_ia32_cmpsd_mask:
2046   case X86::BI__builtin_ia32_cmpss_mask:
2047   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
2048   case X86::BI__builtin_ia32_getexpsd128_round_mask:
2049   case X86::BI__builtin_ia32_getexpss128_round_mask:
2050   case X86::BI__builtin_ia32_maxpd512_mask:
2051   case X86::BI__builtin_ia32_maxps512_mask:
2052   case X86::BI__builtin_ia32_maxsd_round_mask:
2053   case X86::BI__builtin_ia32_maxss_round_mask:
2054   case X86::BI__builtin_ia32_minpd512_mask:
2055   case X86::BI__builtin_ia32_minps512_mask:
2056   case X86::BI__builtin_ia32_minsd_round_mask:
2057   case X86::BI__builtin_ia32_minss_round_mask:
2058   case X86::BI__builtin_ia32_rcp28sd_round_mask:
2059   case X86::BI__builtin_ia32_rcp28ss_round_mask:
2060   case X86::BI__builtin_ia32_reducepd512_mask:
2061   case X86::BI__builtin_ia32_reduceps512_mask:
2062   case X86::BI__builtin_ia32_rndscalepd_mask:
2063   case X86::BI__builtin_ia32_rndscaleps_mask:
2064   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
2065   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
2066     ArgNum = 4;
2067     break;
2068   case X86::BI__builtin_ia32_fixupimmpd512_mask:
2069   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2070   case X86::BI__builtin_ia32_fixupimmps512_mask:
2071   case X86::BI__builtin_ia32_fixupimmps512_maskz:
2072   case X86::BI__builtin_ia32_fixupimmsd_mask:
2073   case X86::BI__builtin_ia32_fixupimmsd_maskz:
2074   case X86::BI__builtin_ia32_fixupimmss_mask:
2075   case X86::BI__builtin_ia32_fixupimmss_maskz:
2076   case X86::BI__builtin_ia32_rangepd512_mask:
2077   case X86::BI__builtin_ia32_rangeps512_mask:
2078   case X86::BI__builtin_ia32_rangesd128_round_mask:
2079   case X86::BI__builtin_ia32_rangess128_round_mask:
2080   case X86::BI__builtin_ia32_reducesd_mask:
2081   case X86::BI__builtin_ia32_reducess_mask:
2082   case X86::BI__builtin_ia32_rndscalesd_round_mask:
2083   case X86::BI__builtin_ia32_rndscaless_round_mask:
2084     ArgNum = 5;
2085     break;
2086   case X86::BI__builtin_ia32_vcvtsd2si64:
2087   case X86::BI__builtin_ia32_vcvtsd2si32:
2088   case X86::BI__builtin_ia32_vcvtsd2usi32:
2089   case X86::BI__builtin_ia32_vcvtsd2usi64:
2090   case X86::BI__builtin_ia32_vcvtss2si32:
2091   case X86::BI__builtin_ia32_vcvtss2si64:
2092   case X86::BI__builtin_ia32_vcvtss2usi32:
2093   case X86::BI__builtin_ia32_vcvtss2usi64:
2094     ArgNum = 1;
2095     HasRC = true;
2096     break;
2097   case X86::BI__builtin_ia32_cvtsi2sd64:
2098   case X86::BI__builtin_ia32_cvtsi2ss32:
2099   case X86::BI__builtin_ia32_cvtsi2ss64:
2100   case X86::BI__builtin_ia32_cvtusi2sd64:
2101   case X86::BI__builtin_ia32_cvtusi2ss32:
2102   case X86::BI__builtin_ia32_cvtusi2ss64:
2103     ArgNum = 2;
2104     HasRC = true;
2105     break;
2106   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
2107   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
2108   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
2109   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
2110   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
2111   case X86::BI__builtin_ia32_cvtps2qq512_mask:
2112   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
2113   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
2114   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
2115   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
2116   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
2117   case X86::BI__builtin_ia32_sqrtpd512_mask:
2118   case X86::BI__builtin_ia32_sqrtps512_mask:
2119     ArgNum = 3;
2120     HasRC = true;
2121     break;
2122   case X86::BI__builtin_ia32_addpd512_mask:
2123   case X86::BI__builtin_ia32_addps512_mask:
2124   case X86::BI__builtin_ia32_divpd512_mask:
2125   case X86::BI__builtin_ia32_divps512_mask:
2126   case X86::BI__builtin_ia32_mulpd512_mask:
2127   case X86::BI__builtin_ia32_mulps512_mask:
2128   case X86::BI__builtin_ia32_subpd512_mask:
2129   case X86::BI__builtin_ia32_subps512_mask:
2130   case X86::BI__builtin_ia32_addss_round_mask:
2131   case X86::BI__builtin_ia32_addsd_round_mask:
2132   case X86::BI__builtin_ia32_divss_round_mask:
2133   case X86::BI__builtin_ia32_divsd_round_mask:
2134   case X86::BI__builtin_ia32_mulss_round_mask:
2135   case X86::BI__builtin_ia32_mulsd_round_mask:
2136   case X86::BI__builtin_ia32_subss_round_mask:
2137   case X86::BI__builtin_ia32_subsd_round_mask:
2138   case X86::BI__builtin_ia32_scalefpd512_mask:
2139   case X86::BI__builtin_ia32_scalefps512_mask:
2140   case X86::BI__builtin_ia32_scalefsd_round_mask:
2141   case X86::BI__builtin_ia32_scalefss_round_mask:
2142   case X86::BI__builtin_ia32_getmantpd512_mask:
2143   case X86::BI__builtin_ia32_getmantps512_mask:
2144   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
2145   case X86::BI__builtin_ia32_sqrtsd_round_mask:
2146   case X86::BI__builtin_ia32_sqrtss_round_mask:
2147   case X86::BI__builtin_ia32_vfmaddpd512_mask:
2148   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
2149   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
2150   case X86::BI__builtin_ia32_vfmaddps512_mask:
2151   case X86::BI__builtin_ia32_vfmaddps512_mask3:
2152   case X86::BI__builtin_ia32_vfmaddps512_maskz:
2153   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
2154   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
2155   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
2156   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
2157   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
2158   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
2159   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
2160   case X86::BI__builtin_ia32_vfmsubps512_mask3:
2161   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
2162   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
2163   case X86::BI__builtin_ia32_vfnmaddpd512_mask:
2164   case X86::BI__builtin_ia32_vfnmaddps512_mask:
2165   case X86::BI__builtin_ia32_vfnmsubpd512_mask:
2166   case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
2167   case X86::BI__builtin_ia32_vfnmsubps512_mask:
2168   case X86::BI__builtin_ia32_vfnmsubps512_mask3:
2169   case X86::BI__builtin_ia32_vfmaddsd3_mask:
2170   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
2171   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
2172   case X86::BI__builtin_ia32_vfmaddss3_mask:
2173   case X86::BI__builtin_ia32_vfmaddss3_maskz:
2174   case X86::BI__builtin_ia32_vfmaddss3_mask3:
2175     ArgNum = 4;
2176     HasRC = true;
2177     break;
2178   case X86::BI__builtin_ia32_getmantsd_round_mask:
2179   case X86::BI__builtin_ia32_getmantss_round_mask:
2180     ArgNum = 5;
2181     HasRC = true;
2182     break;
2183   }
2184 
2185   llvm::APSInt Result;
2186 
2187   // We can't check the value of a dependent argument.
2188   Expr *Arg = TheCall->getArg(ArgNum);
2189   if (Arg->isTypeDependent() || Arg->isValueDependent())
2190     return false;
2191 
2192   // Check constant-ness first.
2193   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2194     return true;
2195 
2196   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
2197   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
2198   // combined with ROUND_NO_EXC.
2199   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
2200       Result == 8/*ROUND_NO_EXC*/ ||
2201       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
2202     return false;
2203 
2204   return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
2205     << Arg->getSourceRange();
2206 }
2207 
2208 // Check if the gather/scatter scale is legal.
2209 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
2210                                              CallExpr *TheCall) {
2211   unsigned ArgNum = 0;
2212   switch (BuiltinID) {
2213   default:
2214     return false;
2215   case X86::BI__builtin_ia32_gatherpfdpd:
2216   case X86::BI__builtin_ia32_gatherpfdps:
2217   case X86::BI__builtin_ia32_gatherpfqpd:
2218   case X86::BI__builtin_ia32_gatherpfqps:
2219   case X86::BI__builtin_ia32_scatterpfdpd:
2220   case X86::BI__builtin_ia32_scatterpfdps:
2221   case X86::BI__builtin_ia32_scatterpfqpd:
2222   case X86::BI__builtin_ia32_scatterpfqps:
2223     ArgNum = 3;
2224     break;
2225   case X86::BI__builtin_ia32_gatherd_pd:
2226   case X86::BI__builtin_ia32_gatherd_pd256:
2227   case X86::BI__builtin_ia32_gatherq_pd:
2228   case X86::BI__builtin_ia32_gatherq_pd256:
2229   case X86::BI__builtin_ia32_gatherd_ps:
2230   case X86::BI__builtin_ia32_gatherd_ps256:
2231   case X86::BI__builtin_ia32_gatherq_ps:
2232   case X86::BI__builtin_ia32_gatherq_ps256:
2233   case X86::BI__builtin_ia32_gatherd_q:
2234   case X86::BI__builtin_ia32_gatherd_q256:
2235   case X86::BI__builtin_ia32_gatherq_q:
2236   case X86::BI__builtin_ia32_gatherq_q256:
2237   case X86::BI__builtin_ia32_gatherd_d:
2238   case X86::BI__builtin_ia32_gatherd_d256:
2239   case X86::BI__builtin_ia32_gatherq_d:
2240   case X86::BI__builtin_ia32_gatherq_d256:
2241   case X86::BI__builtin_ia32_gather3div2df:
2242   case X86::BI__builtin_ia32_gather3div2di:
2243   case X86::BI__builtin_ia32_gather3div4df:
2244   case X86::BI__builtin_ia32_gather3div4di:
2245   case X86::BI__builtin_ia32_gather3div4sf:
2246   case X86::BI__builtin_ia32_gather3div4si:
2247   case X86::BI__builtin_ia32_gather3div8sf:
2248   case X86::BI__builtin_ia32_gather3div8si:
2249   case X86::BI__builtin_ia32_gather3siv2df:
2250   case X86::BI__builtin_ia32_gather3siv2di:
2251   case X86::BI__builtin_ia32_gather3siv4df:
2252   case X86::BI__builtin_ia32_gather3siv4di:
2253   case X86::BI__builtin_ia32_gather3siv4sf:
2254   case X86::BI__builtin_ia32_gather3siv4si:
2255   case X86::BI__builtin_ia32_gather3siv8sf:
2256   case X86::BI__builtin_ia32_gather3siv8si:
2257   case X86::BI__builtin_ia32_gathersiv8df:
2258   case X86::BI__builtin_ia32_gathersiv16sf:
2259   case X86::BI__builtin_ia32_gatherdiv8df:
2260   case X86::BI__builtin_ia32_gatherdiv16sf:
2261   case X86::BI__builtin_ia32_gathersiv8di:
2262   case X86::BI__builtin_ia32_gathersiv16si:
2263   case X86::BI__builtin_ia32_gatherdiv8di:
2264   case X86::BI__builtin_ia32_gatherdiv16si:
2265   case X86::BI__builtin_ia32_scatterdiv2df:
2266   case X86::BI__builtin_ia32_scatterdiv2di:
2267   case X86::BI__builtin_ia32_scatterdiv4df:
2268   case X86::BI__builtin_ia32_scatterdiv4di:
2269   case X86::BI__builtin_ia32_scatterdiv4sf:
2270   case X86::BI__builtin_ia32_scatterdiv4si:
2271   case X86::BI__builtin_ia32_scatterdiv8sf:
2272   case X86::BI__builtin_ia32_scatterdiv8si:
2273   case X86::BI__builtin_ia32_scattersiv2df:
2274   case X86::BI__builtin_ia32_scattersiv2di:
2275   case X86::BI__builtin_ia32_scattersiv4df:
2276   case X86::BI__builtin_ia32_scattersiv4di:
2277   case X86::BI__builtin_ia32_scattersiv4sf:
2278   case X86::BI__builtin_ia32_scattersiv4si:
2279   case X86::BI__builtin_ia32_scattersiv8sf:
2280   case X86::BI__builtin_ia32_scattersiv8si:
2281   case X86::BI__builtin_ia32_scattersiv8df:
2282   case X86::BI__builtin_ia32_scattersiv16sf:
2283   case X86::BI__builtin_ia32_scatterdiv8df:
2284   case X86::BI__builtin_ia32_scatterdiv16sf:
2285   case X86::BI__builtin_ia32_scattersiv8di:
2286   case X86::BI__builtin_ia32_scattersiv16si:
2287   case X86::BI__builtin_ia32_scatterdiv8di:
2288   case X86::BI__builtin_ia32_scatterdiv16si:
2289     ArgNum = 4;
2290     break;
2291   }
2292 
2293   llvm::APSInt Result;
2294 
2295   // We can't check the value of a dependent argument.
2296   Expr *Arg = TheCall->getArg(ArgNum);
2297   if (Arg->isTypeDependent() || Arg->isValueDependent())
2298     return false;
2299 
2300   // Check constant-ness first.
2301   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2302     return true;
2303 
2304   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
2305     return false;
2306 
2307   return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
2308     << Arg->getSourceRange();
2309 }
2310 
2311 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2312   if (BuiltinID == X86::BI__builtin_cpu_supports)
2313     return SemaBuiltinCpuSupports(*this, TheCall);
2314 
2315   if (BuiltinID == X86::BI__builtin_cpu_is)
2316     return SemaBuiltinCpuIs(*this, TheCall);
2317 
2318   // If the intrinsic has rounding or SAE make sure its valid.
2319   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2320     return true;
2321 
2322   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
2323   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
2324     return true;
2325 
2326   // For intrinsics which take an immediate value as part of the instruction,
2327   // range check them here.
2328   int i = 0, l = 0, u = 0;
2329   switch (BuiltinID) {
2330   default:
2331     return false;
2332   case X86::BI_mm_prefetch:
2333     i = 1; l = 0; u = 7;
2334     break;
2335   case X86::BI__builtin_ia32_sha1rnds4:
2336   case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2337   case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2338   case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2339   case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
2340     i = 2; l = 0; u = 3;
2341     break;
2342   case X86::BI__builtin_ia32_vpermil2pd:
2343   case X86::BI__builtin_ia32_vpermil2pd256:
2344   case X86::BI__builtin_ia32_vpermil2ps:
2345   case X86::BI__builtin_ia32_vpermil2ps256:
2346     i = 3; l = 0; u = 3;
2347     break;
2348   case X86::BI__builtin_ia32_cmpb128_mask:
2349   case X86::BI__builtin_ia32_cmpw128_mask:
2350   case X86::BI__builtin_ia32_cmpd128_mask:
2351   case X86::BI__builtin_ia32_cmpq128_mask:
2352   case X86::BI__builtin_ia32_cmpb256_mask:
2353   case X86::BI__builtin_ia32_cmpw256_mask:
2354   case X86::BI__builtin_ia32_cmpd256_mask:
2355   case X86::BI__builtin_ia32_cmpq256_mask:
2356   case X86::BI__builtin_ia32_cmpb512_mask:
2357   case X86::BI__builtin_ia32_cmpw512_mask:
2358   case X86::BI__builtin_ia32_cmpd512_mask:
2359   case X86::BI__builtin_ia32_cmpq512_mask:
2360   case X86::BI__builtin_ia32_ucmpb128_mask:
2361   case X86::BI__builtin_ia32_ucmpw128_mask:
2362   case X86::BI__builtin_ia32_ucmpd128_mask:
2363   case X86::BI__builtin_ia32_ucmpq128_mask:
2364   case X86::BI__builtin_ia32_ucmpb256_mask:
2365   case X86::BI__builtin_ia32_ucmpw256_mask:
2366   case X86::BI__builtin_ia32_ucmpd256_mask:
2367   case X86::BI__builtin_ia32_ucmpq256_mask:
2368   case X86::BI__builtin_ia32_ucmpb512_mask:
2369   case X86::BI__builtin_ia32_ucmpw512_mask:
2370   case X86::BI__builtin_ia32_ucmpd512_mask:
2371   case X86::BI__builtin_ia32_ucmpq512_mask:
2372   case X86::BI__builtin_ia32_vpcomub:
2373   case X86::BI__builtin_ia32_vpcomuw:
2374   case X86::BI__builtin_ia32_vpcomud:
2375   case X86::BI__builtin_ia32_vpcomuq:
2376   case X86::BI__builtin_ia32_vpcomb:
2377   case X86::BI__builtin_ia32_vpcomw:
2378   case X86::BI__builtin_ia32_vpcomd:
2379   case X86::BI__builtin_ia32_vpcomq:
2380     i = 2; l = 0; u = 7;
2381     break;
2382   case X86::BI__builtin_ia32_roundps:
2383   case X86::BI__builtin_ia32_roundpd:
2384   case X86::BI__builtin_ia32_roundps256:
2385   case X86::BI__builtin_ia32_roundpd256:
2386     i = 1; l = 0; u = 15;
2387     break;
2388   case X86::BI__builtin_ia32_roundss:
2389   case X86::BI__builtin_ia32_roundsd:
2390   case X86::BI__builtin_ia32_rangepd128_mask:
2391   case X86::BI__builtin_ia32_rangepd256_mask:
2392   case X86::BI__builtin_ia32_rangepd512_mask:
2393   case X86::BI__builtin_ia32_rangeps128_mask:
2394   case X86::BI__builtin_ia32_rangeps256_mask:
2395   case X86::BI__builtin_ia32_rangeps512_mask:
2396   case X86::BI__builtin_ia32_getmantsd_round_mask:
2397   case X86::BI__builtin_ia32_getmantss_round_mask:
2398     i = 2; l = 0; u = 15;
2399     break;
2400   case X86::BI__builtin_ia32_cmpps:
2401   case X86::BI__builtin_ia32_cmpss:
2402   case X86::BI__builtin_ia32_cmppd:
2403   case X86::BI__builtin_ia32_cmpsd:
2404   case X86::BI__builtin_ia32_cmpps256:
2405   case X86::BI__builtin_ia32_cmppd256:
2406   case X86::BI__builtin_ia32_cmpps128_mask:
2407   case X86::BI__builtin_ia32_cmppd128_mask:
2408   case X86::BI__builtin_ia32_cmpps256_mask:
2409   case X86::BI__builtin_ia32_cmppd256_mask:
2410   case X86::BI__builtin_ia32_cmpps512_mask:
2411   case X86::BI__builtin_ia32_cmppd512_mask:
2412   case X86::BI__builtin_ia32_cmpsd_mask:
2413   case X86::BI__builtin_ia32_cmpss_mask:
2414     i = 2; l = 0; u = 31;
2415     break;
2416   case X86::BI__builtin_ia32_vcvtps2ph:
2417   case X86::BI__builtin_ia32_vcvtps2ph_mask:
2418   case X86::BI__builtin_ia32_vcvtps2ph256:
2419   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
2420   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
2421   case X86::BI__builtin_ia32_rndscaleps_128_mask:
2422   case X86::BI__builtin_ia32_rndscalepd_128_mask:
2423   case X86::BI__builtin_ia32_rndscaleps_256_mask:
2424   case X86::BI__builtin_ia32_rndscalepd_256_mask:
2425   case X86::BI__builtin_ia32_rndscaleps_mask:
2426   case X86::BI__builtin_ia32_rndscalepd_mask:
2427   case X86::BI__builtin_ia32_reducepd128_mask:
2428   case X86::BI__builtin_ia32_reducepd256_mask:
2429   case X86::BI__builtin_ia32_reducepd512_mask:
2430   case X86::BI__builtin_ia32_reduceps128_mask:
2431   case X86::BI__builtin_ia32_reduceps256_mask:
2432   case X86::BI__builtin_ia32_reduceps512_mask:
2433   case X86::BI__builtin_ia32_prold512_mask:
2434   case X86::BI__builtin_ia32_prolq512_mask:
2435   case X86::BI__builtin_ia32_prold128_mask:
2436   case X86::BI__builtin_ia32_prold256_mask:
2437   case X86::BI__builtin_ia32_prolq128_mask:
2438   case X86::BI__builtin_ia32_prolq256_mask:
2439   case X86::BI__builtin_ia32_prord128_mask:
2440   case X86::BI__builtin_ia32_prord256_mask:
2441   case X86::BI__builtin_ia32_prorq128_mask:
2442   case X86::BI__builtin_ia32_prorq256_mask:
2443   case X86::BI__builtin_ia32_fpclasspd128_mask:
2444   case X86::BI__builtin_ia32_fpclasspd256_mask:
2445   case X86::BI__builtin_ia32_fpclassps128_mask:
2446   case X86::BI__builtin_ia32_fpclassps256_mask:
2447   case X86::BI__builtin_ia32_fpclassps512_mask:
2448   case X86::BI__builtin_ia32_fpclasspd512_mask:
2449   case X86::BI__builtin_ia32_fpclasssd_mask:
2450   case X86::BI__builtin_ia32_fpclassss_mask:
2451     i = 1; l = 0; u = 255;
2452     break;
2453   case X86::BI__builtin_ia32_palignr128:
2454   case X86::BI__builtin_ia32_palignr256:
2455   case X86::BI__builtin_ia32_palignr512_mask:
2456   case X86::BI__builtin_ia32_vcomisd:
2457   case X86::BI__builtin_ia32_vcomiss:
2458   case X86::BI__builtin_ia32_shuf_f32x4_mask:
2459   case X86::BI__builtin_ia32_shuf_f64x2_mask:
2460   case X86::BI__builtin_ia32_shuf_i32x4_mask:
2461   case X86::BI__builtin_ia32_shuf_i64x2_mask:
2462   case X86::BI__builtin_ia32_dbpsadbw128_mask:
2463   case X86::BI__builtin_ia32_dbpsadbw256_mask:
2464   case X86::BI__builtin_ia32_dbpsadbw512_mask:
2465   case X86::BI__builtin_ia32_vpshldd128_mask:
2466   case X86::BI__builtin_ia32_vpshldd256_mask:
2467   case X86::BI__builtin_ia32_vpshldd512_mask:
2468   case X86::BI__builtin_ia32_vpshldq128_mask:
2469   case X86::BI__builtin_ia32_vpshldq256_mask:
2470   case X86::BI__builtin_ia32_vpshldq512_mask:
2471   case X86::BI__builtin_ia32_vpshldw128_mask:
2472   case X86::BI__builtin_ia32_vpshldw256_mask:
2473   case X86::BI__builtin_ia32_vpshldw512_mask:
2474   case X86::BI__builtin_ia32_vpshrdd128_mask:
2475   case X86::BI__builtin_ia32_vpshrdd256_mask:
2476   case X86::BI__builtin_ia32_vpshrdd512_mask:
2477   case X86::BI__builtin_ia32_vpshrdq128_mask:
2478   case X86::BI__builtin_ia32_vpshrdq256_mask:
2479   case X86::BI__builtin_ia32_vpshrdq512_mask:
2480   case X86::BI__builtin_ia32_vpshrdw128_mask:
2481   case X86::BI__builtin_ia32_vpshrdw256_mask:
2482   case X86::BI__builtin_ia32_vpshrdw512_mask:
2483     i = 2; l = 0; u = 255;
2484     break;
2485   case X86::BI__builtin_ia32_fixupimmpd512_mask:
2486   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2487   case X86::BI__builtin_ia32_fixupimmps512_mask:
2488   case X86::BI__builtin_ia32_fixupimmps512_maskz:
2489   case X86::BI__builtin_ia32_fixupimmsd_mask:
2490   case X86::BI__builtin_ia32_fixupimmsd_maskz:
2491   case X86::BI__builtin_ia32_fixupimmss_mask:
2492   case X86::BI__builtin_ia32_fixupimmss_maskz:
2493   case X86::BI__builtin_ia32_fixupimmpd128_mask:
2494   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2495   case X86::BI__builtin_ia32_fixupimmpd256_mask:
2496   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2497   case X86::BI__builtin_ia32_fixupimmps128_mask:
2498   case X86::BI__builtin_ia32_fixupimmps128_maskz:
2499   case X86::BI__builtin_ia32_fixupimmps256_mask:
2500   case X86::BI__builtin_ia32_fixupimmps256_maskz:
2501   case X86::BI__builtin_ia32_pternlogd512_mask:
2502   case X86::BI__builtin_ia32_pternlogd512_maskz:
2503   case X86::BI__builtin_ia32_pternlogq512_mask:
2504   case X86::BI__builtin_ia32_pternlogq512_maskz:
2505   case X86::BI__builtin_ia32_pternlogd128_mask:
2506   case X86::BI__builtin_ia32_pternlogd128_maskz:
2507   case X86::BI__builtin_ia32_pternlogd256_mask:
2508   case X86::BI__builtin_ia32_pternlogd256_maskz:
2509   case X86::BI__builtin_ia32_pternlogq128_mask:
2510   case X86::BI__builtin_ia32_pternlogq128_maskz:
2511   case X86::BI__builtin_ia32_pternlogq256_mask:
2512   case X86::BI__builtin_ia32_pternlogq256_maskz:
2513     i = 3; l = 0; u = 255;
2514     break;
2515   case X86::BI__builtin_ia32_gatherpfdpd:
2516   case X86::BI__builtin_ia32_gatherpfdps:
2517   case X86::BI__builtin_ia32_gatherpfqpd:
2518   case X86::BI__builtin_ia32_gatherpfqps:
2519   case X86::BI__builtin_ia32_scatterpfdpd:
2520   case X86::BI__builtin_ia32_scatterpfdps:
2521   case X86::BI__builtin_ia32_scatterpfqpd:
2522   case X86::BI__builtin_ia32_scatterpfqps:
2523     i = 4; l = 2; u = 3;
2524     break;
2525   case X86::BI__builtin_ia32_rndscalesd_round_mask:
2526   case X86::BI__builtin_ia32_rndscaless_round_mask:
2527     i = 4; l = 0; u = 255;
2528     break;
2529   }
2530   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2531 }
2532 
2533 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2534 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
2535 /// Returns true when the format fits the function and the FormatStringInfo has
2536 /// been populated.
2537 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2538                                FormatStringInfo *FSI) {
2539   FSI->HasVAListArg = Format->getFirstArg() == 0;
2540   FSI->FormatIdx = Format->getFormatIdx() - 1;
2541   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
2542 
2543   // The way the format attribute works in GCC, the implicit this argument
2544   // of member functions is counted. However, it doesn't appear in our own
2545   // lists, so decrement format_idx in that case.
2546   if (IsCXXMember) {
2547     if(FSI->FormatIdx == 0)
2548       return false;
2549     --FSI->FormatIdx;
2550     if (FSI->FirstDataArg != 0)
2551       --FSI->FirstDataArg;
2552   }
2553   return true;
2554 }
2555 
2556 /// Checks if a the given expression evaluates to null.
2557 ///
2558 /// \brief Returns true if the value evaluates to null.
2559 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
2560   // If the expression has non-null type, it doesn't evaluate to null.
2561   if (auto nullability
2562         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2563     if (*nullability == NullabilityKind::NonNull)
2564       return false;
2565   }
2566 
2567   // As a special case, transparent unions initialized with zero are
2568   // considered null for the purposes of the nonnull attribute.
2569   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
2570     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2571       if (const CompoundLiteralExpr *CLE =
2572           dyn_cast<CompoundLiteralExpr>(Expr))
2573         if (const InitListExpr *ILE =
2574             dyn_cast<InitListExpr>(CLE->getInitializer()))
2575           Expr = ILE->getInit(0);
2576   }
2577 
2578   bool Result;
2579   return (!Expr->isValueDependent() &&
2580           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2581           !Result);
2582 }
2583 
2584 static void CheckNonNullArgument(Sema &S,
2585                                  const Expr *ArgExpr,
2586                                  SourceLocation CallSiteLoc) {
2587   if (CheckNonNullExpr(S, ArgExpr))
2588     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2589            S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
2590 }
2591 
2592 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2593   FormatStringInfo FSI;
2594   if ((GetFormatStringType(Format) == FST_NSString) &&
2595       getFormatStringInfo(Format, false, &FSI)) {
2596     Idx = FSI.FormatIdx;
2597     return true;
2598   }
2599   return false;
2600 }
2601 
2602 /// \brief Diagnose use of %s directive in an NSString which is being passed
2603 /// as formatting string to formatting method.
2604 static void
2605 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2606                                         const NamedDecl *FDecl,
2607                                         Expr **Args,
2608                                         unsigned NumArgs) {
2609   unsigned Idx = 0;
2610   bool Format = false;
2611   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2612   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
2613     Idx = 2;
2614     Format = true;
2615   }
2616   else
2617     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2618       if (S.GetFormatNSStringIdx(I, Idx)) {
2619         Format = true;
2620         break;
2621       }
2622     }
2623   if (!Format || NumArgs <= Idx)
2624     return;
2625   const Expr *FormatExpr = Args[Idx];
2626   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2627     FormatExpr = CSCE->getSubExpr();
2628   const StringLiteral *FormatString;
2629   if (const ObjCStringLiteral *OSL =
2630       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2631     FormatString = OSL->getString();
2632   else
2633     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2634   if (!FormatString)
2635     return;
2636   if (S.FormatStringHasSArg(FormatString)) {
2637     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2638       << "%s" << 1 << 1;
2639     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2640       << FDecl->getDeclName();
2641   }
2642 }
2643 
2644 /// Determine whether the given type has a non-null nullability annotation.
2645 static bool isNonNullType(ASTContext &ctx, QualType type) {
2646   if (auto nullability = type->getNullability(ctx))
2647     return *nullability == NullabilityKind::NonNull;
2648 
2649   return false;
2650 }
2651 
2652 static void CheckNonNullArguments(Sema &S,
2653                                   const NamedDecl *FDecl,
2654                                   const FunctionProtoType *Proto,
2655                                   ArrayRef<const Expr *> Args,
2656                                   SourceLocation CallSiteLoc) {
2657   assert((FDecl || Proto) && "Need a function declaration or prototype");
2658 
2659   // Check the attributes attached to the method/function itself.
2660   llvm::SmallBitVector NonNullArgs;
2661   if (FDecl) {
2662     // Handle the nonnull attribute on the function/method declaration itself.
2663     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2664       if (!NonNull->args_size()) {
2665         // Easy case: all pointer arguments are nonnull.
2666         for (const auto *Arg : Args)
2667           if (S.isValidPointerAttrType(Arg->getType()))
2668             CheckNonNullArgument(S, Arg, CallSiteLoc);
2669         return;
2670       }
2671 
2672       for (const ParamIdx &Idx : NonNull->args()) {
2673         unsigned IdxAST = Idx.getASTIndex();
2674         if (IdxAST >= Args.size())
2675           continue;
2676         if (NonNullArgs.empty())
2677           NonNullArgs.resize(Args.size());
2678         NonNullArgs.set(IdxAST);
2679       }
2680     }
2681   }
2682 
2683   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2684     // Handle the nonnull attribute on the parameters of the
2685     // function/method.
2686     ArrayRef<ParmVarDecl*> parms;
2687     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2688       parms = FD->parameters();
2689     else
2690       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2691 
2692     unsigned ParamIndex = 0;
2693     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2694          I != E; ++I, ++ParamIndex) {
2695       const ParmVarDecl *PVD = *I;
2696       if (PVD->hasAttr<NonNullAttr>() ||
2697           isNonNullType(S.Context, PVD->getType())) {
2698         if (NonNullArgs.empty())
2699           NonNullArgs.resize(Args.size());
2700 
2701         NonNullArgs.set(ParamIndex);
2702       }
2703     }
2704   } else {
2705     // If we have a non-function, non-method declaration but no
2706     // function prototype, try to dig out the function prototype.
2707     if (!Proto) {
2708       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2709         QualType type = VD->getType().getNonReferenceType();
2710         if (auto pointerType = type->getAs<PointerType>())
2711           type = pointerType->getPointeeType();
2712         else if (auto blockType = type->getAs<BlockPointerType>())
2713           type = blockType->getPointeeType();
2714         // FIXME: data member pointers?
2715 
2716         // Dig out the function prototype, if there is one.
2717         Proto = type->getAs<FunctionProtoType>();
2718       }
2719     }
2720 
2721     // Fill in non-null argument information from the nullability
2722     // information on the parameter types (if we have them).
2723     if (Proto) {
2724       unsigned Index = 0;
2725       for (auto paramType : Proto->getParamTypes()) {
2726         if (isNonNullType(S.Context, paramType)) {
2727           if (NonNullArgs.empty())
2728             NonNullArgs.resize(Args.size());
2729 
2730           NonNullArgs.set(Index);
2731         }
2732 
2733         ++Index;
2734       }
2735     }
2736   }
2737 
2738   // Check for non-null arguments.
2739   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2740        ArgIndex != ArgIndexEnd; ++ArgIndex) {
2741     if (NonNullArgs[ArgIndex])
2742       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
2743   }
2744 }
2745 
2746 /// Handles the checks for format strings, non-POD arguments to vararg
2747 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
2748 /// attributes.
2749 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2750                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
2751                      bool IsMemberFunction, SourceLocation Loc,
2752                      SourceRange Range, VariadicCallType CallType) {
2753   // FIXME: We should check as much as we can in the template definition.
2754   if (CurContext->isDependentContext())
2755     return;
2756 
2757   // Printf and scanf checking.
2758   llvm::SmallBitVector CheckedVarArgs;
2759   if (FDecl) {
2760     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2761       // Only create vector if there are format attributes.
2762       CheckedVarArgs.resize(Args.size());
2763 
2764       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
2765                            CheckedVarArgs);
2766     }
2767   }
2768 
2769   // Refuse POD arguments that weren't caught by the format string
2770   // checks above.
2771   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
2772   if (CallType != VariadicDoesNotApply &&
2773       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
2774     unsigned NumParams = Proto ? Proto->getNumParams()
2775                        : FDecl && isa<FunctionDecl>(FDecl)
2776                            ? cast<FunctionDecl>(FDecl)->getNumParams()
2777                        : FDecl && isa<ObjCMethodDecl>(FDecl)
2778                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
2779                        : 0;
2780 
2781     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
2782       // Args[ArgIdx] can be null in malformed code.
2783       if (const Expr *Arg = Args[ArgIdx]) {
2784         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2785           checkVariadicArgument(Arg, CallType);
2786       }
2787     }
2788   }
2789 
2790   if (FDecl || Proto) {
2791     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
2792 
2793     // Type safety checking.
2794     if (FDecl) {
2795       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2796         CheckArgumentWithTypeTag(I, Args, Loc);
2797     }
2798   }
2799 
2800   if (FD)
2801     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
2802 }
2803 
2804 /// CheckConstructorCall - Check a constructor call for correctness and safety
2805 /// properties not enforced by the C type system.
2806 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2807                                 ArrayRef<const Expr *> Args,
2808                                 const FunctionProtoType *Proto,
2809                                 SourceLocation Loc) {
2810   VariadicCallType CallType =
2811     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
2812   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
2813             Loc, SourceRange(), CallType);
2814 }
2815 
2816 /// CheckFunctionCall - Check a direct function call for various correctness
2817 /// and safety properties not strictly enforced by the C type system.
2818 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2819                              const FunctionProtoType *Proto) {
2820   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2821                               isa<CXXMethodDecl>(FDecl);
2822   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2823                           IsMemberOperatorCall;
2824   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2825                                                   TheCall->getCallee());
2826   Expr** Args = TheCall->getArgs();
2827   unsigned NumArgs = TheCall->getNumArgs();
2828 
2829   Expr *ImplicitThis = nullptr;
2830   if (IsMemberOperatorCall) {
2831     // If this is a call to a member operator, hide the first argument
2832     // from checkCall.
2833     // FIXME: Our choice of AST representation here is less than ideal.
2834     ImplicitThis = Args[0];
2835     ++Args;
2836     --NumArgs;
2837   } else if (IsMemberFunction)
2838     ImplicitThis =
2839         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
2840 
2841   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
2842             IsMemberFunction, TheCall->getRParenLoc(),
2843             TheCall->getCallee()->getSourceRange(), CallType);
2844 
2845   IdentifierInfo *FnInfo = FDecl->getIdentifier();
2846   // None of the checks below are needed for functions that don't have
2847   // simple names (e.g., C++ conversion functions).
2848   if (!FnInfo)
2849     return false;
2850 
2851   CheckAbsoluteValueFunction(TheCall, FDecl);
2852   CheckMaxUnsignedZero(TheCall, FDecl);
2853 
2854   if (getLangOpts().ObjC1)
2855     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
2856 
2857   unsigned CMId = FDecl->getMemoryFunctionKind();
2858   if (CMId == 0)
2859     return false;
2860 
2861   // Handle memory setting and copying functions.
2862   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
2863     CheckStrlcpycatArguments(TheCall, FnInfo);
2864   else if (CMId == Builtin::BIstrncat)
2865     CheckStrncatArguments(TheCall, FnInfo);
2866   else
2867     CheckMemaccessArguments(TheCall, CMId, FnInfo);
2868 
2869   return false;
2870 }
2871 
2872 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
2873                                ArrayRef<const Expr *> Args) {
2874   VariadicCallType CallType =
2875       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
2876 
2877   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
2878             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
2879             CallType);
2880 
2881   return false;
2882 }
2883 
2884 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2885                             const FunctionProtoType *Proto) {
2886   QualType Ty;
2887   if (const auto *V = dyn_cast<VarDecl>(NDecl))
2888     Ty = V->getType().getNonReferenceType();
2889   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
2890     Ty = F->getType().getNonReferenceType();
2891   else
2892     return false;
2893 
2894   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2895       !Ty->isFunctionProtoType())
2896     return false;
2897 
2898   VariadicCallType CallType;
2899   if (!Proto || !Proto->isVariadic()) {
2900     CallType = VariadicDoesNotApply;
2901   } else if (Ty->isBlockPointerType()) {
2902     CallType = VariadicBlock;
2903   } else { // Ty->isFunctionPointerType()
2904     CallType = VariadicFunction;
2905   }
2906 
2907   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
2908             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2909             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2910             TheCall->getCallee()->getSourceRange(), CallType);
2911 
2912   return false;
2913 }
2914 
2915 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2916 /// such as function pointers returned from functions.
2917 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
2918   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
2919                                                   TheCall->getCallee());
2920   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
2921             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2922             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2923             TheCall->getCallee()->getSourceRange(), CallType);
2924 
2925   return false;
2926 }
2927 
2928 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
2929   if (!llvm::isValidAtomicOrderingCABI(Ordering))
2930     return false;
2931 
2932   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
2933   switch (Op) {
2934   case AtomicExpr::AO__c11_atomic_init:
2935   case AtomicExpr::AO__opencl_atomic_init:
2936     llvm_unreachable("There is no ordering argument for an init");
2937 
2938   case AtomicExpr::AO__c11_atomic_load:
2939   case AtomicExpr::AO__opencl_atomic_load:
2940   case AtomicExpr::AO__atomic_load_n:
2941   case AtomicExpr::AO__atomic_load:
2942     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2943            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2944 
2945   case AtomicExpr::AO__c11_atomic_store:
2946   case AtomicExpr::AO__opencl_atomic_store:
2947   case AtomicExpr::AO__atomic_store:
2948   case AtomicExpr::AO__atomic_store_n:
2949     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2950            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2951            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2952 
2953   default:
2954     return true;
2955   }
2956 }
2957 
2958 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2959                                          AtomicExpr::AtomicOp Op) {
2960   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2961   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2962 
2963   // All the non-OpenCL operations take one of the following forms.
2964   // The OpenCL operations take the __c11 forms with one extra argument for
2965   // synchronization scope.
2966   enum {
2967     // C    __c11_atomic_init(A *, C)
2968     Init,
2969 
2970     // C    __c11_atomic_load(A *, int)
2971     Load,
2972 
2973     // void __atomic_load(A *, CP, int)
2974     LoadCopy,
2975 
2976     // void __atomic_store(A *, CP, int)
2977     Copy,
2978 
2979     // C    __c11_atomic_add(A *, M, int)
2980     Arithmetic,
2981 
2982     // C    __atomic_exchange_n(A *, CP, int)
2983     Xchg,
2984 
2985     // void __atomic_exchange(A *, C *, CP, int)
2986     GNUXchg,
2987 
2988     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2989     C11CmpXchg,
2990 
2991     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2992     GNUCmpXchg
2993   } Form = Init;
2994 
2995   const unsigned NumForm = GNUCmpXchg + 1;
2996   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2997   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
2998   // where:
2999   //   C is an appropriate type,
3000   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
3001   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
3002   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
3003   //   the int parameters are for orderings.
3004 
3005   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
3006       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
3007       "need to update code for modified forms");
3008   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
3009                     AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
3010                         AtomicExpr::AO__atomic_load,
3011                 "need to update code for modified C11 atomics");
3012   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
3013                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
3014   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
3015                Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
3016                IsOpenCL;
3017   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
3018              Op == AtomicExpr::AO__atomic_store_n ||
3019              Op == AtomicExpr::AO__atomic_exchange_n ||
3020              Op == AtomicExpr::AO__atomic_compare_exchange_n;
3021   bool IsAddSub = false;
3022 
3023   switch (Op) {
3024   case AtomicExpr::AO__c11_atomic_init:
3025   case AtomicExpr::AO__opencl_atomic_init:
3026     Form = Init;
3027     break;
3028 
3029   case AtomicExpr::AO__c11_atomic_load:
3030   case AtomicExpr::AO__opencl_atomic_load:
3031   case AtomicExpr::AO__atomic_load_n:
3032     Form = Load;
3033     break;
3034 
3035   case AtomicExpr::AO__atomic_load:
3036     Form = LoadCopy;
3037     break;
3038 
3039   case AtomicExpr::AO__c11_atomic_store:
3040   case AtomicExpr::AO__opencl_atomic_store:
3041   case AtomicExpr::AO__atomic_store:
3042   case AtomicExpr::AO__atomic_store_n:
3043     Form = Copy;
3044     break;
3045 
3046   case AtomicExpr::AO__c11_atomic_fetch_add:
3047   case AtomicExpr::AO__c11_atomic_fetch_sub:
3048   case AtomicExpr::AO__opencl_atomic_fetch_add:
3049   case AtomicExpr::AO__opencl_atomic_fetch_sub:
3050   case AtomicExpr::AO__opencl_atomic_fetch_min:
3051   case AtomicExpr::AO__opencl_atomic_fetch_max:
3052   case AtomicExpr::AO__atomic_fetch_add:
3053   case AtomicExpr::AO__atomic_fetch_sub:
3054   case AtomicExpr::AO__atomic_add_fetch:
3055   case AtomicExpr::AO__atomic_sub_fetch:
3056     IsAddSub = true;
3057     LLVM_FALLTHROUGH;
3058   case AtomicExpr::AO__c11_atomic_fetch_and:
3059   case AtomicExpr::AO__c11_atomic_fetch_or:
3060   case AtomicExpr::AO__c11_atomic_fetch_xor:
3061   case AtomicExpr::AO__opencl_atomic_fetch_and:
3062   case AtomicExpr::AO__opencl_atomic_fetch_or:
3063   case AtomicExpr::AO__opencl_atomic_fetch_xor:
3064   case AtomicExpr::AO__atomic_fetch_and:
3065   case AtomicExpr::AO__atomic_fetch_or:
3066   case AtomicExpr::AO__atomic_fetch_xor:
3067   case AtomicExpr::AO__atomic_fetch_nand:
3068   case AtomicExpr::AO__atomic_and_fetch:
3069   case AtomicExpr::AO__atomic_or_fetch:
3070   case AtomicExpr::AO__atomic_xor_fetch:
3071   case AtomicExpr::AO__atomic_nand_fetch:
3072     Form = Arithmetic;
3073     break;
3074 
3075   case AtomicExpr::AO__c11_atomic_exchange:
3076   case AtomicExpr::AO__opencl_atomic_exchange:
3077   case AtomicExpr::AO__atomic_exchange_n:
3078     Form = Xchg;
3079     break;
3080 
3081   case AtomicExpr::AO__atomic_exchange:
3082     Form = GNUXchg;
3083     break;
3084 
3085   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3086   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
3087   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
3088   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
3089     Form = C11CmpXchg;
3090     break;
3091 
3092   case AtomicExpr::AO__atomic_compare_exchange:
3093   case AtomicExpr::AO__atomic_compare_exchange_n:
3094     Form = GNUCmpXchg;
3095     break;
3096   }
3097 
3098   unsigned AdjustedNumArgs = NumArgs[Form];
3099   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
3100     ++AdjustedNumArgs;
3101   // Check we have the right number of arguments.
3102   if (TheCall->getNumArgs() < AdjustedNumArgs) {
3103     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3104       << 0 << AdjustedNumArgs << TheCall->getNumArgs()
3105       << TheCall->getCallee()->getSourceRange();
3106     return ExprError();
3107   } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
3108     Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(),
3109          diag::err_typecheck_call_too_many_args)
3110       << 0 << AdjustedNumArgs << TheCall->getNumArgs()
3111       << TheCall->getCallee()->getSourceRange();
3112     return ExprError();
3113   }
3114 
3115   // Inspect the first argument of the atomic operation.
3116   Expr *Ptr = TheCall->getArg(0);
3117   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
3118   if (ConvertedPtr.isInvalid())
3119     return ExprError();
3120 
3121   Ptr = ConvertedPtr.get();
3122   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
3123   if (!pointerType) {
3124     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3125       << Ptr->getType() << Ptr->getSourceRange();
3126     return ExprError();
3127   }
3128 
3129   // For a __c11 builtin, this should be a pointer to an _Atomic type.
3130   QualType AtomTy = pointerType->getPointeeType(); // 'A'
3131   QualType ValType = AtomTy; // 'C'
3132   if (IsC11) {
3133     if (!AtomTy->isAtomicType()) {
3134       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
3135         << Ptr->getType() << Ptr->getSourceRange();
3136       return ExprError();
3137     }
3138     if (AtomTy.isConstQualified() ||
3139         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
3140       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
3141           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
3142           << Ptr->getSourceRange();
3143       return ExprError();
3144     }
3145     ValType = AtomTy->getAs<AtomicType>()->getValueType();
3146   } else if (Form != Load && Form != LoadCopy) {
3147     if (ValType.isConstQualified()) {
3148       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
3149         << Ptr->getType() << Ptr->getSourceRange();
3150       return ExprError();
3151     }
3152   }
3153 
3154   // For an arithmetic operation, the implied arithmetic must be well-formed.
3155   if (Form == Arithmetic) {
3156     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
3157     if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
3158       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3159         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3160       return ExprError();
3161     }
3162     if (!IsAddSub && !ValType->isIntegerType()) {
3163       Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
3164         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3165       return ExprError();
3166     }
3167     if (IsC11 && ValType->isPointerType() &&
3168         RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
3169                             diag::err_incomplete_type)) {
3170       return ExprError();
3171     }
3172   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
3173     // For __atomic_*_n operations, the value type must be a scalar integral or
3174     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
3175     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3176       << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3177     return ExprError();
3178   }
3179 
3180   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
3181       !AtomTy->isScalarType()) {
3182     // For GNU atomics, require a trivially-copyable type. This is not part of
3183     // the GNU atomics specification, but we enforce it for sanity.
3184     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
3185       << Ptr->getType() << Ptr->getSourceRange();
3186     return ExprError();
3187   }
3188 
3189   switch (ValType.getObjCLifetime()) {
3190   case Qualifiers::OCL_None:
3191   case Qualifiers::OCL_ExplicitNone:
3192     // okay
3193     break;
3194 
3195   case Qualifiers::OCL_Weak:
3196   case Qualifiers::OCL_Strong:
3197   case Qualifiers::OCL_Autoreleasing:
3198     // FIXME: Can this happen? By this point, ValType should be known
3199     // to be trivially copyable.
3200     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3201       << ValType << Ptr->getSourceRange();
3202     return ExprError();
3203   }
3204 
3205   // atomic_fetch_or takes a pointer to a volatile 'A'.  We shouldn't let the
3206   // volatile-ness of the pointee-type inject itself into the result or the
3207   // other operands. Similarly atomic_load can take a pointer to a const 'A'.
3208   ValType.removeLocalVolatile();
3209   ValType.removeLocalConst();
3210   QualType ResultType = ValType;
3211   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
3212       Form == Init)
3213     ResultType = Context.VoidTy;
3214   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
3215     ResultType = Context.BoolTy;
3216 
3217   // The type of a parameter passed 'by value'. In the GNU atomics, such
3218   // arguments are actually passed as pointers.
3219   QualType ByValType = ValType; // 'CP'
3220   if (!IsC11 && !IsN)
3221     ByValType = Ptr->getType();
3222 
3223   // The first argument --- the pointer --- has a fixed type; we
3224   // deduce the types of the rest of the arguments accordingly.  Walk
3225   // the remaining arguments, converting them to the deduced value type.
3226   for (unsigned i = 1; i != TheCall->getNumArgs(); ++i) {
3227     QualType Ty;
3228     if (i < NumVals[Form] + 1) {
3229       switch (i) {
3230       case 1:
3231         // The second argument is the non-atomic operand. For arithmetic, this
3232         // is always passed by value, and for a compare_exchange it is always
3233         // passed by address. For the rest, GNU uses by-address and C11 uses
3234         // by-value.
3235         assert(Form != Load);
3236         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
3237           Ty = ValType;
3238         else if (Form == Copy || Form == Xchg)
3239           Ty = ByValType;
3240         else if (Form == Arithmetic)
3241           Ty = Context.getPointerDiffType();
3242         else {
3243           Expr *ValArg = TheCall->getArg(i);
3244           // Treat this argument as _Nonnull as we want to show a warning if
3245           // NULL is passed into it.
3246           CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
3247           LangAS AS = LangAS::Default;
3248           // Keep address space of non-atomic pointer type.
3249           if (const PointerType *PtrTy =
3250                   ValArg->getType()->getAs<PointerType>()) {
3251             AS = PtrTy->getPointeeType().getAddressSpace();
3252           }
3253           Ty = Context.getPointerType(
3254               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
3255         }
3256         break;
3257       case 2:
3258         // The third argument to compare_exchange / GNU exchange is a
3259         // (pointer to a) desired value.
3260         Ty = ByValType;
3261         break;
3262       case 3:
3263         // The fourth argument to GNU compare_exchange is a 'weak' flag.
3264         Ty = Context.BoolTy;
3265         break;
3266       }
3267     } else {
3268       // The order(s) and scope are always converted to int.
3269       Ty = Context.IntTy;
3270     }
3271 
3272     InitializedEntity Entity =
3273         InitializedEntity::InitializeParameter(Context, Ty, false);
3274     ExprResult Arg = TheCall->getArg(i);
3275     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3276     if (Arg.isInvalid())
3277       return true;
3278     TheCall->setArg(i, Arg.get());
3279   }
3280 
3281   // Permute the arguments into a 'consistent' order.
3282   SmallVector<Expr*, 5> SubExprs;
3283   SubExprs.push_back(Ptr);
3284   switch (Form) {
3285   case Init:
3286     // Note, AtomicExpr::getVal1() has a special case for this atomic.
3287     SubExprs.push_back(TheCall->getArg(1)); // Val1
3288     break;
3289   case Load:
3290     SubExprs.push_back(TheCall->getArg(1)); // Order
3291     break;
3292   case LoadCopy:
3293   case Copy:
3294   case Arithmetic:
3295   case Xchg:
3296     SubExprs.push_back(TheCall->getArg(2)); // Order
3297     SubExprs.push_back(TheCall->getArg(1)); // Val1
3298     break;
3299   case GNUXchg:
3300     // Note, AtomicExpr::getVal2() has a special case for this atomic.
3301     SubExprs.push_back(TheCall->getArg(3)); // Order
3302     SubExprs.push_back(TheCall->getArg(1)); // Val1
3303     SubExprs.push_back(TheCall->getArg(2)); // Val2
3304     break;
3305   case C11CmpXchg:
3306     SubExprs.push_back(TheCall->getArg(3)); // Order
3307     SubExprs.push_back(TheCall->getArg(1)); // Val1
3308     SubExprs.push_back(TheCall->getArg(4)); // OrderFail
3309     SubExprs.push_back(TheCall->getArg(2)); // Val2
3310     break;
3311   case GNUCmpXchg:
3312     SubExprs.push_back(TheCall->getArg(4)); // Order
3313     SubExprs.push_back(TheCall->getArg(1)); // Val1
3314     SubExprs.push_back(TheCall->getArg(5)); // OrderFail
3315     SubExprs.push_back(TheCall->getArg(2)); // Val2
3316     SubExprs.push_back(TheCall->getArg(3)); // Weak
3317     break;
3318   }
3319 
3320   if (SubExprs.size() >= 2 && Form != Init) {
3321     llvm::APSInt Result(32);
3322     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
3323         !isValidOrderingForOp(Result.getSExtValue(), Op))
3324       Diag(SubExprs[1]->getLocStart(),
3325            diag::warn_atomic_op_has_invalid_memory_order)
3326           << SubExprs[1]->getSourceRange();
3327   }
3328 
3329   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
3330     auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
3331     llvm::APSInt Result(32);
3332     if (Scope->isIntegerConstantExpr(Result, Context) &&
3333         !ScopeModel->isValid(Result.getZExtValue())) {
3334       Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope)
3335           << Scope->getSourceRange();
3336     }
3337     SubExprs.push_back(Scope);
3338   }
3339 
3340   AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
3341                                             SubExprs, ResultType, Op,
3342                                             TheCall->getRParenLoc());
3343 
3344   if ((Op == AtomicExpr::AO__c11_atomic_load ||
3345        Op == AtomicExpr::AO__c11_atomic_store ||
3346        Op == AtomicExpr::AO__opencl_atomic_load ||
3347        Op == AtomicExpr::AO__opencl_atomic_store ) &&
3348       Context.AtomicUsesUnsupportedLibcall(AE))
3349     Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib)
3350         << ((Op == AtomicExpr::AO__c11_atomic_load ||
3351             Op == AtomicExpr::AO__opencl_atomic_load)
3352                 ? 0 : 1);
3353 
3354   return AE;
3355 }
3356 
3357 /// checkBuiltinArgument - Given a call to a builtin function, perform
3358 /// normal type-checking on the given argument, updating the call in
3359 /// place.  This is useful when a builtin function requires custom
3360 /// type-checking for some of its arguments but not necessarily all of
3361 /// them.
3362 ///
3363 /// Returns true on error.
3364 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
3365   FunctionDecl *Fn = E->getDirectCallee();
3366   assert(Fn && "builtin call without direct callee!");
3367 
3368   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
3369   InitializedEntity Entity =
3370     InitializedEntity::InitializeParameter(S.Context, Param);
3371 
3372   ExprResult Arg = E->getArg(0);
3373   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3374   if (Arg.isInvalid())
3375     return true;
3376 
3377   E->setArg(ArgIndex, Arg.get());
3378   return false;
3379 }
3380 
3381 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
3382 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
3383 /// type of its first argument.  The main ActOnCallExpr routines have already
3384 /// promoted the types of arguments because all of these calls are prototyped as
3385 /// void(...).
3386 ///
3387 /// This function goes through and does final semantic checking for these
3388 /// builtins,
3389 ExprResult
3390 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
3391   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3392   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3393   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3394 
3395   // Ensure that we have at least one argument to do type inference from.
3396   if (TheCall->getNumArgs() < 1) {
3397     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3398       << 0 << 1 << TheCall->getNumArgs()
3399       << TheCall->getCallee()->getSourceRange();
3400     return ExprError();
3401   }
3402 
3403   // Inspect the first argument of the atomic builtin.  This should always be
3404   // a pointer type, whose element is an integral scalar or pointer type.
3405   // Because it is a pointer type, we don't have to worry about any implicit
3406   // casts here.
3407   // FIXME: We don't allow floating point scalars as input.
3408   Expr *FirstArg = TheCall->getArg(0);
3409   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3410   if (FirstArgResult.isInvalid())
3411     return ExprError();
3412   FirstArg = FirstArgResult.get();
3413   TheCall->setArg(0, FirstArg);
3414 
3415   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3416   if (!pointerType) {
3417     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3418       << FirstArg->getType() << FirstArg->getSourceRange();
3419     return ExprError();
3420   }
3421 
3422   QualType ValType = pointerType->getPointeeType();
3423   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3424       !ValType->isBlockPointerType()) {
3425     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3426       << FirstArg->getType() << FirstArg->getSourceRange();
3427     return ExprError();
3428   }
3429 
3430   switch (ValType.getObjCLifetime()) {
3431   case Qualifiers::OCL_None:
3432   case Qualifiers::OCL_ExplicitNone:
3433     // okay
3434     break;
3435 
3436   case Qualifiers::OCL_Weak:
3437   case Qualifiers::OCL_Strong:
3438   case Qualifiers::OCL_Autoreleasing:
3439     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3440       << ValType << FirstArg->getSourceRange();
3441     return ExprError();
3442   }
3443 
3444   // Strip any qualifiers off ValType.
3445   ValType = ValType.getUnqualifiedType();
3446 
3447   // The majority of builtins return a value, but a few have special return
3448   // types, so allow them to override appropriately below.
3449   QualType ResultType = ValType;
3450 
3451   // We need to figure out which concrete builtin this maps onto.  For example,
3452   // __sync_fetch_and_add with a 2 byte object turns into
3453   // __sync_fetch_and_add_2.
3454 #define BUILTIN_ROW(x) \
3455   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3456     Builtin::BI##x##_8, Builtin::BI##x##_16 }
3457 
3458   static const unsigned BuiltinIndices[][5] = {
3459     BUILTIN_ROW(__sync_fetch_and_add),
3460     BUILTIN_ROW(__sync_fetch_and_sub),
3461     BUILTIN_ROW(__sync_fetch_and_or),
3462     BUILTIN_ROW(__sync_fetch_and_and),
3463     BUILTIN_ROW(__sync_fetch_and_xor),
3464     BUILTIN_ROW(__sync_fetch_and_nand),
3465 
3466     BUILTIN_ROW(__sync_add_and_fetch),
3467     BUILTIN_ROW(__sync_sub_and_fetch),
3468     BUILTIN_ROW(__sync_and_and_fetch),
3469     BUILTIN_ROW(__sync_or_and_fetch),
3470     BUILTIN_ROW(__sync_xor_and_fetch),
3471     BUILTIN_ROW(__sync_nand_and_fetch),
3472 
3473     BUILTIN_ROW(__sync_val_compare_and_swap),
3474     BUILTIN_ROW(__sync_bool_compare_and_swap),
3475     BUILTIN_ROW(__sync_lock_test_and_set),
3476     BUILTIN_ROW(__sync_lock_release),
3477     BUILTIN_ROW(__sync_swap)
3478   };
3479 #undef BUILTIN_ROW
3480 
3481   // Determine the index of the size.
3482   unsigned SizeIndex;
3483   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
3484   case 1: SizeIndex = 0; break;
3485   case 2: SizeIndex = 1; break;
3486   case 4: SizeIndex = 2; break;
3487   case 8: SizeIndex = 3; break;
3488   case 16: SizeIndex = 4; break;
3489   default:
3490     Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3491       << FirstArg->getType() << FirstArg->getSourceRange();
3492     return ExprError();
3493   }
3494 
3495   // Each of these builtins has one pointer argument, followed by some number of
3496   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3497   // that we ignore.  Find out which row of BuiltinIndices to read from as well
3498   // as the number of fixed args.
3499   unsigned BuiltinID = FDecl->getBuiltinID();
3500   unsigned BuiltinIndex, NumFixed = 1;
3501   bool WarnAboutSemanticsChange = false;
3502   switch (BuiltinID) {
3503   default: llvm_unreachable("Unknown overloaded atomic builtin!");
3504   case Builtin::BI__sync_fetch_and_add:
3505   case Builtin::BI__sync_fetch_and_add_1:
3506   case Builtin::BI__sync_fetch_and_add_2:
3507   case Builtin::BI__sync_fetch_and_add_4:
3508   case Builtin::BI__sync_fetch_and_add_8:
3509   case Builtin::BI__sync_fetch_and_add_16:
3510     BuiltinIndex = 0;
3511     break;
3512 
3513   case Builtin::BI__sync_fetch_and_sub:
3514   case Builtin::BI__sync_fetch_and_sub_1:
3515   case Builtin::BI__sync_fetch_and_sub_2:
3516   case Builtin::BI__sync_fetch_and_sub_4:
3517   case Builtin::BI__sync_fetch_and_sub_8:
3518   case Builtin::BI__sync_fetch_and_sub_16:
3519     BuiltinIndex = 1;
3520     break;
3521 
3522   case Builtin::BI__sync_fetch_and_or:
3523   case Builtin::BI__sync_fetch_and_or_1:
3524   case Builtin::BI__sync_fetch_and_or_2:
3525   case Builtin::BI__sync_fetch_and_or_4:
3526   case Builtin::BI__sync_fetch_and_or_8:
3527   case Builtin::BI__sync_fetch_and_or_16:
3528     BuiltinIndex = 2;
3529     break;
3530 
3531   case Builtin::BI__sync_fetch_and_and:
3532   case Builtin::BI__sync_fetch_and_and_1:
3533   case Builtin::BI__sync_fetch_and_and_2:
3534   case Builtin::BI__sync_fetch_and_and_4:
3535   case Builtin::BI__sync_fetch_and_and_8:
3536   case Builtin::BI__sync_fetch_and_and_16:
3537     BuiltinIndex = 3;
3538     break;
3539 
3540   case Builtin::BI__sync_fetch_and_xor:
3541   case Builtin::BI__sync_fetch_and_xor_1:
3542   case Builtin::BI__sync_fetch_and_xor_2:
3543   case Builtin::BI__sync_fetch_and_xor_4:
3544   case Builtin::BI__sync_fetch_and_xor_8:
3545   case Builtin::BI__sync_fetch_and_xor_16:
3546     BuiltinIndex = 4;
3547     break;
3548 
3549   case Builtin::BI__sync_fetch_and_nand:
3550   case Builtin::BI__sync_fetch_and_nand_1:
3551   case Builtin::BI__sync_fetch_and_nand_2:
3552   case Builtin::BI__sync_fetch_and_nand_4:
3553   case Builtin::BI__sync_fetch_and_nand_8:
3554   case Builtin::BI__sync_fetch_and_nand_16:
3555     BuiltinIndex = 5;
3556     WarnAboutSemanticsChange = true;
3557     break;
3558 
3559   case Builtin::BI__sync_add_and_fetch:
3560   case Builtin::BI__sync_add_and_fetch_1:
3561   case Builtin::BI__sync_add_and_fetch_2:
3562   case Builtin::BI__sync_add_and_fetch_4:
3563   case Builtin::BI__sync_add_and_fetch_8:
3564   case Builtin::BI__sync_add_and_fetch_16:
3565     BuiltinIndex = 6;
3566     break;
3567 
3568   case Builtin::BI__sync_sub_and_fetch:
3569   case Builtin::BI__sync_sub_and_fetch_1:
3570   case Builtin::BI__sync_sub_and_fetch_2:
3571   case Builtin::BI__sync_sub_and_fetch_4:
3572   case Builtin::BI__sync_sub_and_fetch_8:
3573   case Builtin::BI__sync_sub_and_fetch_16:
3574     BuiltinIndex = 7;
3575     break;
3576 
3577   case Builtin::BI__sync_and_and_fetch:
3578   case Builtin::BI__sync_and_and_fetch_1:
3579   case Builtin::BI__sync_and_and_fetch_2:
3580   case Builtin::BI__sync_and_and_fetch_4:
3581   case Builtin::BI__sync_and_and_fetch_8:
3582   case Builtin::BI__sync_and_and_fetch_16:
3583     BuiltinIndex = 8;
3584     break;
3585 
3586   case Builtin::BI__sync_or_and_fetch:
3587   case Builtin::BI__sync_or_and_fetch_1:
3588   case Builtin::BI__sync_or_and_fetch_2:
3589   case Builtin::BI__sync_or_and_fetch_4:
3590   case Builtin::BI__sync_or_and_fetch_8:
3591   case Builtin::BI__sync_or_and_fetch_16:
3592     BuiltinIndex = 9;
3593     break;
3594 
3595   case Builtin::BI__sync_xor_and_fetch:
3596   case Builtin::BI__sync_xor_and_fetch_1:
3597   case Builtin::BI__sync_xor_and_fetch_2:
3598   case Builtin::BI__sync_xor_and_fetch_4:
3599   case Builtin::BI__sync_xor_and_fetch_8:
3600   case Builtin::BI__sync_xor_and_fetch_16:
3601     BuiltinIndex = 10;
3602     break;
3603 
3604   case Builtin::BI__sync_nand_and_fetch:
3605   case Builtin::BI__sync_nand_and_fetch_1:
3606   case Builtin::BI__sync_nand_and_fetch_2:
3607   case Builtin::BI__sync_nand_and_fetch_4:
3608   case Builtin::BI__sync_nand_and_fetch_8:
3609   case Builtin::BI__sync_nand_and_fetch_16:
3610     BuiltinIndex = 11;
3611     WarnAboutSemanticsChange = true;
3612     break;
3613 
3614   case Builtin::BI__sync_val_compare_and_swap:
3615   case Builtin::BI__sync_val_compare_and_swap_1:
3616   case Builtin::BI__sync_val_compare_and_swap_2:
3617   case Builtin::BI__sync_val_compare_and_swap_4:
3618   case Builtin::BI__sync_val_compare_and_swap_8:
3619   case Builtin::BI__sync_val_compare_and_swap_16:
3620     BuiltinIndex = 12;
3621     NumFixed = 2;
3622     break;
3623 
3624   case Builtin::BI__sync_bool_compare_and_swap:
3625   case Builtin::BI__sync_bool_compare_and_swap_1:
3626   case Builtin::BI__sync_bool_compare_and_swap_2:
3627   case Builtin::BI__sync_bool_compare_and_swap_4:
3628   case Builtin::BI__sync_bool_compare_and_swap_8:
3629   case Builtin::BI__sync_bool_compare_and_swap_16:
3630     BuiltinIndex = 13;
3631     NumFixed = 2;
3632     ResultType = Context.BoolTy;
3633     break;
3634 
3635   case Builtin::BI__sync_lock_test_and_set:
3636   case Builtin::BI__sync_lock_test_and_set_1:
3637   case Builtin::BI__sync_lock_test_and_set_2:
3638   case Builtin::BI__sync_lock_test_and_set_4:
3639   case Builtin::BI__sync_lock_test_and_set_8:
3640   case Builtin::BI__sync_lock_test_and_set_16:
3641     BuiltinIndex = 14;
3642     break;
3643 
3644   case Builtin::BI__sync_lock_release:
3645   case Builtin::BI__sync_lock_release_1:
3646   case Builtin::BI__sync_lock_release_2:
3647   case Builtin::BI__sync_lock_release_4:
3648   case Builtin::BI__sync_lock_release_8:
3649   case Builtin::BI__sync_lock_release_16:
3650     BuiltinIndex = 15;
3651     NumFixed = 0;
3652     ResultType = Context.VoidTy;
3653     break;
3654 
3655   case Builtin::BI__sync_swap:
3656   case Builtin::BI__sync_swap_1:
3657   case Builtin::BI__sync_swap_2:
3658   case Builtin::BI__sync_swap_4:
3659   case Builtin::BI__sync_swap_8:
3660   case Builtin::BI__sync_swap_16:
3661     BuiltinIndex = 16;
3662     break;
3663   }
3664 
3665   // Now that we know how many fixed arguments we expect, first check that we
3666   // have at least that many.
3667   if (TheCall->getNumArgs() < 1+NumFixed) {
3668     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3669       << 0 << 1+NumFixed << TheCall->getNumArgs()
3670       << TheCall->getCallee()->getSourceRange();
3671     return ExprError();
3672   }
3673 
3674   if (WarnAboutSemanticsChange) {
3675     Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3676       << TheCall->getCallee()->getSourceRange();
3677   }
3678 
3679   // Get the decl for the concrete builtin from this, we can tell what the
3680   // concrete integer type we should convert to is.
3681   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
3682   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
3683   FunctionDecl *NewBuiltinDecl;
3684   if (NewBuiltinID == BuiltinID)
3685     NewBuiltinDecl = FDecl;
3686   else {
3687     // Perform builtin lookup to avoid redeclaring it.
3688     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3689     LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3690     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3691     assert(Res.getFoundDecl());
3692     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
3693     if (!NewBuiltinDecl)
3694       return ExprError();
3695   }
3696 
3697   // The first argument --- the pointer --- has a fixed type; we
3698   // deduce the types of the rest of the arguments accordingly.  Walk
3699   // the remaining arguments, converting them to the deduced value type.
3700   for (unsigned i = 0; i != NumFixed; ++i) {
3701     ExprResult Arg = TheCall->getArg(i+1);
3702 
3703     // GCC does an implicit conversion to the pointer or integer ValType.  This
3704     // can fail in some cases (1i -> int**), check for this error case now.
3705     // Initialize the argument.
3706     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3707                                                    ValType, /*consume*/ false);
3708     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3709     if (Arg.isInvalid())
3710       return ExprError();
3711 
3712     // Okay, we have something that *can* be converted to the right type.  Check
3713     // to see if there is a potentially weird extension going on here.  This can
3714     // happen when you do an atomic operation on something like an char* and
3715     // pass in 42.  The 42 gets converted to char.  This is even more strange
3716     // for things like 45.123 -> char, etc.
3717     // FIXME: Do this check.
3718     TheCall->setArg(i+1, Arg.get());
3719   }
3720 
3721   ASTContext& Context = this->getASTContext();
3722 
3723   // Create a new DeclRefExpr to refer to the new decl.
3724   DeclRefExpr* NewDRE = DeclRefExpr::Create(
3725       Context,
3726       DRE->getQualifierLoc(),
3727       SourceLocation(),
3728       NewBuiltinDecl,
3729       /*enclosing*/ false,
3730       DRE->getLocation(),
3731       Context.BuiltinFnTy,
3732       DRE->getValueKind());
3733 
3734   // Set the callee in the CallExpr.
3735   // FIXME: This loses syntactic information.
3736   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3737   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3738                                               CK_BuiltinFnToFnPtr);
3739   TheCall->setCallee(PromotedCall.get());
3740 
3741   // Change the result type of the call to match the original value type. This
3742   // is arbitrary, but the codegen for these builtins ins design to handle it
3743   // gracefully.
3744   TheCall->setType(ResultType);
3745 
3746   return TheCallResult;
3747 }
3748 
3749 /// SemaBuiltinNontemporalOverloaded - We have a call to
3750 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3751 /// overloaded function based on the pointer type of its last argument.
3752 ///
3753 /// This function goes through and does final semantic checking for these
3754 /// builtins.
3755 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3756   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3757   DeclRefExpr *DRE =
3758       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3759   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3760   unsigned BuiltinID = FDecl->getBuiltinID();
3761   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3762           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3763          "Unexpected nontemporal load/store builtin!");
3764   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3765   unsigned numArgs = isStore ? 2 : 1;
3766 
3767   // Ensure that we have the proper number of arguments.
3768   if (checkArgCount(*this, TheCall, numArgs))
3769     return ExprError();
3770 
3771   // Inspect the last argument of the nontemporal builtin.  This should always
3772   // be a pointer type, from which we imply the type of the memory access.
3773   // Because it is a pointer type, we don't have to worry about any implicit
3774   // casts here.
3775   Expr *PointerArg = TheCall->getArg(numArgs - 1);
3776   ExprResult PointerArgResult =
3777       DefaultFunctionArrayLvalueConversion(PointerArg);
3778 
3779   if (PointerArgResult.isInvalid())
3780     return ExprError();
3781   PointerArg = PointerArgResult.get();
3782   TheCall->setArg(numArgs - 1, PointerArg);
3783 
3784   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3785   if (!pointerType) {
3786     Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3787         << PointerArg->getType() << PointerArg->getSourceRange();
3788     return ExprError();
3789   }
3790 
3791   QualType ValType = pointerType->getPointeeType();
3792 
3793   // Strip any qualifiers off ValType.
3794   ValType = ValType.getUnqualifiedType();
3795   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3796       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3797       !ValType->isVectorType()) {
3798     Diag(DRE->getLocStart(),
3799          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3800         << PointerArg->getType() << PointerArg->getSourceRange();
3801     return ExprError();
3802   }
3803 
3804   if (!isStore) {
3805     TheCall->setType(ValType);
3806     return TheCallResult;
3807   }
3808 
3809   ExprResult ValArg = TheCall->getArg(0);
3810   InitializedEntity Entity = InitializedEntity::InitializeParameter(
3811       Context, ValType, /*consume*/ false);
3812   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3813   if (ValArg.isInvalid())
3814     return ExprError();
3815 
3816   TheCall->setArg(0, ValArg.get());
3817   TheCall->setType(Context.VoidTy);
3818   return TheCallResult;
3819 }
3820 
3821 /// CheckObjCString - Checks that the argument to the builtin
3822 /// CFString constructor is correct
3823 /// Note: It might also make sense to do the UTF-16 conversion here (would
3824 /// simplify the backend).
3825 bool Sema::CheckObjCString(Expr *Arg) {
3826   Arg = Arg->IgnoreParenCasts();
3827   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3828 
3829   if (!Literal || !Literal->isAscii()) {
3830     Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3831       << Arg->getSourceRange();
3832     return true;
3833   }
3834 
3835   if (Literal->containsNonAsciiOrNull()) {
3836     StringRef String = Literal->getString();
3837     unsigned NumBytes = String.size();
3838     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3839     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3840     llvm::UTF16 *ToPtr = &ToBuf[0];
3841 
3842     llvm::ConversionResult Result =
3843         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3844                                  ToPtr + NumBytes, llvm::strictConversion);
3845     // Check for conversion failure.
3846     if (Result != llvm::conversionOK)
3847       Diag(Arg->getLocStart(),
3848            diag::warn_cfstring_truncated) << Arg->getSourceRange();
3849   }
3850   return false;
3851 }
3852 
3853 /// CheckObjCString - Checks that the format string argument to the os_log()
3854 /// and os_trace() functions is correct, and converts it to const char *.
3855 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3856   Arg = Arg->IgnoreParenCasts();
3857   auto *Literal = dyn_cast<StringLiteral>(Arg);
3858   if (!Literal) {
3859     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3860       Literal = ObjcLiteral->getString();
3861     }
3862   }
3863 
3864   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3865     return ExprError(
3866         Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3867         << Arg->getSourceRange());
3868   }
3869 
3870   ExprResult Result(Literal);
3871   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3872   InitializedEntity Entity =
3873       InitializedEntity::InitializeParameter(Context, ResultTy, false);
3874   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3875   return Result;
3876 }
3877 
3878 /// Check that the user is calling the appropriate va_start builtin for the
3879 /// target and calling convention.
3880 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
3881   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
3882   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
3883   bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
3884   bool IsWindows = TT.isOSWindows();
3885   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
3886   if (IsX64 || IsAArch64) {
3887     CallingConv CC = CC_C;
3888     if (const FunctionDecl *FD = S.getCurFunctionDecl())
3889       CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3890     if (IsMSVAStart) {
3891       // Don't allow this in System V ABI functions.
3892       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
3893         return S.Diag(Fn->getLocStart(),
3894                       diag::err_ms_va_start_used_in_sysv_function);
3895     } else {
3896       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
3897       // On x64 Windows, don't allow this in System V ABI functions.
3898       // (Yes, that means there's no corresponding way to support variadic
3899       // System V ABI functions on Windows.)
3900       if ((IsWindows && CC == CC_X86_64SysV) ||
3901           (!IsWindows && CC == CC_Win64))
3902         return S.Diag(Fn->getLocStart(),
3903                       diag::err_va_start_used_in_wrong_abi_function)
3904                << !IsWindows;
3905     }
3906     return false;
3907   }
3908 
3909   if (IsMSVAStart)
3910     return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only);
3911   return false;
3912 }
3913 
3914 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
3915                                              ParmVarDecl **LastParam = nullptr) {
3916   // Determine whether the current function, block, or obj-c method is variadic
3917   // and get its parameter list.
3918   bool IsVariadic = false;
3919   ArrayRef<ParmVarDecl *> Params;
3920   DeclContext *Caller = S.CurContext;
3921   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
3922     IsVariadic = Block->isVariadic();
3923     Params = Block->parameters();
3924   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
3925     IsVariadic = FD->isVariadic();
3926     Params = FD->parameters();
3927   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
3928     IsVariadic = MD->isVariadic();
3929     // FIXME: This isn't correct for methods (results in bogus warning).
3930     Params = MD->parameters();
3931   } else if (isa<CapturedDecl>(Caller)) {
3932     // We don't support va_start in a CapturedDecl.
3933     S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
3934     return true;
3935   } else {
3936     // This must be some other declcontext that parses exprs.
3937     S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
3938     return true;
3939   }
3940 
3941   if (!IsVariadic) {
3942     S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
3943     return true;
3944   }
3945 
3946   if (LastParam)
3947     *LastParam = Params.empty() ? nullptr : Params.back();
3948 
3949   return false;
3950 }
3951 
3952 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3953 /// for validity.  Emit an error and return true on failure; return false
3954 /// on success.
3955 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
3956   Expr *Fn = TheCall->getCallee();
3957 
3958   if (checkVAStartABI(*this, BuiltinID, Fn))
3959     return true;
3960 
3961   if (TheCall->getNumArgs() > 2) {
3962     Diag(TheCall->getArg(2)->getLocStart(),
3963          diag::err_typecheck_call_too_many_args)
3964       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3965       << Fn->getSourceRange()
3966       << SourceRange(TheCall->getArg(2)->getLocStart(),
3967                      (*(TheCall->arg_end()-1))->getLocEnd());
3968     return true;
3969   }
3970 
3971   if (TheCall->getNumArgs() < 2) {
3972     return Diag(TheCall->getLocEnd(),
3973       diag::err_typecheck_call_too_few_args_at_least)
3974       << 0 /*function call*/ << 2 << TheCall->getNumArgs();
3975   }
3976 
3977   // Type-check the first argument normally.
3978   if (checkBuiltinArgument(*this, TheCall, 0))
3979     return true;
3980 
3981   // Check that the current function is variadic, and get its last parameter.
3982   ParmVarDecl *LastParam;
3983   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
3984     return true;
3985 
3986   // Verify that the second argument to the builtin is the last argument of the
3987   // current function or method.
3988   bool SecondArgIsLastNamedArgument = false;
3989   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
3990 
3991   // These are valid if SecondArgIsLastNamedArgument is false after the next
3992   // block.
3993   QualType Type;
3994   SourceLocation ParamLoc;
3995   bool IsCRegister = false;
3996 
3997   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3998     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
3999       SecondArgIsLastNamedArgument = PV == LastParam;
4000 
4001       Type = PV->getType();
4002       ParamLoc = PV->getLocation();
4003       IsCRegister =
4004           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
4005     }
4006   }
4007 
4008   if (!SecondArgIsLastNamedArgument)
4009     Diag(TheCall->getArg(1)->getLocStart(),
4010          diag::warn_second_arg_of_va_start_not_last_named_param);
4011   else if (IsCRegister || Type->isReferenceType() ||
4012            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
4013              // Promotable integers are UB, but enumerations need a bit of
4014              // extra checking to see what their promotable type actually is.
4015              if (!Type->isPromotableIntegerType())
4016                return false;
4017              if (!Type->isEnumeralType())
4018                return true;
4019              const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
4020              return !(ED &&
4021                       Context.typesAreCompatible(ED->getPromotionType(), Type));
4022            }()) {
4023     unsigned Reason = 0;
4024     if (Type->isReferenceType())  Reason = 1;
4025     else if (IsCRegister)         Reason = 2;
4026     Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
4027     Diag(ParamLoc, diag::note_parameter_type) << Type;
4028   }
4029 
4030   TheCall->setType(Context.VoidTy);
4031   return false;
4032 }
4033 
4034 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
4035   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
4036   //                 const char *named_addr);
4037 
4038   Expr *Func = Call->getCallee();
4039 
4040   if (Call->getNumArgs() < 3)
4041     return Diag(Call->getLocEnd(),
4042                 diag::err_typecheck_call_too_few_args_at_least)
4043            << 0 /*function call*/ << 3 << Call->getNumArgs();
4044 
4045   // Type-check the first argument normally.
4046   if (checkBuiltinArgument(*this, Call, 0))
4047     return true;
4048 
4049   // Check that the current function is variadic.
4050   if (checkVAStartIsInVariadicFunction(*this, Func))
4051     return true;
4052 
4053   // __va_start on Windows does not validate the parameter qualifiers
4054 
4055   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
4056   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
4057 
4058   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
4059   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
4060 
4061   const QualType &ConstCharPtrTy =
4062       Context.getPointerType(Context.CharTy.withConst());
4063   if (!Arg1Ty->isPointerType() ||
4064       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
4065     Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible)
4066         << Arg1->getType() << ConstCharPtrTy
4067         << 1 /* different class */
4068         << 0 /* qualifier difference */
4069         << 3 /* parameter mismatch */
4070         << 2 << Arg1->getType() << ConstCharPtrTy;
4071 
4072   const QualType SizeTy = Context.getSizeType();
4073   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
4074     Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible)
4075         << Arg2->getType() << SizeTy
4076         << 1 /* different class */
4077         << 0 /* qualifier difference */
4078         << 3 /* parameter mismatch */
4079         << 3 << Arg2->getType() << SizeTy;
4080 
4081   return false;
4082 }
4083 
4084 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
4085 /// friends.  This is declared to take (...), so we have to check everything.
4086 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
4087   if (TheCall->getNumArgs() < 2)
4088     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4089       << 0 << 2 << TheCall->getNumArgs()/*function call*/;
4090   if (TheCall->getNumArgs() > 2)
4091     return Diag(TheCall->getArg(2)->getLocStart(),
4092                 diag::err_typecheck_call_too_many_args)
4093       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4094       << SourceRange(TheCall->getArg(2)->getLocStart(),
4095                      (*(TheCall->arg_end()-1))->getLocEnd());
4096 
4097   ExprResult OrigArg0 = TheCall->getArg(0);
4098   ExprResult OrigArg1 = TheCall->getArg(1);
4099 
4100   // Do standard promotions between the two arguments, returning their common
4101   // type.
4102   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
4103   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
4104     return true;
4105 
4106   // Make sure any conversions are pushed back into the call; this is
4107   // type safe since unordered compare builtins are declared as "_Bool
4108   // foo(...)".
4109   TheCall->setArg(0, OrigArg0.get());
4110   TheCall->setArg(1, OrigArg1.get());
4111 
4112   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
4113     return false;
4114 
4115   // If the common type isn't a real floating type, then the arguments were
4116   // invalid for this operation.
4117   if (Res.isNull() || !Res->isRealFloatingType())
4118     return Diag(OrigArg0.get()->getLocStart(),
4119                 diag::err_typecheck_call_invalid_ordered_compare)
4120       << OrigArg0.get()->getType() << OrigArg1.get()->getType()
4121       << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
4122 
4123   return false;
4124 }
4125 
4126 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
4127 /// __builtin_isnan and friends.  This is declared to take (...), so we have
4128 /// to check everything. We expect the last argument to be a floating point
4129 /// value.
4130 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
4131   if (TheCall->getNumArgs() < NumArgs)
4132     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4133       << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
4134   if (TheCall->getNumArgs() > NumArgs)
4135     return Diag(TheCall->getArg(NumArgs)->getLocStart(),
4136                 diag::err_typecheck_call_too_many_args)
4137       << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
4138       << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
4139                      (*(TheCall->arg_end()-1))->getLocEnd());
4140 
4141   Expr *OrigArg = TheCall->getArg(NumArgs-1);
4142 
4143   if (OrigArg->isTypeDependent())
4144     return false;
4145 
4146   // This operation requires a non-_Complex floating-point number.
4147   if (!OrigArg->getType()->isRealFloatingType())
4148     return Diag(OrigArg->getLocStart(),
4149                 diag::err_typecheck_call_invalid_unary_fp)
4150       << OrigArg->getType() << OrigArg->getSourceRange();
4151 
4152   // If this is an implicit conversion from float -> float or double, remove it.
4153   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
4154     // Only remove standard FloatCasts, leaving other casts inplace
4155     if (Cast->getCastKind() == CK_FloatingCast) {
4156       Expr *CastArg = Cast->getSubExpr();
4157       if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
4158           assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
4159                   Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
4160                "promotion from float to either float or double is the only expected cast here");
4161         Cast->setSubExpr(nullptr);
4162         TheCall->setArg(NumArgs-1, CastArg);
4163       }
4164     }
4165   }
4166 
4167   return false;
4168 }
4169 
4170 // Customized Sema Checking for VSX builtins that have the following signature:
4171 // vector [...] builtinName(vector [...], vector [...], const int);
4172 // Which takes the same type of vectors (any legal vector type) for the first
4173 // two arguments and takes compile time constant for the third argument.
4174 // Example builtins are :
4175 // vector double vec_xxpermdi(vector double, vector double, int);
4176 // vector short vec_xxsldwi(vector short, vector short, int);
4177 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
4178   unsigned ExpectedNumArgs = 3;
4179   if (TheCall->getNumArgs() < ExpectedNumArgs)
4180     return Diag(TheCall->getLocEnd(),
4181                 diag::err_typecheck_call_too_few_args_at_least)
4182            << 0 /*function call*/ <<  ExpectedNumArgs << TheCall->getNumArgs()
4183            << TheCall->getSourceRange();
4184 
4185   if (TheCall->getNumArgs() > ExpectedNumArgs)
4186     return Diag(TheCall->getLocEnd(),
4187                 diag::err_typecheck_call_too_many_args_at_most)
4188            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4189            << TheCall->getSourceRange();
4190 
4191   // Check the third argument is a compile time constant
4192   llvm::APSInt Value;
4193   if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
4194     return Diag(TheCall->getLocStart(),
4195                 diag::err_vsx_builtin_nonconstant_argument)
4196            << 3 /* argument index */ << TheCall->getDirectCallee()
4197            << SourceRange(TheCall->getArg(2)->getLocStart(),
4198                           TheCall->getArg(2)->getLocEnd());
4199 
4200   QualType Arg1Ty = TheCall->getArg(0)->getType();
4201   QualType Arg2Ty = TheCall->getArg(1)->getType();
4202 
4203   // Check the type of argument 1 and argument 2 are vectors.
4204   SourceLocation BuiltinLoc = TheCall->getLocStart();
4205   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
4206       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
4207     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
4208            << TheCall->getDirectCallee()
4209            << SourceRange(TheCall->getArg(0)->getLocStart(),
4210                           TheCall->getArg(1)->getLocEnd());
4211   }
4212 
4213   // Check the first two arguments are the same type.
4214   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
4215     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
4216            << TheCall->getDirectCallee()
4217            << SourceRange(TheCall->getArg(0)->getLocStart(),
4218                           TheCall->getArg(1)->getLocEnd());
4219   }
4220 
4221   // When default clang type checking is turned off and the customized type
4222   // checking is used, the returning type of the function must be explicitly
4223   // set. Otherwise it is _Bool by default.
4224   TheCall->setType(Arg1Ty);
4225 
4226   return false;
4227 }
4228 
4229 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
4230 // This is declared to take (...), so we have to check everything.
4231 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
4232   if (TheCall->getNumArgs() < 2)
4233     return ExprError(Diag(TheCall->getLocEnd(),
4234                           diag::err_typecheck_call_too_few_args_at_least)
4235                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4236                      << TheCall->getSourceRange());
4237 
4238   // Determine which of the following types of shufflevector we're checking:
4239   // 1) unary, vector mask: (lhs, mask)
4240   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
4241   QualType resType = TheCall->getArg(0)->getType();
4242   unsigned numElements = 0;
4243 
4244   if (!TheCall->getArg(0)->isTypeDependent() &&
4245       !TheCall->getArg(1)->isTypeDependent()) {
4246     QualType LHSType = TheCall->getArg(0)->getType();
4247     QualType RHSType = TheCall->getArg(1)->getType();
4248 
4249     if (!LHSType->isVectorType() || !RHSType->isVectorType())
4250       return ExprError(Diag(TheCall->getLocStart(),
4251                             diag::err_vec_builtin_non_vector)
4252                        << TheCall->getDirectCallee()
4253                        << SourceRange(TheCall->getArg(0)->getLocStart(),
4254                                       TheCall->getArg(1)->getLocEnd()));
4255 
4256     numElements = LHSType->getAs<VectorType>()->getNumElements();
4257     unsigned numResElements = TheCall->getNumArgs() - 2;
4258 
4259     // Check to see if we have a call with 2 vector arguments, the unary shuffle
4260     // with mask.  If so, verify that RHS is an integer vector type with the
4261     // same number of elts as lhs.
4262     if (TheCall->getNumArgs() == 2) {
4263       if (!RHSType->hasIntegerRepresentation() ||
4264           RHSType->getAs<VectorType>()->getNumElements() != numElements)
4265         return ExprError(Diag(TheCall->getLocStart(),
4266                               diag::err_vec_builtin_incompatible_vector)
4267                          << TheCall->getDirectCallee()
4268                          << SourceRange(TheCall->getArg(1)->getLocStart(),
4269                                         TheCall->getArg(1)->getLocEnd()));
4270     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
4271       return ExprError(Diag(TheCall->getLocStart(),
4272                             diag::err_vec_builtin_incompatible_vector)
4273                        << TheCall->getDirectCallee()
4274                        << SourceRange(TheCall->getArg(0)->getLocStart(),
4275                                       TheCall->getArg(1)->getLocEnd()));
4276     } else if (numElements != numResElements) {
4277       QualType eltType = LHSType->getAs<VectorType>()->getElementType();
4278       resType = Context.getVectorType(eltType, numResElements,
4279                                       VectorType::GenericVector);
4280     }
4281   }
4282 
4283   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
4284     if (TheCall->getArg(i)->isTypeDependent() ||
4285         TheCall->getArg(i)->isValueDependent())
4286       continue;
4287 
4288     llvm::APSInt Result(32);
4289     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
4290       return ExprError(Diag(TheCall->getLocStart(),
4291                             diag::err_shufflevector_nonconstant_argument)
4292                        << TheCall->getArg(i)->getSourceRange());
4293 
4294     // Allow -1 which will be translated to undef in the IR.
4295     if (Result.isSigned() && Result.isAllOnesValue())
4296       continue;
4297 
4298     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
4299       return ExprError(Diag(TheCall->getLocStart(),
4300                             diag::err_shufflevector_argument_too_large)
4301                        << TheCall->getArg(i)->getSourceRange());
4302   }
4303 
4304   SmallVector<Expr*, 32> exprs;
4305 
4306   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
4307     exprs.push_back(TheCall->getArg(i));
4308     TheCall->setArg(i, nullptr);
4309   }
4310 
4311   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
4312                                          TheCall->getCallee()->getLocStart(),
4313                                          TheCall->getRParenLoc());
4314 }
4315 
4316 /// SemaConvertVectorExpr - Handle __builtin_convertvector
4317 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
4318                                        SourceLocation BuiltinLoc,
4319                                        SourceLocation RParenLoc) {
4320   ExprValueKind VK = VK_RValue;
4321   ExprObjectKind OK = OK_Ordinary;
4322   QualType DstTy = TInfo->getType();
4323   QualType SrcTy = E->getType();
4324 
4325   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
4326     return ExprError(Diag(BuiltinLoc,
4327                           diag::err_convertvector_non_vector)
4328                      << E->getSourceRange());
4329   if (!DstTy->isVectorType() && !DstTy->isDependentType())
4330     return ExprError(Diag(BuiltinLoc,
4331                           diag::err_convertvector_non_vector_type));
4332 
4333   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
4334     unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
4335     unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
4336     if (SrcElts != DstElts)
4337       return ExprError(Diag(BuiltinLoc,
4338                             diag::err_convertvector_incompatible_vector)
4339                        << E->getSourceRange());
4340   }
4341 
4342   return new (Context)
4343       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
4344 }
4345 
4346 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
4347 // This is declared to take (const void*, ...) and can take two
4348 // optional constant int args.
4349 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
4350   unsigned NumArgs = TheCall->getNumArgs();
4351 
4352   if (NumArgs > 3)
4353     return Diag(TheCall->getLocEnd(),
4354              diag::err_typecheck_call_too_many_args_at_most)
4355              << 0 /*function call*/ << 3 << NumArgs
4356              << TheCall->getSourceRange();
4357 
4358   // Argument 0 is checked for us and the remaining arguments must be
4359   // constant integers.
4360   for (unsigned i = 1; i != NumArgs; ++i)
4361     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
4362       return true;
4363 
4364   return false;
4365 }
4366 
4367 /// SemaBuiltinAssume - Handle __assume (MS Extension).
4368 // __assume does not evaluate its arguments, and should warn if its argument
4369 // has side effects.
4370 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
4371   Expr *Arg = TheCall->getArg(0);
4372   if (Arg->isInstantiationDependent()) return false;
4373 
4374   if (Arg->HasSideEffects(Context))
4375     Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
4376       << Arg->getSourceRange()
4377       << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
4378 
4379   return false;
4380 }
4381 
4382 /// Handle __builtin_alloca_with_align. This is declared
4383 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
4384 /// than 8.
4385 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
4386   // The alignment must be a constant integer.
4387   Expr *Arg = TheCall->getArg(1);
4388 
4389   // We can't check the value of a dependent argument.
4390   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4391     if (const auto *UE =
4392             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
4393       if (UE->getKind() == UETT_AlignOf)
4394         Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
4395           << Arg->getSourceRange();
4396 
4397     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
4398 
4399     if (!Result.isPowerOf2())
4400       return Diag(TheCall->getLocStart(),
4401                   diag::err_alignment_not_power_of_two)
4402            << Arg->getSourceRange();
4403 
4404     if (Result < Context.getCharWidth())
4405       return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
4406            << (unsigned)Context.getCharWidth()
4407            << Arg->getSourceRange();
4408 
4409     if (Result > std::numeric_limits<int32_t>::max())
4410       return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
4411            << std::numeric_limits<int32_t>::max()
4412            << Arg->getSourceRange();
4413   }
4414 
4415   return false;
4416 }
4417 
4418 /// Handle __builtin_assume_aligned. This is declared
4419 /// as (const void*, size_t, ...) and can take one optional constant int arg.
4420 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
4421   unsigned NumArgs = TheCall->getNumArgs();
4422 
4423   if (NumArgs > 3)
4424     return Diag(TheCall->getLocEnd(),
4425              diag::err_typecheck_call_too_many_args_at_most)
4426              << 0 /*function call*/ << 3 << NumArgs
4427              << TheCall->getSourceRange();
4428 
4429   // The alignment must be a constant integer.
4430   Expr *Arg = TheCall->getArg(1);
4431 
4432   // We can't check the value of a dependent argument.
4433   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4434     llvm::APSInt Result;
4435     if (SemaBuiltinConstantArg(TheCall, 1, Result))
4436       return true;
4437 
4438     if (!Result.isPowerOf2())
4439       return Diag(TheCall->getLocStart(),
4440                   diag::err_alignment_not_power_of_two)
4441            << Arg->getSourceRange();
4442   }
4443 
4444   if (NumArgs > 2) {
4445     ExprResult Arg(TheCall->getArg(2));
4446     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4447       Context.getSizeType(), false);
4448     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4449     if (Arg.isInvalid()) return true;
4450     TheCall->setArg(2, Arg.get());
4451   }
4452 
4453   return false;
4454 }
4455 
4456 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4457   unsigned BuiltinID =
4458       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4459   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4460 
4461   unsigned NumArgs = TheCall->getNumArgs();
4462   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4463   if (NumArgs < NumRequiredArgs) {
4464     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4465            << 0 /* function call */ << NumRequiredArgs << NumArgs
4466            << TheCall->getSourceRange();
4467   }
4468   if (NumArgs >= NumRequiredArgs + 0x100) {
4469     return Diag(TheCall->getLocEnd(),
4470                 diag::err_typecheck_call_too_many_args_at_most)
4471            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4472            << TheCall->getSourceRange();
4473   }
4474   unsigned i = 0;
4475 
4476   // For formatting call, check buffer arg.
4477   if (!IsSizeCall) {
4478     ExprResult Arg(TheCall->getArg(i));
4479     InitializedEntity Entity = InitializedEntity::InitializeParameter(
4480         Context, Context.VoidPtrTy, false);
4481     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4482     if (Arg.isInvalid())
4483       return true;
4484     TheCall->setArg(i, Arg.get());
4485     i++;
4486   }
4487 
4488   // Check string literal arg.
4489   unsigned FormatIdx = i;
4490   {
4491     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4492     if (Arg.isInvalid())
4493       return true;
4494     TheCall->setArg(i, Arg.get());
4495     i++;
4496   }
4497 
4498   // Make sure variadic args are scalar.
4499   unsigned FirstDataArg = i;
4500   while (i < NumArgs) {
4501     ExprResult Arg = DefaultVariadicArgumentPromotion(
4502         TheCall->getArg(i), VariadicFunction, nullptr);
4503     if (Arg.isInvalid())
4504       return true;
4505     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4506     if (ArgSize.getQuantity() >= 0x100) {
4507       return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4508              << i << (int)ArgSize.getQuantity() << 0xff
4509              << TheCall->getSourceRange();
4510     }
4511     TheCall->setArg(i, Arg.get());
4512     i++;
4513   }
4514 
4515   // Check formatting specifiers. NOTE: We're only doing this for the non-size
4516   // call to avoid duplicate diagnostics.
4517   if (!IsSizeCall) {
4518     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4519     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4520     bool Success = CheckFormatArguments(
4521         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4522         VariadicFunction, TheCall->getLocStart(), SourceRange(),
4523         CheckedVarArgs);
4524     if (!Success)
4525       return true;
4526   }
4527 
4528   if (IsSizeCall) {
4529     TheCall->setType(Context.getSizeType());
4530   } else {
4531     TheCall->setType(Context.VoidPtrTy);
4532   }
4533   return false;
4534 }
4535 
4536 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4537 /// TheCall is a constant expression.
4538 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4539                                   llvm::APSInt &Result) {
4540   Expr *Arg = TheCall->getArg(ArgNum);
4541   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4542   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4543 
4544   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4545 
4546   if (!Arg->isIntegerConstantExpr(Result, Context))
4547     return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
4548                 << FDecl->getDeclName() <<  Arg->getSourceRange();
4549 
4550   return false;
4551 }
4552 
4553 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4554 /// TheCall is a constant expression in the range [Low, High].
4555 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4556                                        int Low, int High) {
4557   llvm::APSInt Result;
4558 
4559   // We can't check the value of a dependent argument.
4560   Expr *Arg = TheCall->getArg(ArgNum);
4561   if (Arg->isTypeDependent() || Arg->isValueDependent())
4562     return false;
4563 
4564   // Check constant-ness first.
4565   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4566     return true;
4567 
4568   if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
4569     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
4570       << Low << High << Arg->getSourceRange();
4571 
4572   return false;
4573 }
4574 
4575 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4576 /// TheCall is a constant expression is a multiple of Num..
4577 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4578                                           unsigned Num) {
4579   llvm::APSInt Result;
4580 
4581   // We can't check the value of a dependent argument.
4582   Expr *Arg = TheCall->getArg(ArgNum);
4583   if (Arg->isTypeDependent() || Arg->isValueDependent())
4584     return false;
4585 
4586   // Check constant-ness first.
4587   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4588     return true;
4589 
4590   if (Result.getSExtValue() % Num != 0)
4591     return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4592       << Num << Arg->getSourceRange();
4593 
4594   return false;
4595 }
4596 
4597 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4598 /// TheCall is an ARM/AArch64 special register string literal.
4599 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4600                                     int ArgNum, unsigned ExpectedFieldNum,
4601                                     bool AllowName) {
4602   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4603                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4604                       BuiltinID == ARM::BI__builtin_arm_rsr ||
4605                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
4606                       BuiltinID == ARM::BI__builtin_arm_wsr ||
4607                       BuiltinID == ARM::BI__builtin_arm_wsrp;
4608   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4609                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4610                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
4611                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4612                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
4613                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
4614   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4615 
4616   // We can't check the value of a dependent argument.
4617   Expr *Arg = TheCall->getArg(ArgNum);
4618   if (Arg->isTypeDependent() || Arg->isValueDependent())
4619     return false;
4620 
4621   // Check if the argument is a string literal.
4622   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4623     return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4624            << Arg->getSourceRange();
4625 
4626   // Check the type of special register given.
4627   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4628   SmallVector<StringRef, 6> Fields;
4629   Reg.split(Fields, ":");
4630 
4631   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4632     return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4633            << Arg->getSourceRange();
4634 
4635   // If the string is the name of a register then we cannot check that it is
4636   // valid here but if the string is of one the forms described in ACLE then we
4637   // can check that the supplied fields are integers and within the valid
4638   // ranges.
4639   if (Fields.size() > 1) {
4640     bool FiveFields = Fields.size() == 5;
4641 
4642     bool ValidString = true;
4643     if (IsARMBuiltin) {
4644       ValidString &= Fields[0].startswith_lower("cp") ||
4645                      Fields[0].startswith_lower("p");
4646       if (ValidString)
4647         Fields[0] =
4648           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4649 
4650       ValidString &= Fields[2].startswith_lower("c");
4651       if (ValidString)
4652         Fields[2] = Fields[2].drop_front(1);
4653 
4654       if (FiveFields) {
4655         ValidString &= Fields[3].startswith_lower("c");
4656         if (ValidString)
4657           Fields[3] = Fields[3].drop_front(1);
4658       }
4659     }
4660 
4661     SmallVector<int, 5> Ranges;
4662     if (FiveFields)
4663       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
4664     else
4665       Ranges.append({15, 7, 15});
4666 
4667     for (unsigned i=0; i<Fields.size(); ++i) {
4668       int IntField;
4669       ValidString &= !Fields[i].getAsInteger(10, IntField);
4670       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4671     }
4672 
4673     if (!ValidString)
4674       return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4675              << Arg->getSourceRange();
4676   } else if (IsAArch64Builtin && Fields.size() == 1) {
4677     // If the register name is one of those that appear in the condition below
4678     // and the special register builtin being used is one of the write builtins,
4679     // then we require that the argument provided for writing to the register
4680     // is an integer constant expression. This is because it will be lowered to
4681     // an MSR (immediate) instruction, so we need to know the immediate at
4682     // compile time.
4683     if (TheCall->getNumArgs() != 2)
4684       return false;
4685 
4686     std::string RegLower = Reg.lower();
4687     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4688         RegLower != "pan" && RegLower != "uao")
4689       return false;
4690 
4691     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4692   }
4693 
4694   return false;
4695 }
4696 
4697 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
4698 /// This checks that the target supports __builtin_longjmp and
4699 /// that val is a constant 1.
4700 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
4701   if (!Context.getTargetInfo().hasSjLjLowering())
4702     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4703              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4704 
4705   Expr *Arg = TheCall->getArg(1);
4706   llvm::APSInt Result;
4707 
4708   // TODO: This is less than ideal. Overload this to take a value.
4709   if (SemaBuiltinConstantArg(TheCall, 1, Result))
4710     return true;
4711 
4712   if (Result != 1)
4713     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4714              << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4715 
4716   return false;
4717 }
4718 
4719 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4720 /// This checks that the target supports __builtin_setjmp.
4721 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4722   if (!Context.getTargetInfo().hasSjLjLowering())
4723     return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4724              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4725   return false;
4726 }
4727 
4728 namespace {
4729 
4730 class UncoveredArgHandler {
4731   enum { Unknown = -1, AllCovered = -2 };
4732 
4733   signed FirstUncoveredArg = Unknown;
4734   SmallVector<const Expr *, 4> DiagnosticExprs;
4735 
4736 public:
4737   UncoveredArgHandler() = default;
4738 
4739   bool hasUncoveredArg() const {
4740     return (FirstUncoveredArg >= 0);
4741   }
4742 
4743   unsigned getUncoveredArg() const {
4744     assert(hasUncoveredArg() && "no uncovered argument");
4745     return FirstUncoveredArg;
4746   }
4747 
4748   void setAllCovered() {
4749     // A string has been found with all arguments covered, so clear out
4750     // the diagnostics.
4751     DiagnosticExprs.clear();
4752     FirstUncoveredArg = AllCovered;
4753   }
4754 
4755   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4756     assert(NewFirstUncoveredArg >= 0 && "Outside range");
4757 
4758     // Don't update if a previous string covers all arguments.
4759     if (FirstUncoveredArg == AllCovered)
4760       return;
4761 
4762     // UncoveredArgHandler tracks the highest uncovered argument index
4763     // and with it all the strings that match this index.
4764     if (NewFirstUncoveredArg == FirstUncoveredArg)
4765       DiagnosticExprs.push_back(StrExpr);
4766     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4767       DiagnosticExprs.clear();
4768       DiagnosticExprs.push_back(StrExpr);
4769       FirstUncoveredArg = NewFirstUncoveredArg;
4770     }
4771   }
4772 
4773   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4774 };
4775 
4776 enum StringLiteralCheckType {
4777   SLCT_NotALiteral,
4778   SLCT_UncheckedLiteral,
4779   SLCT_CheckedLiteral
4780 };
4781 
4782 } // namespace
4783 
4784 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4785                                      BinaryOperatorKind BinOpKind,
4786                                      bool AddendIsRight) {
4787   unsigned BitWidth = Offset.getBitWidth();
4788   unsigned AddendBitWidth = Addend.getBitWidth();
4789   // There might be negative interim results.
4790   if (Addend.isUnsigned()) {
4791     Addend = Addend.zext(++AddendBitWidth);
4792     Addend.setIsSigned(true);
4793   }
4794   // Adjust the bit width of the APSInts.
4795   if (AddendBitWidth > BitWidth) {
4796     Offset = Offset.sext(AddendBitWidth);
4797     BitWidth = AddendBitWidth;
4798   } else if (BitWidth > AddendBitWidth) {
4799     Addend = Addend.sext(BitWidth);
4800   }
4801 
4802   bool Ov = false;
4803   llvm::APSInt ResOffset = Offset;
4804   if (BinOpKind == BO_Add)
4805     ResOffset = Offset.sadd_ov(Addend, Ov);
4806   else {
4807     assert(AddendIsRight && BinOpKind == BO_Sub &&
4808            "operator must be add or sub with addend on the right");
4809     ResOffset = Offset.ssub_ov(Addend, Ov);
4810   }
4811 
4812   // We add an offset to a pointer here so we should support an offset as big as
4813   // possible.
4814   if (Ov) {
4815     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
4816            "index (intermediate) result too big");
4817     Offset = Offset.sext(2 * BitWidth);
4818     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4819     return;
4820   }
4821 
4822   Offset = ResOffset;
4823 }
4824 
4825 namespace {
4826 
4827 // This is a wrapper class around StringLiteral to support offsetted string
4828 // literals as format strings. It takes the offset into account when returning
4829 // the string and its length or the source locations to display notes correctly.
4830 class FormatStringLiteral {
4831   const StringLiteral *FExpr;
4832   int64_t Offset;
4833 
4834  public:
4835   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4836       : FExpr(fexpr), Offset(Offset) {}
4837 
4838   StringRef getString() const {
4839     return FExpr->getString().drop_front(Offset);
4840   }
4841 
4842   unsigned getByteLength() const {
4843     return FExpr->getByteLength() - getCharByteWidth() * Offset;
4844   }
4845 
4846   unsigned getLength() const { return FExpr->getLength() - Offset; }
4847   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4848 
4849   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4850 
4851   QualType getType() const { return FExpr->getType(); }
4852 
4853   bool isAscii() const { return FExpr->isAscii(); }
4854   bool isWide() const { return FExpr->isWide(); }
4855   bool isUTF8() const { return FExpr->isUTF8(); }
4856   bool isUTF16() const { return FExpr->isUTF16(); }
4857   bool isUTF32() const { return FExpr->isUTF32(); }
4858   bool isPascal() const { return FExpr->isPascal(); }
4859 
4860   SourceLocation getLocationOfByte(
4861       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4862       const TargetInfo &Target, unsigned *StartToken = nullptr,
4863       unsigned *StartTokenByteOffset = nullptr) const {
4864     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4865                                     StartToken, StartTokenByteOffset);
4866   }
4867 
4868   SourceLocation getLocStart() const LLVM_READONLY {
4869     return FExpr->getLocStart().getLocWithOffset(Offset);
4870   }
4871 
4872   SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4873 };
4874 
4875 }  // namespace
4876 
4877 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
4878                               const Expr *OrigFormatExpr,
4879                               ArrayRef<const Expr *> Args,
4880                               bool HasVAListArg, unsigned format_idx,
4881                               unsigned firstDataArg,
4882                               Sema::FormatStringType Type,
4883                               bool inFunctionCall,
4884                               Sema::VariadicCallType CallType,
4885                               llvm::SmallBitVector &CheckedVarArgs,
4886                               UncoveredArgHandler &UncoveredArg);
4887 
4888 // Determine if an expression is a string literal or constant string.
4889 // If this function returns false on the arguments to a function expecting a
4890 // format string, we will usually need to emit a warning.
4891 // True string literals are then checked by CheckFormatString.
4892 static StringLiteralCheckType
4893 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4894                       bool HasVAListArg, unsigned format_idx,
4895                       unsigned firstDataArg, Sema::FormatStringType Type,
4896                       Sema::VariadicCallType CallType, bool InFunctionCall,
4897                       llvm::SmallBitVector &CheckedVarArgs,
4898                       UncoveredArgHandler &UncoveredArg,
4899                       llvm::APSInt Offset) {
4900  tryAgain:
4901   assert(Offset.isSigned() && "invalid offset");
4902 
4903   if (E->isTypeDependent() || E->isValueDependent())
4904     return SLCT_NotALiteral;
4905 
4906   E = E->IgnoreParenCasts();
4907 
4908   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
4909     // Technically -Wformat-nonliteral does not warn about this case.
4910     // The behavior of printf and friends in this case is implementation
4911     // dependent.  Ideally if the format string cannot be null then
4912     // it should have a 'nonnull' attribute in the function prototype.
4913     return SLCT_UncheckedLiteral;
4914 
4915   switch (E->getStmtClass()) {
4916   case Stmt::BinaryConditionalOperatorClass:
4917   case Stmt::ConditionalOperatorClass: {
4918     // The expression is a literal if both sub-expressions were, and it was
4919     // completely checked only if both sub-expressions were checked.
4920     const AbstractConditionalOperator *C =
4921         cast<AbstractConditionalOperator>(E);
4922 
4923     // Determine whether it is necessary to check both sub-expressions, for
4924     // example, because the condition expression is a constant that can be
4925     // evaluated at compile time.
4926     bool CheckLeft = true, CheckRight = true;
4927 
4928     bool Cond;
4929     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4930       if (Cond)
4931         CheckRight = false;
4932       else
4933         CheckLeft = false;
4934     }
4935 
4936     // We need to maintain the offsets for the right and the left hand side
4937     // separately to check if every possible indexed expression is a valid
4938     // string literal. They might have different offsets for different string
4939     // literals in the end.
4940     StringLiteralCheckType Left;
4941     if (!CheckLeft)
4942       Left = SLCT_UncheckedLiteral;
4943     else {
4944       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4945                                    HasVAListArg, format_idx, firstDataArg,
4946                                    Type, CallType, InFunctionCall,
4947                                    CheckedVarArgs, UncoveredArg, Offset);
4948       if (Left == SLCT_NotALiteral || !CheckRight) {
4949         return Left;
4950       }
4951     }
4952 
4953     StringLiteralCheckType Right =
4954         checkFormatStringExpr(S, C->getFalseExpr(), Args,
4955                               HasVAListArg, format_idx, firstDataArg,
4956                               Type, CallType, InFunctionCall, CheckedVarArgs,
4957                               UncoveredArg, Offset);
4958 
4959     return (CheckLeft && Left < Right) ? Left : Right;
4960   }
4961 
4962   case Stmt::ImplicitCastExprClass:
4963     E = cast<ImplicitCastExpr>(E)->getSubExpr();
4964     goto tryAgain;
4965 
4966   case Stmt::OpaqueValueExprClass:
4967     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4968       E = src;
4969       goto tryAgain;
4970     }
4971     return SLCT_NotALiteral;
4972 
4973   case Stmt::PredefinedExprClass:
4974     // While __func__, etc., are technically not string literals, they
4975     // cannot contain format specifiers and thus are not a security
4976     // liability.
4977     return SLCT_UncheckedLiteral;
4978 
4979   case Stmt::DeclRefExprClass: {
4980     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
4981 
4982     // As an exception, do not flag errors for variables binding to
4983     // const string literals.
4984     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4985       bool isConstant = false;
4986       QualType T = DR->getType();
4987 
4988       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4989         isConstant = AT->getElementType().isConstant(S.Context);
4990       } else if (const PointerType *PT = T->getAs<PointerType>()) {
4991         isConstant = T.isConstant(S.Context) &&
4992                      PT->getPointeeType().isConstant(S.Context);
4993       } else if (T->isObjCObjectPointerType()) {
4994         // In ObjC, there is usually no "const ObjectPointer" type,
4995         // so don't check if the pointee type is constant.
4996         isConstant = T.isConstant(S.Context);
4997       }
4998 
4999       if (isConstant) {
5000         if (const Expr *Init = VD->getAnyInitializer()) {
5001           // Look through initializers like const char c[] = { "foo" }
5002           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
5003             if (InitList->isStringLiteralInit())
5004               Init = InitList->getInit(0)->IgnoreParenImpCasts();
5005           }
5006           return checkFormatStringExpr(S, Init, Args,
5007                                        HasVAListArg, format_idx,
5008                                        firstDataArg, Type, CallType,
5009                                        /*InFunctionCall*/ false, CheckedVarArgs,
5010                                        UncoveredArg, Offset);
5011         }
5012       }
5013 
5014       // For vprintf* functions (i.e., HasVAListArg==true), we add a
5015       // special check to see if the format string is a function parameter
5016       // of the function calling the printf function.  If the function
5017       // has an attribute indicating it is a printf-like function, then we
5018       // should suppress warnings concerning non-literals being used in a call
5019       // to a vprintf function.  For example:
5020       //
5021       // void
5022       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
5023       //      va_list ap;
5024       //      va_start(ap, fmt);
5025       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
5026       //      ...
5027       // }
5028       if (HasVAListArg) {
5029         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
5030           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
5031             int PVIndex = PV->getFunctionScopeIndex() + 1;
5032             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
5033               // adjust for implicit parameter
5034               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5035                 if (MD->isInstance())
5036                   ++PVIndex;
5037               // We also check if the formats are compatible.
5038               // We can't pass a 'scanf' string to a 'printf' function.
5039               if (PVIndex == PVFormat->getFormatIdx() &&
5040                   Type == S.GetFormatStringType(PVFormat))
5041                 return SLCT_UncheckedLiteral;
5042             }
5043           }
5044         }
5045       }
5046     }
5047 
5048     return SLCT_NotALiteral;
5049   }
5050 
5051   case Stmt::CallExprClass:
5052   case Stmt::CXXMemberCallExprClass: {
5053     const CallExpr *CE = cast<CallExpr>(E);
5054     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
5055       if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
5056         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
5057         return checkFormatStringExpr(S, Arg, Args,
5058                                      HasVAListArg, format_idx, firstDataArg,
5059                                      Type, CallType, InFunctionCall,
5060                                      CheckedVarArgs, UncoveredArg, Offset);
5061       } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5062         unsigned BuiltinID = FD->getBuiltinID();
5063         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
5064             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
5065           const Expr *Arg = CE->getArg(0);
5066           return checkFormatStringExpr(S, Arg, Args,
5067                                        HasVAListArg, format_idx,
5068                                        firstDataArg, Type, CallType,
5069                                        InFunctionCall, CheckedVarArgs,
5070                                        UncoveredArg, Offset);
5071         }
5072       }
5073     }
5074 
5075     return SLCT_NotALiteral;
5076   }
5077   case Stmt::ObjCMessageExprClass: {
5078     const auto *ME = cast<ObjCMessageExpr>(E);
5079     if (const auto *ND = ME->getMethodDecl()) {
5080       if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
5081         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
5082         return checkFormatStringExpr(
5083             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
5084             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
5085       }
5086     }
5087 
5088     return SLCT_NotALiteral;
5089   }
5090   case Stmt::ObjCStringLiteralClass:
5091   case Stmt::StringLiteralClass: {
5092     const StringLiteral *StrE = nullptr;
5093 
5094     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
5095       StrE = ObjCFExpr->getString();
5096     else
5097       StrE = cast<StringLiteral>(E);
5098 
5099     if (StrE) {
5100       if (Offset.isNegative() || Offset > StrE->getLength()) {
5101         // TODO: It would be better to have an explicit warning for out of
5102         // bounds literals.
5103         return SLCT_NotALiteral;
5104       }
5105       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
5106       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
5107                         firstDataArg, Type, InFunctionCall, CallType,
5108                         CheckedVarArgs, UncoveredArg);
5109       return SLCT_CheckedLiteral;
5110     }
5111 
5112     return SLCT_NotALiteral;
5113   }
5114   case Stmt::BinaryOperatorClass: {
5115     llvm::APSInt LResult;
5116     llvm::APSInt RResult;
5117 
5118     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
5119 
5120     // A string literal + an int offset is still a string literal.
5121     if (BinOp->isAdditiveOp()) {
5122       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
5123       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
5124 
5125       if (LIsInt != RIsInt) {
5126         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
5127 
5128         if (LIsInt) {
5129           if (BinOpKind == BO_Add) {
5130             sumOffsets(Offset, LResult, BinOpKind, RIsInt);
5131             E = BinOp->getRHS();
5132             goto tryAgain;
5133           }
5134         } else {
5135           sumOffsets(Offset, RResult, BinOpKind, RIsInt);
5136           E = BinOp->getLHS();
5137           goto tryAgain;
5138         }
5139       }
5140     }
5141 
5142     return SLCT_NotALiteral;
5143   }
5144   case Stmt::UnaryOperatorClass: {
5145     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
5146     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
5147     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
5148       llvm::APSInt IndexResult;
5149       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
5150         sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
5151         E = ASE->getBase();
5152         goto tryAgain;
5153       }
5154     }
5155 
5156     return SLCT_NotALiteral;
5157   }
5158 
5159   default:
5160     return SLCT_NotALiteral;
5161   }
5162 }
5163 
5164 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
5165   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
5166       .Case("scanf", FST_Scanf)
5167       .Cases("printf", "printf0", FST_Printf)
5168       .Cases("NSString", "CFString", FST_NSString)
5169       .Case("strftime", FST_Strftime)
5170       .Case("strfmon", FST_Strfmon)
5171       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
5172       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
5173       .Case("os_trace", FST_OSLog)
5174       .Case("os_log", FST_OSLog)
5175       .Default(FST_Unknown);
5176 }
5177 
5178 /// CheckFormatArguments - Check calls to printf and scanf (and similar
5179 /// functions) for correct use of format strings.
5180 /// Returns true if a format string has been fully checked.
5181 bool Sema::CheckFormatArguments(const FormatAttr *Format,
5182                                 ArrayRef<const Expr *> Args,
5183                                 bool IsCXXMember,
5184                                 VariadicCallType CallType,
5185                                 SourceLocation Loc, SourceRange Range,
5186                                 llvm::SmallBitVector &CheckedVarArgs) {
5187   FormatStringInfo FSI;
5188   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
5189     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
5190                                 FSI.FirstDataArg, GetFormatStringType(Format),
5191                                 CallType, Loc, Range, CheckedVarArgs);
5192   return false;
5193 }
5194 
5195 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
5196                                 bool HasVAListArg, unsigned format_idx,
5197                                 unsigned firstDataArg, FormatStringType Type,
5198                                 VariadicCallType CallType,
5199                                 SourceLocation Loc, SourceRange Range,
5200                                 llvm::SmallBitVector &CheckedVarArgs) {
5201   // CHECK: printf/scanf-like function is called with no format string.
5202   if (format_idx >= Args.size()) {
5203     Diag(Loc, diag::warn_missing_format_string) << Range;
5204     return false;
5205   }
5206 
5207   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
5208 
5209   // CHECK: format string is not a string literal.
5210   //
5211   // Dynamically generated format strings are difficult to
5212   // automatically vet at compile time.  Requiring that format strings
5213   // are string literals: (1) permits the checking of format strings by
5214   // the compiler and thereby (2) can practically remove the source of
5215   // many format string exploits.
5216 
5217   // Format string can be either ObjC string (e.g. @"%d") or
5218   // C string (e.g. "%d")
5219   // ObjC string uses the same format specifiers as C string, so we can use
5220   // the same format string checking logic for both ObjC and C strings.
5221   UncoveredArgHandler UncoveredArg;
5222   StringLiteralCheckType CT =
5223       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
5224                             format_idx, firstDataArg, Type, CallType,
5225                             /*IsFunctionCall*/ true, CheckedVarArgs,
5226                             UncoveredArg,
5227                             /*no string offset*/ llvm::APSInt(64, false) = 0);
5228 
5229   // Generate a diagnostic where an uncovered argument is detected.
5230   if (UncoveredArg.hasUncoveredArg()) {
5231     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
5232     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
5233     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
5234   }
5235 
5236   if (CT != SLCT_NotALiteral)
5237     // Literal format string found, check done!
5238     return CT == SLCT_CheckedLiteral;
5239 
5240   // Strftime is particular as it always uses a single 'time' argument,
5241   // so it is safe to pass a non-literal string.
5242   if (Type == FST_Strftime)
5243     return false;
5244 
5245   // Do not emit diag when the string param is a macro expansion and the
5246   // format is either NSString or CFString. This is a hack to prevent
5247   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
5248   // which are usually used in place of NS and CF string literals.
5249   SourceLocation FormatLoc = Args[format_idx]->getLocStart();
5250   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
5251     return false;
5252 
5253   // If there are no arguments specified, warn with -Wformat-security, otherwise
5254   // warn only with -Wformat-nonliteral.
5255   if (Args.size() == firstDataArg) {
5256     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
5257       << OrigFormatExpr->getSourceRange();
5258     switch (Type) {
5259     default:
5260       break;
5261     case FST_Kprintf:
5262     case FST_FreeBSDKPrintf:
5263     case FST_Printf:
5264       Diag(FormatLoc, diag::note_format_security_fixit)
5265         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
5266       break;
5267     case FST_NSString:
5268       Diag(FormatLoc, diag::note_format_security_fixit)
5269         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
5270       break;
5271     }
5272   } else {
5273     Diag(FormatLoc, diag::warn_format_nonliteral)
5274       << OrigFormatExpr->getSourceRange();
5275   }
5276   return false;
5277 }
5278 
5279 namespace {
5280 
5281 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
5282 protected:
5283   Sema &S;
5284   const FormatStringLiteral *FExpr;
5285   const Expr *OrigFormatExpr;
5286   const Sema::FormatStringType FSType;
5287   const unsigned FirstDataArg;
5288   const unsigned NumDataArgs;
5289   const char *Beg; // Start of format string.
5290   const bool HasVAListArg;
5291   ArrayRef<const Expr *> Args;
5292   unsigned FormatIdx;
5293   llvm::SmallBitVector CoveredArgs;
5294   bool usesPositionalArgs = false;
5295   bool atFirstArg = true;
5296   bool inFunctionCall;
5297   Sema::VariadicCallType CallType;
5298   llvm::SmallBitVector &CheckedVarArgs;
5299   UncoveredArgHandler &UncoveredArg;
5300 
5301 public:
5302   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
5303                      const Expr *origFormatExpr,
5304                      const Sema::FormatStringType type, unsigned firstDataArg,
5305                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
5306                      ArrayRef<const Expr *> Args, unsigned formatIdx,
5307                      bool inFunctionCall, Sema::VariadicCallType callType,
5308                      llvm::SmallBitVector &CheckedVarArgs,
5309                      UncoveredArgHandler &UncoveredArg)
5310       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
5311         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
5312         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
5313         inFunctionCall(inFunctionCall), CallType(callType),
5314         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
5315     CoveredArgs.resize(numDataArgs);
5316     CoveredArgs.reset();
5317   }
5318 
5319   void DoneProcessing();
5320 
5321   void HandleIncompleteSpecifier(const char *startSpecifier,
5322                                  unsigned specifierLen) override;
5323 
5324   void HandleInvalidLengthModifier(
5325                            const analyze_format_string::FormatSpecifier &FS,
5326                            const analyze_format_string::ConversionSpecifier &CS,
5327                            const char *startSpecifier, unsigned specifierLen,
5328                            unsigned DiagID);
5329 
5330   void HandleNonStandardLengthModifier(
5331                     const analyze_format_string::FormatSpecifier &FS,
5332                     const char *startSpecifier, unsigned specifierLen);
5333 
5334   void HandleNonStandardConversionSpecifier(
5335                     const analyze_format_string::ConversionSpecifier &CS,
5336                     const char *startSpecifier, unsigned specifierLen);
5337 
5338   void HandlePosition(const char *startPos, unsigned posLen) override;
5339 
5340   void HandleInvalidPosition(const char *startSpecifier,
5341                              unsigned specifierLen,
5342                              analyze_format_string::PositionContext p) override;
5343 
5344   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
5345 
5346   void HandleNullChar(const char *nullCharacter) override;
5347 
5348   template <typename Range>
5349   static void
5350   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
5351                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
5352                        bool IsStringLocation, Range StringRange,
5353                        ArrayRef<FixItHint> Fixit = None);
5354 
5355 protected:
5356   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
5357                                         const char *startSpec,
5358                                         unsigned specifierLen,
5359                                         const char *csStart, unsigned csLen);
5360 
5361   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
5362                                          const char *startSpec,
5363                                          unsigned specifierLen);
5364 
5365   SourceRange getFormatStringRange();
5366   CharSourceRange getSpecifierRange(const char *startSpecifier,
5367                                     unsigned specifierLen);
5368   SourceLocation getLocationOfByte(const char *x);
5369 
5370   const Expr *getDataArg(unsigned i) const;
5371 
5372   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
5373                     const analyze_format_string::ConversionSpecifier &CS,
5374                     const char *startSpecifier, unsigned specifierLen,
5375                     unsigned argIndex);
5376 
5377   template <typename Range>
5378   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5379                             bool IsStringLocation, Range StringRange,
5380                             ArrayRef<FixItHint> Fixit = None);
5381 };
5382 
5383 } // namespace
5384 
5385 SourceRange CheckFormatHandler::getFormatStringRange() {
5386   return OrigFormatExpr->getSourceRange();
5387 }
5388 
5389 CharSourceRange CheckFormatHandler::
5390 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
5391   SourceLocation Start = getLocationOfByte(startSpecifier);
5392   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
5393 
5394   // Advance the end SourceLocation by one due to half-open ranges.
5395   End = End.getLocWithOffset(1);
5396 
5397   return CharSourceRange::getCharRange(Start, End);
5398 }
5399 
5400 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
5401   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
5402                                   S.getLangOpts(), S.Context.getTargetInfo());
5403 }
5404 
5405 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
5406                                                    unsigned specifierLen){
5407   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
5408                        getLocationOfByte(startSpecifier),
5409                        /*IsStringLocation*/true,
5410                        getSpecifierRange(startSpecifier, specifierLen));
5411 }
5412 
5413 void CheckFormatHandler::HandleInvalidLengthModifier(
5414     const analyze_format_string::FormatSpecifier &FS,
5415     const analyze_format_string::ConversionSpecifier &CS,
5416     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
5417   using namespace analyze_format_string;
5418 
5419   const LengthModifier &LM = FS.getLengthModifier();
5420   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5421 
5422   // See if we know how to fix this length modifier.
5423   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
5424   if (FixedLM) {
5425     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
5426                          getLocationOfByte(LM.getStart()),
5427                          /*IsStringLocation*/true,
5428                          getSpecifierRange(startSpecifier, specifierLen));
5429 
5430     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5431       << FixedLM->toString()
5432       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5433 
5434   } else {
5435     FixItHint Hint;
5436     if (DiagID == diag::warn_format_nonsensical_length)
5437       Hint = FixItHint::CreateRemoval(LMRange);
5438 
5439     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
5440                          getLocationOfByte(LM.getStart()),
5441                          /*IsStringLocation*/true,
5442                          getSpecifierRange(startSpecifier, specifierLen),
5443                          Hint);
5444   }
5445 }
5446 
5447 void CheckFormatHandler::HandleNonStandardLengthModifier(
5448     const analyze_format_string::FormatSpecifier &FS,
5449     const char *startSpecifier, unsigned specifierLen) {
5450   using namespace analyze_format_string;
5451 
5452   const LengthModifier &LM = FS.getLengthModifier();
5453   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5454 
5455   // See if we know how to fix this length modifier.
5456   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
5457   if (FixedLM) {
5458     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5459                            << LM.toString() << 0,
5460                          getLocationOfByte(LM.getStart()),
5461                          /*IsStringLocation*/true,
5462                          getSpecifierRange(startSpecifier, specifierLen));
5463 
5464     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5465       << FixedLM->toString()
5466       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5467 
5468   } else {
5469     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5470                            << LM.toString() << 0,
5471                          getLocationOfByte(LM.getStart()),
5472                          /*IsStringLocation*/true,
5473                          getSpecifierRange(startSpecifier, specifierLen));
5474   }
5475 }
5476 
5477 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5478     const analyze_format_string::ConversionSpecifier &CS,
5479     const char *startSpecifier, unsigned specifierLen) {
5480   using namespace analyze_format_string;
5481 
5482   // See if we know how to fix this conversion specifier.
5483   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
5484   if (FixedCS) {
5485     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5486                           << CS.toString() << /*conversion specifier*/1,
5487                          getLocationOfByte(CS.getStart()),
5488                          /*IsStringLocation*/true,
5489                          getSpecifierRange(startSpecifier, specifierLen));
5490 
5491     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5492     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5493       << FixedCS->toString()
5494       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5495   } else {
5496     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5497                           << CS.toString() << /*conversion specifier*/1,
5498                          getLocationOfByte(CS.getStart()),
5499                          /*IsStringLocation*/true,
5500                          getSpecifierRange(startSpecifier, specifierLen));
5501   }
5502 }
5503 
5504 void CheckFormatHandler::HandlePosition(const char *startPos,
5505                                         unsigned posLen) {
5506   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5507                                getLocationOfByte(startPos),
5508                                /*IsStringLocation*/true,
5509                                getSpecifierRange(startPos, posLen));
5510 }
5511 
5512 void
5513 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5514                                      analyze_format_string::PositionContext p) {
5515   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5516                          << (unsigned) p,
5517                        getLocationOfByte(startPos), /*IsStringLocation*/true,
5518                        getSpecifierRange(startPos, posLen));
5519 }
5520 
5521 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
5522                                             unsigned posLen) {
5523   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5524                                getLocationOfByte(startPos),
5525                                /*IsStringLocation*/true,
5526                                getSpecifierRange(startPos, posLen));
5527 }
5528 
5529 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
5530   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
5531     // The presence of a null character is likely an error.
5532     EmitFormatDiagnostic(
5533       S.PDiag(diag::warn_printf_format_string_contains_null_char),
5534       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5535       getFormatStringRange());
5536   }
5537 }
5538 
5539 // Note that this may return NULL if there was an error parsing or building
5540 // one of the argument expressions.
5541 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
5542   return Args[FirstDataArg + i];
5543 }
5544 
5545 void CheckFormatHandler::DoneProcessing() {
5546   // Does the number of data arguments exceed the number of
5547   // format conversions in the format string?
5548   if (!HasVAListArg) {
5549       // Find any arguments that weren't covered.
5550     CoveredArgs.flip();
5551     signed notCoveredArg = CoveredArgs.find_first();
5552     if (notCoveredArg >= 0) {
5553       assert((unsigned)notCoveredArg < NumDataArgs);
5554       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5555     } else {
5556       UncoveredArg.setAllCovered();
5557     }
5558   }
5559 }
5560 
5561 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5562                                    const Expr *ArgExpr) {
5563   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5564          "Invalid state");
5565 
5566   if (!ArgExpr)
5567     return;
5568 
5569   SourceLocation Loc = ArgExpr->getLocStart();
5570 
5571   if (S.getSourceManager().isInSystemMacro(Loc))
5572     return;
5573 
5574   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5575   for (auto E : DiagnosticExprs)
5576     PDiag << E->getSourceRange();
5577 
5578   CheckFormatHandler::EmitFormatDiagnostic(
5579                                   S, IsFunctionCall, DiagnosticExprs[0],
5580                                   PDiag, Loc, /*IsStringLocation*/false,
5581                                   DiagnosticExprs[0]->getSourceRange());
5582 }
5583 
5584 bool
5585 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5586                                                      SourceLocation Loc,
5587                                                      const char *startSpec,
5588                                                      unsigned specifierLen,
5589                                                      const char *csStart,
5590                                                      unsigned csLen) {
5591   bool keepGoing = true;
5592   if (argIndex < NumDataArgs) {
5593     // Consider the argument coverered, even though the specifier doesn't
5594     // make sense.
5595     CoveredArgs.set(argIndex);
5596   }
5597   else {
5598     // If argIndex exceeds the number of data arguments we
5599     // don't issue a warning because that is just a cascade of warnings (and
5600     // they may have intended '%%' anyway). We don't want to continue processing
5601     // the format string after this point, however, as we will like just get
5602     // gibberish when trying to match arguments.
5603     keepGoing = false;
5604   }
5605 
5606   StringRef Specifier(csStart, csLen);
5607 
5608   // If the specifier in non-printable, it could be the first byte of a UTF-8
5609   // sequence. In that case, print the UTF-8 code point. If not, print the byte
5610   // hex value.
5611   std::string CodePointStr;
5612   if (!llvm::sys::locale::isPrint(*csStart)) {
5613     llvm::UTF32 CodePoint;
5614     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5615     const llvm::UTF8 *E =
5616         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5617     llvm::ConversionResult Result =
5618         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
5619 
5620     if (Result != llvm::conversionOK) {
5621       unsigned char FirstChar = *csStart;
5622       CodePoint = (llvm::UTF32)FirstChar;
5623     }
5624 
5625     llvm::raw_string_ostream OS(CodePointStr);
5626     if (CodePoint < 256)
5627       OS << "\\x" << llvm::format("%02x", CodePoint);
5628     else if (CodePoint <= 0xFFFF)
5629       OS << "\\u" << llvm::format("%04x", CodePoint);
5630     else
5631       OS << "\\U" << llvm::format("%08x", CodePoint);
5632     OS.flush();
5633     Specifier = CodePointStr;
5634   }
5635 
5636   EmitFormatDiagnostic(
5637       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5638       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5639 
5640   return keepGoing;
5641 }
5642 
5643 void
5644 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5645                                                       const char *startSpec,
5646                                                       unsigned specifierLen) {
5647   EmitFormatDiagnostic(
5648     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5649     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5650 }
5651 
5652 bool
5653 CheckFormatHandler::CheckNumArgs(
5654   const analyze_format_string::FormatSpecifier &FS,
5655   const analyze_format_string::ConversionSpecifier &CS,
5656   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5657 
5658   if (argIndex >= NumDataArgs) {
5659     PartialDiagnostic PDiag = FS.usesPositionalArg()
5660       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5661            << (argIndex+1) << NumDataArgs)
5662       : S.PDiag(diag::warn_printf_insufficient_data_args);
5663     EmitFormatDiagnostic(
5664       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5665       getSpecifierRange(startSpecifier, specifierLen));
5666 
5667     // Since more arguments than conversion tokens are given, by extension
5668     // all arguments are covered, so mark this as so.
5669     UncoveredArg.setAllCovered();
5670     return false;
5671   }
5672   return true;
5673 }
5674 
5675 template<typename Range>
5676 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5677                                               SourceLocation Loc,
5678                                               bool IsStringLocation,
5679                                               Range StringRange,
5680                                               ArrayRef<FixItHint> FixIt) {
5681   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
5682                        Loc, IsStringLocation, StringRange, FixIt);
5683 }
5684 
5685 /// \brief If the format string is not within the function call, emit a note
5686 /// so that the function call and string are in diagnostic messages.
5687 ///
5688 /// \param InFunctionCall if true, the format string is within the function
5689 /// call and only one diagnostic message will be produced.  Otherwise, an
5690 /// extra note will be emitted pointing to location of the format string.
5691 ///
5692 /// \param ArgumentExpr the expression that is passed as the format string
5693 /// argument in the function call.  Used for getting locations when two
5694 /// diagnostics are emitted.
5695 ///
5696 /// \param PDiag the callee should already have provided any strings for the
5697 /// diagnostic message.  This function only adds locations and fixits
5698 /// to diagnostics.
5699 ///
5700 /// \param Loc primary location for diagnostic.  If two diagnostics are
5701 /// required, one will be at Loc and a new SourceLocation will be created for
5702 /// the other one.
5703 ///
5704 /// \param IsStringLocation if true, Loc points to the format string should be
5705 /// used for the note.  Otherwise, Loc points to the argument list and will
5706 /// be used with PDiag.
5707 ///
5708 /// \param StringRange some or all of the string to highlight.  This is
5709 /// templated so it can accept either a CharSourceRange or a SourceRange.
5710 ///
5711 /// \param FixIt optional fix it hint for the format string.
5712 template <typename Range>
5713 void CheckFormatHandler::EmitFormatDiagnostic(
5714     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5715     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5716     Range StringRange, ArrayRef<FixItHint> FixIt) {
5717   if (InFunctionCall) {
5718     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5719     D << StringRange;
5720     D << FixIt;
5721   } else {
5722     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5723       << ArgumentExpr->getSourceRange();
5724 
5725     const Sema::SemaDiagnosticBuilder &Note =
5726       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5727              diag::note_format_string_defined);
5728 
5729     Note << StringRange;
5730     Note << FixIt;
5731   }
5732 }
5733 
5734 //===--- CHECK: Printf format string checking ------------------------------===//
5735 
5736 namespace {
5737 
5738 class CheckPrintfHandler : public CheckFormatHandler {
5739 public:
5740   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
5741                      const Expr *origFormatExpr,
5742                      const Sema::FormatStringType type, unsigned firstDataArg,
5743                      unsigned numDataArgs, bool isObjC, const char *beg,
5744                      bool hasVAListArg, ArrayRef<const Expr *> Args,
5745                      unsigned formatIdx, bool inFunctionCall,
5746                      Sema::VariadicCallType CallType,
5747                      llvm::SmallBitVector &CheckedVarArgs,
5748                      UncoveredArgHandler &UncoveredArg)
5749       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5750                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
5751                            inFunctionCall, CallType, CheckedVarArgs,
5752                            UncoveredArg) {}
5753 
5754   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5755 
5756   /// Returns true if '%@' specifiers are allowed in the format string.
5757   bool allowsObjCArg() const {
5758     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5759            FSType == Sema::FST_OSTrace;
5760   }
5761 
5762   bool HandleInvalidPrintfConversionSpecifier(
5763                                       const analyze_printf::PrintfSpecifier &FS,
5764                                       const char *startSpecifier,
5765                                       unsigned specifierLen) override;
5766 
5767   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5768                              const char *startSpecifier,
5769                              unsigned specifierLen) override;
5770   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5771                        const char *StartSpecifier,
5772                        unsigned SpecifierLen,
5773                        const Expr *E);
5774 
5775   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5776                     const char *startSpecifier, unsigned specifierLen);
5777   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5778                            const analyze_printf::OptionalAmount &Amt,
5779                            unsigned type,
5780                            const char *startSpecifier, unsigned specifierLen);
5781   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5782                   const analyze_printf::OptionalFlag &flag,
5783                   const char *startSpecifier, unsigned specifierLen);
5784   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5785                          const analyze_printf::OptionalFlag &ignoredFlag,
5786                          const analyze_printf::OptionalFlag &flag,
5787                          const char *startSpecifier, unsigned specifierLen);
5788   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
5789                            const Expr *E);
5790 
5791   void HandleEmptyObjCModifierFlag(const char *startFlag,
5792                                    unsigned flagLen) override;
5793 
5794   void HandleInvalidObjCModifierFlag(const char *startFlag,
5795                                             unsigned flagLen) override;
5796 
5797   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5798                                            const char *flagsEnd,
5799                                            const char *conversionPosition)
5800                                              override;
5801 };
5802 
5803 } // namespace
5804 
5805 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5806                                       const analyze_printf::PrintfSpecifier &FS,
5807                                       const char *startSpecifier,
5808                                       unsigned specifierLen) {
5809   const analyze_printf::PrintfConversionSpecifier &CS =
5810     FS.getConversionSpecifier();
5811 
5812   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5813                                           getLocationOfByte(CS.getStart()),
5814                                           startSpecifier, specifierLen,
5815                                           CS.getStart(), CS.getLength());
5816 }
5817 
5818 bool CheckPrintfHandler::HandleAmount(
5819                                const analyze_format_string::OptionalAmount &Amt,
5820                                unsigned k, const char *startSpecifier,
5821                                unsigned specifierLen) {
5822   if (Amt.hasDataArgument()) {
5823     if (!HasVAListArg) {
5824       unsigned argIndex = Amt.getArgIndex();
5825       if (argIndex >= NumDataArgs) {
5826         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5827                                << k,
5828                              getLocationOfByte(Amt.getStart()),
5829                              /*IsStringLocation*/true,
5830                              getSpecifierRange(startSpecifier, specifierLen));
5831         // Don't do any more checking.  We will just emit
5832         // spurious errors.
5833         return false;
5834       }
5835 
5836       // Type check the data argument.  It should be an 'int'.
5837       // Although not in conformance with C99, we also allow the argument to be
5838       // an 'unsigned int' as that is a reasonably safe case.  GCC also
5839       // doesn't emit a warning for that case.
5840       CoveredArgs.set(argIndex);
5841       const Expr *Arg = getDataArg(argIndex);
5842       if (!Arg)
5843         return false;
5844 
5845       QualType T = Arg->getType();
5846 
5847       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5848       assert(AT.isValid());
5849 
5850       if (!AT.matchesType(S.Context, T)) {
5851         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
5852                                << k << AT.getRepresentativeTypeName(S.Context)
5853                                << T << Arg->getSourceRange(),
5854                              getLocationOfByte(Amt.getStart()),
5855                              /*IsStringLocation*/true,
5856                              getSpecifierRange(startSpecifier, specifierLen));
5857         // Don't do any more checking.  We will just emit
5858         // spurious errors.
5859         return false;
5860       }
5861     }
5862   }
5863   return true;
5864 }
5865 
5866 void CheckPrintfHandler::HandleInvalidAmount(
5867                                       const analyze_printf::PrintfSpecifier &FS,
5868                                       const analyze_printf::OptionalAmount &Amt,
5869                                       unsigned type,
5870                                       const char *startSpecifier,
5871                                       unsigned specifierLen) {
5872   const analyze_printf::PrintfConversionSpecifier &CS =
5873     FS.getConversionSpecifier();
5874 
5875   FixItHint fixit =
5876     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5877       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5878                                  Amt.getConstantLength()))
5879       : FixItHint();
5880 
5881   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5882                          << type << CS.toString(),
5883                        getLocationOfByte(Amt.getStart()),
5884                        /*IsStringLocation*/true,
5885                        getSpecifierRange(startSpecifier, specifierLen),
5886                        fixit);
5887 }
5888 
5889 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5890                                     const analyze_printf::OptionalFlag &flag,
5891                                     const char *startSpecifier,
5892                                     unsigned specifierLen) {
5893   // Warn about pointless flag with a fixit removal.
5894   const analyze_printf::PrintfConversionSpecifier &CS =
5895     FS.getConversionSpecifier();
5896   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5897                          << flag.toString() << CS.toString(),
5898                        getLocationOfByte(flag.getPosition()),
5899                        /*IsStringLocation*/true,
5900                        getSpecifierRange(startSpecifier, specifierLen),
5901                        FixItHint::CreateRemoval(
5902                          getSpecifierRange(flag.getPosition(), 1)));
5903 }
5904 
5905 void CheckPrintfHandler::HandleIgnoredFlag(
5906                                 const analyze_printf::PrintfSpecifier &FS,
5907                                 const analyze_printf::OptionalFlag &ignoredFlag,
5908                                 const analyze_printf::OptionalFlag &flag,
5909                                 const char *startSpecifier,
5910                                 unsigned specifierLen) {
5911   // Warn about ignored flag with a fixit removal.
5912   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5913                          << ignoredFlag.toString() << flag.toString(),
5914                        getLocationOfByte(ignoredFlag.getPosition()),
5915                        /*IsStringLocation*/true,
5916                        getSpecifierRange(startSpecifier, specifierLen),
5917                        FixItHint::CreateRemoval(
5918                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
5919 }
5920 
5921 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5922                                                      unsigned flagLen) {
5923   // Warn about an empty flag.
5924   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5925                        getLocationOfByte(startFlag),
5926                        /*IsStringLocation*/true,
5927                        getSpecifierRange(startFlag, flagLen));
5928 }
5929 
5930 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5931                                                        unsigned flagLen) {
5932   // Warn about an invalid flag.
5933   auto Range = getSpecifierRange(startFlag, flagLen);
5934   StringRef flag(startFlag, flagLen);
5935   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5936                       getLocationOfByte(startFlag),
5937                       /*IsStringLocation*/true,
5938                       Range, FixItHint::CreateRemoval(Range));
5939 }
5940 
5941 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5942     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5943     // Warn about using '[...]' without a '@' conversion.
5944     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5945     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5946     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5947                          getLocationOfByte(conversionPosition),
5948                          /*IsStringLocation*/true,
5949                          Range, FixItHint::CreateRemoval(Range));
5950 }
5951 
5952 // Determines if the specified is a C++ class or struct containing
5953 // a member with the specified name and kind (e.g. a CXXMethodDecl named
5954 // "c_str()").
5955 template<typename MemberKind>
5956 static llvm::SmallPtrSet<MemberKind*, 1>
5957 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5958   const RecordType *RT = Ty->getAs<RecordType>();
5959   llvm::SmallPtrSet<MemberKind*, 1> Results;
5960 
5961   if (!RT)
5962     return Results;
5963   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
5964   if (!RD || !RD->getDefinition())
5965     return Results;
5966 
5967   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
5968                  Sema::LookupMemberName);
5969   R.suppressDiagnostics();
5970 
5971   // We just need to include all members of the right kind turned up by the
5972   // filter, at this point.
5973   if (S.LookupQualifiedName(R, RT->getDecl()))
5974     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5975       NamedDecl *decl = (*I)->getUnderlyingDecl();
5976       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5977         Results.insert(FK);
5978     }
5979   return Results;
5980 }
5981 
5982 /// Check if we could call '.c_str()' on an object.
5983 ///
5984 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5985 /// allow the call, or if it would be ambiguous).
5986 bool Sema::hasCStrMethod(const Expr *E) {
5987   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
5988 
5989   MethodSet Results =
5990       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5991   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5992        MI != ME; ++MI)
5993     if ((*MI)->getMinRequiredArguments() == 0)
5994       return true;
5995   return false;
5996 }
5997 
5998 // Check if a (w)string was passed when a (w)char* was needed, and offer a
5999 // better diagnostic if so. AT is assumed to be valid.
6000 // Returns true when a c_str() conversion method is found.
6001 bool CheckPrintfHandler::checkForCStrMembers(
6002     const analyze_printf::ArgType &AT, const Expr *E) {
6003   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
6004 
6005   MethodSet Results =
6006       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
6007 
6008   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
6009        MI != ME; ++MI) {
6010     const CXXMethodDecl *Method = *MI;
6011     if (Method->getMinRequiredArguments() == 0 &&
6012         AT.matchesType(S.Context, Method->getReturnType())) {
6013       // FIXME: Suggest parens if the expression needs them.
6014       SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
6015       S.Diag(E->getLocStart(), diag::note_printf_c_str)
6016           << "c_str()"
6017           << FixItHint::CreateInsertion(EndLoc, ".c_str()");
6018       return true;
6019     }
6020   }
6021 
6022   return false;
6023 }
6024 
6025 bool
6026 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
6027                                             &FS,
6028                                           const char *startSpecifier,
6029                                           unsigned specifierLen) {
6030   using namespace analyze_format_string;
6031   using namespace analyze_printf;
6032 
6033   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
6034 
6035   if (FS.consumesDataArgument()) {
6036     if (atFirstArg) {
6037         atFirstArg = false;
6038         usesPositionalArgs = FS.usesPositionalArg();
6039     }
6040     else if (usesPositionalArgs != FS.usesPositionalArg()) {
6041       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6042                                         startSpecifier, specifierLen);
6043       return false;
6044     }
6045   }
6046 
6047   // First check if the field width, precision, and conversion specifier
6048   // have matching data arguments.
6049   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
6050                     startSpecifier, specifierLen)) {
6051     return false;
6052   }
6053 
6054   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
6055                     startSpecifier, specifierLen)) {
6056     return false;
6057   }
6058 
6059   if (!CS.consumesDataArgument()) {
6060     // FIXME: Technically specifying a precision or field width here
6061     // makes no sense.  Worth issuing a warning at some point.
6062     return true;
6063   }
6064 
6065   // Consume the argument.
6066   unsigned argIndex = FS.getArgIndex();
6067   if (argIndex < NumDataArgs) {
6068     // The check to see if the argIndex is valid will come later.
6069     // We set the bit here because we may exit early from this
6070     // function if we encounter some other error.
6071     CoveredArgs.set(argIndex);
6072   }
6073 
6074   // FreeBSD kernel extensions.
6075   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
6076       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
6077     // We need at least two arguments.
6078     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
6079       return false;
6080 
6081     // Claim the second argument.
6082     CoveredArgs.set(argIndex + 1);
6083 
6084     // Type check the first argument (int for %b, pointer for %D)
6085     const Expr *Ex = getDataArg(argIndex);
6086     const analyze_printf::ArgType &AT =
6087       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
6088         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
6089     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
6090       EmitFormatDiagnostic(
6091         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6092         << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
6093         << false << Ex->getSourceRange(),
6094         Ex->getLocStart(), /*IsStringLocation*/false,
6095         getSpecifierRange(startSpecifier, specifierLen));
6096 
6097     // Type check the second argument (char * for both %b and %D)
6098     Ex = getDataArg(argIndex + 1);
6099     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
6100     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
6101       EmitFormatDiagnostic(
6102         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6103         << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
6104         << false << Ex->getSourceRange(),
6105         Ex->getLocStart(), /*IsStringLocation*/false,
6106         getSpecifierRange(startSpecifier, specifierLen));
6107 
6108      return true;
6109   }
6110 
6111   // Check for using an Objective-C specific conversion specifier
6112   // in a non-ObjC literal.
6113   if (!allowsObjCArg() && CS.isObjCArg()) {
6114     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6115                                                   specifierLen);
6116   }
6117 
6118   // %P can only be used with os_log.
6119   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
6120     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6121                                                   specifierLen);
6122   }
6123 
6124   // %n is not allowed with os_log.
6125   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
6126     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
6127                          getLocationOfByte(CS.getStart()),
6128                          /*IsStringLocation*/ false,
6129                          getSpecifierRange(startSpecifier, specifierLen));
6130 
6131     return true;
6132   }
6133 
6134   // Only scalars are allowed for os_trace.
6135   if (FSType == Sema::FST_OSTrace &&
6136       (CS.getKind() == ConversionSpecifier::PArg ||
6137        CS.getKind() == ConversionSpecifier::sArg ||
6138        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
6139     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6140                                                   specifierLen);
6141   }
6142 
6143   // Check for use of public/private annotation outside of os_log().
6144   if (FSType != Sema::FST_OSLog) {
6145     if (FS.isPublic().isSet()) {
6146       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6147                                << "public",
6148                            getLocationOfByte(FS.isPublic().getPosition()),
6149                            /*IsStringLocation*/ false,
6150                            getSpecifierRange(startSpecifier, specifierLen));
6151     }
6152     if (FS.isPrivate().isSet()) {
6153       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6154                                << "private",
6155                            getLocationOfByte(FS.isPrivate().getPosition()),
6156                            /*IsStringLocation*/ false,
6157                            getSpecifierRange(startSpecifier, specifierLen));
6158     }
6159   }
6160 
6161   // Check for invalid use of field width
6162   if (!FS.hasValidFieldWidth()) {
6163     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
6164         startSpecifier, specifierLen);
6165   }
6166 
6167   // Check for invalid use of precision
6168   if (!FS.hasValidPrecision()) {
6169     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
6170         startSpecifier, specifierLen);
6171   }
6172 
6173   // Precision is mandatory for %P specifier.
6174   if (CS.getKind() == ConversionSpecifier::PArg &&
6175       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
6176     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
6177                          getLocationOfByte(startSpecifier),
6178                          /*IsStringLocation*/ false,
6179                          getSpecifierRange(startSpecifier, specifierLen));
6180   }
6181 
6182   // Check each flag does not conflict with any other component.
6183   if (!FS.hasValidThousandsGroupingPrefix())
6184     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
6185   if (!FS.hasValidLeadingZeros())
6186     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
6187   if (!FS.hasValidPlusPrefix())
6188     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
6189   if (!FS.hasValidSpacePrefix())
6190     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
6191   if (!FS.hasValidAlternativeForm())
6192     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
6193   if (!FS.hasValidLeftJustified())
6194     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
6195 
6196   // Check that flags are not ignored by another flag
6197   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
6198     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
6199         startSpecifier, specifierLen);
6200   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
6201     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
6202             startSpecifier, specifierLen);
6203 
6204   // Check the length modifier is valid with the given conversion specifier.
6205   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
6206     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6207                                 diag::warn_format_nonsensical_length);
6208   else if (!FS.hasStandardLengthModifier())
6209     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
6210   else if (!FS.hasStandardLengthConversionCombination())
6211     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6212                                 diag::warn_format_non_standard_conversion_spec);
6213 
6214   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6215     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6216 
6217   // The remaining checks depend on the data arguments.
6218   if (HasVAListArg)
6219     return true;
6220 
6221   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
6222     return false;
6223 
6224   const Expr *Arg = getDataArg(argIndex);
6225   if (!Arg)
6226     return true;
6227 
6228   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
6229 }
6230 
6231 static bool requiresParensToAddCast(const Expr *E) {
6232   // FIXME: We should have a general way to reason about operator
6233   // precedence and whether parens are actually needed here.
6234   // Take care of a few common cases where they aren't.
6235   const Expr *Inside = E->IgnoreImpCasts();
6236   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
6237     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
6238 
6239   switch (Inside->getStmtClass()) {
6240   case Stmt::ArraySubscriptExprClass:
6241   case Stmt::CallExprClass:
6242   case Stmt::CharacterLiteralClass:
6243   case Stmt::CXXBoolLiteralExprClass:
6244   case Stmt::DeclRefExprClass:
6245   case Stmt::FloatingLiteralClass:
6246   case Stmt::IntegerLiteralClass:
6247   case Stmt::MemberExprClass:
6248   case Stmt::ObjCArrayLiteralClass:
6249   case Stmt::ObjCBoolLiteralExprClass:
6250   case Stmt::ObjCBoxedExprClass:
6251   case Stmt::ObjCDictionaryLiteralClass:
6252   case Stmt::ObjCEncodeExprClass:
6253   case Stmt::ObjCIvarRefExprClass:
6254   case Stmt::ObjCMessageExprClass:
6255   case Stmt::ObjCPropertyRefExprClass:
6256   case Stmt::ObjCStringLiteralClass:
6257   case Stmt::ObjCSubscriptRefExprClass:
6258   case Stmt::ParenExprClass:
6259   case Stmt::StringLiteralClass:
6260   case Stmt::UnaryOperatorClass:
6261     return false;
6262   default:
6263     return true;
6264   }
6265 }
6266 
6267 static std::pair<QualType, StringRef>
6268 shouldNotPrintDirectly(const ASTContext &Context,
6269                        QualType IntendedTy,
6270                        const Expr *E) {
6271   // Use a 'while' to peel off layers of typedefs.
6272   QualType TyTy = IntendedTy;
6273   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
6274     StringRef Name = UserTy->getDecl()->getName();
6275     QualType CastTy = llvm::StringSwitch<QualType>(Name)
6276       .Case("CFIndex", Context.getNSIntegerType())
6277       .Case("NSInteger", Context.getNSIntegerType())
6278       .Case("NSUInteger", Context.getNSUIntegerType())
6279       .Case("SInt32", Context.IntTy)
6280       .Case("UInt32", Context.UnsignedIntTy)
6281       .Default(QualType());
6282 
6283     if (!CastTy.isNull())
6284       return std::make_pair(CastTy, Name);
6285 
6286     TyTy = UserTy->desugar();
6287   }
6288 
6289   // Strip parens if necessary.
6290   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
6291     return shouldNotPrintDirectly(Context,
6292                                   PE->getSubExpr()->getType(),
6293                                   PE->getSubExpr());
6294 
6295   // If this is a conditional expression, then its result type is constructed
6296   // via usual arithmetic conversions and thus there might be no necessary
6297   // typedef sugar there.  Recurse to operands to check for NSInteger &
6298   // Co. usage condition.
6299   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6300     QualType TrueTy, FalseTy;
6301     StringRef TrueName, FalseName;
6302 
6303     std::tie(TrueTy, TrueName) =
6304       shouldNotPrintDirectly(Context,
6305                              CO->getTrueExpr()->getType(),
6306                              CO->getTrueExpr());
6307     std::tie(FalseTy, FalseName) =
6308       shouldNotPrintDirectly(Context,
6309                              CO->getFalseExpr()->getType(),
6310                              CO->getFalseExpr());
6311 
6312     if (TrueTy == FalseTy)
6313       return std::make_pair(TrueTy, TrueName);
6314     else if (TrueTy.isNull())
6315       return std::make_pair(FalseTy, FalseName);
6316     else if (FalseTy.isNull())
6317       return std::make_pair(TrueTy, TrueName);
6318   }
6319 
6320   return std::make_pair(QualType(), StringRef());
6321 }
6322 
6323 bool
6324 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6325                                     const char *StartSpecifier,
6326                                     unsigned SpecifierLen,
6327                                     const Expr *E) {
6328   using namespace analyze_format_string;
6329   using namespace analyze_printf;
6330 
6331   // Now type check the data expression that matches the
6332   // format specifier.
6333   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
6334   if (!AT.isValid())
6335     return true;
6336 
6337   QualType ExprTy = E->getType();
6338   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
6339     ExprTy = TET->getUnderlyingExpr()->getType();
6340   }
6341 
6342   analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
6343 
6344   if (match == analyze_printf::ArgType::Match) {
6345     return true;
6346   }
6347 
6348   // Look through argument promotions for our error message's reported type.
6349   // This includes the integral and floating promotions, but excludes array
6350   // and function pointer decay; seeing that an argument intended to be a
6351   // string has type 'char [6]' is probably more confusing than 'char *'.
6352   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6353     if (ICE->getCastKind() == CK_IntegralCast ||
6354         ICE->getCastKind() == CK_FloatingCast) {
6355       E = ICE->getSubExpr();
6356       ExprTy = E->getType();
6357 
6358       // Check if we didn't match because of an implicit cast from a 'char'
6359       // or 'short' to an 'int'.  This is done because printf is a varargs
6360       // function.
6361       if (ICE->getType() == S.Context.IntTy ||
6362           ICE->getType() == S.Context.UnsignedIntTy) {
6363         // All further checking is done on the subexpression.
6364         if (AT.matchesType(S.Context, ExprTy))
6365           return true;
6366       }
6367     }
6368   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
6369     // Special case for 'a', which has type 'int' in C.
6370     // Note, however, that we do /not/ want to treat multibyte constants like
6371     // 'MooV' as characters! This form is deprecated but still exists.
6372     if (ExprTy == S.Context.IntTy)
6373       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6374         ExprTy = S.Context.CharTy;
6375   }
6376 
6377   // Look through enums to their underlying type.
6378   bool IsEnum = false;
6379   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
6380     ExprTy = EnumTy->getDecl()->getIntegerType();
6381     IsEnum = true;
6382   }
6383 
6384   // %C in an Objective-C context prints a unichar, not a wchar_t.
6385   // If the argument is an integer of some kind, believe the %C and suggest
6386   // a cast instead of changing the conversion specifier.
6387   QualType IntendedTy = ExprTy;
6388   if (isObjCContext() &&
6389       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
6390     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6391         !ExprTy->isCharType()) {
6392       // 'unichar' is defined as a typedef of unsigned short, but we should
6393       // prefer using the typedef if it is visible.
6394       IntendedTy = S.Context.UnsignedShortTy;
6395 
6396       // While we are here, check if the value is an IntegerLiteral that happens
6397       // to be within the valid range.
6398       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
6399         const llvm::APInt &V = IL->getValue();
6400         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6401           return true;
6402       }
6403 
6404       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
6405                           Sema::LookupOrdinaryName);
6406       if (S.LookupName(Result, S.getCurScope())) {
6407         NamedDecl *ND = Result.getFoundDecl();
6408         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
6409           if (TD->getUnderlyingType() == IntendedTy)
6410             IntendedTy = S.Context.getTypedefType(TD);
6411       }
6412     }
6413   }
6414 
6415   // Special-case some of Darwin's platform-independence types by suggesting
6416   // casts to primitive types that are known to be large enough.
6417   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
6418   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
6419     QualType CastTy;
6420     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
6421     if (!CastTy.isNull()) {
6422       IntendedTy = CastTy;
6423       ShouldNotPrintDirectly = true;
6424     }
6425   }
6426 
6427   // We may be able to offer a FixItHint if it is a supported type.
6428   PrintfSpecifier fixedFS = FS;
6429   bool success =
6430       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
6431 
6432   if (success) {
6433     // Get the fix string from the fixed format specifier
6434     SmallString<16> buf;
6435     llvm::raw_svector_ostream os(buf);
6436     fixedFS.toString(os);
6437 
6438     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6439 
6440     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
6441       unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6442       if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6443         diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6444       }
6445       // In this case, the specifier is wrong and should be changed to match
6446       // the argument.
6447       EmitFormatDiagnostic(S.PDiag(diag)
6448                                << AT.getRepresentativeTypeName(S.Context)
6449                                << IntendedTy << IsEnum << E->getSourceRange(),
6450                            E->getLocStart(),
6451                            /*IsStringLocation*/ false, SpecRange,
6452                            FixItHint::CreateReplacement(SpecRange, os.str()));
6453     } else {
6454       // The canonical type for formatting this value is different from the
6455       // actual type of the expression. (This occurs, for example, with Darwin's
6456       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6457       // should be printed as 'long' for 64-bit compatibility.)
6458       // Rather than emitting a normal format/argument mismatch, we want to
6459       // add a cast to the recommended type (and correct the format string
6460       // if necessary).
6461       SmallString<16> CastBuf;
6462       llvm::raw_svector_ostream CastFix(CastBuf);
6463       CastFix << "(";
6464       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6465       CastFix << ")";
6466 
6467       SmallVector<FixItHint,4> Hints;
6468       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
6469         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6470 
6471       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6472         // If there's already a cast present, just replace it.
6473         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6474         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6475 
6476       } else if (!requiresParensToAddCast(E)) {
6477         // If the expression has high enough precedence,
6478         // just write the C-style cast.
6479         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6480                                                    CastFix.str()));
6481       } else {
6482         // Otherwise, add parens around the expression as well as the cast.
6483         CastFix << "(";
6484         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6485                                                    CastFix.str()));
6486 
6487         SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
6488         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6489       }
6490 
6491       if (ShouldNotPrintDirectly) {
6492         // The expression has a type that should not be printed directly.
6493         // We extract the name from the typedef because we don't want to show
6494         // the underlying type in the diagnostic.
6495         StringRef Name;
6496         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6497           Name = TypedefTy->getDecl()->getName();
6498         else
6499           Name = CastTyName;
6500         EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
6501                                << Name << IntendedTy << IsEnum
6502                                << E->getSourceRange(),
6503                              E->getLocStart(), /*IsStringLocation=*/false,
6504                              SpecRange, Hints);
6505       } else {
6506         // In this case, the expression could be printed using a different
6507         // specifier, but we've decided that the specifier is probably correct
6508         // and we should cast instead. Just use the normal warning message.
6509         EmitFormatDiagnostic(
6510           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6511             << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
6512             << E->getSourceRange(),
6513           E->getLocStart(), /*IsStringLocation*/false,
6514           SpecRange, Hints);
6515       }
6516     }
6517   } else {
6518     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6519                                                    SpecifierLen);
6520     // Since the warning for passing non-POD types to variadic functions
6521     // was deferred until now, we emit a warning for non-POD
6522     // arguments here.
6523     switch (S.isValidVarArgType(ExprTy)) {
6524     case Sema::VAK_Valid:
6525     case Sema::VAK_ValidInCXX11: {
6526       unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6527       if (match == analyze_printf::ArgType::NoMatchPedantic) {
6528         diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6529       }
6530 
6531       EmitFormatDiagnostic(
6532           S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6533                         << IsEnum << CSR << E->getSourceRange(),
6534           E->getLocStart(), /*IsStringLocation*/ false, CSR);
6535       break;
6536     }
6537     case Sema::VAK_Undefined:
6538     case Sema::VAK_MSVCUndefined:
6539       EmitFormatDiagnostic(
6540         S.PDiag(diag::warn_non_pod_vararg_with_format_string)
6541           << S.getLangOpts().CPlusPlus11
6542           << ExprTy
6543           << CallType
6544           << AT.getRepresentativeTypeName(S.Context)
6545           << CSR
6546           << E->getSourceRange(),
6547         E->getLocStart(), /*IsStringLocation*/false, CSR);
6548       checkForCStrMembers(AT, E);
6549       break;
6550 
6551     case Sema::VAK_Invalid:
6552       if (ExprTy->isObjCObjectType())
6553         EmitFormatDiagnostic(
6554           S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6555             << S.getLangOpts().CPlusPlus11
6556             << ExprTy
6557             << CallType
6558             << AT.getRepresentativeTypeName(S.Context)
6559             << CSR
6560             << E->getSourceRange(),
6561           E->getLocStart(), /*IsStringLocation*/false, CSR);
6562       else
6563         // FIXME: If this is an initializer list, suggest removing the braces
6564         // or inserting a cast to the target type.
6565         S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6566           << isa<InitListExpr>(E) << ExprTy << CallType
6567           << AT.getRepresentativeTypeName(S.Context)
6568           << E->getSourceRange();
6569       break;
6570     }
6571 
6572     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6573            "format string specifier index out of range");
6574     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
6575   }
6576 
6577   return true;
6578 }
6579 
6580 //===--- CHECK: Scanf format string checking ------------------------------===//
6581 
6582 namespace {
6583 
6584 class CheckScanfHandler : public CheckFormatHandler {
6585 public:
6586   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
6587                     const Expr *origFormatExpr, Sema::FormatStringType type,
6588                     unsigned firstDataArg, unsigned numDataArgs,
6589                     const char *beg, bool hasVAListArg,
6590                     ArrayRef<const Expr *> Args, unsigned formatIdx,
6591                     bool inFunctionCall, Sema::VariadicCallType CallType,
6592                     llvm::SmallBitVector &CheckedVarArgs,
6593                     UncoveredArgHandler &UncoveredArg)
6594       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6595                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
6596                            inFunctionCall, CallType, CheckedVarArgs,
6597                            UncoveredArg) {}
6598 
6599   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6600                             const char *startSpecifier,
6601                             unsigned specifierLen) override;
6602 
6603   bool HandleInvalidScanfConversionSpecifier(
6604           const analyze_scanf::ScanfSpecifier &FS,
6605           const char *startSpecifier,
6606           unsigned specifierLen) override;
6607 
6608   void HandleIncompleteScanList(const char *start, const char *end) override;
6609 };
6610 
6611 } // namespace
6612 
6613 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6614                                                  const char *end) {
6615   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6616                        getLocationOfByte(end), /*IsStringLocation*/true,
6617                        getSpecifierRange(start, end - start));
6618 }
6619 
6620 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6621                                         const analyze_scanf::ScanfSpecifier &FS,
6622                                         const char *startSpecifier,
6623                                         unsigned specifierLen) {
6624   const analyze_scanf::ScanfConversionSpecifier &CS =
6625     FS.getConversionSpecifier();
6626 
6627   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6628                                           getLocationOfByte(CS.getStart()),
6629                                           startSpecifier, specifierLen,
6630                                           CS.getStart(), CS.getLength());
6631 }
6632 
6633 bool CheckScanfHandler::HandleScanfSpecifier(
6634                                        const analyze_scanf::ScanfSpecifier &FS,
6635                                        const char *startSpecifier,
6636                                        unsigned specifierLen) {
6637   using namespace analyze_scanf;
6638   using namespace analyze_format_string;
6639 
6640   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
6641 
6642   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
6643   // be used to decide if we are using positional arguments consistently.
6644   if (FS.consumesDataArgument()) {
6645     if (atFirstArg) {
6646       atFirstArg = false;
6647       usesPositionalArgs = FS.usesPositionalArg();
6648     }
6649     else if (usesPositionalArgs != FS.usesPositionalArg()) {
6650       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6651                                         startSpecifier, specifierLen);
6652       return false;
6653     }
6654   }
6655 
6656   // Check if the field with is non-zero.
6657   const OptionalAmount &Amt = FS.getFieldWidth();
6658   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6659     if (Amt.getConstantAmount() == 0) {
6660       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6661                                                    Amt.getConstantLength());
6662       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6663                            getLocationOfByte(Amt.getStart()),
6664                            /*IsStringLocation*/true, R,
6665                            FixItHint::CreateRemoval(R));
6666     }
6667   }
6668 
6669   if (!FS.consumesDataArgument()) {
6670     // FIXME: Technically specifying a precision or field width here
6671     // makes no sense.  Worth issuing a warning at some point.
6672     return true;
6673   }
6674 
6675   // Consume the argument.
6676   unsigned argIndex = FS.getArgIndex();
6677   if (argIndex < NumDataArgs) {
6678       // The check to see if the argIndex is valid will come later.
6679       // We set the bit here because we may exit early from this
6680       // function if we encounter some other error.
6681     CoveredArgs.set(argIndex);
6682   }
6683 
6684   // Check the length modifier is valid with the given conversion specifier.
6685   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
6686     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6687                                 diag::warn_format_nonsensical_length);
6688   else if (!FS.hasStandardLengthModifier())
6689     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
6690   else if (!FS.hasStandardLengthConversionCombination())
6691     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6692                                 diag::warn_format_non_standard_conversion_spec);
6693 
6694   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6695     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6696 
6697   // The remaining checks depend on the data arguments.
6698   if (HasVAListArg)
6699     return true;
6700 
6701   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
6702     return false;
6703 
6704   // Check that the argument type matches the format specifier.
6705   const Expr *Ex = getDataArg(argIndex);
6706   if (!Ex)
6707     return true;
6708 
6709   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
6710 
6711   if (!AT.isValid()) {
6712     return true;
6713   }
6714 
6715   analyze_format_string::ArgType::MatchKind match =
6716       AT.matchesType(S.Context, Ex->getType());
6717   if (match == analyze_format_string::ArgType::Match) {
6718     return true;
6719   }
6720 
6721   ScanfSpecifier fixedFS = FS;
6722   bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6723                                  S.getLangOpts(), S.Context);
6724 
6725   unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6726   if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6727     diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6728   }
6729 
6730   if (success) {
6731     // Get the fix string from the fixed format specifier.
6732     SmallString<128> buf;
6733     llvm::raw_svector_ostream os(buf);
6734     fixedFS.toString(os);
6735 
6736     EmitFormatDiagnostic(
6737         S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6738                       << Ex->getType() << false << Ex->getSourceRange(),
6739         Ex->getLocStart(),
6740         /*IsStringLocation*/ false,
6741         getSpecifierRange(startSpecifier, specifierLen),
6742         FixItHint::CreateReplacement(
6743             getSpecifierRange(startSpecifier, specifierLen), os.str()));
6744   } else {
6745     EmitFormatDiagnostic(S.PDiag(diag)
6746                              << AT.getRepresentativeTypeName(S.Context)
6747                              << Ex->getType() << false << Ex->getSourceRange(),
6748                          Ex->getLocStart(),
6749                          /*IsStringLocation*/ false,
6750                          getSpecifierRange(startSpecifier, specifierLen));
6751   }
6752 
6753   return true;
6754 }
6755 
6756 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6757                               const Expr *OrigFormatExpr,
6758                               ArrayRef<const Expr *> Args,
6759                               bool HasVAListArg, unsigned format_idx,
6760                               unsigned firstDataArg,
6761                               Sema::FormatStringType Type,
6762                               bool inFunctionCall,
6763                               Sema::VariadicCallType CallType,
6764                               llvm::SmallBitVector &CheckedVarArgs,
6765                               UncoveredArgHandler &UncoveredArg) {
6766   // CHECK: is the format string a wide literal?
6767   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
6768     CheckFormatHandler::EmitFormatDiagnostic(
6769       S, inFunctionCall, Args[format_idx],
6770       S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
6771       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
6772     return;
6773   }
6774 
6775   // Str - The format string.  NOTE: this is NOT null-terminated!
6776   StringRef StrRef = FExpr->getString();
6777   const char *Str = StrRef.data();
6778   // Account for cases where the string literal is truncated in a declaration.
6779   const ConstantArrayType *T =
6780     S.Context.getAsConstantArrayType(FExpr->getType());
6781   assert(T && "String literal not of constant array type!");
6782   size_t TypeSize = T->getSize().getZExtValue();
6783   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6784   const unsigned numDataArgs = Args.size() - firstDataArg;
6785 
6786   // Emit a warning if the string literal is truncated and does not contain an
6787   // embedded null character.
6788   if (TypeSize <= StrRef.size() &&
6789       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6790     CheckFormatHandler::EmitFormatDiagnostic(
6791         S, inFunctionCall, Args[format_idx],
6792         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
6793         FExpr->getLocStart(),
6794         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6795     return;
6796   }
6797 
6798   // CHECK: empty format string?
6799   if (StrLen == 0 && numDataArgs > 0) {
6800     CheckFormatHandler::EmitFormatDiagnostic(
6801       S, inFunctionCall, Args[format_idx],
6802       S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
6803       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
6804     return;
6805   }
6806 
6807   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
6808       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6809       Type == Sema::FST_OSTrace) {
6810     CheckPrintfHandler H(
6811         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6812         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6813         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6814         CheckedVarArgs, UncoveredArg);
6815 
6816     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
6817                                                   S.getLangOpts(),
6818                                                   S.Context.getTargetInfo(),
6819                                             Type == Sema::FST_FreeBSDKPrintf))
6820       H.DoneProcessing();
6821   } else if (Type == Sema::FST_Scanf) {
6822     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6823                         numDataArgs, Str, HasVAListArg, Args, format_idx,
6824                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
6825 
6826     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
6827                                                  S.getLangOpts(),
6828                                                  S.Context.getTargetInfo()))
6829       H.DoneProcessing();
6830   } // TODO: handle other formats
6831 }
6832 
6833 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6834   // Str - The format string.  NOTE: this is NOT null-terminated!
6835   StringRef StrRef = FExpr->getString();
6836   const char *Str = StrRef.data();
6837   // Account for cases where the string literal is truncated in a declaration.
6838   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6839   assert(T && "String literal not of constant array type!");
6840   size_t TypeSize = T->getSize().getZExtValue();
6841   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6842   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6843                                                          getLangOpts(),
6844                                                          Context.getTargetInfo());
6845 }
6846 
6847 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6848 
6849 // Returns the related absolute value function that is larger, of 0 if one
6850 // does not exist.
6851 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6852   switch (AbsFunction) {
6853   default:
6854     return 0;
6855 
6856   case Builtin::BI__builtin_abs:
6857     return Builtin::BI__builtin_labs;
6858   case Builtin::BI__builtin_labs:
6859     return Builtin::BI__builtin_llabs;
6860   case Builtin::BI__builtin_llabs:
6861     return 0;
6862 
6863   case Builtin::BI__builtin_fabsf:
6864     return Builtin::BI__builtin_fabs;
6865   case Builtin::BI__builtin_fabs:
6866     return Builtin::BI__builtin_fabsl;
6867   case Builtin::BI__builtin_fabsl:
6868     return 0;
6869 
6870   case Builtin::BI__builtin_cabsf:
6871     return Builtin::BI__builtin_cabs;
6872   case Builtin::BI__builtin_cabs:
6873     return Builtin::BI__builtin_cabsl;
6874   case Builtin::BI__builtin_cabsl:
6875     return 0;
6876 
6877   case Builtin::BIabs:
6878     return Builtin::BIlabs;
6879   case Builtin::BIlabs:
6880     return Builtin::BIllabs;
6881   case Builtin::BIllabs:
6882     return 0;
6883 
6884   case Builtin::BIfabsf:
6885     return Builtin::BIfabs;
6886   case Builtin::BIfabs:
6887     return Builtin::BIfabsl;
6888   case Builtin::BIfabsl:
6889     return 0;
6890 
6891   case Builtin::BIcabsf:
6892    return Builtin::BIcabs;
6893   case Builtin::BIcabs:
6894     return Builtin::BIcabsl;
6895   case Builtin::BIcabsl:
6896     return 0;
6897   }
6898 }
6899 
6900 // Returns the argument type of the absolute value function.
6901 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6902                                              unsigned AbsType) {
6903   if (AbsType == 0)
6904     return QualType();
6905 
6906   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6907   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6908   if (Error != ASTContext::GE_None)
6909     return QualType();
6910 
6911   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6912   if (!FT)
6913     return QualType();
6914 
6915   if (FT->getNumParams() != 1)
6916     return QualType();
6917 
6918   return FT->getParamType(0);
6919 }
6920 
6921 // Returns the best absolute value function, or zero, based on type and
6922 // current absolute value function.
6923 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6924                                    unsigned AbsFunctionKind) {
6925   unsigned BestKind = 0;
6926   uint64_t ArgSize = Context.getTypeSize(ArgType);
6927   for (unsigned Kind = AbsFunctionKind; Kind != 0;
6928        Kind = getLargerAbsoluteValueFunction(Kind)) {
6929     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6930     if (Context.getTypeSize(ParamType) >= ArgSize) {
6931       if (BestKind == 0)
6932         BestKind = Kind;
6933       else if (Context.hasSameType(ParamType, ArgType)) {
6934         BestKind = Kind;
6935         break;
6936       }
6937     }
6938   }
6939   return BestKind;
6940 }
6941 
6942 enum AbsoluteValueKind {
6943   AVK_Integer,
6944   AVK_Floating,
6945   AVK_Complex
6946 };
6947 
6948 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6949   if (T->isIntegralOrEnumerationType())
6950     return AVK_Integer;
6951   if (T->isRealFloatingType())
6952     return AVK_Floating;
6953   if (T->isAnyComplexType())
6954     return AVK_Complex;
6955 
6956   llvm_unreachable("Type not integer, floating, or complex");
6957 }
6958 
6959 // Changes the absolute value function to a different type.  Preserves whether
6960 // the function is a builtin.
6961 static unsigned changeAbsFunction(unsigned AbsKind,
6962                                   AbsoluteValueKind ValueKind) {
6963   switch (ValueKind) {
6964   case AVK_Integer:
6965     switch (AbsKind) {
6966     default:
6967       return 0;
6968     case Builtin::BI__builtin_fabsf:
6969     case Builtin::BI__builtin_fabs:
6970     case Builtin::BI__builtin_fabsl:
6971     case Builtin::BI__builtin_cabsf:
6972     case Builtin::BI__builtin_cabs:
6973     case Builtin::BI__builtin_cabsl:
6974       return Builtin::BI__builtin_abs;
6975     case Builtin::BIfabsf:
6976     case Builtin::BIfabs:
6977     case Builtin::BIfabsl:
6978     case Builtin::BIcabsf:
6979     case Builtin::BIcabs:
6980     case Builtin::BIcabsl:
6981       return Builtin::BIabs;
6982     }
6983   case AVK_Floating:
6984     switch (AbsKind) {
6985     default:
6986       return 0;
6987     case Builtin::BI__builtin_abs:
6988     case Builtin::BI__builtin_labs:
6989     case Builtin::BI__builtin_llabs:
6990     case Builtin::BI__builtin_cabsf:
6991     case Builtin::BI__builtin_cabs:
6992     case Builtin::BI__builtin_cabsl:
6993       return Builtin::BI__builtin_fabsf;
6994     case Builtin::BIabs:
6995     case Builtin::BIlabs:
6996     case Builtin::BIllabs:
6997     case Builtin::BIcabsf:
6998     case Builtin::BIcabs:
6999     case Builtin::BIcabsl:
7000       return Builtin::BIfabsf;
7001     }
7002   case AVK_Complex:
7003     switch (AbsKind) {
7004     default:
7005       return 0;
7006     case Builtin::BI__builtin_abs:
7007     case Builtin::BI__builtin_labs:
7008     case Builtin::BI__builtin_llabs:
7009     case Builtin::BI__builtin_fabsf:
7010     case Builtin::BI__builtin_fabs:
7011     case Builtin::BI__builtin_fabsl:
7012       return Builtin::BI__builtin_cabsf;
7013     case Builtin::BIabs:
7014     case Builtin::BIlabs:
7015     case Builtin::BIllabs:
7016     case Builtin::BIfabsf:
7017     case Builtin::BIfabs:
7018     case Builtin::BIfabsl:
7019       return Builtin::BIcabsf;
7020     }
7021   }
7022   llvm_unreachable("Unable to convert function");
7023 }
7024 
7025 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
7026   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
7027   if (!FnInfo)
7028     return 0;
7029 
7030   switch (FDecl->getBuiltinID()) {
7031   default:
7032     return 0;
7033   case Builtin::BI__builtin_abs:
7034   case Builtin::BI__builtin_fabs:
7035   case Builtin::BI__builtin_fabsf:
7036   case Builtin::BI__builtin_fabsl:
7037   case Builtin::BI__builtin_labs:
7038   case Builtin::BI__builtin_llabs:
7039   case Builtin::BI__builtin_cabs:
7040   case Builtin::BI__builtin_cabsf:
7041   case Builtin::BI__builtin_cabsl:
7042   case Builtin::BIabs:
7043   case Builtin::BIlabs:
7044   case Builtin::BIllabs:
7045   case Builtin::BIfabs:
7046   case Builtin::BIfabsf:
7047   case Builtin::BIfabsl:
7048   case Builtin::BIcabs:
7049   case Builtin::BIcabsf:
7050   case Builtin::BIcabsl:
7051     return FDecl->getBuiltinID();
7052   }
7053   llvm_unreachable("Unknown Builtin type");
7054 }
7055 
7056 // If the replacement is valid, emit a note with replacement function.
7057 // Additionally, suggest including the proper header if not already included.
7058 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
7059                             unsigned AbsKind, QualType ArgType) {
7060   bool EmitHeaderHint = true;
7061   const char *HeaderName = nullptr;
7062   const char *FunctionName = nullptr;
7063   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
7064     FunctionName = "std::abs";
7065     if (ArgType->isIntegralOrEnumerationType()) {
7066       HeaderName = "cstdlib";
7067     } else if (ArgType->isRealFloatingType()) {
7068       HeaderName = "cmath";
7069     } else {
7070       llvm_unreachable("Invalid Type");
7071     }
7072 
7073     // Lookup all std::abs
7074     if (NamespaceDecl *Std = S.getStdNamespace()) {
7075       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
7076       R.suppressDiagnostics();
7077       S.LookupQualifiedName(R, Std);
7078 
7079       for (const auto *I : R) {
7080         const FunctionDecl *FDecl = nullptr;
7081         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
7082           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
7083         } else {
7084           FDecl = dyn_cast<FunctionDecl>(I);
7085         }
7086         if (!FDecl)
7087           continue;
7088 
7089         // Found std::abs(), check that they are the right ones.
7090         if (FDecl->getNumParams() != 1)
7091           continue;
7092 
7093         // Check that the parameter type can handle the argument.
7094         QualType ParamType = FDecl->getParamDecl(0)->getType();
7095         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
7096             S.Context.getTypeSize(ArgType) <=
7097                 S.Context.getTypeSize(ParamType)) {
7098           // Found a function, don't need the header hint.
7099           EmitHeaderHint = false;
7100           break;
7101         }
7102       }
7103     }
7104   } else {
7105     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
7106     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
7107 
7108     if (HeaderName) {
7109       DeclarationName DN(&S.Context.Idents.get(FunctionName));
7110       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
7111       R.suppressDiagnostics();
7112       S.LookupName(R, S.getCurScope());
7113 
7114       if (R.isSingleResult()) {
7115         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
7116         if (FD && FD->getBuiltinID() == AbsKind) {
7117           EmitHeaderHint = false;
7118         } else {
7119           return;
7120         }
7121       } else if (!R.empty()) {
7122         return;
7123       }
7124     }
7125   }
7126 
7127   S.Diag(Loc, diag::note_replace_abs_function)
7128       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
7129 
7130   if (!HeaderName)
7131     return;
7132 
7133   if (!EmitHeaderHint)
7134     return;
7135 
7136   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
7137                                                     << FunctionName;
7138 }
7139 
7140 template <std::size_t StrLen>
7141 static bool IsStdFunction(const FunctionDecl *FDecl,
7142                           const char (&Str)[StrLen]) {
7143   if (!FDecl)
7144     return false;
7145   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
7146     return false;
7147   if (!FDecl->isInStdNamespace())
7148     return false;
7149 
7150   return true;
7151 }
7152 
7153 // Warn when using the wrong abs() function.
7154 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
7155                                       const FunctionDecl *FDecl) {
7156   if (Call->getNumArgs() != 1)
7157     return;
7158 
7159   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
7160   bool IsStdAbs = IsStdFunction(FDecl, "abs");
7161   if (AbsKind == 0 && !IsStdAbs)
7162     return;
7163 
7164   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7165   QualType ParamType = Call->getArg(0)->getType();
7166 
7167   // Unsigned types cannot be negative.  Suggest removing the absolute value
7168   // function call.
7169   if (ArgType->isUnsignedIntegerType()) {
7170     const char *FunctionName =
7171         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
7172     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
7173     Diag(Call->getExprLoc(), diag::note_remove_abs)
7174         << FunctionName
7175         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
7176     return;
7177   }
7178 
7179   // Taking the absolute value of a pointer is very suspicious, they probably
7180   // wanted to index into an array, dereference a pointer, call a function, etc.
7181   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
7182     unsigned DiagType = 0;
7183     if (ArgType->isFunctionType())
7184       DiagType = 1;
7185     else if (ArgType->isArrayType())
7186       DiagType = 2;
7187 
7188     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
7189     return;
7190   }
7191 
7192   // std::abs has overloads which prevent most of the absolute value problems
7193   // from occurring.
7194   if (IsStdAbs)
7195     return;
7196 
7197   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
7198   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
7199 
7200   // The argument and parameter are the same kind.  Check if they are the right
7201   // size.
7202   if (ArgValueKind == ParamValueKind) {
7203     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
7204       return;
7205 
7206     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
7207     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
7208         << FDecl << ArgType << ParamType;
7209 
7210     if (NewAbsKind == 0)
7211       return;
7212 
7213     emitReplacement(*this, Call->getExprLoc(),
7214                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
7215     return;
7216   }
7217 
7218   // ArgValueKind != ParamValueKind
7219   // The wrong type of absolute value function was used.  Attempt to find the
7220   // proper one.
7221   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
7222   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
7223   if (NewAbsKind == 0)
7224     return;
7225 
7226   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
7227       << FDecl << ParamValueKind << ArgValueKind;
7228 
7229   emitReplacement(*this, Call->getExprLoc(),
7230                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
7231 }
7232 
7233 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
7234 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
7235                                 const FunctionDecl *FDecl) {
7236   if (!Call || !FDecl) return;
7237 
7238   // Ignore template specializations and macros.
7239   if (inTemplateInstantiation()) return;
7240   if (Call->getExprLoc().isMacroID()) return;
7241 
7242   // Only care about the one template argument, two function parameter std::max
7243   if (Call->getNumArgs() != 2) return;
7244   if (!IsStdFunction(FDecl, "max")) return;
7245   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
7246   if (!ArgList) return;
7247   if (ArgList->size() != 1) return;
7248 
7249   // Check that template type argument is unsigned integer.
7250   const auto& TA = ArgList->get(0);
7251   if (TA.getKind() != TemplateArgument::Type) return;
7252   QualType ArgType = TA.getAsType();
7253   if (!ArgType->isUnsignedIntegerType()) return;
7254 
7255   // See if either argument is a literal zero.
7256   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
7257     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
7258     if (!MTE) return false;
7259     const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
7260     if (!Num) return false;
7261     if (Num->getValue() != 0) return false;
7262     return true;
7263   };
7264 
7265   const Expr *FirstArg = Call->getArg(0);
7266   const Expr *SecondArg = Call->getArg(1);
7267   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
7268   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
7269 
7270   // Only warn when exactly one argument is zero.
7271   if (IsFirstArgZero == IsSecondArgZero) return;
7272 
7273   SourceRange FirstRange = FirstArg->getSourceRange();
7274   SourceRange SecondRange = SecondArg->getSourceRange();
7275 
7276   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
7277 
7278   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
7279       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
7280 
7281   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
7282   SourceRange RemovalRange;
7283   if (IsFirstArgZero) {
7284     RemovalRange = SourceRange(FirstRange.getBegin(),
7285                                SecondRange.getBegin().getLocWithOffset(-1));
7286   } else {
7287     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
7288                                SecondRange.getEnd());
7289   }
7290 
7291   Diag(Call->getExprLoc(), diag::note_remove_max_call)
7292         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
7293         << FixItHint::CreateRemoval(RemovalRange);
7294 }
7295 
7296 //===--- CHECK: Standard memory functions ---------------------------------===//
7297 
7298 /// \brief Takes the expression passed to the size_t parameter of functions
7299 /// such as memcmp, strncat, etc and warns if it's a comparison.
7300 ///
7301 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
7302 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
7303                                            IdentifierInfo *FnName,
7304                                            SourceLocation FnLoc,
7305                                            SourceLocation RParenLoc) {
7306   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
7307   if (!Size)
7308     return false;
7309 
7310   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
7311   if (!Size->isComparisonOp() && !Size->isLogicalOp())
7312     return false;
7313 
7314   SourceRange SizeRange = Size->getSourceRange();
7315   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
7316       << SizeRange << FnName;
7317   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
7318       << FnName << FixItHint::CreateInsertion(
7319                        S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
7320       << FixItHint::CreateRemoval(RParenLoc);
7321   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
7322       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
7323       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
7324                                     ")");
7325 
7326   return true;
7327 }
7328 
7329 /// \brief Determine whether the given type is or contains a dynamic class type
7330 /// (e.g., whether it has a vtable).
7331 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
7332                                                      bool &IsContained) {
7333   // Look through array types while ignoring qualifiers.
7334   const Type *Ty = T->getBaseElementTypeUnsafe();
7335   IsContained = false;
7336 
7337   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
7338   RD = RD ? RD->getDefinition() : nullptr;
7339   if (!RD || RD->isInvalidDecl())
7340     return nullptr;
7341 
7342   if (RD->isDynamicClass())
7343     return RD;
7344 
7345   // Check all the fields.  If any bases were dynamic, the class is dynamic.
7346   // It's impossible for a class to transitively contain itself by value, so
7347   // infinite recursion is impossible.
7348   for (auto *FD : RD->fields()) {
7349     bool SubContained;
7350     if (const CXXRecordDecl *ContainedRD =
7351             getContainedDynamicClass(FD->getType(), SubContained)) {
7352       IsContained = true;
7353       return ContainedRD;
7354     }
7355   }
7356 
7357   return nullptr;
7358 }
7359 
7360 /// \brief If E is a sizeof expression, returns its argument expression,
7361 /// otherwise returns NULL.
7362 static const Expr *getSizeOfExprArg(const Expr *E) {
7363   if (const UnaryExprOrTypeTraitExpr *SizeOf =
7364       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7365     if (SizeOf->getKind() == UETT_SizeOf && !SizeOf->isArgumentType())
7366       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
7367 
7368   return nullptr;
7369 }
7370 
7371 /// \brief If E is a sizeof expression, returns its argument type.
7372 static QualType getSizeOfArgType(const Expr *E) {
7373   if (const UnaryExprOrTypeTraitExpr *SizeOf =
7374       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7375     if (SizeOf->getKind() == UETT_SizeOf)
7376       return SizeOf->getTypeOfArgument();
7377 
7378   return QualType();
7379 }
7380 
7381 /// \brief Check for dangerous or invalid arguments to memset().
7382 ///
7383 /// This issues warnings on known problematic, dangerous or unspecified
7384 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
7385 /// function calls.
7386 ///
7387 /// \param Call The call expression to diagnose.
7388 void Sema::CheckMemaccessArguments(const CallExpr *Call,
7389                                    unsigned BId,
7390                                    IdentifierInfo *FnName) {
7391   assert(BId != 0);
7392 
7393   // It is possible to have a non-standard definition of memset.  Validate
7394   // we have enough arguments, and if not, abort further checking.
7395   unsigned ExpectedNumArgs =
7396       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
7397   if (Call->getNumArgs() < ExpectedNumArgs)
7398     return;
7399 
7400   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
7401                       BId == Builtin::BIstrndup ? 1 : 2);
7402   unsigned LenArg =
7403       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
7404   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
7405 
7406   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
7407                                      Call->getLocStart(), Call->getRParenLoc()))
7408     return;
7409 
7410   // We have special checking when the length is a sizeof expression.
7411   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
7412   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
7413   llvm::FoldingSetNodeID SizeOfArgID;
7414 
7415   // Although widely used, 'bzero' is not a standard function. Be more strict
7416   // with the argument types before allowing diagnostics and only allow the
7417   // form bzero(ptr, sizeof(...)).
7418   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7419   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
7420     return;
7421 
7422   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7423     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
7424     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
7425 
7426     QualType DestTy = Dest->getType();
7427     QualType PointeeTy;
7428     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
7429       PointeeTy = DestPtrTy->getPointeeType();
7430 
7431       // Never warn about void type pointers. This can be used to suppress
7432       // false positives.
7433       if (PointeeTy->isVoidType())
7434         continue;
7435 
7436       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
7437       // actually comparing the expressions for equality. Because computing the
7438       // expression IDs can be expensive, we only do this if the diagnostic is
7439       // enabled.
7440       if (SizeOfArg &&
7441           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
7442                            SizeOfArg->getExprLoc())) {
7443         // We only compute IDs for expressions if the warning is enabled, and
7444         // cache the sizeof arg's ID.
7445         if (SizeOfArgID == llvm::FoldingSetNodeID())
7446           SizeOfArg->Profile(SizeOfArgID, Context, true);
7447         llvm::FoldingSetNodeID DestID;
7448         Dest->Profile(DestID, Context, true);
7449         if (DestID == SizeOfArgID) {
7450           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
7451           //       over sizeof(src) as well.
7452           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
7453           StringRef ReadableName = FnName->getName();
7454 
7455           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
7456             if (UnaryOp->getOpcode() == UO_AddrOf)
7457               ActionIdx = 1; // If its an address-of operator, just remove it.
7458           if (!PointeeTy->isIncompleteType() &&
7459               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
7460             ActionIdx = 2; // If the pointee's size is sizeof(char),
7461                            // suggest an explicit length.
7462 
7463           // If the function is defined as a builtin macro, do not show macro
7464           // expansion.
7465           SourceLocation SL = SizeOfArg->getExprLoc();
7466           SourceRange DSR = Dest->getSourceRange();
7467           SourceRange SSR = SizeOfArg->getSourceRange();
7468           SourceManager &SM = getSourceManager();
7469 
7470           if (SM.isMacroArgExpansion(SL)) {
7471             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7472             SL = SM.getSpellingLoc(SL);
7473             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7474                              SM.getSpellingLoc(DSR.getEnd()));
7475             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7476                              SM.getSpellingLoc(SSR.getEnd()));
7477           }
7478 
7479           DiagRuntimeBehavior(SL, SizeOfArg,
7480                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
7481                                 << ReadableName
7482                                 << PointeeTy
7483                                 << DestTy
7484                                 << DSR
7485                                 << SSR);
7486           DiagRuntimeBehavior(SL, SizeOfArg,
7487                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7488                                 << ActionIdx
7489                                 << SSR);
7490 
7491           break;
7492         }
7493       }
7494 
7495       // Also check for cases where the sizeof argument is the exact same
7496       // type as the memory argument, and where it points to a user-defined
7497       // record type.
7498       if (SizeOfArgTy != QualType()) {
7499         if (PointeeTy->isRecordType() &&
7500             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7501           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7502                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
7503                                 << FnName << SizeOfArgTy << ArgIdx
7504                                 << PointeeTy << Dest->getSourceRange()
7505                                 << LenExpr->getSourceRange());
7506           break;
7507         }
7508       }
7509     } else if (DestTy->isArrayType()) {
7510       PointeeTy = DestTy;
7511     }
7512 
7513     if (PointeeTy == QualType())
7514       continue;
7515 
7516     // Always complain about dynamic classes.
7517     bool IsContained;
7518     if (const CXXRecordDecl *ContainedRD =
7519             getContainedDynamicClass(PointeeTy, IsContained)) {
7520 
7521       unsigned OperationType = 0;
7522       // "overwritten" if we're warning about the destination for any call
7523       // but memcmp; otherwise a verb appropriate to the call.
7524       if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7525         if (BId == Builtin::BImemcpy)
7526           OperationType = 1;
7527         else if(BId == Builtin::BImemmove)
7528           OperationType = 2;
7529         else if (BId == Builtin::BImemcmp)
7530           OperationType = 3;
7531       }
7532 
7533       DiagRuntimeBehavior(
7534         Dest->getExprLoc(), Dest,
7535         PDiag(diag::warn_dyn_class_memaccess)
7536           << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7537           << FnName << IsContained << ContainedRD << OperationType
7538           << Call->getCallee()->getSourceRange());
7539     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7540              BId != Builtin::BImemset)
7541       DiagRuntimeBehavior(
7542         Dest->getExprLoc(), Dest,
7543         PDiag(diag::warn_arc_object_memaccess)
7544           << ArgIdx << FnName << PointeeTy
7545           << Call->getCallee()->getSourceRange());
7546     else
7547       continue;
7548 
7549     DiagRuntimeBehavior(
7550       Dest->getExprLoc(), Dest,
7551       PDiag(diag::note_bad_memaccess_silence)
7552         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7553     break;
7554   }
7555 }
7556 
7557 // A little helper routine: ignore addition and subtraction of integer literals.
7558 // This intentionally does not ignore all integer constant expressions because
7559 // we don't want to remove sizeof().
7560 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7561   Ex = Ex->IgnoreParenCasts();
7562 
7563   while (true) {
7564     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7565     if (!BO || !BO->isAdditiveOp())
7566       break;
7567 
7568     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7569     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7570 
7571     if (isa<IntegerLiteral>(RHS))
7572       Ex = LHS;
7573     else if (isa<IntegerLiteral>(LHS))
7574       Ex = RHS;
7575     else
7576       break;
7577   }
7578 
7579   return Ex;
7580 }
7581 
7582 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7583                                                       ASTContext &Context) {
7584   // Only handle constant-sized or VLAs, but not flexible members.
7585   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7586     // Only issue the FIXIT for arrays of size > 1.
7587     if (CAT->getSize().getSExtValue() <= 1)
7588       return false;
7589   } else if (!Ty->isVariableArrayType()) {
7590     return false;
7591   }
7592   return true;
7593 }
7594 
7595 // Warn if the user has made the 'size' argument to strlcpy or strlcat
7596 // be the size of the source, instead of the destination.
7597 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7598                                     IdentifierInfo *FnName) {
7599 
7600   // Don't crash if the user has the wrong number of arguments
7601   unsigned NumArgs = Call->getNumArgs();
7602   if ((NumArgs != 3) && (NumArgs != 4))
7603     return;
7604 
7605   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7606   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
7607   const Expr *CompareWithSrc = nullptr;
7608 
7609   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7610                                      Call->getLocStart(), Call->getRParenLoc()))
7611     return;
7612 
7613   // Look for 'strlcpy(dst, x, sizeof(x))'
7614   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7615     CompareWithSrc = Ex;
7616   else {
7617     // Look for 'strlcpy(dst, x, strlen(x))'
7618     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
7619       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7620           SizeCall->getNumArgs() == 1)
7621         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7622     }
7623   }
7624 
7625   if (!CompareWithSrc)
7626     return;
7627 
7628   // Determine if the argument to sizeof/strlen is equal to the source
7629   // argument.  In principle there's all kinds of things you could do
7630   // here, for instance creating an == expression and evaluating it with
7631   // EvaluateAsBooleanCondition, but this uses a more direct technique:
7632   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7633   if (!SrcArgDRE)
7634     return;
7635 
7636   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7637   if (!CompareWithSrcDRE ||
7638       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7639     return;
7640 
7641   const Expr *OriginalSizeArg = Call->getArg(2);
7642   Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7643     << OriginalSizeArg->getSourceRange() << FnName;
7644 
7645   // Output a FIXIT hint if the destination is an array (rather than a
7646   // pointer to an array).  This could be enhanced to handle some
7647   // pointers if we know the actual size, like if DstArg is 'array+2'
7648   // we could say 'sizeof(array)-2'.
7649   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
7650   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
7651     return;
7652 
7653   SmallString<128> sizeString;
7654   llvm::raw_svector_ostream OS(sizeString);
7655   OS << "sizeof(";
7656   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7657   OS << ")";
7658 
7659   Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7660     << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7661                                     OS.str());
7662 }
7663 
7664 /// Check if two expressions refer to the same declaration.
7665 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7666   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7667     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7668       return D1->getDecl() == D2->getDecl();
7669   return false;
7670 }
7671 
7672 static const Expr *getStrlenExprArg(const Expr *E) {
7673   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7674     const FunctionDecl *FD = CE->getDirectCallee();
7675     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
7676       return nullptr;
7677     return CE->getArg(0)->IgnoreParenCasts();
7678   }
7679   return nullptr;
7680 }
7681 
7682 // Warn on anti-patterns as the 'size' argument to strncat.
7683 // The correct size argument should look like following:
7684 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7685 void Sema::CheckStrncatArguments(const CallExpr *CE,
7686                                  IdentifierInfo *FnName) {
7687   // Don't crash if the user has the wrong number of arguments.
7688   if (CE->getNumArgs() < 3)
7689     return;
7690   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7691   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7692   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7693 
7694   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7695                                      CE->getRParenLoc()))
7696     return;
7697 
7698   // Identify common expressions, which are wrongly used as the size argument
7699   // to strncat and may lead to buffer overflows.
7700   unsigned PatternType = 0;
7701   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7702     // - sizeof(dst)
7703     if (referToTheSameDecl(SizeOfArg, DstArg))
7704       PatternType = 1;
7705     // - sizeof(src)
7706     else if (referToTheSameDecl(SizeOfArg, SrcArg))
7707       PatternType = 2;
7708   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7709     if (BE->getOpcode() == BO_Sub) {
7710       const Expr *L = BE->getLHS()->IgnoreParenCasts();
7711       const Expr *R = BE->getRHS()->IgnoreParenCasts();
7712       // - sizeof(dst) - strlen(dst)
7713       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7714           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7715         PatternType = 1;
7716       // - sizeof(src) - (anything)
7717       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7718         PatternType = 2;
7719     }
7720   }
7721 
7722   if (PatternType == 0)
7723     return;
7724 
7725   // Generate the diagnostic.
7726   SourceLocation SL = LenArg->getLocStart();
7727   SourceRange SR = LenArg->getSourceRange();
7728   SourceManager &SM = getSourceManager();
7729 
7730   // If the function is defined as a builtin macro, do not show macro expansion.
7731   if (SM.isMacroArgExpansion(SL)) {
7732     SL = SM.getSpellingLoc(SL);
7733     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7734                      SM.getSpellingLoc(SR.getEnd()));
7735   }
7736 
7737   // Check if the destination is an array (rather than a pointer to an array).
7738   QualType DstTy = DstArg->getType();
7739   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7740                                                                     Context);
7741   if (!isKnownSizeArray) {
7742     if (PatternType == 1)
7743       Diag(SL, diag::warn_strncat_wrong_size) << SR;
7744     else
7745       Diag(SL, diag::warn_strncat_src_size) << SR;
7746     return;
7747   }
7748 
7749   if (PatternType == 1)
7750     Diag(SL, diag::warn_strncat_large_size) << SR;
7751   else
7752     Diag(SL, diag::warn_strncat_src_size) << SR;
7753 
7754   SmallString<128> sizeString;
7755   llvm::raw_svector_ostream OS(sizeString);
7756   OS << "sizeof(";
7757   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7758   OS << ") - ";
7759   OS << "strlen(";
7760   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7761   OS << ") - 1";
7762 
7763   Diag(SL, diag::note_strncat_wrong_size)
7764     << FixItHint::CreateReplacement(SR, OS.str());
7765 }
7766 
7767 //===--- CHECK: Return Address of Stack Variable --------------------------===//
7768 
7769 static const Expr *EvalVal(const Expr *E,
7770                            SmallVectorImpl<const DeclRefExpr *> &refVars,
7771                            const Decl *ParentDecl);
7772 static const Expr *EvalAddr(const Expr *E,
7773                             SmallVectorImpl<const DeclRefExpr *> &refVars,
7774                             const Decl *ParentDecl);
7775 
7776 /// CheckReturnStackAddr - Check if a return statement returns the address
7777 ///   of a stack variable.
7778 static void
7779 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7780                      SourceLocation ReturnLoc) {
7781   const Expr *stackE = nullptr;
7782   SmallVector<const DeclRefExpr *, 8> refVars;
7783 
7784   // Perform checking for returned stack addresses, local blocks,
7785   // label addresses or references to temporaries.
7786   if (lhsType->isPointerType() ||
7787       (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
7788     stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
7789   } else if (lhsType->isReferenceType()) {
7790     stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
7791   }
7792 
7793   if (!stackE)
7794     return; // Nothing suspicious was found.
7795 
7796   // Parameters are initialized in the calling scope, so taking the address
7797   // of a parameter reference doesn't need a warning.
7798   for (auto *DRE : refVars)
7799     if (isa<ParmVarDecl>(DRE->getDecl()))
7800       return;
7801 
7802   SourceLocation diagLoc;
7803   SourceRange diagRange;
7804   if (refVars.empty()) {
7805     diagLoc = stackE->getLocStart();
7806     diagRange = stackE->getSourceRange();
7807   } else {
7808     // We followed through a reference variable. 'stackE' contains the
7809     // problematic expression but we will warn at the return statement pointing
7810     // at the reference variable. We will later display the "trail" of
7811     // reference variables using notes.
7812     diagLoc = refVars[0]->getLocStart();
7813     diagRange = refVars[0]->getSourceRange();
7814   }
7815 
7816   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7817     // address of local var
7818     S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
7819      << DR->getDecl()->getDeclName() << diagRange;
7820   } else if (isa<BlockExpr>(stackE)) { // local block.
7821     S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
7822   } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
7823     S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
7824   } else { // local temporary.
7825     // If there is an LValue->RValue conversion, then the value of the
7826     // reference type is used, not the reference.
7827     if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7828       if (ICE->getCastKind() == CK_LValueToRValue) {
7829         return;
7830       }
7831     }
7832     S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7833      << lhsType->isReferenceType() << diagRange;
7834   }
7835 
7836   // Display the "trail" of reference variables that we followed until we
7837   // found the problematic expression using notes.
7838   for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
7839     const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
7840     // If this var binds to another reference var, show the range of the next
7841     // var, otherwise the var binds to the problematic expression, in which case
7842     // show the range of the expression.
7843     SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7844                                     : stackE->getSourceRange();
7845     S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7846         << VD->getDeclName() << range;
7847   }
7848 }
7849 
7850 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7851 ///  check if the expression in a return statement evaluates to an address
7852 ///  to a location on the stack, a local block, an address of a label, or a
7853 ///  reference to local temporary. The recursion is used to traverse the
7854 ///  AST of the return expression, with recursion backtracking when we
7855 ///  encounter a subexpression that (1) clearly does not lead to one of the
7856 ///  above problematic expressions (2) is something we cannot determine leads to
7857 ///  a problematic expression based on such local checking.
7858 ///
7859 ///  Both EvalAddr and EvalVal follow through reference variables to evaluate
7860 ///  the expression that they point to. Such variables are added to the
7861 ///  'refVars' vector so that we know what the reference variable "trail" was.
7862 ///
7863 ///  EvalAddr processes expressions that are pointers that are used as
7864 ///  references (and not L-values).  EvalVal handles all other values.
7865 ///  At the base case of the recursion is a check for the above problematic
7866 ///  expressions.
7867 ///
7868 ///  This implementation handles:
7869 ///
7870 ///   * pointer-to-pointer casts
7871 ///   * implicit conversions from array references to pointers
7872 ///   * taking the address of fields
7873 ///   * arbitrary interplay between "&" and "*" operators
7874 ///   * pointer arithmetic from an address of a stack variable
7875 ///   * taking the address of an array element where the array is on the stack
7876 static const Expr *EvalAddr(const Expr *E,
7877                             SmallVectorImpl<const DeclRefExpr *> &refVars,
7878                             const Decl *ParentDecl) {
7879   if (E->isTypeDependent())
7880     return nullptr;
7881 
7882   // We should only be called for evaluating pointer expressions.
7883   assert((E->getType()->isAnyPointerType() ||
7884           E->getType()->isBlockPointerType() ||
7885           E->getType()->isObjCQualifiedIdType()) &&
7886          "EvalAddr only works on pointers");
7887 
7888   E = E->IgnoreParens();
7889 
7890   // Our "symbolic interpreter" is just a dispatch off the currently
7891   // viewed AST node.  We then recursively traverse the AST by calling
7892   // EvalAddr and EvalVal appropriately.
7893   switch (E->getStmtClass()) {
7894   case Stmt::DeclRefExprClass: {
7895     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7896 
7897     // If we leave the immediate function, the lifetime isn't about to end.
7898     if (DR->refersToEnclosingVariableOrCapture())
7899       return nullptr;
7900 
7901     if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
7902       // If this is a reference variable, follow through to the expression that
7903       // it points to.
7904       if (V->hasLocalStorage() &&
7905           V->getType()->isReferenceType() && V->hasInit()) {
7906         // Add the reference variable to the "trail".
7907         refVars.push_back(DR);
7908         return EvalAddr(V->getInit(), refVars, ParentDecl);
7909       }
7910 
7911     return nullptr;
7912   }
7913 
7914   case Stmt::UnaryOperatorClass: {
7915     // The only unary operator that make sense to handle here
7916     // is AddrOf.  All others don't make sense as pointers.
7917     const UnaryOperator *U = cast<UnaryOperator>(E);
7918 
7919     if (U->getOpcode() == UO_AddrOf)
7920       return EvalVal(U->getSubExpr(), refVars, ParentDecl);
7921     return nullptr;
7922   }
7923 
7924   case Stmt::BinaryOperatorClass: {
7925     // Handle pointer arithmetic.  All other binary operators are not valid
7926     // in this context.
7927     const BinaryOperator *B = cast<BinaryOperator>(E);
7928     BinaryOperatorKind op = B->getOpcode();
7929 
7930     if (op != BO_Add && op != BO_Sub)
7931       return nullptr;
7932 
7933     const Expr *Base = B->getLHS();
7934 
7935     // Determine which argument is the real pointer base.  It could be
7936     // the RHS argument instead of the LHS.
7937     if (!Base->getType()->isPointerType())
7938       Base = B->getRHS();
7939 
7940     assert(Base->getType()->isPointerType());
7941     return EvalAddr(Base, refVars, ParentDecl);
7942   }
7943 
7944   // For conditional operators we need to see if either the LHS or RHS are
7945   // valid DeclRefExpr*s.  If one of them is valid, we return it.
7946   case Stmt::ConditionalOperatorClass: {
7947     const ConditionalOperator *C = cast<ConditionalOperator>(E);
7948 
7949     // Handle the GNU extension for missing LHS.
7950     // FIXME: That isn't a ConditionalOperator, so doesn't get here.
7951     if (const Expr *LHSExpr = C->getLHS()) {
7952       // In C++, we can have a throw-expression, which has 'void' type.
7953       if (!LHSExpr->getType()->isVoidType())
7954         if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
7955           return LHS;
7956     }
7957 
7958     // In C++, we can have a throw-expression, which has 'void' type.
7959     if (C->getRHS()->getType()->isVoidType())
7960       return nullptr;
7961 
7962     return EvalAddr(C->getRHS(), refVars, ParentDecl);
7963   }
7964 
7965   case Stmt::BlockExprClass:
7966     if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
7967       return E; // local block.
7968     return nullptr;
7969 
7970   case Stmt::AddrLabelExprClass:
7971     return E; // address of label.
7972 
7973   case Stmt::ExprWithCleanupsClass:
7974     return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7975                     ParentDecl);
7976 
7977   // For casts, we need to handle conversions from arrays to
7978   // pointer values, and pointer-to-pointer conversions.
7979   case Stmt::ImplicitCastExprClass:
7980   case Stmt::CStyleCastExprClass:
7981   case Stmt::CXXFunctionalCastExprClass:
7982   case Stmt::ObjCBridgedCastExprClass:
7983   case Stmt::CXXStaticCastExprClass:
7984   case Stmt::CXXDynamicCastExprClass:
7985   case Stmt::CXXConstCastExprClass:
7986   case Stmt::CXXReinterpretCastExprClass: {
7987     const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
7988     switch (cast<CastExpr>(E)->getCastKind()) {
7989     case CK_LValueToRValue:
7990     case CK_NoOp:
7991     case CK_BaseToDerived:
7992     case CK_DerivedToBase:
7993     case CK_UncheckedDerivedToBase:
7994     case CK_Dynamic:
7995     case CK_CPointerToObjCPointerCast:
7996     case CK_BlockPointerToObjCPointerCast:
7997     case CK_AnyPointerToBlockPointerCast:
7998       return EvalAddr(SubExpr, refVars, ParentDecl);
7999 
8000     case CK_ArrayToPointerDecay:
8001       return EvalVal(SubExpr, refVars, ParentDecl);
8002 
8003     case CK_BitCast:
8004       if (SubExpr->getType()->isAnyPointerType() ||
8005           SubExpr->getType()->isBlockPointerType() ||
8006           SubExpr->getType()->isObjCQualifiedIdType())
8007         return EvalAddr(SubExpr, refVars, ParentDecl);
8008       else
8009         return nullptr;
8010 
8011     default:
8012       return nullptr;
8013     }
8014   }
8015 
8016   case Stmt::MaterializeTemporaryExprClass:
8017     if (const Expr *Result =
8018             EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8019                      refVars, ParentDecl))
8020       return Result;
8021     return E;
8022 
8023   // Everything else: we simply don't reason about them.
8024   default:
8025     return nullptr;
8026   }
8027 }
8028 
8029 ///  EvalVal - This function is complements EvalAddr in the mutual recursion.
8030 ///   See the comments for EvalAddr for more details.
8031 static const Expr *EvalVal(const Expr *E,
8032                            SmallVectorImpl<const DeclRefExpr *> &refVars,
8033                            const Decl *ParentDecl) {
8034   do {
8035     // We should only be called for evaluating non-pointer expressions, or
8036     // expressions with a pointer type that are not used as references but
8037     // instead
8038     // are l-values (e.g., DeclRefExpr with a pointer type).
8039 
8040     // Our "symbolic interpreter" is just a dispatch off the currently
8041     // viewed AST node.  We then recursively traverse the AST by calling
8042     // EvalAddr and EvalVal appropriately.
8043 
8044     E = E->IgnoreParens();
8045     switch (E->getStmtClass()) {
8046     case Stmt::ImplicitCastExprClass: {
8047       const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
8048       if (IE->getValueKind() == VK_LValue) {
8049         E = IE->getSubExpr();
8050         continue;
8051       }
8052       return nullptr;
8053     }
8054 
8055     case Stmt::ExprWithCleanupsClass:
8056       return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
8057                      ParentDecl);
8058 
8059     case Stmt::DeclRefExprClass: {
8060       // When we hit a DeclRefExpr we are looking at code that refers to a
8061       // variable's name. If it's not a reference variable we check if it has
8062       // local storage within the function, and if so, return the expression.
8063       const DeclRefExpr *DR = cast<DeclRefExpr>(E);
8064 
8065       // If we leave the immediate function, the lifetime isn't about to end.
8066       if (DR->refersToEnclosingVariableOrCapture())
8067         return nullptr;
8068 
8069       if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
8070         // Check if it refers to itself, e.g. "int& i = i;".
8071         if (V == ParentDecl)
8072           return DR;
8073 
8074         if (V->hasLocalStorage()) {
8075           if (!V->getType()->isReferenceType())
8076             return DR;
8077 
8078           // Reference variable, follow through to the expression that
8079           // it points to.
8080           if (V->hasInit()) {
8081             // Add the reference variable to the "trail".
8082             refVars.push_back(DR);
8083             return EvalVal(V->getInit(), refVars, V);
8084           }
8085         }
8086       }
8087 
8088       return nullptr;
8089     }
8090 
8091     case Stmt::UnaryOperatorClass: {
8092       // The only unary operator that make sense to handle here
8093       // is Deref.  All others don't resolve to a "name."  This includes
8094       // handling all sorts of rvalues passed to a unary operator.
8095       const UnaryOperator *U = cast<UnaryOperator>(E);
8096 
8097       if (U->getOpcode() == UO_Deref)
8098         return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
8099 
8100       return nullptr;
8101     }
8102 
8103     case Stmt::ArraySubscriptExprClass: {
8104       // Array subscripts are potential references to data on the stack.  We
8105       // retrieve the DeclRefExpr* for the array variable if it indeed
8106       // has local storage.
8107       const auto *ASE = cast<ArraySubscriptExpr>(E);
8108       if (ASE->isTypeDependent())
8109         return nullptr;
8110       return EvalAddr(ASE->getBase(), refVars, ParentDecl);
8111     }
8112 
8113     case Stmt::OMPArraySectionExprClass: {
8114       return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
8115                       ParentDecl);
8116     }
8117 
8118     case Stmt::ConditionalOperatorClass: {
8119       // For conditional operators we need to see if either the LHS or RHS are
8120       // non-NULL Expr's.  If one is non-NULL, we return it.
8121       const ConditionalOperator *C = cast<ConditionalOperator>(E);
8122 
8123       // Handle the GNU extension for missing LHS.
8124       if (const Expr *LHSExpr = C->getLHS()) {
8125         // In C++, we can have a throw-expression, which has 'void' type.
8126         if (!LHSExpr->getType()->isVoidType())
8127           if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
8128             return LHS;
8129       }
8130 
8131       // In C++, we can have a throw-expression, which has 'void' type.
8132       if (C->getRHS()->getType()->isVoidType())
8133         return nullptr;
8134 
8135       return EvalVal(C->getRHS(), refVars, ParentDecl);
8136     }
8137 
8138     // Accesses to members are potential references to data on the stack.
8139     case Stmt::MemberExprClass: {
8140       const MemberExpr *M = cast<MemberExpr>(E);
8141 
8142       // Check for indirect access.  We only want direct field accesses.
8143       if (M->isArrow())
8144         return nullptr;
8145 
8146       // Check whether the member type is itself a reference, in which case
8147       // we're not going to refer to the member, but to what the member refers
8148       // to.
8149       if (M->getMemberDecl()->getType()->isReferenceType())
8150         return nullptr;
8151 
8152       return EvalVal(M->getBase(), refVars, ParentDecl);
8153     }
8154 
8155     case Stmt::MaterializeTemporaryExprClass:
8156       if (const Expr *Result =
8157               EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8158                       refVars, ParentDecl))
8159         return Result;
8160       return E;
8161 
8162     default:
8163       // Check that we don't return or take the address of a reference to a
8164       // temporary. This is only useful in C++.
8165       if (!E->isTypeDependent() && E->isRValue())
8166         return E;
8167 
8168       // Everything else: we simply don't reason about them.
8169       return nullptr;
8170     }
8171   } while (true);
8172 }
8173 
8174 void
8175 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
8176                          SourceLocation ReturnLoc,
8177                          bool isObjCMethod,
8178                          const AttrVec *Attrs,
8179                          const FunctionDecl *FD) {
8180   CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
8181 
8182   // Check if the return value is null but should not be.
8183   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
8184        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
8185       CheckNonNullExpr(*this, RetValExp))
8186     Diag(ReturnLoc, diag::warn_null_ret)
8187       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
8188 
8189   // C++11 [basic.stc.dynamic.allocation]p4:
8190   //   If an allocation function declared with a non-throwing
8191   //   exception-specification fails to allocate storage, it shall return
8192   //   a null pointer. Any other allocation function that fails to allocate
8193   //   storage shall indicate failure only by throwing an exception [...]
8194   if (FD) {
8195     OverloadedOperatorKind Op = FD->getOverloadedOperator();
8196     if (Op == OO_New || Op == OO_Array_New) {
8197       const FunctionProtoType *Proto
8198         = FD->getType()->castAs<FunctionProtoType>();
8199       if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
8200           CheckNonNullExpr(*this, RetValExp))
8201         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
8202           << FD << getLangOpts().CPlusPlus11;
8203     }
8204   }
8205 }
8206 
8207 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
8208 
8209 /// Check for comparisons of floating point operands using != and ==.
8210 /// Issue a warning if these are no self-comparisons, as they are not likely
8211 /// to do what the programmer intended.
8212 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
8213   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
8214   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
8215 
8216   // Special case: check for x == x (which is OK).
8217   // Do not emit warnings for such cases.
8218   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
8219     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
8220       if (DRL->getDecl() == DRR->getDecl())
8221         return;
8222 
8223   // Special case: check for comparisons against literals that can be exactly
8224   //  represented by APFloat.  In such cases, do not emit a warning.  This
8225   //  is a heuristic: often comparison against such literals are used to
8226   //  detect if a value in a variable has not changed.  This clearly can
8227   //  lead to false negatives.
8228   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
8229     if (FLL->isExact())
8230       return;
8231   } else
8232     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
8233       if (FLR->isExact())
8234         return;
8235 
8236   // Check for comparisons with builtin types.
8237   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
8238     if (CL->getBuiltinCallee())
8239       return;
8240 
8241   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
8242     if (CR->getBuiltinCallee())
8243       return;
8244 
8245   // Emit the diagnostic.
8246   Diag(Loc, diag::warn_floatingpoint_eq)
8247     << LHS->getSourceRange() << RHS->getSourceRange();
8248 }
8249 
8250 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
8251 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
8252 
8253 namespace {
8254 
8255 /// Structure recording the 'active' range of an integer-valued
8256 /// expression.
8257 struct IntRange {
8258   /// The number of bits active in the int.
8259   unsigned Width;
8260 
8261   /// True if the int is known not to have negative values.
8262   bool NonNegative;
8263 
8264   IntRange(unsigned Width, bool NonNegative)
8265       : Width(Width), NonNegative(NonNegative) {}
8266 
8267   /// Returns the range of the bool type.
8268   static IntRange forBoolType() {
8269     return IntRange(1, true);
8270   }
8271 
8272   /// Returns the range of an opaque value of the given integral type.
8273   static IntRange forValueOfType(ASTContext &C, QualType T) {
8274     return forValueOfCanonicalType(C,
8275                           T->getCanonicalTypeInternal().getTypePtr());
8276   }
8277 
8278   /// Returns the range of an opaque value of a canonical integral type.
8279   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
8280     assert(T->isCanonicalUnqualified());
8281 
8282     if (const VectorType *VT = dyn_cast<VectorType>(T))
8283       T = VT->getElementType().getTypePtr();
8284     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8285       T = CT->getElementType().getTypePtr();
8286     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8287       T = AT->getValueType().getTypePtr();
8288 
8289     if (!C.getLangOpts().CPlusPlus) {
8290       // For enum types in C code, use the underlying datatype.
8291       if (const EnumType *ET = dyn_cast<EnumType>(T))
8292         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
8293     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
8294       // For enum types in C++, use the known bit width of the enumerators.
8295       EnumDecl *Enum = ET->getDecl();
8296       // In C++11, enums can have a fixed underlying type. Use this type to
8297       // compute the range.
8298       if (Enum->isFixed()) {
8299         return IntRange(C.getIntWidth(QualType(T, 0)),
8300                         !ET->isSignedIntegerOrEnumerationType());
8301       }
8302 
8303       unsigned NumPositive = Enum->getNumPositiveBits();
8304       unsigned NumNegative = Enum->getNumNegativeBits();
8305 
8306       if (NumNegative == 0)
8307         return IntRange(NumPositive, true/*NonNegative*/);
8308       else
8309         return IntRange(std::max(NumPositive + 1, NumNegative),
8310                         false/*NonNegative*/);
8311     }
8312 
8313     const BuiltinType *BT = cast<BuiltinType>(T);
8314     assert(BT->isInteger());
8315 
8316     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8317   }
8318 
8319   /// Returns the "target" range of a canonical integral type, i.e.
8320   /// the range of values expressible in the type.
8321   ///
8322   /// This matches forValueOfCanonicalType except that enums have the
8323   /// full range of their type, not the range of their enumerators.
8324   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
8325     assert(T->isCanonicalUnqualified());
8326 
8327     if (const VectorType *VT = dyn_cast<VectorType>(T))
8328       T = VT->getElementType().getTypePtr();
8329     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8330       T = CT->getElementType().getTypePtr();
8331     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8332       T = AT->getValueType().getTypePtr();
8333     if (const EnumType *ET = dyn_cast<EnumType>(T))
8334       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
8335 
8336     const BuiltinType *BT = cast<BuiltinType>(T);
8337     assert(BT->isInteger());
8338 
8339     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8340   }
8341 
8342   /// Returns the supremum of two ranges: i.e. their conservative merge.
8343   static IntRange join(IntRange L, IntRange R) {
8344     return IntRange(std::max(L.Width, R.Width),
8345                     L.NonNegative && R.NonNegative);
8346   }
8347 
8348   /// Returns the infinum of two ranges: i.e. their aggressive merge.
8349   static IntRange meet(IntRange L, IntRange R) {
8350     return IntRange(std::min(L.Width, R.Width),
8351                     L.NonNegative || R.NonNegative);
8352   }
8353 };
8354 
8355 } // namespace
8356 
8357 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
8358                               unsigned MaxWidth) {
8359   if (value.isSigned() && value.isNegative())
8360     return IntRange(value.getMinSignedBits(), false);
8361 
8362   if (value.getBitWidth() > MaxWidth)
8363     value = value.trunc(MaxWidth);
8364 
8365   // isNonNegative() just checks the sign bit without considering
8366   // signedness.
8367   return IntRange(value.getActiveBits(), true);
8368 }
8369 
8370 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
8371                               unsigned MaxWidth) {
8372   if (result.isInt())
8373     return GetValueRange(C, result.getInt(), MaxWidth);
8374 
8375   if (result.isVector()) {
8376     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
8377     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
8378       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
8379       R = IntRange::join(R, El);
8380     }
8381     return R;
8382   }
8383 
8384   if (result.isComplexInt()) {
8385     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
8386     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
8387     return IntRange::join(R, I);
8388   }
8389 
8390   // This can happen with lossless casts to intptr_t of "based" lvalues.
8391   // Assume it might use arbitrary bits.
8392   // FIXME: The only reason we need to pass the type in here is to get
8393   // the sign right on this one case.  It would be nice if APValue
8394   // preserved this.
8395   assert(result.isLValue() || result.isAddrLabelDiff());
8396   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
8397 }
8398 
8399 static QualType GetExprType(const Expr *E) {
8400   QualType Ty = E->getType();
8401   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
8402     Ty = AtomicRHS->getValueType();
8403   return Ty;
8404 }
8405 
8406 /// Pseudo-evaluate the given integer expression, estimating the
8407 /// range of values it might take.
8408 ///
8409 /// \param MaxWidth - the width to which the value will be truncated
8410 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
8411   E = E->IgnoreParens();
8412 
8413   // Try a full evaluation first.
8414   Expr::EvalResult result;
8415   if (E->EvaluateAsRValue(result, C))
8416     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
8417 
8418   // I think we only want to look through implicit casts here; if the
8419   // user has an explicit widening cast, we should treat the value as
8420   // being of the new, wider type.
8421   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
8422     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
8423       return GetExprRange(C, CE->getSubExpr(), MaxWidth);
8424 
8425     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
8426 
8427     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
8428                          CE->getCastKind() == CK_BooleanToSignedIntegral;
8429 
8430     // Assume that non-integer casts can span the full range of the type.
8431     if (!isIntegerCast)
8432       return OutputTypeRange;
8433 
8434     IntRange SubRange
8435       = GetExprRange(C, CE->getSubExpr(),
8436                      std::min(MaxWidth, OutputTypeRange.Width));
8437 
8438     // Bail out if the subexpr's range is as wide as the cast type.
8439     if (SubRange.Width >= OutputTypeRange.Width)
8440       return OutputTypeRange;
8441 
8442     // Otherwise, we take the smaller width, and we're non-negative if
8443     // either the output type or the subexpr is.
8444     return IntRange(SubRange.Width,
8445                     SubRange.NonNegative || OutputTypeRange.NonNegative);
8446   }
8447 
8448   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
8449     // If we can fold the condition, just take that operand.
8450     bool CondResult;
8451     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
8452       return GetExprRange(C, CondResult ? CO->getTrueExpr()
8453                                         : CO->getFalseExpr(),
8454                           MaxWidth);
8455 
8456     // Otherwise, conservatively merge.
8457     IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
8458     IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
8459     return IntRange::join(L, R);
8460   }
8461 
8462   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
8463     switch (BO->getOpcode()) {
8464     case BO_Cmp:
8465       llvm_unreachable("builtin <=> should have class type");
8466 
8467     // Boolean-valued operations are single-bit and positive.
8468     case BO_LAnd:
8469     case BO_LOr:
8470     case BO_LT:
8471     case BO_GT:
8472     case BO_LE:
8473     case BO_GE:
8474     case BO_EQ:
8475     case BO_NE:
8476       return IntRange::forBoolType();
8477 
8478     // The type of the assignments is the type of the LHS, so the RHS
8479     // is not necessarily the same type.
8480     case BO_MulAssign:
8481     case BO_DivAssign:
8482     case BO_RemAssign:
8483     case BO_AddAssign:
8484     case BO_SubAssign:
8485     case BO_XorAssign:
8486     case BO_OrAssign:
8487       // TODO: bitfields?
8488       return IntRange::forValueOfType(C, GetExprType(E));
8489 
8490     // Simple assignments just pass through the RHS, which will have
8491     // been coerced to the LHS type.
8492     case BO_Assign:
8493       // TODO: bitfields?
8494       return GetExprRange(C, BO->getRHS(), MaxWidth);
8495 
8496     // Operations with opaque sources are black-listed.
8497     case BO_PtrMemD:
8498     case BO_PtrMemI:
8499       return IntRange::forValueOfType(C, GetExprType(E));
8500 
8501     // Bitwise-and uses the *infinum* of the two source ranges.
8502     case BO_And:
8503     case BO_AndAssign:
8504       return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8505                             GetExprRange(C, BO->getRHS(), MaxWidth));
8506 
8507     // Left shift gets black-listed based on a judgement call.
8508     case BO_Shl:
8509       // ...except that we want to treat '1 << (blah)' as logically
8510       // positive.  It's an important idiom.
8511       if (IntegerLiteral *I
8512             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8513         if (I->getValue() == 1) {
8514           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
8515           return IntRange(R.Width, /*NonNegative*/ true);
8516         }
8517       }
8518       LLVM_FALLTHROUGH;
8519 
8520     case BO_ShlAssign:
8521       return IntRange::forValueOfType(C, GetExprType(E));
8522 
8523     // Right shift by a constant can narrow its left argument.
8524     case BO_Shr:
8525     case BO_ShrAssign: {
8526       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8527 
8528       // If the shift amount is a positive constant, drop the width by
8529       // that much.
8530       llvm::APSInt shift;
8531       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8532           shift.isNonNegative()) {
8533         unsigned zext = shift.getZExtValue();
8534         if (zext >= L.Width)
8535           L.Width = (L.NonNegative ? 0 : 1);
8536         else
8537           L.Width -= zext;
8538       }
8539 
8540       return L;
8541     }
8542 
8543     // Comma acts as its right operand.
8544     case BO_Comma:
8545       return GetExprRange(C, BO->getRHS(), MaxWidth);
8546 
8547     // Black-list pointer subtractions.
8548     case BO_Sub:
8549       if (BO->getLHS()->getType()->isPointerType())
8550         return IntRange::forValueOfType(C, GetExprType(E));
8551       break;
8552 
8553     // The width of a division result is mostly determined by the size
8554     // of the LHS.
8555     case BO_Div: {
8556       // Don't 'pre-truncate' the operands.
8557       unsigned opWidth = C.getIntWidth(GetExprType(E));
8558       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8559 
8560       // If the divisor is constant, use that.
8561       llvm::APSInt divisor;
8562       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8563         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8564         if (log2 >= L.Width)
8565           L.Width = (L.NonNegative ? 0 : 1);
8566         else
8567           L.Width = std::min(L.Width - log2, MaxWidth);
8568         return L;
8569       }
8570 
8571       // Otherwise, just use the LHS's width.
8572       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8573       return IntRange(L.Width, L.NonNegative && R.NonNegative);
8574     }
8575 
8576     // The result of a remainder can't be larger than the result of
8577     // either side.
8578     case BO_Rem: {
8579       // Don't 'pre-truncate' the operands.
8580       unsigned opWidth = C.getIntWidth(GetExprType(E));
8581       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8582       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8583 
8584       IntRange meet = IntRange::meet(L, R);
8585       meet.Width = std::min(meet.Width, MaxWidth);
8586       return meet;
8587     }
8588 
8589     // The default behavior is okay for these.
8590     case BO_Mul:
8591     case BO_Add:
8592     case BO_Xor:
8593     case BO_Or:
8594       break;
8595     }
8596 
8597     // The default case is to treat the operation as if it were closed
8598     // on the narrowest type that encompasses both operands.
8599     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8600     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8601     return IntRange::join(L, R);
8602   }
8603 
8604   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
8605     switch (UO->getOpcode()) {
8606     // Boolean-valued operations are white-listed.
8607     case UO_LNot:
8608       return IntRange::forBoolType();
8609 
8610     // Operations with opaque sources are black-listed.
8611     case UO_Deref:
8612     case UO_AddrOf: // should be impossible
8613       return IntRange::forValueOfType(C, GetExprType(E));
8614 
8615     default:
8616       return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8617     }
8618   }
8619 
8620   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
8621     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8622 
8623   if (const auto *BitField = E->getSourceBitField())
8624     return IntRange(BitField->getBitWidthValue(C),
8625                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
8626 
8627   return IntRange::forValueOfType(C, GetExprType(E));
8628 }
8629 
8630 static IntRange GetExprRange(ASTContext &C, const Expr *E) {
8631   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
8632 }
8633 
8634 /// Checks whether the given value, which currently has the given
8635 /// source semantics, has the same value when coerced through the
8636 /// target semantics.
8637 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
8638                                  const llvm::fltSemantics &Src,
8639                                  const llvm::fltSemantics &Tgt) {
8640   llvm::APFloat truncated = value;
8641 
8642   bool ignored;
8643   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8644   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8645 
8646   return truncated.bitwiseIsEqual(value);
8647 }
8648 
8649 /// Checks whether the given value, which currently has the given
8650 /// source semantics, has the same value when coerced through the
8651 /// target semantics.
8652 ///
8653 /// The value might be a vector of floats (or a complex number).
8654 static bool IsSameFloatAfterCast(const APValue &value,
8655                                  const llvm::fltSemantics &Src,
8656                                  const llvm::fltSemantics &Tgt) {
8657   if (value.isFloat())
8658     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8659 
8660   if (value.isVector()) {
8661     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8662       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8663         return false;
8664     return true;
8665   }
8666 
8667   assert(value.isComplexFloat());
8668   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8669           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8670 }
8671 
8672 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
8673 
8674 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
8675   // Suppress cases where we are comparing against an enum constant.
8676   if (const DeclRefExpr *DR =
8677       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8678     if (isa<EnumConstantDecl>(DR->getDecl()))
8679       return true;
8680 
8681   // Suppress cases where the '0' value is expanded from a macro.
8682   if (E->getLocStart().isMacroID())
8683     return true;
8684 
8685   return false;
8686 }
8687 
8688 static bool isKnownToHaveUnsignedValue(Expr *E) {
8689   return E->getType()->isIntegerType() &&
8690          (!E->getType()->isSignedIntegerType() ||
8691           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
8692 }
8693 
8694 namespace {
8695 /// The promoted range of values of a type. In general this has the
8696 /// following structure:
8697 ///
8698 ///     |-----------| . . . |-----------|
8699 ///     ^           ^       ^           ^
8700 ///    Min       HoleMin  HoleMax      Max
8701 ///
8702 /// ... where there is only a hole if a signed type is promoted to unsigned
8703 /// (in which case Min and Max are the smallest and largest representable
8704 /// values).
8705 struct PromotedRange {
8706   // Min, or HoleMax if there is a hole.
8707   llvm::APSInt PromotedMin;
8708   // Max, or HoleMin if there is a hole.
8709   llvm::APSInt PromotedMax;
8710 
8711   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
8712     if (R.Width == 0)
8713       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
8714     else if (R.Width >= BitWidth && !Unsigned) {
8715       // Promotion made the type *narrower*. This happens when promoting
8716       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
8717       // Treat all values of 'signed int' as being in range for now.
8718       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
8719       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
8720     } else {
8721       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
8722                         .extOrTrunc(BitWidth);
8723       PromotedMin.setIsUnsigned(Unsigned);
8724 
8725       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
8726                         .extOrTrunc(BitWidth);
8727       PromotedMax.setIsUnsigned(Unsigned);
8728     }
8729   }
8730 
8731   // Determine whether this range is contiguous (has no hole).
8732   bool isContiguous() const { return PromotedMin <= PromotedMax; }
8733 
8734   // Where a constant value is within the range.
8735   enum ComparisonResult {
8736     LT = 0x1,
8737     LE = 0x2,
8738     GT = 0x4,
8739     GE = 0x8,
8740     EQ = 0x10,
8741     NE = 0x20,
8742     InRangeFlag = 0x40,
8743 
8744     Less = LE | LT | NE,
8745     Min = LE | InRangeFlag,
8746     InRange = InRangeFlag,
8747     Max = GE | InRangeFlag,
8748     Greater = GE | GT | NE,
8749 
8750     OnlyValue = LE | GE | EQ | InRangeFlag,
8751     InHole = NE
8752   };
8753 
8754   ComparisonResult compare(const llvm::APSInt &Value) const {
8755     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
8756            Value.isUnsigned() == PromotedMin.isUnsigned());
8757     if (!isContiguous()) {
8758       assert(Value.isUnsigned() && "discontiguous range for signed compare");
8759       if (Value.isMinValue()) return Min;
8760       if (Value.isMaxValue()) return Max;
8761       if (Value >= PromotedMin) return InRange;
8762       if (Value <= PromotedMax) return InRange;
8763       return InHole;
8764     }
8765 
8766     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
8767     case -1: return Less;
8768     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
8769     case 1:
8770       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
8771       case -1: return InRange;
8772       case 0: return Max;
8773       case 1: return Greater;
8774       }
8775     }
8776 
8777     llvm_unreachable("impossible compare result");
8778   }
8779 
8780   static llvm::Optional<StringRef>
8781   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
8782     if (Op == BO_Cmp) {
8783       ComparisonResult LTFlag = LT, GTFlag = GT;
8784       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
8785 
8786       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
8787       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
8788       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
8789       return llvm::None;
8790     }
8791 
8792     ComparisonResult TrueFlag, FalseFlag;
8793     if (Op == BO_EQ) {
8794       TrueFlag = EQ;
8795       FalseFlag = NE;
8796     } else if (Op == BO_NE) {
8797       TrueFlag = NE;
8798       FalseFlag = EQ;
8799     } else {
8800       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
8801         TrueFlag = LT;
8802         FalseFlag = GE;
8803       } else {
8804         TrueFlag = GT;
8805         FalseFlag = LE;
8806       }
8807       if (Op == BO_GE || Op == BO_LE)
8808         std::swap(TrueFlag, FalseFlag);
8809     }
8810     if (R & TrueFlag)
8811       return StringRef("true");
8812     if (R & FalseFlag)
8813       return StringRef("false");
8814     return llvm::None;
8815   }
8816 };
8817 }
8818 
8819 static bool HasEnumType(Expr *E) {
8820   // Strip off implicit integral promotions.
8821   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8822     if (ICE->getCastKind() != CK_IntegralCast &&
8823         ICE->getCastKind() != CK_NoOp)
8824       break;
8825     E = ICE->getSubExpr();
8826   }
8827 
8828   return E->getType()->isEnumeralType();
8829 }
8830 
8831 static int classifyConstantValue(Expr *Constant) {
8832   // The values of this enumeration are used in the diagnostics
8833   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
8834   enum ConstantValueKind {
8835     Miscellaneous = 0,
8836     LiteralTrue,
8837     LiteralFalse
8838   };
8839   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
8840     return BL->getValue() ? ConstantValueKind::LiteralTrue
8841                           : ConstantValueKind::LiteralFalse;
8842   return ConstantValueKind::Miscellaneous;
8843 }
8844 
8845 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
8846                                         Expr *Constant, Expr *Other,
8847                                         const llvm::APSInt &Value,
8848                                         bool RhsConstant) {
8849   if (S.inTemplateInstantiation())
8850     return false;
8851 
8852   Expr *OriginalOther = Other;
8853 
8854   Constant = Constant->IgnoreParenImpCasts();
8855   Other = Other->IgnoreParenImpCasts();
8856 
8857   // Suppress warnings on tautological comparisons between values of the same
8858   // enumeration type. There are only two ways we could warn on this:
8859   //  - If the constant is outside the range of representable values of
8860   //    the enumeration. In such a case, we should warn about the cast
8861   //    to enumeration type, not about the comparison.
8862   //  - If the constant is the maximum / minimum in-range value. For an
8863   //    enumeratin type, such comparisons can be meaningful and useful.
8864   if (Constant->getType()->isEnumeralType() &&
8865       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
8866     return false;
8867 
8868   // TODO: Investigate using GetExprRange() to get tighter bounds
8869   // on the bit ranges.
8870   QualType OtherT = Other->getType();
8871   if (const auto *AT = OtherT->getAs<AtomicType>())
8872     OtherT = AT->getValueType();
8873   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8874 
8875   // Whether we're treating Other as being a bool because of the form of
8876   // expression despite it having another type (typically 'int' in C).
8877   bool OtherIsBooleanDespiteType =
8878       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
8879   if (OtherIsBooleanDespiteType)
8880     OtherRange = IntRange::forBoolType();
8881 
8882   // Determine the promoted range of the other type and see if a comparison of
8883   // the constant against that range is tautological.
8884   PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
8885                                    Value.isUnsigned());
8886   auto Cmp = OtherPromotedRange.compare(Value);
8887   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
8888   if (!Result)
8889     return false;
8890 
8891   // Suppress the diagnostic for an in-range comparison if the constant comes
8892   // from a macro or enumerator. We don't want to diagnose
8893   //
8894   //   some_long_value <= INT_MAX
8895   //
8896   // when sizeof(int) == sizeof(long).
8897   bool InRange = Cmp & PromotedRange::InRangeFlag;
8898   if (InRange && IsEnumConstOrFromMacro(S, Constant))
8899     return false;
8900 
8901   // If this is a comparison to an enum constant, include that
8902   // constant in the diagnostic.
8903   const EnumConstantDecl *ED = nullptr;
8904   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8905     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8906 
8907   // Should be enough for uint128 (39 decimal digits)
8908   SmallString<64> PrettySourceValue;
8909   llvm::raw_svector_ostream OS(PrettySourceValue);
8910   if (ED)
8911     OS << '\'' << *ED << "' (" << Value << ")";
8912   else
8913     OS << Value;
8914 
8915   // FIXME: We use a somewhat different formatting for the in-range cases and
8916   // cases involving boolean values for historical reasons. We should pick a
8917   // consistent way of presenting these diagnostics.
8918   if (!InRange || Other->isKnownToHaveBooleanValue()) {
8919     S.DiagRuntimeBehavior(
8920       E->getOperatorLoc(), E,
8921       S.PDiag(!InRange ? diag::warn_out_of_range_compare
8922                        : diag::warn_tautological_bool_compare)
8923           << OS.str() << classifyConstantValue(Constant)
8924           << OtherT << OtherIsBooleanDespiteType << *Result
8925           << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
8926   } else {
8927     unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
8928                         ? (HasEnumType(OriginalOther)
8929                                ? diag::warn_unsigned_enum_always_true_comparison
8930                                : diag::warn_unsigned_always_true_comparison)
8931                         : diag::warn_tautological_constant_compare;
8932 
8933     S.Diag(E->getOperatorLoc(), Diag)
8934         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
8935         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8936   }
8937 
8938   return true;
8939 }
8940 
8941 /// Analyze the operands of the given comparison.  Implements the
8942 /// fallback case from AnalyzeComparison.
8943 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
8944   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8945   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8946 }
8947 
8948 /// \brief Implements -Wsign-compare.
8949 ///
8950 /// \param E the binary operator to check for warnings
8951 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
8952   // The type the comparison is being performed in.
8953   QualType T = E->getLHS()->getType();
8954 
8955   // Only analyze comparison operators where both sides have been converted to
8956   // the same type.
8957   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8958     return AnalyzeImpConvsInComparison(S, E);
8959 
8960   // Don't analyze value-dependent comparisons directly.
8961   if (E->isValueDependent())
8962     return AnalyzeImpConvsInComparison(S, E);
8963 
8964   Expr *LHS = E->getLHS();
8965   Expr *RHS = E->getRHS();
8966 
8967   if (T->isIntegralType(S.Context)) {
8968     llvm::APSInt RHSValue;
8969     llvm::APSInt LHSValue;
8970 
8971     bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
8972     bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
8973 
8974     // We don't care about expressions whose result is a constant.
8975     if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8976       return AnalyzeImpConvsInComparison(S, E);
8977 
8978     // We only care about expressions where just one side is literal
8979     if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
8980       // Is the constant on the RHS or LHS?
8981       const bool RhsConstant = IsRHSIntegralLiteral;
8982       Expr *Const = RhsConstant ? RHS : LHS;
8983       Expr *Other = RhsConstant ? LHS : RHS;
8984       const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
8985 
8986       // Check whether an integer constant comparison results in a value
8987       // of 'true' or 'false'.
8988       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
8989         return AnalyzeImpConvsInComparison(S, E);
8990     }
8991   }
8992 
8993   if (!T->hasUnsignedIntegerRepresentation()) {
8994     // We don't do anything special if this isn't an unsigned integral
8995     // comparison:  we're only interested in integral comparisons, and
8996     // signed comparisons only happen in cases we don't care to warn about.
8997     return AnalyzeImpConvsInComparison(S, E);
8998   }
8999 
9000   LHS = LHS->IgnoreParenImpCasts();
9001   RHS = RHS->IgnoreParenImpCasts();
9002 
9003   if (!S.getLangOpts().CPlusPlus) {
9004     // Avoid warning about comparison of integers with different signs when
9005     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
9006     // the type of `E`.
9007     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
9008       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
9009     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
9010       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
9011   }
9012 
9013   // Check to see if one of the (unmodified) operands is of different
9014   // signedness.
9015   Expr *signedOperand, *unsignedOperand;
9016   if (LHS->getType()->hasSignedIntegerRepresentation()) {
9017     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
9018            "unsigned comparison between two signed integer expressions?");
9019     signedOperand = LHS;
9020     unsignedOperand = RHS;
9021   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
9022     signedOperand = RHS;
9023     unsignedOperand = LHS;
9024   } else {
9025     return AnalyzeImpConvsInComparison(S, E);
9026   }
9027 
9028   // Otherwise, calculate the effective range of the signed operand.
9029   IntRange signedRange = GetExprRange(S.Context, signedOperand);
9030 
9031   // Go ahead and analyze implicit conversions in the operands.  Note
9032   // that we skip the implicit conversions on both sides.
9033   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
9034   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
9035 
9036   // If the signed range is non-negative, -Wsign-compare won't fire.
9037   if (signedRange.NonNegative)
9038     return;
9039 
9040   // For (in)equality comparisons, if the unsigned operand is a
9041   // constant which cannot collide with a overflowed signed operand,
9042   // then reinterpreting the signed operand as unsigned will not
9043   // change the result of the comparison.
9044   if (E->isEqualityOp()) {
9045     unsigned comparisonWidth = S.Context.getIntWidth(T);
9046     IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
9047 
9048     // We should never be unable to prove that the unsigned operand is
9049     // non-negative.
9050     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
9051 
9052     if (unsignedRange.Width < comparisonWidth)
9053       return;
9054   }
9055 
9056   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
9057     S.PDiag(diag::warn_mixed_sign_comparison)
9058       << LHS->getType() << RHS->getType()
9059       << LHS->getSourceRange() << RHS->getSourceRange());
9060 }
9061 
9062 /// Analyzes an attempt to assign the given value to a bitfield.
9063 ///
9064 /// Returns true if there was something fishy about the attempt.
9065 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
9066                                       SourceLocation InitLoc) {
9067   assert(Bitfield->isBitField());
9068   if (Bitfield->isInvalidDecl())
9069     return false;
9070 
9071   // White-list bool bitfields.
9072   QualType BitfieldType = Bitfield->getType();
9073   if (BitfieldType->isBooleanType())
9074      return false;
9075 
9076   if (BitfieldType->isEnumeralType()) {
9077     EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
9078     // If the underlying enum type was not explicitly specified as an unsigned
9079     // type and the enum contain only positive values, MSVC++ will cause an
9080     // inconsistency by storing this as a signed type.
9081     if (S.getLangOpts().CPlusPlus11 &&
9082         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
9083         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
9084         BitfieldEnumDecl->getNumNegativeBits() == 0) {
9085       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
9086         << BitfieldEnumDecl->getNameAsString();
9087     }
9088   }
9089 
9090   if (Bitfield->getType()->isBooleanType())
9091     return false;
9092 
9093   // Ignore value- or type-dependent expressions.
9094   if (Bitfield->getBitWidth()->isValueDependent() ||
9095       Bitfield->getBitWidth()->isTypeDependent() ||
9096       Init->isValueDependent() ||
9097       Init->isTypeDependent())
9098     return false;
9099 
9100   Expr *OriginalInit = Init->IgnoreParenImpCasts();
9101   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
9102 
9103   llvm::APSInt Value;
9104   if (!OriginalInit->EvaluateAsInt(Value, S.Context,
9105                                    Expr::SE_AllowSideEffects)) {
9106     // The RHS is not constant.  If the RHS has an enum type, make sure the
9107     // bitfield is wide enough to hold all the values of the enum without
9108     // truncation.
9109     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
9110       EnumDecl *ED = EnumTy->getDecl();
9111       bool SignedBitfield = BitfieldType->isSignedIntegerType();
9112 
9113       // Enum types are implicitly signed on Windows, so check if there are any
9114       // negative enumerators to see if the enum was intended to be signed or
9115       // not.
9116       bool SignedEnum = ED->getNumNegativeBits() > 0;
9117 
9118       // Check for surprising sign changes when assigning enum values to a
9119       // bitfield of different signedness.  If the bitfield is signed and we
9120       // have exactly the right number of bits to store this unsigned enum,
9121       // suggest changing the enum to an unsigned type. This typically happens
9122       // on Windows where unfixed enums always use an underlying type of 'int'.
9123       unsigned DiagID = 0;
9124       if (SignedEnum && !SignedBitfield) {
9125         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
9126       } else if (SignedBitfield && !SignedEnum &&
9127                  ED->getNumPositiveBits() == FieldWidth) {
9128         DiagID = diag::warn_signed_bitfield_enum_conversion;
9129       }
9130 
9131       if (DiagID) {
9132         S.Diag(InitLoc, DiagID) << Bitfield << ED;
9133         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
9134         SourceRange TypeRange =
9135             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
9136         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
9137             << SignedEnum << TypeRange;
9138       }
9139 
9140       // Compute the required bitwidth. If the enum has negative values, we need
9141       // one more bit than the normal number of positive bits to represent the
9142       // sign bit.
9143       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
9144                                                   ED->getNumNegativeBits())
9145                                        : ED->getNumPositiveBits();
9146 
9147       // Check the bitwidth.
9148       if (BitsNeeded > FieldWidth) {
9149         Expr *WidthExpr = Bitfield->getBitWidth();
9150         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
9151             << Bitfield << ED;
9152         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
9153             << BitsNeeded << ED << WidthExpr->getSourceRange();
9154       }
9155     }
9156 
9157     return false;
9158   }
9159 
9160   unsigned OriginalWidth = Value.getBitWidth();
9161 
9162   if (!Value.isSigned() || Value.isNegative())
9163     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
9164       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
9165         OriginalWidth = Value.getMinSignedBits();
9166 
9167   if (OriginalWidth <= FieldWidth)
9168     return false;
9169 
9170   // Compute the value which the bitfield will contain.
9171   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
9172   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
9173 
9174   // Check whether the stored value is equal to the original value.
9175   TruncatedValue = TruncatedValue.extend(OriginalWidth);
9176   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
9177     return false;
9178 
9179   // Special-case bitfields of width 1: booleans are naturally 0/1, and
9180   // therefore don't strictly fit into a signed bitfield of width 1.
9181   if (FieldWidth == 1 && Value == 1)
9182     return false;
9183 
9184   std::string PrettyValue = Value.toString(10);
9185   std::string PrettyTrunc = TruncatedValue.toString(10);
9186 
9187   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
9188     << PrettyValue << PrettyTrunc << OriginalInit->getType()
9189     << Init->getSourceRange();
9190 
9191   return true;
9192 }
9193 
9194 /// Analyze the given simple or compound assignment for warning-worthy
9195 /// operations.
9196 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
9197   // Just recurse on the LHS.
9198   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9199 
9200   // We want to recurse on the RHS as normal unless we're assigning to
9201   // a bitfield.
9202   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
9203     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
9204                                   E->getOperatorLoc())) {
9205       // Recurse, ignoring any implicit conversions on the RHS.
9206       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
9207                                         E->getOperatorLoc());
9208     }
9209   }
9210 
9211   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9212 }
9213 
9214 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
9215 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
9216                             SourceLocation CContext, unsigned diag,
9217                             bool pruneControlFlow = false) {
9218   if (pruneControlFlow) {
9219     S.DiagRuntimeBehavior(E->getExprLoc(), E,
9220                           S.PDiag(diag)
9221                             << SourceType << T << E->getSourceRange()
9222                             << SourceRange(CContext));
9223     return;
9224   }
9225   S.Diag(E->getExprLoc(), diag)
9226     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
9227 }
9228 
9229 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
9230 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
9231                             SourceLocation CContext,
9232                             unsigned diag, bool pruneControlFlow = false) {
9233   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
9234 }
9235 
9236 /// Analyze the given compound assignment for the possible losing of
9237 /// floating-point precision.
9238 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
9239   assert(isa<CompoundAssignOperator>(E) &&
9240          "Must be compound assignment operation");
9241   // Recurse on the LHS and RHS in here
9242   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9243   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9244 
9245   // Now check the outermost expression
9246   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
9247   const auto *RBT = cast<CompoundAssignOperator>(E)
9248                         ->getComputationResultType()
9249                         ->getAs<BuiltinType>();
9250 
9251   // If both source and target are floating points.
9252   if (ResultBT && ResultBT->isFloatingPoint() && RBT && RBT->isFloatingPoint())
9253     // Builtin FP kinds are ordered by increasing FP rank.
9254     if (ResultBT->getKind() < RBT->getKind())
9255       // We don't want to warn for system macro.
9256       if (!S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
9257         // warn about dropping FP rank.
9258         DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(),
9259                         E->getOperatorLoc(),
9260                         diag::warn_impcast_float_result_precision);
9261 }
9262 
9263 /// Diagnose an implicit cast from a floating point value to an integer value.
9264 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
9265                                     SourceLocation CContext) {
9266   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
9267   const bool PruneWarnings = S.inTemplateInstantiation();
9268 
9269   Expr *InnerE = E->IgnoreParenImpCasts();
9270   // We also want to warn on, e.g., "int i = -1.234"
9271   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
9272     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
9273       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
9274 
9275   const bool IsLiteral =
9276       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
9277 
9278   llvm::APFloat Value(0.0);
9279   bool IsConstant =
9280     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
9281   if (!IsConstant) {
9282     return DiagnoseImpCast(S, E, T, CContext,
9283                            diag::warn_impcast_float_integer, PruneWarnings);
9284   }
9285 
9286   bool isExact = false;
9287 
9288   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
9289                             T->hasUnsignedIntegerRepresentation());
9290   if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
9291                              &isExact) == llvm::APFloat::opOK &&
9292       isExact) {
9293     if (IsLiteral) return;
9294     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
9295                            PruneWarnings);
9296   }
9297 
9298   unsigned DiagID = 0;
9299   if (IsLiteral) {
9300     // Warn on floating point literal to integer.
9301     DiagID = diag::warn_impcast_literal_float_to_integer;
9302   } else if (IntegerValue == 0) {
9303     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
9304       return DiagnoseImpCast(S, E, T, CContext,
9305                              diag::warn_impcast_float_integer, PruneWarnings);
9306     }
9307     // Warn on non-zero to zero conversion.
9308     DiagID = diag::warn_impcast_float_to_integer_zero;
9309   } else {
9310     if (IntegerValue.isUnsigned()) {
9311       if (!IntegerValue.isMaxValue()) {
9312         return DiagnoseImpCast(S, E, T, CContext,
9313                                diag::warn_impcast_float_integer, PruneWarnings);
9314       }
9315     } else {  // IntegerValue.isSigned()
9316       if (!IntegerValue.isMaxSignedValue() &&
9317           !IntegerValue.isMinSignedValue()) {
9318         return DiagnoseImpCast(S, E, T, CContext,
9319                                diag::warn_impcast_float_integer, PruneWarnings);
9320       }
9321     }
9322     // Warn on evaluatable floating point expression to integer conversion.
9323     DiagID = diag::warn_impcast_float_to_integer;
9324   }
9325 
9326   // FIXME: Force the precision of the source value down so we don't print
9327   // digits which are usually useless (we don't really care here if we
9328   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
9329   // would automatically print the shortest representation, but it's a bit
9330   // tricky to implement.
9331   SmallString<16> PrettySourceValue;
9332   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
9333   precision = (precision * 59 + 195) / 196;
9334   Value.toString(PrettySourceValue, precision);
9335 
9336   SmallString<16> PrettyTargetValue;
9337   if (IsBool)
9338     PrettyTargetValue = Value.isZero() ? "false" : "true";
9339   else
9340     IntegerValue.toString(PrettyTargetValue);
9341 
9342   if (PruneWarnings) {
9343     S.DiagRuntimeBehavior(E->getExprLoc(), E,
9344                           S.PDiag(DiagID)
9345                               << E->getType() << T.getUnqualifiedType()
9346                               << PrettySourceValue << PrettyTargetValue
9347                               << E->getSourceRange() << SourceRange(CContext));
9348   } else {
9349     S.Diag(E->getExprLoc(), DiagID)
9350         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
9351         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
9352   }
9353 }
9354 
9355 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
9356                                       IntRange Range) {
9357   if (!Range.Width) return "0";
9358 
9359   llvm::APSInt ValueInRange = Value;
9360   ValueInRange.setIsSigned(!Range.NonNegative);
9361   ValueInRange = ValueInRange.trunc(Range.Width);
9362   return ValueInRange.toString(10);
9363 }
9364 
9365 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
9366   if (!isa<ImplicitCastExpr>(Ex))
9367     return false;
9368 
9369   Expr *InnerE = Ex->IgnoreParenImpCasts();
9370   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
9371   const Type *Source =
9372     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
9373   if (Target->isDependentType())
9374     return false;
9375 
9376   const BuiltinType *FloatCandidateBT =
9377     dyn_cast<BuiltinType>(ToBool ? Source : Target);
9378   const Type *BoolCandidateType = ToBool ? Target : Source;
9379 
9380   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
9381           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
9382 }
9383 
9384 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
9385                                              SourceLocation CC) {
9386   unsigned NumArgs = TheCall->getNumArgs();
9387   for (unsigned i = 0; i < NumArgs; ++i) {
9388     Expr *CurrA = TheCall->getArg(i);
9389     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
9390       continue;
9391 
9392     bool IsSwapped = ((i > 0) &&
9393         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
9394     IsSwapped |= ((i < (NumArgs - 1)) &&
9395         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
9396     if (IsSwapped) {
9397       // Warn on this floating-point to bool conversion.
9398       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
9399                       CurrA->getType(), CC,
9400                       diag::warn_impcast_floating_point_to_bool);
9401     }
9402   }
9403 }
9404 
9405 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
9406                                    SourceLocation CC) {
9407   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
9408                         E->getExprLoc()))
9409     return;
9410 
9411   // Don't warn on functions which have return type nullptr_t.
9412   if (isa<CallExpr>(E))
9413     return;
9414 
9415   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
9416   const Expr::NullPointerConstantKind NullKind =
9417       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
9418   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
9419     return;
9420 
9421   // Return if target type is a safe conversion.
9422   if (T->isAnyPointerType() || T->isBlockPointerType() ||
9423       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
9424     return;
9425 
9426   SourceLocation Loc = E->getSourceRange().getBegin();
9427 
9428   // Venture through the macro stacks to get to the source of macro arguments.
9429   // The new location is a better location than the complete location that was
9430   // passed in.
9431   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
9432   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
9433 
9434   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
9435   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
9436     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
9437         Loc, S.SourceMgr, S.getLangOpts());
9438     if (MacroName == "NULL")
9439       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
9440   }
9441 
9442   // Only warn if the null and context location are in the same macro expansion.
9443   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
9444     return;
9445 
9446   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
9447       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
9448       << FixItHint::CreateReplacement(Loc,
9449                                       S.getFixItZeroLiteralForType(T, Loc));
9450 }
9451 
9452 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9453                                   ObjCArrayLiteral *ArrayLiteral);
9454 
9455 static void
9456 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9457                            ObjCDictionaryLiteral *DictionaryLiteral);
9458 
9459 /// Check a single element within a collection literal against the
9460 /// target element type.
9461 static void checkObjCCollectionLiteralElement(Sema &S,
9462                                               QualType TargetElementType,
9463                                               Expr *Element,
9464                                               unsigned ElementKind) {
9465   // Skip a bitcast to 'id' or qualified 'id'.
9466   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
9467     if (ICE->getCastKind() == CK_BitCast &&
9468         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
9469       Element = ICE->getSubExpr();
9470   }
9471 
9472   QualType ElementType = Element->getType();
9473   ExprResult ElementResult(Element);
9474   if (ElementType->getAs<ObjCObjectPointerType>() &&
9475       S.CheckSingleAssignmentConstraints(TargetElementType,
9476                                          ElementResult,
9477                                          false, false)
9478         != Sema::Compatible) {
9479     S.Diag(Element->getLocStart(),
9480            diag::warn_objc_collection_literal_element)
9481       << ElementType << ElementKind << TargetElementType
9482       << Element->getSourceRange();
9483   }
9484 
9485   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
9486     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
9487   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
9488     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
9489 }
9490 
9491 /// Check an Objective-C array literal being converted to the given
9492 /// target type.
9493 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9494                                   ObjCArrayLiteral *ArrayLiteral) {
9495   if (!S.NSArrayDecl)
9496     return;
9497 
9498   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9499   if (!TargetObjCPtr)
9500     return;
9501 
9502   if (TargetObjCPtr->isUnspecialized() ||
9503       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9504         != S.NSArrayDecl->getCanonicalDecl())
9505     return;
9506 
9507   auto TypeArgs = TargetObjCPtr->getTypeArgs();
9508   if (TypeArgs.size() != 1)
9509     return;
9510 
9511   QualType TargetElementType = TypeArgs[0];
9512   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
9513     checkObjCCollectionLiteralElement(S, TargetElementType,
9514                                       ArrayLiteral->getElement(I),
9515                                       0);
9516   }
9517 }
9518 
9519 /// Check an Objective-C dictionary literal being converted to the given
9520 /// target type.
9521 static void
9522 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9523                            ObjCDictionaryLiteral *DictionaryLiteral) {
9524   if (!S.NSDictionaryDecl)
9525     return;
9526 
9527   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9528   if (!TargetObjCPtr)
9529     return;
9530 
9531   if (TargetObjCPtr->isUnspecialized() ||
9532       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9533         != S.NSDictionaryDecl->getCanonicalDecl())
9534     return;
9535 
9536   auto TypeArgs = TargetObjCPtr->getTypeArgs();
9537   if (TypeArgs.size() != 2)
9538     return;
9539 
9540   QualType TargetKeyType = TypeArgs[0];
9541   QualType TargetObjectType = TypeArgs[1];
9542   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
9543     auto Element = DictionaryLiteral->getKeyValueElement(I);
9544     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
9545     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
9546   }
9547 }
9548 
9549 // Helper function to filter out cases for constant width constant conversion.
9550 // Don't warn on char array initialization or for non-decimal values.
9551 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
9552                                           SourceLocation CC) {
9553   // If initializing from a constant, and the constant starts with '0',
9554   // then it is a binary, octal, or hexadecimal.  Allow these constants
9555   // to fill all the bits, even if there is a sign change.
9556   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
9557     const char FirstLiteralCharacter =
9558         S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
9559     if (FirstLiteralCharacter == '0')
9560       return false;
9561   }
9562 
9563   // If the CC location points to a '{', and the type is char, then assume
9564   // assume it is an array initialization.
9565   if (CC.isValid() && T->isCharType()) {
9566     const char FirstContextCharacter =
9567         S.getSourceManager().getCharacterData(CC)[0];
9568     if (FirstContextCharacter == '{')
9569       return false;
9570   }
9571 
9572   return true;
9573 }
9574 
9575 static void
9576 CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
9577                         bool *ICContext = nullptr) {
9578   if (E->isTypeDependent() || E->isValueDependent()) return;
9579 
9580   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
9581   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
9582   if (Source == Target) return;
9583   if (Target->isDependentType()) return;
9584 
9585   // If the conversion context location is invalid don't complain. We also
9586   // don't want to emit a warning if the issue occurs from the expansion of
9587   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
9588   // delay this check as long as possible. Once we detect we are in that
9589   // scenario, we just return.
9590   if (CC.isInvalid())
9591     return;
9592 
9593   // Diagnose implicit casts to bool.
9594   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
9595     if (isa<StringLiteral>(E))
9596       // Warn on string literal to bool.  Checks for string literals in logical
9597       // and expressions, for instance, assert(0 && "error here"), are
9598       // prevented by a check in AnalyzeImplicitConversions().
9599       return DiagnoseImpCast(S, E, T, CC,
9600                              diag::warn_impcast_string_literal_to_bool);
9601     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
9602         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
9603       // This covers the literal expressions that evaluate to Objective-C
9604       // objects.
9605       return DiagnoseImpCast(S, E, T, CC,
9606                              diag::warn_impcast_objective_c_literal_to_bool);
9607     }
9608     if (Source->isPointerType() || Source->canDecayToPointerType()) {
9609       // Warn on pointer to bool conversion that is always true.
9610       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
9611                                      SourceRange(CC));
9612     }
9613   }
9614 
9615   // Check implicit casts from Objective-C collection literals to specialized
9616   // collection types, e.g., NSArray<NSString *> *.
9617   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
9618     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
9619   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
9620     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
9621 
9622   // Strip vector types.
9623   if (isa<VectorType>(Source)) {
9624     if (!isa<VectorType>(Target)) {
9625       if (S.SourceMgr.isInSystemMacro(CC))
9626         return;
9627       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
9628     }
9629 
9630     // If the vector cast is cast between two vectors of the same size, it is
9631     // a bitcast, not a conversion.
9632     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
9633       return;
9634 
9635     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
9636     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
9637   }
9638   if (auto VecTy = dyn_cast<VectorType>(Target))
9639     Target = VecTy->getElementType().getTypePtr();
9640 
9641   // Strip complex types.
9642   if (isa<ComplexType>(Source)) {
9643     if (!isa<ComplexType>(Target)) {
9644       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
9645         return;
9646 
9647       return DiagnoseImpCast(S, E, T, CC,
9648                              S.getLangOpts().CPlusPlus
9649                                  ? diag::err_impcast_complex_scalar
9650                                  : diag::warn_impcast_complex_scalar);
9651     }
9652 
9653     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
9654     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
9655   }
9656 
9657   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
9658   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
9659 
9660   // If the source is floating point...
9661   if (SourceBT && SourceBT->isFloatingPoint()) {
9662     // ...and the target is floating point...
9663     if (TargetBT && TargetBT->isFloatingPoint()) {
9664       // ...then warn if we're dropping FP rank.
9665 
9666       // Builtin FP kinds are ordered by increasing FP rank.
9667       if (SourceBT->getKind() > TargetBT->getKind()) {
9668         // Don't warn about float constants that are precisely
9669         // representable in the target type.
9670         Expr::EvalResult result;
9671         if (E->EvaluateAsRValue(result, S.Context)) {
9672           // Value might be a float, a float vector, or a float complex.
9673           if (IsSameFloatAfterCast(result.Val,
9674                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9675                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
9676             return;
9677         }
9678 
9679         if (S.SourceMgr.isInSystemMacro(CC))
9680           return;
9681 
9682         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
9683       }
9684       // ... or possibly if we're increasing rank, too
9685       else if (TargetBT->getKind() > SourceBT->getKind()) {
9686         if (S.SourceMgr.isInSystemMacro(CC))
9687           return;
9688 
9689         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
9690       }
9691       return;
9692     }
9693 
9694     // If the target is integral, always warn.
9695     if (TargetBT && TargetBT->isInteger()) {
9696       if (S.SourceMgr.isInSystemMacro(CC))
9697         return;
9698 
9699       DiagnoseFloatingImpCast(S, E, T, CC);
9700     }
9701 
9702     // Detect the case where a call result is converted from floating-point to
9703     // to bool, and the final argument to the call is converted from bool, to
9704     // discover this typo:
9705     //
9706     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
9707     //
9708     // FIXME: This is an incredibly special case; is there some more general
9709     // way to detect this class of misplaced-parentheses bug?
9710     if (Target->isBooleanType() && isa<CallExpr>(E)) {
9711       // Check last argument of function call to see if it is an
9712       // implicit cast from a type matching the type the result
9713       // is being cast to.
9714       CallExpr *CEx = cast<CallExpr>(E);
9715       if (unsigned NumArgs = CEx->getNumArgs()) {
9716         Expr *LastA = CEx->getArg(NumArgs - 1);
9717         Expr *InnerE = LastA->IgnoreParenImpCasts();
9718         if (isa<ImplicitCastExpr>(LastA) &&
9719             InnerE->getType()->isBooleanType()) {
9720           // Warn on this floating-point to bool conversion
9721           DiagnoseImpCast(S, E, T, CC,
9722                           diag::warn_impcast_floating_point_to_bool);
9723         }
9724       }
9725     }
9726     return;
9727   }
9728 
9729   DiagnoseNullConversion(S, E, T, CC);
9730 
9731   S.DiscardMisalignedMemberAddress(Target, E);
9732 
9733   if (!Source->isIntegerType() || !Target->isIntegerType())
9734     return;
9735 
9736   // TODO: remove this early return once the false positives for constant->bool
9737   // in templates, macros, etc, are reduced or removed.
9738   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9739     return;
9740 
9741   IntRange SourceRange = GetExprRange(S.Context, E);
9742   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
9743 
9744   if (SourceRange.Width > TargetRange.Width) {
9745     // If the source is a constant, use a default-on diagnostic.
9746     // TODO: this should happen for bitfield stores, too.
9747     llvm::APSInt Value(32);
9748     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
9749       if (S.SourceMgr.isInSystemMacro(CC))
9750         return;
9751 
9752       std::string PrettySourceValue = Value.toString(10);
9753       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
9754 
9755       S.DiagRuntimeBehavior(E->getExprLoc(), E,
9756         S.PDiag(diag::warn_impcast_integer_precision_constant)
9757             << PrettySourceValue << PrettyTargetValue
9758             << E->getType() << T << E->getSourceRange()
9759             << clang::SourceRange(CC));
9760       return;
9761     }
9762 
9763     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9764     if (S.SourceMgr.isInSystemMacro(CC))
9765       return;
9766 
9767     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
9768       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9769                              /* pruneControlFlow */ true);
9770     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
9771   }
9772 
9773   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9774       SourceRange.NonNegative && Source->isSignedIntegerType()) {
9775     // Warn when doing a signed to signed conversion, warn if the positive
9776     // source value is exactly the width of the target type, which will
9777     // cause a negative value to be stored.
9778 
9779     llvm::APSInt Value;
9780     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9781         !S.SourceMgr.isInSystemMacro(CC)) {
9782       if (isSameWidthConstantConversion(S, E, T, CC)) {
9783         std::string PrettySourceValue = Value.toString(10);
9784         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
9785 
9786         S.DiagRuntimeBehavior(
9787             E->getExprLoc(), E,
9788             S.PDiag(diag::warn_impcast_integer_precision_constant)
9789                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
9790                 << E->getSourceRange() << clang::SourceRange(CC));
9791         return;
9792       }
9793     }
9794 
9795     // Fall through for non-constants to give a sign conversion warning.
9796   }
9797 
9798   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9799       (!TargetRange.NonNegative && SourceRange.NonNegative &&
9800        SourceRange.Width == TargetRange.Width)) {
9801     if (S.SourceMgr.isInSystemMacro(CC))
9802       return;
9803 
9804     unsigned DiagID = diag::warn_impcast_integer_sign;
9805 
9806     // Traditionally, gcc has warned about this under -Wsign-compare.
9807     // We also want to warn about it in -Wconversion.
9808     // So if -Wconversion is off, use a completely identical diagnostic
9809     // in the sign-compare group.
9810     // The conditional-checking code will
9811     if (ICContext) {
9812       DiagID = diag::warn_impcast_integer_sign_conditional;
9813       *ICContext = true;
9814     }
9815 
9816     return DiagnoseImpCast(S, E, T, CC, DiagID);
9817   }
9818 
9819   // Diagnose conversions between different enumeration types.
9820   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9821   // type, to give us better diagnostics.
9822   QualType SourceType = E->getType();
9823   if (!S.getLangOpts().CPlusPlus) {
9824     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9825       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9826         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9827         SourceType = S.Context.getTypeDeclType(Enum);
9828         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9829       }
9830   }
9831 
9832   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9833     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
9834       if (SourceEnum->getDecl()->hasNameForLinkage() &&
9835           TargetEnum->getDecl()->hasNameForLinkage() &&
9836           SourceEnum != TargetEnum) {
9837         if (S.SourceMgr.isInSystemMacro(CC))
9838           return;
9839 
9840         return DiagnoseImpCast(S, E, SourceType, T, CC,
9841                                diag::warn_impcast_different_enum_types);
9842       }
9843 }
9844 
9845 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9846                                      SourceLocation CC, QualType T);
9847 
9848 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
9849                                     SourceLocation CC, bool &ICContext) {
9850   E = E->IgnoreParenImpCasts();
9851 
9852   if (isa<ConditionalOperator>(E))
9853     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
9854 
9855   AnalyzeImplicitConversions(S, E, CC);
9856   if (E->getType() != T)
9857     return CheckImplicitConversion(S, E, T, CC, &ICContext);
9858 }
9859 
9860 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9861                                      SourceLocation CC, QualType T) {
9862   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
9863 
9864   bool Suspicious = false;
9865   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9866   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
9867 
9868   // If -Wconversion would have warned about either of the candidates
9869   // for a signedness conversion to the context type...
9870   if (!Suspicious) return;
9871 
9872   // ...but it's currently ignored...
9873   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
9874     return;
9875 
9876   // ...then check whether it would have warned about either of the
9877   // candidates for a signedness conversion to the condition type.
9878   if (E->getType() == T) return;
9879 
9880   Suspicious = false;
9881   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
9882                           E->getType(), CC, &Suspicious);
9883   if (!Suspicious)
9884     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
9885                             E->getType(), CC, &Suspicious);
9886 }
9887 
9888 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9889 /// Input argument E is a logical expression.
9890 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
9891   if (S.getLangOpts().Bool)
9892     return;
9893   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
9894 }
9895 
9896 /// AnalyzeImplicitConversions - Find and report any interesting
9897 /// implicit conversions in the given expression.  There are a couple
9898 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
9899 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
9900                                        SourceLocation CC) {
9901   QualType T = OrigE->getType();
9902   Expr *E = OrigE->IgnoreParenImpCasts();
9903 
9904   if (E->isTypeDependent() || E->isValueDependent())
9905     return;
9906 
9907   // For conditional operators, we analyze the arguments as if they
9908   // were being fed directly into the output.
9909   if (isa<ConditionalOperator>(E)) {
9910     ConditionalOperator *CO = cast<ConditionalOperator>(E);
9911     CheckConditionalOperator(S, CO, CC, T);
9912     return;
9913   }
9914 
9915   // Check implicit argument conversions for function calls.
9916   if (CallExpr *Call = dyn_cast<CallExpr>(E))
9917     CheckImplicitArgumentConversions(S, Call, CC);
9918 
9919   // Go ahead and check any implicit conversions we might have skipped.
9920   // The non-canonical typecheck is just an optimization;
9921   // CheckImplicitConversion will filter out dead implicit conversions.
9922   if (E->getType() != T)
9923     CheckImplicitConversion(S, E, T, CC);
9924 
9925   // Now continue drilling into this expression.
9926 
9927   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
9928     // The bound subexpressions in a PseudoObjectExpr are not reachable
9929     // as transitive children.
9930     // FIXME: Use a more uniform representation for this.
9931     for (auto *SE : POE->semantics())
9932       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9933         AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
9934   }
9935 
9936   // Skip past explicit casts.
9937   if (isa<ExplicitCastExpr>(E)) {
9938     E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
9939     return AnalyzeImplicitConversions(S, E, CC);
9940   }
9941 
9942   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9943     // Do a somewhat different check with comparison operators.
9944     if (BO->isComparisonOp())
9945       return AnalyzeComparison(S, BO);
9946 
9947     // And with simple assignments.
9948     if (BO->getOpcode() == BO_Assign)
9949       return AnalyzeAssignment(S, BO);
9950     // And with compound assignments.
9951     if (BO->isAssignmentOp())
9952       return AnalyzeCompoundAssignment(S, BO);
9953   }
9954 
9955   // These break the otherwise-useful invariant below.  Fortunately,
9956   // we don't really need to recurse into them, because any internal
9957   // expressions should have been analyzed already when they were
9958   // built into statements.
9959   if (isa<StmtExpr>(E)) return;
9960 
9961   // Don't descend into unevaluated contexts.
9962   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
9963 
9964   // Now just recurse over the expression's children.
9965   CC = E->getExprLoc();
9966   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
9967   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
9968   for (Stmt *SubStmt : E->children()) {
9969     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
9970     if (!ChildExpr)
9971       continue;
9972 
9973     if (IsLogicalAndOperator &&
9974         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
9975       // Ignore checking string literals that are in logical and operators.
9976       // This is a common pattern for asserts.
9977       continue;
9978     AnalyzeImplicitConversions(S, ChildExpr, CC);
9979   }
9980 
9981   if (BO && BO->isLogicalOp()) {
9982     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
9983     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
9984       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
9985 
9986     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
9987     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
9988       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
9989   }
9990 
9991   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
9992     if (U->getOpcode() == UO_LNot)
9993       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
9994 }
9995 
9996 /// Diagnose integer type and any valid implicit conversion to it.
9997 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
9998   // Taking into account implicit conversions,
9999   // allow any integer.
10000   if (!E->getType()->isIntegerType()) {
10001     S.Diag(E->getLocStart(),
10002            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
10003     return true;
10004   }
10005   // Potentially emit standard warnings for implicit conversions if enabled
10006   // using -Wconversion.
10007   CheckImplicitConversion(S, E, IntT, E->getLocStart());
10008   return false;
10009 }
10010 
10011 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
10012 // Returns true when emitting a warning about taking the address of a reference.
10013 static bool CheckForReference(Sema &SemaRef, const Expr *E,
10014                               const PartialDiagnostic &PD) {
10015   E = E->IgnoreParenImpCasts();
10016 
10017   const FunctionDecl *FD = nullptr;
10018 
10019   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10020     if (!DRE->getDecl()->getType()->isReferenceType())
10021       return false;
10022   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10023     if (!M->getMemberDecl()->getType()->isReferenceType())
10024       return false;
10025   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
10026     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
10027       return false;
10028     FD = Call->getDirectCallee();
10029   } else {
10030     return false;
10031   }
10032 
10033   SemaRef.Diag(E->getExprLoc(), PD);
10034 
10035   // If possible, point to location of function.
10036   if (FD) {
10037     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
10038   }
10039 
10040   return true;
10041 }
10042 
10043 // Returns true if the SourceLocation is expanded from any macro body.
10044 // Returns false if the SourceLocation is invalid, is from not in a macro
10045 // expansion, or is from expanded from a top-level macro argument.
10046 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
10047   if (Loc.isInvalid())
10048     return false;
10049 
10050   while (Loc.isMacroID()) {
10051     if (SM.isMacroBodyExpansion(Loc))
10052       return true;
10053     Loc = SM.getImmediateMacroCallerLoc(Loc);
10054   }
10055 
10056   return false;
10057 }
10058 
10059 /// \brief Diagnose pointers that are always non-null.
10060 /// \param E the expression containing the pointer
10061 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
10062 /// compared to a null pointer
10063 /// \param IsEqual True when the comparison is equal to a null pointer
10064 /// \param Range Extra SourceRange to highlight in the diagnostic
10065 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
10066                                         Expr::NullPointerConstantKind NullKind,
10067                                         bool IsEqual, SourceRange Range) {
10068   if (!E)
10069     return;
10070 
10071   // Don't warn inside macros.
10072   if (E->getExprLoc().isMacroID()) {
10073     const SourceManager &SM = getSourceManager();
10074     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
10075         IsInAnyMacroBody(SM, Range.getBegin()))
10076       return;
10077   }
10078   E = E->IgnoreImpCasts();
10079 
10080   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
10081 
10082   if (isa<CXXThisExpr>(E)) {
10083     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
10084                                 : diag::warn_this_bool_conversion;
10085     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
10086     return;
10087   }
10088 
10089   bool IsAddressOf = false;
10090 
10091   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10092     if (UO->getOpcode() != UO_AddrOf)
10093       return;
10094     IsAddressOf = true;
10095     E = UO->getSubExpr();
10096   }
10097 
10098   if (IsAddressOf) {
10099     unsigned DiagID = IsCompare
10100                           ? diag::warn_address_of_reference_null_compare
10101                           : diag::warn_address_of_reference_bool_conversion;
10102     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
10103                                          << IsEqual;
10104     if (CheckForReference(*this, E, PD)) {
10105       return;
10106     }
10107   }
10108 
10109   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
10110     bool IsParam = isa<NonNullAttr>(NonnullAttr);
10111     std::string Str;
10112     llvm::raw_string_ostream S(Str);
10113     E->printPretty(S, nullptr, getPrintingPolicy());
10114     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
10115                                 : diag::warn_cast_nonnull_to_bool;
10116     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
10117       << E->getSourceRange() << Range << IsEqual;
10118     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
10119   };
10120 
10121   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
10122   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
10123     if (auto *Callee = Call->getDirectCallee()) {
10124       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
10125         ComplainAboutNonnullParamOrCall(A);
10126         return;
10127       }
10128     }
10129   }
10130 
10131   // Expect to find a single Decl.  Skip anything more complicated.
10132   ValueDecl *D = nullptr;
10133   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
10134     D = R->getDecl();
10135   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10136     D = M->getMemberDecl();
10137   }
10138 
10139   // Weak Decls can be null.
10140   if (!D || D->isWeak())
10141     return;
10142 
10143   // Check for parameter decl with nonnull attribute
10144   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
10145     if (getCurFunction() &&
10146         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
10147       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
10148         ComplainAboutNonnullParamOrCall(A);
10149         return;
10150       }
10151 
10152       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
10153         auto ParamIter = llvm::find(FD->parameters(), PV);
10154         assert(ParamIter != FD->param_end());
10155         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
10156 
10157         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
10158           if (!NonNull->args_size()) {
10159               ComplainAboutNonnullParamOrCall(NonNull);
10160               return;
10161           }
10162 
10163           for (const ParamIdx &ArgNo : NonNull->args()) {
10164             if (ArgNo.getASTIndex() == ParamNo) {
10165               ComplainAboutNonnullParamOrCall(NonNull);
10166               return;
10167             }
10168           }
10169         }
10170       }
10171     }
10172   }
10173 
10174   QualType T = D->getType();
10175   const bool IsArray = T->isArrayType();
10176   const bool IsFunction = T->isFunctionType();
10177 
10178   // Address of function is used to silence the function warning.
10179   if (IsAddressOf && IsFunction) {
10180     return;
10181   }
10182 
10183   // Found nothing.
10184   if (!IsAddressOf && !IsFunction && !IsArray)
10185     return;
10186 
10187   // Pretty print the expression for the diagnostic.
10188   std::string Str;
10189   llvm::raw_string_ostream S(Str);
10190   E->printPretty(S, nullptr, getPrintingPolicy());
10191 
10192   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
10193                               : diag::warn_impcast_pointer_to_bool;
10194   enum {
10195     AddressOf,
10196     FunctionPointer,
10197     ArrayPointer
10198   } DiagType;
10199   if (IsAddressOf)
10200     DiagType = AddressOf;
10201   else if (IsFunction)
10202     DiagType = FunctionPointer;
10203   else if (IsArray)
10204     DiagType = ArrayPointer;
10205   else
10206     llvm_unreachable("Could not determine diagnostic.");
10207   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
10208                                 << Range << IsEqual;
10209 
10210   if (!IsFunction)
10211     return;
10212 
10213   // Suggest '&' to silence the function warning.
10214   Diag(E->getExprLoc(), diag::note_function_warning_silence)
10215       << FixItHint::CreateInsertion(E->getLocStart(), "&");
10216 
10217   // Check to see if '()' fixit should be emitted.
10218   QualType ReturnType;
10219   UnresolvedSet<4> NonTemplateOverloads;
10220   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
10221   if (ReturnType.isNull())
10222     return;
10223 
10224   if (IsCompare) {
10225     // There are two cases here.  If there is null constant, the only suggest
10226     // for a pointer return type.  If the null is 0, then suggest if the return
10227     // type is a pointer or an integer type.
10228     if (!ReturnType->isPointerType()) {
10229       if (NullKind == Expr::NPCK_ZeroExpression ||
10230           NullKind == Expr::NPCK_ZeroLiteral) {
10231         if (!ReturnType->isIntegerType())
10232           return;
10233       } else {
10234         return;
10235       }
10236     }
10237   } else { // !IsCompare
10238     // For function to bool, only suggest if the function pointer has bool
10239     // return type.
10240     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
10241       return;
10242   }
10243   Diag(E->getExprLoc(), diag::note_function_to_function_call)
10244       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
10245 }
10246 
10247 /// Diagnoses "dangerous" implicit conversions within the given
10248 /// expression (which is a full expression).  Implements -Wconversion
10249 /// and -Wsign-compare.
10250 ///
10251 /// \param CC the "context" location of the implicit conversion, i.e.
10252 ///   the most location of the syntactic entity requiring the implicit
10253 ///   conversion
10254 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
10255   // Don't diagnose in unevaluated contexts.
10256   if (isUnevaluatedContext())
10257     return;
10258 
10259   // Don't diagnose for value- or type-dependent expressions.
10260   if (E->isTypeDependent() || E->isValueDependent())
10261     return;
10262 
10263   // Check for array bounds violations in cases where the check isn't triggered
10264   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
10265   // ArraySubscriptExpr is on the RHS of a variable initialization.
10266   CheckArrayAccess(E);
10267 
10268   // This is not the right CC for (e.g.) a variable initialization.
10269   AnalyzeImplicitConversions(*this, E, CC);
10270 }
10271 
10272 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10273 /// Input argument E is a logical expression.
10274 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
10275   ::CheckBoolLikeConversion(*this, E, CC);
10276 }
10277 
10278 /// Diagnose when expression is an integer constant expression and its evaluation
10279 /// results in integer overflow
10280 void Sema::CheckForIntOverflow (Expr *E) {
10281   // Use a work list to deal with nested struct initializers.
10282   SmallVector<Expr *, 2> Exprs(1, E);
10283 
10284   do {
10285     Expr *OriginalE = Exprs.pop_back_val();
10286     Expr *E = OriginalE->IgnoreParenCasts();
10287 
10288     if (isa<BinaryOperator>(E)) {
10289       E->EvaluateForOverflow(Context);
10290       continue;
10291     }
10292 
10293     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
10294       Exprs.append(InitList->inits().begin(), InitList->inits().end());
10295     else if (isa<ObjCBoxedExpr>(OriginalE))
10296       E->EvaluateForOverflow(Context);
10297     else if (auto Call = dyn_cast<CallExpr>(E))
10298       Exprs.append(Call->arg_begin(), Call->arg_end());
10299     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
10300       Exprs.append(Message->arg_begin(), Message->arg_end());
10301   } while (!Exprs.empty());
10302 }
10303 
10304 namespace {
10305 
10306 /// \brief Visitor for expressions which looks for unsequenced operations on the
10307 /// same object.
10308 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
10309   using Base = EvaluatedExprVisitor<SequenceChecker>;
10310 
10311   /// \brief A tree of sequenced regions within an expression. Two regions are
10312   /// unsequenced if one is an ancestor or a descendent of the other. When we
10313   /// finish processing an expression with sequencing, such as a comma
10314   /// expression, we fold its tree nodes into its parent, since they are
10315   /// unsequenced with respect to nodes we will visit later.
10316   class SequenceTree {
10317     struct Value {
10318       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
10319       unsigned Parent : 31;
10320       unsigned Merged : 1;
10321     };
10322     SmallVector<Value, 8> Values;
10323 
10324   public:
10325     /// \brief A region within an expression which may be sequenced with respect
10326     /// to some other region.
10327     class Seq {
10328       friend class SequenceTree;
10329 
10330       unsigned Index = 0;
10331 
10332       explicit Seq(unsigned N) : Index(N) {}
10333 
10334     public:
10335       Seq() = default;
10336     };
10337 
10338     SequenceTree() { Values.push_back(Value(0)); }
10339     Seq root() const { return Seq(0); }
10340 
10341     /// \brief Create a new sequence of operations, which is an unsequenced
10342     /// subset of \p Parent. This sequence of operations is sequenced with
10343     /// respect to other children of \p Parent.
10344     Seq allocate(Seq Parent) {
10345       Values.push_back(Value(Parent.Index));
10346       return Seq(Values.size() - 1);
10347     }
10348 
10349     /// \brief Merge a sequence of operations into its parent.
10350     void merge(Seq S) {
10351       Values[S.Index].Merged = true;
10352     }
10353 
10354     /// \brief Determine whether two operations are unsequenced. This operation
10355     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
10356     /// should have been merged into its parent as appropriate.
10357     bool isUnsequenced(Seq Cur, Seq Old) {
10358       unsigned C = representative(Cur.Index);
10359       unsigned Target = representative(Old.Index);
10360       while (C >= Target) {
10361         if (C == Target)
10362           return true;
10363         C = Values[C].Parent;
10364       }
10365       return false;
10366     }
10367 
10368   private:
10369     /// \brief Pick a representative for a sequence.
10370     unsigned representative(unsigned K) {
10371       if (Values[K].Merged)
10372         // Perform path compression as we go.
10373         return Values[K].Parent = representative(Values[K].Parent);
10374       return K;
10375     }
10376   };
10377 
10378   /// An object for which we can track unsequenced uses.
10379   using Object = NamedDecl *;
10380 
10381   /// Different flavors of object usage which we track. We only track the
10382   /// least-sequenced usage of each kind.
10383   enum UsageKind {
10384     /// A read of an object. Multiple unsequenced reads are OK.
10385     UK_Use,
10386 
10387     /// A modification of an object which is sequenced before the value
10388     /// computation of the expression, such as ++n in C++.
10389     UK_ModAsValue,
10390 
10391     /// A modification of an object which is not sequenced before the value
10392     /// computation of the expression, such as n++.
10393     UK_ModAsSideEffect,
10394 
10395     UK_Count = UK_ModAsSideEffect + 1
10396   };
10397 
10398   struct Usage {
10399     Expr *Use = nullptr;
10400     SequenceTree::Seq Seq;
10401 
10402     Usage() = default;
10403   };
10404 
10405   struct UsageInfo {
10406     Usage Uses[UK_Count];
10407 
10408     /// Have we issued a diagnostic for this variable already?
10409     bool Diagnosed = false;
10410 
10411     UsageInfo() = default;
10412   };
10413   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
10414 
10415   Sema &SemaRef;
10416 
10417   /// Sequenced regions within the expression.
10418   SequenceTree Tree;
10419 
10420   /// Declaration modifications and references which we have seen.
10421   UsageInfoMap UsageMap;
10422 
10423   /// The region we are currently within.
10424   SequenceTree::Seq Region;
10425 
10426   /// Filled in with declarations which were modified as a side-effect
10427   /// (that is, post-increment operations).
10428   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
10429 
10430   /// Expressions to check later. We defer checking these to reduce
10431   /// stack usage.
10432   SmallVectorImpl<Expr *> &WorkList;
10433 
10434   /// RAII object wrapping the visitation of a sequenced subexpression of an
10435   /// expression. At the end of this process, the side-effects of the evaluation
10436   /// become sequenced with respect to the value computation of the result, so
10437   /// we downgrade any UK_ModAsSideEffect within the evaluation to
10438   /// UK_ModAsValue.
10439   struct SequencedSubexpression {
10440     SequencedSubexpression(SequenceChecker &Self)
10441       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
10442       Self.ModAsSideEffect = &ModAsSideEffect;
10443     }
10444 
10445     ~SequencedSubexpression() {
10446       for (auto &M : llvm::reverse(ModAsSideEffect)) {
10447         UsageInfo &U = Self.UsageMap[M.first];
10448         auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
10449         Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
10450         SideEffectUsage = M.second;
10451       }
10452       Self.ModAsSideEffect = OldModAsSideEffect;
10453     }
10454 
10455     SequenceChecker &Self;
10456     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
10457     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
10458   };
10459 
10460   /// RAII object wrapping the visitation of a subexpression which we might
10461   /// choose to evaluate as a constant. If any subexpression is evaluated and
10462   /// found to be non-constant, this allows us to suppress the evaluation of
10463   /// the outer expression.
10464   class EvaluationTracker {
10465   public:
10466     EvaluationTracker(SequenceChecker &Self)
10467         : Self(Self), Prev(Self.EvalTracker) {
10468       Self.EvalTracker = this;
10469     }
10470 
10471     ~EvaluationTracker() {
10472       Self.EvalTracker = Prev;
10473       if (Prev)
10474         Prev->EvalOK &= EvalOK;
10475     }
10476 
10477     bool evaluate(const Expr *E, bool &Result) {
10478       if (!EvalOK || E->isValueDependent())
10479         return false;
10480       EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
10481       return EvalOK;
10482     }
10483 
10484   private:
10485     SequenceChecker &Self;
10486     EvaluationTracker *Prev;
10487     bool EvalOK = true;
10488   } *EvalTracker = nullptr;
10489 
10490   /// \brief Find the object which is produced by the specified expression,
10491   /// if any.
10492   Object getObject(Expr *E, bool Mod) const {
10493     E = E->IgnoreParenCasts();
10494     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10495       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
10496         return getObject(UO->getSubExpr(), Mod);
10497     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10498       if (BO->getOpcode() == BO_Comma)
10499         return getObject(BO->getRHS(), Mod);
10500       if (Mod && BO->isAssignmentOp())
10501         return getObject(BO->getLHS(), Mod);
10502     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10503       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
10504       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
10505         return ME->getMemberDecl();
10506     } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10507       // FIXME: If this is a reference, map through to its value.
10508       return DRE->getDecl();
10509     return nullptr;
10510   }
10511 
10512   /// \brief Note that an object was modified or used by an expression.
10513   void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
10514     Usage &U = UI.Uses[UK];
10515     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
10516       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
10517         ModAsSideEffect->push_back(std::make_pair(O, U));
10518       U.Use = Ref;
10519       U.Seq = Region;
10520     }
10521   }
10522 
10523   /// \brief Check whether a modification or use conflicts with a prior usage.
10524   void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
10525                   bool IsModMod) {
10526     if (UI.Diagnosed)
10527       return;
10528 
10529     const Usage &U = UI.Uses[OtherKind];
10530     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
10531       return;
10532 
10533     Expr *Mod = U.Use;
10534     Expr *ModOrUse = Ref;
10535     if (OtherKind == UK_Use)
10536       std::swap(Mod, ModOrUse);
10537 
10538     SemaRef.Diag(Mod->getExprLoc(),
10539                  IsModMod ? diag::warn_unsequenced_mod_mod
10540                           : diag::warn_unsequenced_mod_use)
10541       << O << SourceRange(ModOrUse->getExprLoc());
10542     UI.Diagnosed = true;
10543   }
10544 
10545   void notePreUse(Object O, Expr *Use) {
10546     UsageInfo &U = UsageMap[O];
10547     // Uses conflict with other modifications.
10548     checkUsage(O, U, Use, UK_ModAsValue, false);
10549   }
10550 
10551   void notePostUse(Object O, Expr *Use) {
10552     UsageInfo &U = UsageMap[O];
10553     checkUsage(O, U, Use, UK_ModAsSideEffect, false);
10554     addUsage(U, O, Use, UK_Use);
10555   }
10556 
10557   void notePreMod(Object O, Expr *Mod) {
10558     UsageInfo &U = UsageMap[O];
10559     // Modifications conflict with other modifications and with uses.
10560     checkUsage(O, U, Mod, UK_ModAsValue, true);
10561     checkUsage(O, U, Mod, UK_Use, false);
10562   }
10563 
10564   void notePostMod(Object O, Expr *Use, UsageKind UK) {
10565     UsageInfo &U = UsageMap[O];
10566     checkUsage(O, U, Use, UK_ModAsSideEffect, true);
10567     addUsage(U, O, Use, UK);
10568   }
10569 
10570 public:
10571   SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
10572       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
10573     Visit(E);
10574   }
10575 
10576   void VisitStmt(Stmt *S) {
10577     // Skip all statements which aren't expressions for now.
10578   }
10579 
10580   void VisitExpr(Expr *E) {
10581     // By default, just recurse to evaluated subexpressions.
10582     Base::VisitStmt(E);
10583   }
10584 
10585   void VisitCastExpr(CastExpr *E) {
10586     Object O = Object();
10587     if (E->getCastKind() == CK_LValueToRValue)
10588       O = getObject(E->getSubExpr(), false);
10589 
10590     if (O)
10591       notePreUse(O, E);
10592     VisitExpr(E);
10593     if (O)
10594       notePostUse(O, E);
10595   }
10596 
10597   void VisitBinComma(BinaryOperator *BO) {
10598     // C++11 [expr.comma]p1:
10599     //   Every value computation and side effect associated with the left
10600     //   expression is sequenced before every value computation and side
10601     //   effect associated with the right expression.
10602     SequenceTree::Seq LHS = Tree.allocate(Region);
10603     SequenceTree::Seq RHS = Tree.allocate(Region);
10604     SequenceTree::Seq OldRegion = Region;
10605 
10606     {
10607       SequencedSubexpression SeqLHS(*this);
10608       Region = LHS;
10609       Visit(BO->getLHS());
10610     }
10611 
10612     Region = RHS;
10613     Visit(BO->getRHS());
10614 
10615     Region = OldRegion;
10616 
10617     // Forget that LHS and RHS are sequenced. They are both unsequenced
10618     // with respect to other stuff.
10619     Tree.merge(LHS);
10620     Tree.merge(RHS);
10621   }
10622 
10623   void VisitBinAssign(BinaryOperator *BO) {
10624     // The modification is sequenced after the value computation of the LHS
10625     // and RHS, so check it before inspecting the operands and update the
10626     // map afterwards.
10627     Object O = getObject(BO->getLHS(), true);
10628     if (!O)
10629       return VisitExpr(BO);
10630 
10631     notePreMod(O, BO);
10632 
10633     // C++11 [expr.ass]p7:
10634     //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
10635     //   only once.
10636     //
10637     // Therefore, for a compound assignment operator, O is considered used
10638     // everywhere except within the evaluation of E1 itself.
10639     if (isa<CompoundAssignOperator>(BO))
10640       notePreUse(O, BO);
10641 
10642     Visit(BO->getLHS());
10643 
10644     if (isa<CompoundAssignOperator>(BO))
10645       notePostUse(O, BO);
10646 
10647     Visit(BO->getRHS());
10648 
10649     // C++11 [expr.ass]p1:
10650     //   the assignment is sequenced [...] before the value computation of the
10651     //   assignment expression.
10652     // C11 6.5.16/3 has no such rule.
10653     notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10654                                                        : UK_ModAsSideEffect);
10655   }
10656 
10657   void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
10658     VisitBinAssign(CAO);
10659   }
10660 
10661   void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10662   void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10663   void VisitUnaryPreIncDec(UnaryOperator *UO) {
10664     Object O = getObject(UO->getSubExpr(), true);
10665     if (!O)
10666       return VisitExpr(UO);
10667 
10668     notePreMod(O, UO);
10669     Visit(UO->getSubExpr());
10670     // C++11 [expr.pre.incr]p1:
10671     //   the expression ++x is equivalent to x+=1
10672     notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10673                                                        : UK_ModAsSideEffect);
10674   }
10675 
10676   void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10677   void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10678   void VisitUnaryPostIncDec(UnaryOperator *UO) {
10679     Object O = getObject(UO->getSubExpr(), true);
10680     if (!O)
10681       return VisitExpr(UO);
10682 
10683     notePreMod(O, UO);
10684     Visit(UO->getSubExpr());
10685     notePostMod(O, UO, UK_ModAsSideEffect);
10686   }
10687 
10688   /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
10689   void VisitBinLOr(BinaryOperator *BO) {
10690     // The side-effects of the LHS of an '&&' are sequenced before the
10691     // value computation of the RHS, and hence before the value computation
10692     // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10693     // as if they were unconditionally sequenced.
10694     EvaluationTracker Eval(*this);
10695     {
10696       SequencedSubexpression Sequenced(*this);
10697       Visit(BO->getLHS());
10698     }
10699 
10700     bool Result;
10701     if (Eval.evaluate(BO->getLHS(), Result)) {
10702       if (!Result)
10703         Visit(BO->getRHS());
10704     } else {
10705       // Check for unsequenced operations in the RHS, treating it as an
10706       // entirely separate evaluation.
10707       //
10708       // FIXME: If there are operations in the RHS which are unsequenced
10709       // with respect to operations outside the RHS, and those operations
10710       // are unconditionally evaluated, diagnose them.
10711       WorkList.push_back(BO->getRHS());
10712     }
10713   }
10714   void VisitBinLAnd(BinaryOperator *BO) {
10715     EvaluationTracker Eval(*this);
10716     {
10717       SequencedSubexpression Sequenced(*this);
10718       Visit(BO->getLHS());
10719     }
10720 
10721     bool Result;
10722     if (Eval.evaluate(BO->getLHS(), Result)) {
10723       if (Result)
10724         Visit(BO->getRHS());
10725     } else {
10726       WorkList.push_back(BO->getRHS());
10727     }
10728   }
10729 
10730   // Only visit the condition, unless we can be sure which subexpression will
10731   // be chosen.
10732   void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
10733     EvaluationTracker Eval(*this);
10734     {
10735       SequencedSubexpression Sequenced(*this);
10736       Visit(CO->getCond());
10737     }
10738 
10739     bool Result;
10740     if (Eval.evaluate(CO->getCond(), Result))
10741       Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
10742     else {
10743       WorkList.push_back(CO->getTrueExpr());
10744       WorkList.push_back(CO->getFalseExpr());
10745     }
10746   }
10747 
10748   void VisitCallExpr(CallExpr *CE) {
10749     // C++11 [intro.execution]p15:
10750     //   When calling a function [...], every value computation and side effect
10751     //   associated with any argument expression, or with the postfix expression
10752     //   designating the called function, is sequenced before execution of every
10753     //   expression or statement in the body of the function [and thus before
10754     //   the value computation of its result].
10755     SequencedSubexpression Sequenced(*this);
10756     Base::VisitCallExpr(CE);
10757 
10758     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10759   }
10760 
10761   void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
10762     // This is a call, so all subexpressions are sequenced before the result.
10763     SequencedSubexpression Sequenced(*this);
10764 
10765     if (!CCE->isListInitialization())
10766       return VisitExpr(CCE);
10767 
10768     // In C++11, list initializations are sequenced.
10769     SmallVector<SequenceTree::Seq, 32> Elts;
10770     SequenceTree::Seq Parent = Region;
10771     for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10772                                         E = CCE->arg_end();
10773          I != E; ++I) {
10774       Region = Tree.allocate(Parent);
10775       Elts.push_back(Region);
10776       Visit(*I);
10777     }
10778 
10779     // Forget that the initializers are sequenced.
10780     Region = Parent;
10781     for (unsigned I = 0; I < Elts.size(); ++I)
10782       Tree.merge(Elts[I]);
10783   }
10784 
10785   void VisitInitListExpr(InitListExpr *ILE) {
10786     if (!SemaRef.getLangOpts().CPlusPlus11)
10787       return VisitExpr(ILE);
10788 
10789     // In C++11, list initializations are sequenced.
10790     SmallVector<SequenceTree::Seq, 32> Elts;
10791     SequenceTree::Seq Parent = Region;
10792     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10793       Expr *E = ILE->getInit(I);
10794       if (!E) continue;
10795       Region = Tree.allocate(Parent);
10796       Elts.push_back(Region);
10797       Visit(E);
10798     }
10799 
10800     // Forget that the initializers are sequenced.
10801     Region = Parent;
10802     for (unsigned I = 0; I < Elts.size(); ++I)
10803       Tree.merge(Elts[I]);
10804   }
10805 };
10806 
10807 } // namespace
10808 
10809 void Sema::CheckUnsequencedOperations(Expr *E) {
10810   SmallVector<Expr *, 8> WorkList;
10811   WorkList.push_back(E);
10812   while (!WorkList.empty()) {
10813     Expr *Item = WorkList.pop_back_val();
10814     SequenceChecker(*this, Item, WorkList);
10815   }
10816 }
10817 
10818 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10819                               bool IsConstexpr) {
10820   CheckImplicitConversions(E, CheckLoc);
10821   if (!E->isInstantiationDependent())
10822     CheckUnsequencedOperations(E);
10823   if (!IsConstexpr && !E->isValueDependent())
10824     CheckForIntOverflow(E);
10825   DiagnoseMisalignedMembers();
10826 }
10827 
10828 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10829                                        FieldDecl *BitField,
10830                                        Expr *Init) {
10831   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10832 }
10833 
10834 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
10835                                          SourceLocation Loc) {
10836   if (!PType->isVariablyModifiedType())
10837     return;
10838   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10839     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10840     return;
10841   }
10842   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10843     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10844     return;
10845   }
10846   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10847     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10848     return;
10849   }
10850 
10851   const ArrayType *AT = S.Context.getAsArrayType(PType);
10852   if (!AT)
10853     return;
10854 
10855   if (AT->getSizeModifier() != ArrayType::Star) {
10856     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
10857     return;
10858   }
10859 
10860   S.Diag(Loc, diag::err_array_star_in_function_definition);
10861 }
10862 
10863 /// CheckParmsForFunctionDef - Check that the parameters of the given
10864 /// function are appropriate for the definition of a function. This
10865 /// takes care of any checks that cannot be performed on the
10866 /// declaration itself, e.g., that the types of each of the function
10867 /// parameters are complete.
10868 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
10869                                     bool CheckParameterNames) {
10870   bool HasInvalidParm = false;
10871   for (ParmVarDecl *Param : Parameters) {
10872     // C99 6.7.5.3p4: the parameters in a parameter type list in a
10873     // function declarator that is part of a function definition of
10874     // that function shall not have incomplete type.
10875     //
10876     // This is also C++ [dcl.fct]p6.
10877     if (!Param->isInvalidDecl() &&
10878         RequireCompleteType(Param->getLocation(), Param->getType(),
10879                             diag::err_typecheck_decl_incomplete_type)) {
10880       Param->setInvalidDecl();
10881       HasInvalidParm = true;
10882     }
10883 
10884     // C99 6.9.1p5: If the declarator includes a parameter type list, the
10885     // declaration of each parameter shall include an identifier.
10886     if (CheckParameterNames &&
10887         Param->getIdentifier() == nullptr &&
10888         !Param->isImplicit() &&
10889         !getLangOpts().CPlusPlus)
10890       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
10891 
10892     // C99 6.7.5.3p12:
10893     //   If the function declarator is not part of a definition of that
10894     //   function, parameters may have incomplete type and may use the [*]
10895     //   notation in their sequences of declarator specifiers to specify
10896     //   variable length array types.
10897     QualType PType = Param->getOriginalType();
10898     // FIXME: This diagnostic should point the '[*]' if source-location
10899     // information is added for it.
10900     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
10901 
10902     // If the parameter is a c++ class type and it has to be destructed in the
10903     // callee function, declare the destructor so that it can be called by the
10904     // callee function. Do not perform any direct access check on the dtor here.
10905     if (!Param->isInvalidDecl()) {
10906       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
10907         if (!ClassDecl->isInvalidDecl() &&
10908             !ClassDecl->hasIrrelevantDestructor() &&
10909             !ClassDecl->isDependentContext() &&
10910             Context.isParamDestroyedInCallee(Param->getType())) {
10911           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10912           MarkFunctionReferenced(Param->getLocation(), Destructor);
10913           DiagnoseUseOfDecl(Destructor, Param->getLocation());
10914         }
10915       }
10916     }
10917 
10918     // Parameters with the pass_object_size attribute only need to be marked
10919     // constant at function definitions. Because we lack information about
10920     // whether we're on a declaration or definition when we're instantiating the
10921     // attribute, we need to check for constness here.
10922     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
10923       if (!Param->getType().isConstQualified())
10924         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10925             << Attr->getSpelling() << 1;
10926   }
10927 
10928   return HasInvalidParm;
10929 }
10930 
10931 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
10932 /// or MemberExpr.
10933 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
10934                               ASTContext &Context) {
10935   if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
10936     return Context.getDeclAlign(DRE->getDecl());
10937 
10938   if (const auto *ME = dyn_cast<MemberExpr>(E))
10939     return Context.getDeclAlign(ME->getMemberDecl());
10940 
10941   return TypeAlign;
10942 }
10943 
10944 /// CheckCastAlign - Implements -Wcast-align, which warns when a
10945 /// pointer cast increases the alignment requirements.
10946 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
10947   // This is actually a lot of work to potentially be doing on every
10948   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
10949   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
10950     return;
10951 
10952   // Ignore dependent types.
10953   if (T->isDependentType() || Op->getType()->isDependentType())
10954     return;
10955 
10956   // Require that the destination be a pointer type.
10957   const PointerType *DestPtr = T->getAs<PointerType>();
10958   if (!DestPtr) return;
10959 
10960   // If the destination has alignment 1, we're done.
10961   QualType DestPointee = DestPtr->getPointeeType();
10962   if (DestPointee->isIncompleteType()) return;
10963   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
10964   if (DestAlign.isOne()) return;
10965 
10966   // Require that the source be a pointer type.
10967   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
10968   if (!SrcPtr) return;
10969   QualType SrcPointee = SrcPtr->getPointeeType();
10970 
10971   // Whitelist casts from cv void*.  We already implicitly
10972   // whitelisted casts to cv void*, since they have alignment 1.
10973   // Also whitelist casts involving incomplete types, which implicitly
10974   // includes 'void'.
10975   if (SrcPointee->isIncompleteType()) return;
10976 
10977   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
10978 
10979   if (auto *CE = dyn_cast<CastExpr>(Op)) {
10980     if (CE->getCastKind() == CK_ArrayToPointerDecay)
10981       SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
10982   } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
10983     if (UO->getOpcode() == UO_AddrOf)
10984       SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
10985   }
10986 
10987   if (SrcAlign >= DestAlign) return;
10988 
10989   Diag(TRange.getBegin(), diag::warn_cast_align)
10990     << Op->getType() << T
10991     << static_cast<unsigned>(SrcAlign.getQuantity())
10992     << static_cast<unsigned>(DestAlign.getQuantity())
10993     << TRange << Op->getSourceRange();
10994 }
10995 
10996 /// \brief Check whether this array fits the idiom of a size-one tail padded
10997 /// array member of a struct.
10998 ///
10999 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
11000 /// commonly used to emulate flexible arrays in C89 code.
11001 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
11002                                     const NamedDecl *ND) {
11003   if (Size != 1 || !ND) return false;
11004 
11005   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
11006   if (!FD) return false;
11007 
11008   // Don't consider sizes resulting from macro expansions or template argument
11009   // substitution to form C89 tail-padded arrays.
11010 
11011   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
11012   while (TInfo) {
11013     TypeLoc TL = TInfo->getTypeLoc();
11014     // Look through typedefs.
11015     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
11016       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
11017       TInfo = TDL->getTypeSourceInfo();
11018       continue;
11019     }
11020     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
11021       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
11022       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
11023         return false;
11024     }
11025     break;
11026   }
11027 
11028   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
11029   if (!RD) return false;
11030   if (RD->isUnion()) return false;
11031   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
11032     if (!CRD->isStandardLayout()) return false;
11033   }
11034 
11035   // See if this is the last field decl in the record.
11036   const Decl *D = FD;
11037   while ((D = D->getNextDeclInContext()))
11038     if (isa<FieldDecl>(D))
11039       return false;
11040   return true;
11041 }
11042 
11043 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
11044                             const ArraySubscriptExpr *ASE,
11045                             bool AllowOnePastEnd, bool IndexNegated) {
11046   IndexExpr = IndexExpr->IgnoreParenImpCasts();
11047   if (IndexExpr->isValueDependent())
11048     return;
11049 
11050   const Type *EffectiveType =
11051       BaseExpr->getType()->getPointeeOrArrayElementType();
11052   BaseExpr = BaseExpr->IgnoreParenCasts();
11053   const ConstantArrayType *ArrayTy =
11054     Context.getAsConstantArrayType(BaseExpr->getType());
11055   if (!ArrayTy)
11056     return;
11057 
11058   llvm::APSInt index;
11059   if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
11060     return;
11061   if (IndexNegated)
11062     index = -index;
11063 
11064   const NamedDecl *ND = nullptr;
11065   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
11066     ND = DRE->getDecl();
11067   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
11068     ND = ME->getMemberDecl();
11069 
11070   if (index.isUnsigned() || !index.isNegative()) {
11071     llvm::APInt size = ArrayTy->getSize();
11072     if (!size.isStrictlyPositive())
11073       return;
11074 
11075     const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
11076     if (BaseType != EffectiveType) {
11077       // Make sure we're comparing apples to apples when comparing index to size
11078       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
11079       uint64_t array_typesize = Context.getTypeSize(BaseType);
11080       // Handle ptrarith_typesize being zero, such as when casting to void*
11081       if (!ptrarith_typesize) ptrarith_typesize = 1;
11082       if (ptrarith_typesize != array_typesize) {
11083         // There's a cast to a different size type involved
11084         uint64_t ratio = array_typesize / ptrarith_typesize;
11085         // TODO: Be smarter about handling cases where array_typesize is not a
11086         // multiple of ptrarith_typesize
11087         if (ptrarith_typesize * ratio == array_typesize)
11088           size *= llvm::APInt(size.getBitWidth(), ratio);
11089       }
11090     }
11091 
11092     if (size.getBitWidth() > index.getBitWidth())
11093       index = index.zext(size.getBitWidth());
11094     else if (size.getBitWidth() < index.getBitWidth())
11095       size = size.zext(index.getBitWidth());
11096 
11097     // For array subscripting the index must be less than size, but for pointer
11098     // arithmetic also allow the index (offset) to be equal to size since
11099     // computing the next address after the end of the array is legal and
11100     // commonly done e.g. in C++ iterators and range-based for loops.
11101     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
11102       return;
11103 
11104     // Also don't warn for arrays of size 1 which are members of some
11105     // structure. These are often used to approximate flexible arrays in C89
11106     // code.
11107     if (IsTailPaddedMemberArray(*this, size, ND))
11108       return;
11109 
11110     // Suppress the warning if the subscript expression (as identified by the
11111     // ']' location) and the index expression are both from macro expansions
11112     // within a system header.
11113     if (ASE) {
11114       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
11115           ASE->getRBracketLoc());
11116       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
11117         SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
11118             IndexExpr->getLocStart());
11119         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
11120           return;
11121       }
11122     }
11123 
11124     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
11125     if (ASE)
11126       DiagID = diag::warn_array_index_exceeds_bounds;
11127 
11128     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11129                         PDiag(DiagID) << index.toString(10, true)
11130                           << size.toString(10, true)
11131                           << (unsigned)size.getLimitedValue(~0U)
11132                           << IndexExpr->getSourceRange());
11133   } else {
11134     unsigned DiagID = diag::warn_array_index_precedes_bounds;
11135     if (!ASE) {
11136       DiagID = diag::warn_ptr_arith_precedes_bounds;
11137       if (index.isNegative()) index = -index;
11138     }
11139 
11140     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11141                         PDiag(DiagID) << index.toString(10, true)
11142                           << IndexExpr->getSourceRange());
11143   }
11144 
11145   if (!ND) {
11146     // Try harder to find a NamedDecl to point at in the note.
11147     while (const ArraySubscriptExpr *ASE =
11148            dyn_cast<ArraySubscriptExpr>(BaseExpr))
11149       BaseExpr = ASE->getBase()->IgnoreParenCasts();
11150     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
11151       ND = DRE->getDecl();
11152     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
11153       ND = ME->getMemberDecl();
11154   }
11155 
11156   if (ND)
11157     DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
11158                         PDiag(diag::note_array_index_out_of_bounds)
11159                           << ND->getDeclName());
11160 }
11161 
11162 void Sema::CheckArrayAccess(const Expr *expr) {
11163   int AllowOnePastEnd = 0;
11164   while (expr) {
11165     expr = expr->IgnoreParenImpCasts();
11166     switch (expr->getStmtClass()) {
11167       case Stmt::ArraySubscriptExprClass: {
11168         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
11169         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
11170                          AllowOnePastEnd > 0);
11171         return;
11172       }
11173       case Stmt::OMPArraySectionExprClass: {
11174         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
11175         if (ASE->getLowerBound())
11176           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
11177                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
11178         return;
11179       }
11180       case Stmt::UnaryOperatorClass: {
11181         // Only unwrap the * and & unary operators
11182         const UnaryOperator *UO = cast<UnaryOperator>(expr);
11183         expr = UO->getSubExpr();
11184         switch (UO->getOpcode()) {
11185           case UO_AddrOf:
11186             AllowOnePastEnd++;
11187             break;
11188           case UO_Deref:
11189             AllowOnePastEnd--;
11190             break;
11191           default:
11192             return;
11193         }
11194         break;
11195       }
11196       case Stmt::ConditionalOperatorClass: {
11197         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
11198         if (const Expr *lhs = cond->getLHS())
11199           CheckArrayAccess(lhs);
11200         if (const Expr *rhs = cond->getRHS())
11201           CheckArrayAccess(rhs);
11202         return;
11203       }
11204       case Stmt::CXXOperatorCallExprClass: {
11205         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
11206         for (const auto *Arg : OCE->arguments())
11207           CheckArrayAccess(Arg);
11208         return;
11209       }
11210       default:
11211         return;
11212     }
11213   }
11214 }
11215 
11216 //===--- CHECK: Objective-C retain cycles ----------------------------------//
11217 
11218 namespace {
11219 
11220 struct RetainCycleOwner {
11221   VarDecl *Variable = nullptr;
11222   SourceRange Range;
11223   SourceLocation Loc;
11224   bool Indirect = false;
11225 
11226   RetainCycleOwner() = default;
11227 
11228   void setLocsFrom(Expr *e) {
11229     Loc = e->getExprLoc();
11230     Range = e->getSourceRange();
11231   }
11232 };
11233 
11234 } // namespace
11235 
11236 /// Consider whether capturing the given variable can possibly lead to
11237 /// a retain cycle.
11238 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
11239   // In ARC, it's captured strongly iff the variable has __strong
11240   // lifetime.  In MRR, it's captured strongly if the variable is
11241   // __block and has an appropriate type.
11242   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11243     return false;
11244 
11245   owner.Variable = var;
11246   if (ref)
11247     owner.setLocsFrom(ref);
11248   return true;
11249 }
11250 
11251 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
11252   while (true) {
11253     e = e->IgnoreParens();
11254     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
11255       switch (cast->getCastKind()) {
11256       case CK_BitCast:
11257       case CK_LValueBitCast:
11258       case CK_LValueToRValue:
11259       case CK_ARCReclaimReturnedObject:
11260         e = cast->getSubExpr();
11261         continue;
11262 
11263       default:
11264         return false;
11265       }
11266     }
11267 
11268     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
11269       ObjCIvarDecl *ivar = ref->getDecl();
11270       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11271         return false;
11272 
11273       // Try to find a retain cycle in the base.
11274       if (!findRetainCycleOwner(S, ref->getBase(), owner))
11275         return false;
11276 
11277       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
11278       owner.Indirect = true;
11279       return true;
11280     }
11281 
11282     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
11283       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
11284       if (!var) return false;
11285       return considerVariable(var, ref, owner);
11286     }
11287 
11288     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
11289       if (member->isArrow()) return false;
11290 
11291       // Don't count this as an indirect ownership.
11292       e = member->getBase();
11293       continue;
11294     }
11295 
11296     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
11297       // Only pay attention to pseudo-objects on property references.
11298       ObjCPropertyRefExpr *pre
11299         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
11300                                               ->IgnoreParens());
11301       if (!pre) return false;
11302       if (pre->isImplicitProperty()) return false;
11303       ObjCPropertyDecl *property = pre->getExplicitProperty();
11304       if (!property->isRetaining() &&
11305           !(property->getPropertyIvarDecl() &&
11306             property->getPropertyIvarDecl()->getType()
11307               .getObjCLifetime() == Qualifiers::OCL_Strong))
11308           return false;
11309 
11310       owner.Indirect = true;
11311       if (pre->isSuperReceiver()) {
11312         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
11313         if (!owner.Variable)
11314           return false;
11315         owner.Loc = pre->getLocation();
11316         owner.Range = pre->getSourceRange();
11317         return true;
11318       }
11319       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
11320                               ->getSourceExpr());
11321       continue;
11322     }
11323 
11324     // Array ivars?
11325 
11326     return false;
11327   }
11328 }
11329 
11330 namespace {
11331 
11332   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
11333     ASTContext &Context;
11334     VarDecl *Variable;
11335     Expr *Capturer = nullptr;
11336     bool VarWillBeReased = false;
11337 
11338     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
11339         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
11340           Context(Context), Variable(variable) {}
11341 
11342     void VisitDeclRefExpr(DeclRefExpr *ref) {
11343       if (ref->getDecl() == Variable && !Capturer)
11344         Capturer = ref;
11345     }
11346 
11347     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
11348       if (Capturer) return;
11349       Visit(ref->getBase());
11350       if (Capturer && ref->isFreeIvar())
11351         Capturer = ref;
11352     }
11353 
11354     void VisitBlockExpr(BlockExpr *block) {
11355       // Look inside nested blocks
11356       if (block->getBlockDecl()->capturesVariable(Variable))
11357         Visit(block->getBlockDecl()->getBody());
11358     }
11359 
11360     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
11361       if (Capturer) return;
11362       if (OVE->getSourceExpr())
11363         Visit(OVE->getSourceExpr());
11364     }
11365 
11366     void VisitBinaryOperator(BinaryOperator *BinOp) {
11367       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
11368         return;
11369       Expr *LHS = BinOp->getLHS();
11370       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
11371         if (DRE->getDecl() != Variable)
11372           return;
11373         if (Expr *RHS = BinOp->getRHS()) {
11374           RHS = RHS->IgnoreParenCasts();
11375           llvm::APSInt Value;
11376           VarWillBeReased =
11377             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
11378         }
11379       }
11380     }
11381   };
11382 
11383 } // namespace
11384 
11385 /// Check whether the given argument is a block which captures a
11386 /// variable.
11387 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
11388   assert(owner.Variable && owner.Loc.isValid());
11389 
11390   e = e->IgnoreParenCasts();
11391 
11392   // Look through [^{...} copy] and Block_copy(^{...}).
11393   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
11394     Selector Cmd = ME->getSelector();
11395     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
11396       e = ME->getInstanceReceiver();
11397       if (!e)
11398         return nullptr;
11399       e = e->IgnoreParenCasts();
11400     }
11401   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
11402     if (CE->getNumArgs() == 1) {
11403       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
11404       if (Fn) {
11405         const IdentifierInfo *FnI = Fn->getIdentifier();
11406         if (FnI && FnI->isStr("_Block_copy")) {
11407           e = CE->getArg(0)->IgnoreParenCasts();
11408         }
11409       }
11410     }
11411   }
11412 
11413   BlockExpr *block = dyn_cast<BlockExpr>(e);
11414   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
11415     return nullptr;
11416 
11417   FindCaptureVisitor visitor(S.Context, owner.Variable);
11418   visitor.Visit(block->getBlockDecl()->getBody());
11419   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
11420 }
11421 
11422 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
11423                                 RetainCycleOwner &owner) {
11424   assert(capturer);
11425   assert(owner.Variable && owner.Loc.isValid());
11426 
11427   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
11428     << owner.Variable << capturer->getSourceRange();
11429   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
11430     << owner.Indirect << owner.Range;
11431 }
11432 
11433 /// Check for a keyword selector that starts with the word 'add' or
11434 /// 'set'.
11435 static bool isSetterLikeSelector(Selector sel) {
11436   if (sel.isUnarySelector()) return false;
11437 
11438   StringRef str = sel.getNameForSlot(0);
11439   while (!str.empty() && str.front() == '_') str = str.substr(1);
11440   if (str.startswith("set"))
11441     str = str.substr(3);
11442   else if (str.startswith("add")) {
11443     // Specially whitelist 'addOperationWithBlock:'.
11444     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
11445       return false;
11446     str = str.substr(3);
11447   }
11448   else
11449     return false;
11450 
11451   if (str.empty()) return true;
11452   return !isLowercase(str.front());
11453 }
11454 
11455 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
11456                                                     ObjCMessageExpr *Message) {
11457   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
11458                                                 Message->getReceiverInterface(),
11459                                                 NSAPI::ClassId_NSMutableArray);
11460   if (!IsMutableArray) {
11461     return None;
11462   }
11463 
11464   Selector Sel = Message->getSelector();
11465 
11466   Optional<NSAPI::NSArrayMethodKind> MKOpt =
11467     S.NSAPIObj->getNSArrayMethodKind(Sel);
11468   if (!MKOpt) {
11469     return None;
11470   }
11471 
11472   NSAPI::NSArrayMethodKind MK = *MKOpt;
11473 
11474   switch (MK) {
11475     case NSAPI::NSMutableArr_addObject:
11476     case NSAPI::NSMutableArr_insertObjectAtIndex:
11477     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
11478       return 0;
11479     case NSAPI::NSMutableArr_replaceObjectAtIndex:
11480       return 1;
11481 
11482     default:
11483       return None;
11484   }
11485 
11486   return None;
11487 }
11488 
11489 static
11490 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
11491                                                   ObjCMessageExpr *Message) {
11492   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
11493                                             Message->getReceiverInterface(),
11494                                             NSAPI::ClassId_NSMutableDictionary);
11495   if (!IsMutableDictionary) {
11496     return None;
11497   }
11498 
11499   Selector Sel = Message->getSelector();
11500 
11501   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
11502     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
11503   if (!MKOpt) {
11504     return None;
11505   }
11506 
11507   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
11508 
11509   switch (MK) {
11510     case NSAPI::NSMutableDict_setObjectForKey:
11511     case NSAPI::NSMutableDict_setValueForKey:
11512     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
11513       return 0;
11514 
11515     default:
11516       return None;
11517   }
11518 
11519   return None;
11520 }
11521 
11522 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
11523   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
11524                                                 Message->getReceiverInterface(),
11525                                                 NSAPI::ClassId_NSMutableSet);
11526 
11527   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
11528                                             Message->getReceiverInterface(),
11529                                             NSAPI::ClassId_NSMutableOrderedSet);
11530   if (!IsMutableSet && !IsMutableOrderedSet) {
11531     return None;
11532   }
11533 
11534   Selector Sel = Message->getSelector();
11535 
11536   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
11537   if (!MKOpt) {
11538     return None;
11539   }
11540 
11541   NSAPI::NSSetMethodKind MK = *MKOpt;
11542 
11543   switch (MK) {
11544     case NSAPI::NSMutableSet_addObject:
11545     case NSAPI::NSOrderedSet_setObjectAtIndex:
11546     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
11547     case NSAPI::NSOrderedSet_insertObjectAtIndex:
11548       return 0;
11549     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
11550       return 1;
11551   }
11552 
11553   return None;
11554 }
11555 
11556 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
11557   if (!Message->isInstanceMessage()) {
11558     return;
11559   }
11560 
11561   Optional<int> ArgOpt;
11562 
11563   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
11564       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
11565       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
11566     return;
11567   }
11568 
11569   int ArgIndex = *ArgOpt;
11570 
11571   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
11572   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
11573     Arg = OE->getSourceExpr()->IgnoreImpCasts();
11574   }
11575 
11576   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
11577     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11578       if (ArgRE->isObjCSelfExpr()) {
11579         Diag(Message->getSourceRange().getBegin(),
11580              diag::warn_objc_circular_container)
11581           << ArgRE->getDecl() << StringRef("'super'");
11582       }
11583     }
11584   } else {
11585     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
11586 
11587     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
11588       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
11589     }
11590 
11591     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
11592       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11593         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
11594           ValueDecl *Decl = ReceiverRE->getDecl();
11595           Diag(Message->getSourceRange().getBegin(),
11596                diag::warn_objc_circular_container)
11597             << Decl << Decl;
11598           if (!ArgRE->isObjCSelfExpr()) {
11599             Diag(Decl->getLocation(),
11600                  diag::note_objc_circular_container_declared_here)
11601               << Decl;
11602           }
11603         }
11604       }
11605     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
11606       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
11607         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
11608           ObjCIvarDecl *Decl = IvarRE->getDecl();
11609           Diag(Message->getSourceRange().getBegin(),
11610                diag::warn_objc_circular_container)
11611             << Decl << Decl;
11612           Diag(Decl->getLocation(),
11613                diag::note_objc_circular_container_declared_here)
11614             << Decl;
11615         }
11616       }
11617     }
11618   }
11619 }
11620 
11621 /// Check a message send to see if it's likely to cause a retain cycle.
11622 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
11623   // Only check instance methods whose selector looks like a setter.
11624   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
11625     return;
11626 
11627   // Try to find a variable that the receiver is strongly owned by.
11628   RetainCycleOwner owner;
11629   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
11630     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
11631       return;
11632   } else {
11633     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
11634     owner.Variable = getCurMethodDecl()->getSelfDecl();
11635     owner.Loc = msg->getSuperLoc();
11636     owner.Range = msg->getSuperLoc();
11637   }
11638 
11639   // Check whether the receiver is captured by any of the arguments.
11640   const ObjCMethodDecl *MD = msg->getMethodDecl();
11641   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
11642     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
11643       // noescape blocks should not be retained by the method.
11644       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
11645         continue;
11646       return diagnoseRetainCycle(*this, capturer, owner);
11647     }
11648   }
11649 }
11650 
11651 /// Check a property assign to see if it's likely to cause a retain cycle.
11652 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
11653   RetainCycleOwner owner;
11654   if (!findRetainCycleOwner(*this, receiver, owner))
11655     return;
11656 
11657   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
11658     diagnoseRetainCycle(*this, capturer, owner);
11659 }
11660 
11661 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
11662   RetainCycleOwner Owner;
11663   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
11664     return;
11665 
11666   // Because we don't have an expression for the variable, we have to set the
11667   // location explicitly here.
11668   Owner.Loc = Var->getLocation();
11669   Owner.Range = Var->getSourceRange();
11670 
11671   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
11672     diagnoseRetainCycle(*this, Capturer, Owner);
11673 }
11674 
11675 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
11676                                      Expr *RHS, bool isProperty) {
11677   // Check if RHS is an Objective-C object literal, which also can get
11678   // immediately zapped in a weak reference.  Note that we explicitly
11679   // allow ObjCStringLiterals, since those are designed to never really die.
11680   RHS = RHS->IgnoreParenImpCasts();
11681 
11682   // This enum needs to match with the 'select' in
11683   // warn_objc_arc_literal_assign (off-by-1).
11684   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
11685   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
11686     return false;
11687 
11688   S.Diag(Loc, diag::warn_arc_literal_assign)
11689     << (unsigned) Kind
11690     << (isProperty ? 0 : 1)
11691     << RHS->getSourceRange();
11692 
11693   return true;
11694 }
11695 
11696 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
11697                                     Qualifiers::ObjCLifetime LT,
11698                                     Expr *RHS, bool isProperty) {
11699   // Strip off any implicit cast added to get to the one ARC-specific.
11700   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11701     if (cast->getCastKind() == CK_ARCConsumeObject) {
11702       S.Diag(Loc, diag::warn_arc_retained_assign)
11703         << (LT == Qualifiers::OCL_ExplicitNone)
11704         << (isProperty ? 0 : 1)
11705         << RHS->getSourceRange();
11706       return true;
11707     }
11708     RHS = cast->getSubExpr();
11709   }
11710 
11711   if (LT == Qualifiers::OCL_Weak &&
11712       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
11713     return true;
11714 
11715   return false;
11716 }
11717 
11718 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
11719                               QualType LHS, Expr *RHS) {
11720   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
11721 
11722   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
11723     return false;
11724 
11725   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
11726     return true;
11727 
11728   return false;
11729 }
11730 
11731 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
11732                               Expr *LHS, Expr *RHS) {
11733   QualType LHSType;
11734   // PropertyRef on LHS type need be directly obtained from
11735   // its declaration as it has a PseudoType.
11736   ObjCPropertyRefExpr *PRE
11737     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11738   if (PRE && !PRE->isImplicitProperty()) {
11739     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11740     if (PD)
11741       LHSType = PD->getType();
11742   }
11743 
11744   if (LHSType.isNull())
11745     LHSType = LHS->getType();
11746 
11747   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
11748 
11749   if (LT == Qualifiers::OCL_Weak) {
11750     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
11751       getCurFunction()->markSafeWeakUse(LHS);
11752   }
11753 
11754   if (checkUnsafeAssigns(Loc, LHSType, RHS))
11755     return;
11756 
11757   // FIXME. Check for other life times.
11758   if (LT != Qualifiers::OCL_None)
11759     return;
11760 
11761   if (PRE) {
11762     if (PRE->isImplicitProperty())
11763       return;
11764     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11765     if (!PD)
11766       return;
11767 
11768     unsigned Attributes = PD->getPropertyAttributes();
11769     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
11770       // when 'assign' attribute was not explicitly specified
11771       // by user, ignore it and rely on property type itself
11772       // for lifetime info.
11773       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11774       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11775           LHSType->isObjCRetainableType())
11776         return;
11777 
11778       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11779         if (cast->getCastKind() == CK_ARCConsumeObject) {
11780           Diag(Loc, diag::warn_arc_retained_property_assign)
11781           << RHS->getSourceRange();
11782           return;
11783         }
11784         RHS = cast->getSubExpr();
11785       }
11786     }
11787     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
11788       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11789         return;
11790     }
11791   }
11792 }
11793 
11794 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11795 
11796 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11797                                         SourceLocation StmtLoc,
11798                                         const NullStmt *Body) {
11799   // Do not warn if the body is a macro that expands to nothing, e.g:
11800   //
11801   // #define CALL(x)
11802   // if (condition)
11803   //   CALL(0);
11804   if (Body->hasLeadingEmptyMacro())
11805     return false;
11806 
11807   // Get line numbers of statement and body.
11808   bool StmtLineInvalid;
11809   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
11810                                                       &StmtLineInvalid);
11811   if (StmtLineInvalid)
11812     return false;
11813 
11814   bool BodyLineInvalid;
11815   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11816                                                       &BodyLineInvalid);
11817   if (BodyLineInvalid)
11818     return false;
11819 
11820   // Warn if null statement and body are on the same line.
11821   if (StmtLine != BodyLine)
11822     return false;
11823 
11824   return true;
11825 }
11826 
11827 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
11828                                  const Stmt *Body,
11829                                  unsigned DiagID) {
11830   // Since this is a syntactic check, don't emit diagnostic for template
11831   // instantiations, this just adds noise.
11832   if (CurrentInstantiationScope)
11833     return;
11834 
11835   // The body should be a null statement.
11836   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11837   if (!NBody)
11838     return;
11839 
11840   // Do the usual checks.
11841   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11842     return;
11843 
11844   Diag(NBody->getSemiLoc(), DiagID);
11845   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11846 }
11847 
11848 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
11849                                  const Stmt *PossibleBody) {
11850   assert(!CurrentInstantiationScope); // Ensured by caller
11851 
11852   SourceLocation StmtLoc;
11853   const Stmt *Body;
11854   unsigned DiagID;
11855   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11856     StmtLoc = FS->getRParenLoc();
11857     Body = FS->getBody();
11858     DiagID = diag::warn_empty_for_body;
11859   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11860     StmtLoc = WS->getCond()->getSourceRange().getEnd();
11861     Body = WS->getBody();
11862     DiagID = diag::warn_empty_while_body;
11863   } else
11864     return; // Neither `for' nor `while'.
11865 
11866   // The body should be a null statement.
11867   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11868   if (!NBody)
11869     return;
11870 
11871   // Skip expensive checks if diagnostic is disabled.
11872   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
11873     return;
11874 
11875   // Do the usual checks.
11876   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11877     return;
11878 
11879   // `for(...);' and `while(...);' are popular idioms, so in order to keep
11880   // noise level low, emit diagnostics only if for/while is followed by a
11881   // CompoundStmt, e.g.:
11882   //    for (int i = 0; i < n; i++);
11883   //    {
11884   //      a(i);
11885   //    }
11886   // or if for/while is followed by a statement with more indentation
11887   // than for/while itself:
11888   //    for (int i = 0; i < n; i++);
11889   //      a(i);
11890   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
11891   if (!ProbableTypo) {
11892     bool BodyColInvalid;
11893     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
11894                              PossibleBody->getLocStart(),
11895                              &BodyColInvalid);
11896     if (BodyColInvalid)
11897       return;
11898 
11899     bool StmtColInvalid;
11900     unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
11901                              S->getLocStart(),
11902                              &StmtColInvalid);
11903     if (StmtColInvalid)
11904       return;
11905 
11906     if (BodyCol > StmtCol)
11907       ProbableTypo = true;
11908   }
11909 
11910   if (ProbableTypo) {
11911     Diag(NBody->getSemiLoc(), DiagID);
11912     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11913   }
11914 }
11915 
11916 //===--- CHECK: Warn on self move with std::move. -------------------------===//
11917 
11918 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
11919 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
11920                              SourceLocation OpLoc) {
11921   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11922     return;
11923 
11924   if (inTemplateInstantiation())
11925     return;
11926 
11927   // Strip parens and casts away.
11928   LHSExpr = LHSExpr->IgnoreParenImpCasts();
11929   RHSExpr = RHSExpr->IgnoreParenImpCasts();
11930 
11931   // Check for a call expression
11932   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
11933   if (!CE || CE->getNumArgs() != 1)
11934     return;
11935 
11936   // Check for a call to std::move
11937   if (!CE->isCallToStdMove())
11938     return;
11939 
11940   // Get argument from std::move
11941   RHSExpr = CE->getArg(0);
11942 
11943   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11944   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11945 
11946   // Two DeclRefExpr's, check that the decls are the same.
11947   if (LHSDeclRef && RHSDeclRef) {
11948     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11949       return;
11950     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11951         RHSDeclRef->getDecl()->getCanonicalDecl())
11952       return;
11953 
11954     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11955                                         << LHSExpr->getSourceRange()
11956                                         << RHSExpr->getSourceRange();
11957     return;
11958   }
11959 
11960   // Member variables require a different approach to check for self moves.
11961   // MemberExpr's are the same if every nested MemberExpr refers to the same
11962   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
11963   // the base Expr's are CXXThisExpr's.
11964   const Expr *LHSBase = LHSExpr;
11965   const Expr *RHSBase = RHSExpr;
11966   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
11967   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
11968   if (!LHSME || !RHSME)
11969     return;
11970 
11971   while (LHSME && RHSME) {
11972     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
11973         RHSME->getMemberDecl()->getCanonicalDecl())
11974       return;
11975 
11976     LHSBase = LHSME->getBase();
11977     RHSBase = RHSME->getBase();
11978     LHSME = dyn_cast<MemberExpr>(LHSBase);
11979     RHSME = dyn_cast<MemberExpr>(RHSBase);
11980   }
11981 
11982   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
11983   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
11984   if (LHSDeclRef && RHSDeclRef) {
11985     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11986       return;
11987     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11988         RHSDeclRef->getDecl()->getCanonicalDecl())
11989       return;
11990 
11991     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11992                                         << LHSExpr->getSourceRange()
11993                                         << RHSExpr->getSourceRange();
11994     return;
11995   }
11996 
11997   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
11998     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11999                                         << LHSExpr->getSourceRange()
12000                                         << RHSExpr->getSourceRange();
12001 }
12002 
12003 //===--- Layout compatibility ----------------------------------------------//
12004 
12005 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
12006 
12007 /// \brief Check if two enumeration types are layout-compatible.
12008 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
12009   // C++11 [dcl.enum] p8:
12010   // Two enumeration types are layout-compatible if they have the same
12011   // underlying type.
12012   return ED1->isComplete() && ED2->isComplete() &&
12013          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
12014 }
12015 
12016 /// \brief Check if two fields are layout-compatible.
12017 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
12018                                FieldDecl *Field2) {
12019   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
12020     return false;
12021 
12022   if (Field1->isBitField() != Field2->isBitField())
12023     return false;
12024 
12025   if (Field1->isBitField()) {
12026     // Make sure that the bit-fields are the same length.
12027     unsigned Bits1 = Field1->getBitWidthValue(C);
12028     unsigned Bits2 = Field2->getBitWidthValue(C);
12029 
12030     if (Bits1 != Bits2)
12031       return false;
12032   }
12033 
12034   return true;
12035 }
12036 
12037 /// \brief Check if two standard-layout structs are layout-compatible.
12038 /// (C++11 [class.mem] p17)
12039 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
12040                                      RecordDecl *RD2) {
12041   // If both records are C++ classes, check that base classes match.
12042   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
12043     // If one of records is a CXXRecordDecl we are in C++ mode,
12044     // thus the other one is a CXXRecordDecl, too.
12045     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
12046     // Check number of base classes.
12047     if (D1CXX->getNumBases() != D2CXX->getNumBases())
12048       return false;
12049 
12050     // Check the base classes.
12051     for (CXXRecordDecl::base_class_const_iterator
12052                Base1 = D1CXX->bases_begin(),
12053            BaseEnd1 = D1CXX->bases_end(),
12054               Base2 = D2CXX->bases_begin();
12055          Base1 != BaseEnd1;
12056          ++Base1, ++Base2) {
12057       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
12058         return false;
12059     }
12060   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
12061     // If only RD2 is a C++ class, it should have zero base classes.
12062     if (D2CXX->getNumBases() > 0)
12063       return false;
12064   }
12065 
12066   // Check the fields.
12067   RecordDecl::field_iterator Field2 = RD2->field_begin(),
12068                              Field2End = RD2->field_end(),
12069                              Field1 = RD1->field_begin(),
12070                              Field1End = RD1->field_end();
12071   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
12072     if (!isLayoutCompatible(C, *Field1, *Field2))
12073       return false;
12074   }
12075   if (Field1 != Field1End || Field2 != Field2End)
12076     return false;
12077 
12078   return true;
12079 }
12080 
12081 /// \brief Check if two standard-layout unions are layout-compatible.
12082 /// (C++11 [class.mem] p18)
12083 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
12084                                     RecordDecl *RD2) {
12085   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
12086   for (auto *Field2 : RD2->fields())
12087     UnmatchedFields.insert(Field2);
12088 
12089   for (auto *Field1 : RD1->fields()) {
12090     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
12091         I = UnmatchedFields.begin(),
12092         E = UnmatchedFields.end();
12093 
12094     for ( ; I != E; ++I) {
12095       if (isLayoutCompatible(C, Field1, *I)) {
12096         bool Result = UnmatchedFields.erase(*I);
12097         (void) Result;
12098         assert(Result);
12099         break;
12100       }
12101     }
12102     if (I == E)
12103       return false;
12104   }
12105 
12106   return UnmatchedFields.empty();
12107 }
12108 
12109 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
12110                                RecordDecl *RD2) {
12111   if (RD1->isUnion() != RD2->isUnion())
12112     return false;
12113 
12114   if (RD1->isUnion())
12115     return isLayoutCompatibleUnion(C, RD1, RD2);
12116   else
12117     return isLayoutCompatibleStruct(C, RD1, RD2);
12118 }
12119 
12120 /// \brief Check if two types are layout-compatible in C++11 sense.
12121 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
12122   if (T1.isNull() || T2.isNull())
12123     return false;
12124 
12125   // C++11 [basic.types] p11:
12126   // If two types T1 and T2 are the same type, then T1 and T2 are
12127   // layout-compatible types.
12128   if (C.hasSameType(T1, T2))
12129     return true;
12130 
12131   T1 = T1.getCanonicalType().getUnqualifiedType();
12132   T2 = T2.getCanonicalType().getUnqualifiedType();
12133 
12134   const Type::TypeClass TC1 = T1->getTypeClass();
12135   const Type::TypeClass TC2 = T2->getTypeClass();
12136 
12137   if (TC1 != TC2)
12138     return false;
12139 
12140   if (TC1 == Type::Enum) {
12141     return isLayoutCompatible(C,
12142                               cast<EnumType>(T1)->getDecl(),
12143                               cast<EnumType>(T2)->getDecl());
12144   } else if (TC1 == Type::Record) {
12145     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
12146       return false;
12147 
12148     return isLayoutCompatible(C,
12149                               cast<RecordType>(T1)->getDecl(),
12150                               cast<RecordType>(T2)->getDecl());
12151   }
12152 
12153   return false;
12154 }
12155 
12156 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
12157 
12158 /// \brief Given a type tag expression find the type tag itself.
12159 ///
12160 /// \param TypeExpr Type tag expression, as it appears in user's code.
12161 ///
12162 /// \param VD Declaration of an identifier that appears in a type tag.
12163 ///
12164 /// \param MagicValue Type tag magic value.
12165 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
12166                             const ValueDecl **VD, uint64_t *MagicValue) {
12167   while(true) {
12168     if (!TypeExpr)
12169       return false;
12170 
12171     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
12172 
12173     switch (TypeExpr->getStmtClass()) {
12174     case Stmt::UnaryOperatorClass: {
12175       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
12176       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
12177         TypeExpr = UO->getSubExpr();
12178         continue;
12179       }
12180       return false;
12181     }
12182 
12183     case Stmt::DeclRefExprClass: {
12184       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
12185       *VD = DRE->getDecl();
12186       return true;
12187     }
12188 
12189     case Stmt::IntegerLiteralClass: {
12190       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
12191       llvm::APInt MagicValueAPInt = IL->getValue();
12192       if (MagicValueAPInt.getActiveBits() <= 64) {
12193         *MagicValue = MagicValueAPInt.getZExtValue();
12194         return true;
12195       } else
12196         return false;
12197     }
12198 
12199     case Stmt::BinaryConditionalOperatorClass:
12200     case Stmt::ConditionalOperatorClass: {
12201       const AbstractConditionalOperator *ACO =
12202           cast<AbstractConditionalOperator>(TypeExpr);
12203       bool Result;
12204       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
12205         if (Result)
12206           TypeExpr = ACO->getTrueExpr();
12207         else
12208           TypeExpr = ACO->getFalseExpr();
12209         continue;
12210       }
12211       return false;
12212     }
12213 
12214     case Stmt::BinaryOperatorClass: {
12215       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
12216       if (BO->getOpcode() == BO_Comma) {
12217         TypeExpr = BO->getRHS();
12218         continue;
12219       }
12220       return false;
12221     }
12222 
12223     default:
12224       return false;
12225     }
12226   }
12227 }
12228 
12229 /// \brief Retrieve the C type corresponding to type tag TypeExpr.
12230 ///
12231 /// \param TypeExpr Expression that specifies a type tag.
12232 ///
12233 /// \param MagicValues Registered magic values.
12234 ///
12235 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
12236 ///        kind.
12237 ///
12238 /// \param TypeInfo Information about the corresponding C type.
12239 ///
12240 /// \returns true if the corresponding C type was found.
12241 static bool GetMatchingCType(
12242         const IdentifierInfo *ArgumentKind,
12243         const Expr *TypeExpr, const ASTContext &Ctx,
12244         const llvm::DenseMap<Sema::TypeTagMagicValue,
12245                              Sema::TypeTagData> *MagicValues,
12246         bool &FoundWrongKind,
12247         Sema::TypeTagData &TypeInfo) {
12248   FoundWrongKind = false;
12249 
12250   // Variable declaration that has type_tag_for_datatype attribute.
12251   const ValueDecl *VD = nullptr;
12252 
12253   uint64_t MagicValue;
12254 
12255   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
12256     return false;
12257 
12258   if (VD) {
12259     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
12260       if (I->getArgumentKind() != ArgumentKind) {
12261         FoundWrongKind = true;
12262         return false;
12263       }
12264       TypeInfo.Type = I->getMatchingCType();
12265       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
12266       TypeInfo.MustBeNull = I->getMustBeNull();
12267       return true;
12268     }
12269     return false;
12270   }
12271 
12272   if (!MagicValues)
12273     return false;
12274 
12275   llvm::DenseMap<Sema::TypeTagMagicValue,
12276                  Sema::TypeTagData>::const_iterator I =
12277       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
12278   if (I == MagicValues->end())
12279     return false;
12280 
12281   TypeInfo = I->second;
12282   return true;
12283 }
12284 
12285 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
12286                                       uint64_t MagicValue, QualType Type,
12287                                       bool LayoutCompatible,
12288                                       bool MustBeNull) {
12289   if (!TypeTagForDatatypeMagicValues)
12290     TypeTagForDatatypeMagicValues.reset(
12291         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
12292 
12293   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
12294   (*TypeTagForDatatypeMagicValues)[Magic] =
12295       TypeTagData(Type, LayoutCompatible, MustBeNull);
12296 }
12297 
12298 static bool IsSameCharType(QualType T1, QualType T2) {
12299   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
12300   if (!BT1)
12301     return false;
12302 
12303   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
12304   if (!BT2)
12305     return false;
12306 
12307   BuiltinType::Kind T1Kind = BT1->getKind();
12308   BuiltinType::Kind T2Kind = BT2->getKind();
12309 
12310   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
12311          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
12312          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
12313          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
12314 }
12315 
12316 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
12317                                     const ArrayRef<const Expr *> ExprArgs,
12318                                     SourceLocation CallSiteLoc) {
12319   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
12320   bool IsPointerAttr = Attr->getIsPointer();
12321 
12322   // Retrieve the argument representing the 'type_tag'.
12323   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
12324   if (TypeTagIdxAST >= ExprArgs.size()) {
12325     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
12326         << 0 << Attr->getTypeTagIdx().getSourceIndex();
12327     return;
12328   }
12329   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
12330   bool FoundWrongKind;
12331   TypeTagData TypeInfo;
12332   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
12333                         TypeTagForDatatypeMagicValues.get(),
12334                         FoundWrongKind, TypeInfo)) {
12335     if (FoundWrongKind)
12336       Diag(TypeTagExpr->getExprLoc(),
12337            diag::warn_type_tag_for_datatype_wrong_kind)
12338         << TypeTagExpr->getSourceRange();
12339     return;
12340   }
12341 
12342   // Retrieve the argument representing the 'arg_idx'.
12343   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
12344   if (ArgumentIdxAST >= ExprArgs.size()) {
12345     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
12346         << 1 << Attr->getArgumentIdx().getSourceIndex();
12347     return;
12348   }
12349   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
12350   if (IsPointerAttr) {
12351     // Skip implicit cast of pointer to `void *' (as a function argument).
12352     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
12353       if (ICE->getType()->isVoidPointerType() &&
12354           ICE->getCastKind() == CK_BitCast)
12355         ArgumentExpr = ICE->getSubExpr();
12356   }
12357   QualType ArgumentType = ArgumentExpr->getType();
12358 
12359   // Passing a `void*' pointer shouldn't trigger a warning.
12360   if (IsPointerAttr && ArgumentType->isVoidPointerType())
12361     return;
12362 
12363   if (TypeInfo.MustBeNull) {
12364     // Type tag with matching void type requires a null pointer.
12365     if (!ArgumentExpr->isNullPointerConstant(Context,
12366                                              Expr::NPC_ValueDependentIsNotNull)) {
12367       Diag(ArgumentExpr->getExprLoc(),
12368            diag::warn_type_safety_null_pointer_required)
12369           << ArgumentKind->getName()
12370           << ArgumentExpr->getSourceRange()
12371           << TypeTagExpr->getSourceRange();
12372     }
12373     return;
12374   }
12375 
12376   QualType RequiredType = TypeInfo.Type;
12377   if (IsPointerAttr)
12378     RequiredType = Context.getPointerType(RequiredType);
12379 
12380   bool mismatch = false;
12381   if (!TypeInfo.LayoutCompatible) {
12382     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
12383 
12384     // C++11 [basic.fundamental] p1:
12385     // Plain char, signed char, and unsigned char are three distinct types.
12386     //
12387     // But we treat plain `char' as equivalent to `signed char' or `unsigned
12388     // char' depending on the current char signedness mode.
12389     if (mismatch)
12390       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
12391                                            RequiredType->getPointeeType())) ||
12392           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
12393         mismatch = false;
12394   } else
12395     if (IsPointerAttr)
12396       mismatch = !isLayoutCompatible(Context,
12397                                      ArgumentType->getPointeeType(),
12398                                      RequiredType->getPointeeType());
12399     else
12400       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
12401 
12402   if (mismatch)
12403     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
12404         << ArgumentType << ArgumentKind
12405         << TypeInfo.LayoutCompatible << RequiredType
12406         << ArgumentExpr->getSourceRange()
12407         << TypeTagExpr->getSourceRange();
12408 }
12409 
12410 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
12411                                          CharUnits Alignment) {
12412   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
12413 }
12414 
12415 void Sema::DiagnoseMisalignedMembers() {
12416   for (MisalignedMember &m : MisalignedMembers) {
12417     const NamedDecl *ND = m.RD;
12418     if (ND->getName().empty()) {
12419       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
12420         ND = TD;
12421     }
12422     Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
12423         << m.MD << ND << m.E->getSourceRange();
12424   }
12425   MisalignedMembers.clear();
12426 }
12427 
12428 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
12429   E = E->IgnoreParens();
12430   if (!T->isPointerType() && !T->isIntegerType())
12431     return;
12432   if (isa<UnaryOperator>(E) &&
12433       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
12434     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12435     if (isa<MemberExpr>(Op)) {
12436       auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
12437                           MisalignedMember(Op));
12438       if (MA != MisalignedMembers.end() &&
12439           (T->isIntegerType() ||
12440            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
12441                                    Context.getTypeAlignInChars(
12442                                        T->getPointeeType()) <= MA->Alignment))))
12443         MisalignedMembers.erase(MA);
12444     }
12445   }
12446 }
12447 
12448 void Sema::RefersToMemberWithReducedAlignment(
12449     Expr *E,
12450     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
12451         Action) {
12452   const auto *ME = dyn_cast<MemberExpr>(E);
12453   if (!ME)
12454     return;
12455 
12456   // No need to check expressions with an __unaligned-qualified type.
12457   if (E->getType().getQualifiers().hasUnaligned())
12458     return;
12459 
12460   // For a chain of MemberExpr like "a.b.c.d" this list
12461   // will keep FieldDecl's like [d, c, b].
12462   SmallVector<FieldDecl *, 4> ReverseMemberChain;
12463   const MemberExpr *TopME = nullptr;
12464   bool AnyIsPacked = false;
12465   do {
12466     QualType BaseType = ME->getBase()->getType();
12467     if (ME->isArrow())
12468       BaseType = BaseType->getPointeeType();
12469     RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
12470     if (RD->isInvalidDecl())
12471       return;
12472 
12473     ValueDecl *MD = ME->getMemberDecl();
12474     auto *FD = dyn_cast<FieldDecl>(MD);
12475     // We do not care about non-data members.
12476     if (!FD || FD->isInvalidDecl())
12477       return;
12478 
12479     AnyIsPacked =
12480         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
12481     ReverseMemberChain.push_back(FD);
12482 
12483     TopME = ME;
12484     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
12485   } while (ME);
12486   assert(TopME && "We did not compute a topmost MemberExpr!");
12487 
12488   // Not the scope of this diagnostic.
12489   if (!AnyIsPacked)
12490     return;
12491 
12492   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
12493   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
12494   // TODO: The innermost base of the member expression may be too complicated.
12495   // For now, just disregard these cases. This is left for future
12496   // improvement.
12497   if (!DRE && !isa<CXXThisExpr>(TopBase))
12498       return;
12499 
12500   // Alignment expected by the whole expression.
12501   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
12502 
12503   // No need to do anything else with this case.
12504   if (ExpectedAlignment.isOne())
12505     return;
12506 
12507   // Synthesize offset of the whole access.
12508   CharUnits Offset;
12509   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
12510        I++) {
12511     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
12512   }
12513 
12514   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
12515   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
12516       ReverseMemberChain.back()->getParent()->getTypeForDecl());
12517 
12518   // The base expression of the innermost MemberExpr may give
12519   // stronger guarantees than the class containing the member.
12520   if (DRE && !TopME->isArrow()) {
12521     const ValueDecl *VD = DRE->getDecl();
12522     if (!VD->getType()->isReferenceType())
12523       CompleteObjectAlignment =
12524           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
12525   }
12526 
12527   // Check if the synthesized offset fulfills the alignment.
12528   if (Offset % ExpectedAlignment != 0 ||
12529       // It may fulfill the offset it but the effective alignment may still be
12530       // lower than the expected expression alignment.
12531       CompleteObjectAlignment < ExpectedAlignment) {
12532     // If this happens, we want to determine a sensible culprit of this.
12533     // Intuitively, watching the chain of member expressions from right to
12534     // left, we start with the required alignment (as required by the field
12535     // type) but some packed attribute in that chain has reduced the alignment.
12536     // It may happen that another packed structure increases it again. But if
12537     // we are here such increase has not been enough. So pointing the first
12538     // FieldDecl that either is packed or else its RecordDecl is,
12539     // seems reasonable.
12540     FieldDecl *FD = nullptr;
12541     CharUnits Alignment;
12542     for (FieldDecl *FDI : ReverseMemberChain) {
12543       if (FDI->hasAttr<PackedAttr>() ||
12544           FDI->getParent()->hasAttr<PackedAttr>()) {
12545         FD = FDI;
12546         Alignment = std::min(
12547             Context.getTypeAlignInChars(FD->getType()),
12548             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
12549         break;
12550       }
12551     }
12552     assert(FD && "We did not find a packed FieldDecl!");
12553     Action(E, FD->getParent(), FD, Alignment);
12554   }
12555 }
12556 
12557 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
12558   using namespace std::placeholders;
12559 
12560   RefersToMemberWithReducedAlignment(
12561       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
12562                      _2, _3, _4));
12563 }
12564