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/ASTContext.h"
16 #include "clang/AST/CharUnits.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/EvaluatedExprVisitor.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/ExprObjC.h"
23 #include "clang/AST/ExprOpenMP.h"
24 #include "clang/AST/StmtCXX.h"
25 #include "clang/AST/StmtObjC.h"
26 #include "clang/Analysis/Analyses/FormatString.h"
27 #include "clang/Basic/CharInfo.h"
28 #include "clang/Basic/TargetBuiltins.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
31 #include "clang/Sema/Initialization.h"
32 #include "clang/Sema/Lookup.h"
33 #include "clang/Sema/ScopeInfo.h"
34 #include "clang/Sema/Sema.h"
35 #include "clang/Sema/SemaInternal.h"
36 #include "llvm/ADT/STLExtras.h"
37 #include "llvm/ADT/SmallBitVector.h"
38 #include "llvm/ADT/SmallString.h"
39 #include "llvm/Support/ConvertUTF.h"
40 #include "llvm/Support/Format.h"
41 #include "llvm/Support/Locale.h"
42 #include "llvm/Support/raw_ostream.h"
43 
44 using namespace clang;
45 using namespace sema;
46 
47 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
48                                                     unsigned ByteNo) const {
49   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
50                                Context.getTargetInfo());
51 }
52 
53 /// Checks that a call expression's argument count is the desired number.
54 /// This is useful when doing custom type-checking.  Returns true on error.
55 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
56   unsigned argCount = call->getNumArgs();
57   if (argCount == desiredArgCount) return false;
58 
59   if (argCount < desiredArgCount)
60     return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
61         << 0 /*function call*/ << desiredArgCount << argCount
62         << call->getSourceRange();
63 
64   // Highlight all the excess arguments.
65   SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
66                     call->getArg(argCount - 1)->getLocEnd());
67 
68   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
69     << 0 /*function call*/ << desiredArgCount << argCount
70     << call->getArg(1)->getSourceRange();
71 }
72 
73 /// Check that the first argument to __builtin_annotation is an integer
74 /// and the second argument is a non-wide string literal.
75 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
76   if (checkArgCount(S, TheCall, 2))
77     return true;
78 
79   // First argument should be an integer.
80   Expr *ValArg = TheCall->getArg(0);
81   QualType Ty = ValArg->getType();
82   if (!Ty->isIntegerType()) {
83     S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
84       << ValArg->getSourceRange();
85     return true;
86   }
87 
88   // Second argument should be a constant string.
89   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
90   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
91   if (!Literal || !Literal->isAscii()) {
92     S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
93       << StrArg->getSourceRange();
94     return true;
95   }
96 
97   TheCall->setType(Ty);
98   return false;
99 }
100 
101 /// Check that the argument to __builtin_addressof is a glvalue, and set the
102 /// result type to the corresponding pointer type.
103 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
104   if (checkArgCount(S, TheCall, 1))
105     return true;
106 
107   ExprResult Arg(TheCall->getArg(0));
108   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
109   if (ResultType.isNull())
110     return true;
111 
112   TheCall->setArg(0, Arg.get());
113   TheCall->setType(ResultType);
114   return false;
115 }
116 
117 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
118   if (checkArgCount(S, TheCall, 3))
119     return true;
120 
121   // First two arguments should be integers.
122   for (unsigned I = 0; I < 2; ++I) {
123     Expr *Arg = TheCall->getArg(I);
124     QualType Ty = Arg->getType();
125     if (!Ty->isIntegerType()) {
126       S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
127           << Ty << Arg->getSourceRange();
128       return true;
129     }
130   }
131 
132   // Third argument should be a pointer to a non-const integer.
133   // IRGen correctly handles volatile, restrict, and address spaces, and
134   // the other qualifiers aren't possible.
135   {
136     Expr *Arg = TheCall->getArg(2);
137     QualType Ty = Arg->getType();
138     const auto *PtrTy = Ty->getAs<PointerType>();
139     if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
140           !PtrTy->getPointeeType().isConstQualified())) {
141       S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
142           << Ty << Arg->getSourceRange();
143       return true;
144     }
145   }
146 
147   return false;
148 }
149 
150 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
151 		                  CallExpr *TheCall, unsigned SizeIdx,
152                                   unsigned DstSizeIdx) {
153   if (TheCall->getNumArgs() <= SizeIdx ||
154       TheCall->getNumArgs() <= DstSizeIdx)
155     return;
156 
157   const Expr *SizeArg = TheCall->getArg(SizeIdx);
158   const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
159 
160   llvm::APSInt Size, DstSize;
161 
162   // find out if both sizes are known at compile time
163   if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
164       !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
165     return;
166 
167   if (Size.ule(DstSize))
168     return;
169 
170   // confirmed overflow so generate the diagnostic.
171   IdentifierInfo *FnName = FDecl->getIdentifier();
172   SourceLocation SL = TheCall->getLocStart();
173   SourceRange SR = TheCall->getSourceRange();
174 
175   S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
176 }
177 
178 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
179   if (checkArgCount(S, BuiltinCall, 2))
180     return true;
181 
182   SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
183   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
184   Expr *Call = BuiltinCall->getArg(0);
185   Expr *Chain = BuiltinCall->getArg(1);
186 
187   if (Call->getStmtClass() != Stmt::CallExprClass) {
188     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
189         << Call->getSourceRange();
190     return true;
191   }
192 
193   auto CE = cast<CallExpr>(Call);
194   if (CE->getCallee()->getType()->isBlockPointerType()) {
195     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
196         << Call->getSourceRange();
197     return true;
198   }
199 
200   const Decl *TargetDecl = CE->getCalleeDecl();
201   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
202     if (FD->getBuiltinID()) {
203       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
204           << Call->getSourceRange();
205       return true;
206     }
207 
208   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
209     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
210         << Call->getSourceRange();
211     return true;
212   }
213 
214   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
215   if (ChainResult.isInvalid())
216     return true;
217   if (!ChainResult.get()->getType()->isPointerType()) {
218     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
219         << Chain->getSourceRange();
220     return true;
221   }
222 
223   QualType ReturnTy = CE->getCallReturnType(S.Context);
224   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
225   QualType BuiltinTy = S.Context.getFunctionType(
226       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
227   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
228 
229   Builtin =
230       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
231 
232   BuiltinCall->setType(CE->getType());
233   BuiltinCall->setValueKind(CE->getValueKind());
234   BuiltinCall->setObjectKind(CE->getObjectKind());
235   BuiltinCall->setCallee(Builtin);
236   BuiltinCall->setArg(1, ChainResult.get());
237 
238   return false;
239 }
240 
241 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
242                                      Scope::ScopeFlags NeededScopeFlags,
243                                      unsigned DiagID) {
244   // Scopes aren't available during instantiation. Fortunately, builtin
245   // functions cannot be template args so they cannot be formed through template
246   // instantiation. Therefore checking once during the parse is sufficient.
247   if (!SemaRef.ActiveTemplateInstantiations.empty())
248     return false;
249 
250   Scope *S = SemaRef.getCurScope();
251   while (S && !S->isSEHExceptScope())
252     S = S->getParent();
253   if (!S || !(S->getFlags() & NeededScopeFlags)) {
254     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
255     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
256         << DRE->getDecl()->getIdentifier();
257     return true;
258   }
259 
260   return false;
261 }
262 
263 static inline bool isBlockPointer(Expr *Arg) {
264   return Arg->getType()->isBlockPointerType();
265 }
266 
267 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
268 /// void*, which is a requirement of device side enqueue.
269 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
270   const BlockPointerType *BPT =
271       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
272   ArrayRef<QualType> Params =
273       BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
274   unsigned ArgCounter = 0;
275   bool IllegalParams = false;
276   // Iterate through the block parameters until either one is found that is not
277   // a local void*, or the block is valid.
278   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
279        I != E; ++I, ++ArgCounter) {
280     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
281         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
282             LangAS::opencl_local) {
283       // Get the location of the error. If a block literal has been passed
284       // (BlockExpr) then we can point straight to the offending argument,
285       // else we just point to the variable reference.
286       SourceLocation ErrorLoc;
287       if (isa<BlockExpr>(BlockArg)) {
288         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
289         ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
290       } else if (isa<DeclRefExpr>(BlockArg)) {
291         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
292       }
293       S.Diag(ErrorLoc,
294              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
295       IllegalParams = true;
296     }
297   }
298 
299   return IllegalParams;
300 }
301 
302 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
303 /// get_kernel_work_group_size
304 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
305 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
306   if (checkArgCount(S, TheCall, 1))
307     return true;
308 
309   Expr *BlockArg = TheCall->getArg(0);
310   if (!isBlockPointer(BlockArg)) {
311     S.Diag(BlockArg->getLocStart(),
312            diag::err_opencl_enqueue_kernel_expected_type) << "block";
313     return true;
314   }
315   return checkOpenCLBlockArgs(S, BlockArg);
316 }
317 
318 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
319                                             unsigned Start, unsigned End);
320 
321 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
322 /// 'local void*' parameter of passed block.
323 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
324                                            Expr *BlockArg,
325                                            unsigned NumNonVarArgs) {
326   const BlockPointerType *BPT =
327       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
328   unsigned NumBlockParams =
329       BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
330   unsigned TotalNumArgs = TheCall->getNumArgs();
331 
332   // For each argument passed to the block, a corresponding uint needs to
333   // be passed to describe the size of the local memory.
334   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
335     S.Diag(TheCall->getLocStart(),
336            diag::err_opencl_enqueue_kernel_local_size_args);
337     return true;
338   }
339 
340   // Check that the sizes of the local memory are specified by integers.
341   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
342                                          TotalNumArgs - 1);
343 }
344 
345 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
346 /// overload formats specified in Table 6.13.17.1.
347 /// int enqueue_kernel(queue_t queue,
348 ///                    kernel_enqueue_flags_t flags,
349 ///                    const ndrange_t ndrange,
350 ///                    void (^block)(void))
351 /// int enqueue_kernel(queue_t queue,
352 ///                    kernel_enqueue_flags_t flags,
353 ///                    const ndrange_t ndrange,
354 ///                    uint num_events_in_wait_list,
355 ///                    clk_event_t *event_wait_list,
356 ///                    clk_event_t *event_ret,
357 ///                    void (^block)(void))
358 /// int enqueue_kernel(queue_t queue,
359 ///                    kernel_enqueue_flags_t flags,
360 ///                    const ndrange_t ndrange,
361 ///                    void (^block)(local void*, ...),
362 ///                    uint size0, ...)
363 /// int enqueue_kernel(queue_t queue,
364 ///                    kernel_enqueue_flags_t flags,
365 ///                    const ndrange_t ndrange,
366 ///                    uint num_events_in_wait_list,
367 ///                    clk_event_t *event_wait_list,
368 ///                    clk_event_t *event_ret,
369 ///                    void (^block)(local void*, ...),
370 ///                    uint size0, ...)
371 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
372   unsigned NumArgs = TheCall->getNumArgs();
373 
374   if (NumArgs < 4) {
375     S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
376     return true;
377   }
378 
379   Expr *Arg0 = TheCall->getArg(0);
380   Expr *Arg1 = TheCall->getArg(1);
381   Expr *Arg2 = TheCall->getArg(2);
382   Expr *Arg3 = TheCall->getArg(3);
383 
384   // First argument always needs to be a queue_t type.
385   if (!Arg0->getType()->isQueueT()) {
386     S.Diag(TheCall->getArg(0)->getLocStart(),
387            diag::err_opencl_enqueue_kernel_expected_type)
388         << S.Context.OCLQueueTy;
389     return true;
390   }
391 
392   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
393   if (!Arg1->getType()->isIntegerType()) {
394     S.Diag(TheCall->getArg(1)->getLocStart(),
395            diag::err_opencl_enqueue_kernel_expected_type)
396         << "'kernel_enqueue_flags_t' (i.e. uint)";
397     return true;
398   }
399 
400   // Third argument is always an ndrange_t type.
401   if (!Arg2->getType()->isNDRangeT()) {
402     S.Diag(TheCall->getArg(2)->getLocStart(),
403            diag::err_opencl_enqueue_kernel_expected_type)
404         << S.Context.OCLNDRangeTy;
405     return true;
406   }
407 
408   // With four arguments, there is only one form that the function could be
409   // called in: no events and no variable arguments.
410   if (NumArgs == 4) {
411     // check that the last argument is the right block type.
412     if (!isBlockPointer(Arg3)) {
413       S.Diag(Arg3->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type)
414           << "block";
415       return true;
416     }
417     // we have a block type, check the prototype
418     const BlockPointerType *BPT =
419         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
420     if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
421       S.Diag(Arg3->getLocStart(),
422              diag::err_opencl_enqueue_kernel_blocks_no_args);
423       return true;
424     }
425     return false;
426   }
427   // we can have block + varargs.
428   if (isBlockPointer(Arg3))
429     return (checkOpenCLBlockArgs(S, Arg3) ||
430             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
431   // last two cases with either exactly 7 args or 7 args and varargs.
432   if (NumArgs >= 7) {
433     // check common block argument.
434     Expr *Arg6 = TheCall->getArg(6);
435     if (!isBlockPointer(Arg6)) {
436       S.Diag(Arg6->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type)
437           << "block";
438       return true;
439     }
440     if (checkOpenCLBlockArgs(S, Arg6))
441       return true;
442 
443     // Forth argument has to be any integer type.
444     if (!Arg3->getType()->isIntegerType()) {
445       S.Diag(TheCall->getArg(3)->getLocStart(),
446              diag::err_opencl_enqueue_kernel_expected_type)
447           << "integer";
448       return true;
449     }
450     // check remaining common arguments.
451     Expr *Arg4 = TheCall->getArg(4);
452     Expr *Arg5 = TheCall->getArg(5);
453 
454     // Fith argument is always passed as pointers to clk_event_t.
455     if (!Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
456       S.Diag(TheCall->getArg(4)->getLocStart(),
457              diag::err_opencl_enqueue_kernel_expected_type)
458           << S.Context.getPointerType(S.Context.OCLClkEventTy);
459       return true;
460     }
461 
462     // Sixth argument is always passed as pointers to clk_event_t.
463     if (!(Arg5->getType()->isPointerType() &&
464           Arg5->getType()->getPointeeType()->isClkEventT())) {
465       S.Diag(TheCall->getArg(5)->getLocStart(),
466              diag::err_opencl_enqueue_kernel_expected_type)
467           << S.Context.getPointerType(S.Context.OCLClkEventTy);
468       return true;
469     }
470 
471     if (NumArgs == 7)
472       return false;
473 
474     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
475   }
476 
477   // None of the specific case has been detected, give generic error
478   S.Diag(TheCall->getLocStart(),
479          diag::err_opencl_enqueue_kernel_incorrect_args);
480   return true;
481 }
482 
483 /// Returns OpenCL access qual.
484 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
485     return D->getAttr<OpenCLAccessAttr>();
486 }
487 
488 /// Returns true if pipe element type is different from the pointer.
489 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
490   const Expr *Arg0 = Call->getArg(0);
491   // First argument type should always be pipe.
492   if (!Arg0->getType()->isPipeType()) {
493     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
494         << Call->getDirectCallee() << Arg0->getSourceRange();
495     return true;
496   }
497   OpenCLAccessAttr *AccessQual =
498       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
499   // Validates the access qualifier is compatible with the call.
500   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
501   // read_only and write_only, and assumed to be read_only if no qualifier is
502   // specified.
503   switch (Call->getDirectCallee()->getBuiltinID()) {
504   case Builtin::BIread_pipe:
505   case Builtin::BIreserve_read_pipe:
506   case Builtin::BIcommit_read_pipe:
507   case Builtin::BIwork_group_reserve_read_pipe:
508   case Builtin::BIsub_group_reserve_read_pipe:
509   case Builtin::BIwork_group_commit_read_pipe:
510   case Builtin::BIsub_group_commit_read_pipe:
511     if (!(!AccessQual || AccessQual->isReadOnly())) {
512       S.Diag(Arg0->getLocStart(),
513              diag::err_opencl_builtin_pipe_invalid_access_modifier)
514           << "read_only" << Arg0->getSourceRange();
515       return true;
516     }
517     break;
518   case Builtin::BIwrite_pipe:
519   case Builtin::BIreserve_write_pipe:
520   case Builtin::BIcommit_write_pipe:
521   case Builtin::BIwork_group_reserve_write_pipe:
522   case Builtin::BIsub_group_reserve_write_pipe:
523   case Builtin::BIwork_group_commit_write_pipe:
524   case Builtin::BIsub_group_commit_write_pipe:
525     if (!(AccessQual && AccessQual->isWriteOnly())) {
526       S.Diag(Arg0->getLocStart(),
527              diag::err_opencl_builtin_pipe_invalid_access_modifier)
528           << "write_only" << Arg0->getSourceRange();
529       return true;
530     }
531     break;
532   default:
533     break;
534   }
535   return false;
536 }
537 
538 /// Returns true if pipe element type is different from the pointer.
539 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
540   const Expr *Arg0 = Call->getArg(0);
541   const Expr *ArgIdx = Call->getArg(Idx);
542   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
543   const QualType EltTy = PipeTy->getElementType();
544   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
545   // The Idx argument should be a pointer and the type of the pointer and
546   // the type of pipe element should also be the same.
547   if (!ArgTy ||
548       !S.Context.hasSameType(
549           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
550     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
551         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
552         << ArgIdx->getType() << ArgIdx->getSourceRange();
553     return true;
554   }
555   return false;
556 }
557 
558 // \brief Performs semantic analysis for the read/write_pipe call.
559 // \param S Reference to the semantic analyzer.
560 // \param Call A pointer to the builtin call.
561 // \return True if a semantic error has been found, false otherwise.
562 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
563   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
564   // functions have two forms.
565   switch (Call->getNumArgs()) {
566   case 2: {
567     if (checkOpenCLPipeArg(S, Call))
568       return true;
569     // The call with 2 arguments should be
570     // read/write_pipe(pipe T, T*).
571     // Check packet type T.
572     if (checkOpenCLPipePacketType(S, Call, 1))
573       return true;
574   } break;
575 
576   case 4: {
577     if (checkOpenCLPipeArg(S, Call))
578       return true;
579     // The call with 4 arguments should be
580     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
581     // Check reserve_id_t.
582     if (!Call->getArg(1)->getType()->isReserveIDT()) {
583       S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
584           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
585           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
586       return true;
587     }
588 
589     // Check the index.
590     const Expr *Arg2 = Call->getArg(2);
591     if (!Arg2->getType()->isIntegerType() &&
592         !Arg2->getType()->isUnsignedIntegerType()) {
593       S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
594           << Call->getDirectCallee() << S.Context.UnsignedIntTy
595           << Arg2->getType() << Arg2->getSourceRange();
596       return true;
597     }
598 
599     // Check packet type T.
600     if (checkOpenCLPipePacketType(S, Call, 3))
601       return true;
602   } break;
603   default:
604     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
605         << Call->getDirectCallee() << Call->getSourceRange();
606     return true;
607   }
608 
609   return false;
610 }
611 
612 // \brief Performs a semantic analysis on the {work_group_/sub_group_
613 //        /_}reserve_{read/write}_pipe
614 // \param S Reference to the semantic analyzer.
615 // \param Call The call to the builtin function to be analyzed.
616 // \return True if a semantic error was found, false otherwise.
617 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
618   if (checkArgCount(S, Call, 2))
619     return true;
620 
621   if (checkOpenCLPipeArg(S, Call))
622     return true;
623 
624   // Check the reserve size.
625   if (!Call->getArg(1)->getType()->isIntegerType() &&
626       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
627     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
628         << Call->getDirectCallee() << S.Context.UnsignedIntTy
629         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
630     return true;
631   }
632 
633   return false;
634 }
635 
636 // \brief Performs a semantic analysis on {work_group_/sub_group_
637 //        /_}commit_{read/write}_pipe
638 // \param S Reference to the semantic analyzer.
639 // \param Call The call to the builtin function to be analyzed.
640 // \return True if a semantic error was found, false otherwise.
641 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
642   if (checkArgCount(S, Call, 2))
643     return true;
644 
645   if (checkOpenCLPipeArg(S, Call))
646     return true;
647 
648   // Check reserve_id_t.
649   if (!Call->getArg(1)->getType()->isReserveIDT()) {
650     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
651         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
652         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
653     return true;
654   }
655 
656   return false;
657 }
658 
659 // \brief Performs a semantic analysis on the call to built-in Pipe
660 //        Query Functions.
661 // \param S Reference to the semantic analyzer.
662 // \param Call The call to the builtin function to be analyzed.
663 // \return True if a semantic error was found, false otherwise.
664 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
665   if (checkArgCount(S, Call, 1))
666     return true;
667 
668   if (!Call->getArg(0)->getType()->isPipeType()) {
669     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
670         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
671     return true;
672   }
673 
674   return false;
675 }
676 // \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
677 // \brief Performs semantic analysis for the to_global/local/private call.
678 // \param S Reference to the semantic analyzer.
679 // \param BuiltinID ID of the builtin function.
680 // \param Call A pointer to the builtin call.
681 // \return True if a semantic error has been found, false otherwise.
682 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
683                                     CallExpr *Call) {
684   if (Call->getNumArgs() != 1) {
685     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
686         << Call->getDirectCallee() << Call->getSourceRange();
687     return true;
688   }
689 
690   auto RT = Call->getArg(0)->getType();
691   if (!RT->isPointerType() || RT->getPointeeType()
692       .getAddressSpace() == LangAS::opencl_constant) {
693     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
694         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
695     return true;
696   }
697 
698   RT = RT->getPointeeType();
699   auto Qual = RT.getQualifiers();
700   switch (BuiltinID) {
701   case Builtin::BIto_global:
702     Qual.setAddressSpace(LangAS::opencl_global);
703     break;
704   case Builtin::BIto_local:
705     Qual.setAddressSpace(LangAS::opencl_local);
706     break;
707   default:
708     Qual.removeAddressSpace();
709   }
710   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
711       RT.getUnqualifiedType(), Qual)));
712 
713   return false;
714 }
715 
716 ExprResult
717 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
718                                CallExpr *TheCall) {
719   ExprResult TheCallResult(TheCall);
720 
721   // Find out if any arguments are required to be integer constant expressions.
722   unsigned ICEArguments = 0;
723   ASTContext::GetBuiltinTypeError Error;
724   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
725   if (Error != ASTContext::GE_None)
726     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
727 
728   // If any arguments are required to be ICE's, check and diagnose.
729   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
730     // Skip arguments not required to be ICE's.
731     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
732 
733     llvm::APSInt Result;
734     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
735       return true;
736     ICEArguments &= ~(1 << ArgNo);
737   }
738 
739   switch (BuiltinID) {
740   case Builtin::BI__builtin___CFStringMakeConstantString:
741     assert(TheCall->getNumArgs() == 1 &&
742            "Wrong # arguments to builtin CFStringMakeConstantString");
743     if (CheckObjCString(TheCall->getArg(0)))
744       return ExprError();
745     break;
746   case Builtin::BI__builtin_stdarg_start:
747   case Builtin::BI__builtin_va_start:
748     if (SemaBuiltinVAStart(TheCall))
749       return ExprError();
750     break;
751   case Builtin::BI__va_start: {
752     switch (Context.getTargetInfo().getTriple().getArch()) {
753     case llvm::Triple::arm:
754     case llvm::Triple::thumb:
755       if (SemaBuiltinVAStartARM(TheCall))
756         return ExprError();
757       break;
758     default:
759       if (SemaBuiltinVAStart(TheCall))
760         return ExprError();
761       break;
762     }
763     break;
764   }
765   case Builtin::BI__builtin_isgreater:
766   case Builtin::BI__builtin_isgreaterequal:
767   case Builtin::BI__builtin_isless:
768   case Builtin::BI__builtin_islessequal:
769   case Builtin::BI__builtin_islessgreater:
770   case Builtin::BI__builtin_isunordered:
771     if (SemaBuiltinUnorderedCompare(TheCall))
772       return ExprError();
773     break;
774   case Builtin::BI__builtin_fpclassify:
775     if (SemaBuiltinFPClassification(TheCall, 6))
776       return ExprError();
777     break;
778   case Builtin::BI__builtin_isfinite:
779   case Builtin::BI__builtin_isinf:
780   case Builtin::BI__builtin_isinf_sign:
781   case Builtin::BI__builtin_isnan:
782   case Builtin::BI__builtin_isnormal:
783     if (SemaBuiltinFPClassification(TheCall, 1))
784       return ExprError();
785     break;
786   case Builtin::BI__builtin_shufflevector:
787     return SemaBuiltinShuffleVector(TheCall);
788     // TheCall will be freed by the smart pointer here, but that's fine, since
789     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
790   case Builtin::BI__builtin_prefetch:
791     if (SemaBuiltinPrefetch(TheCall))
792       return ExprError();
793     break;
794   case Builtin::BI__builtin_alloca_with_align:
795     if (SemaBuiltinAllocaWithAlign(TheCall))
796       return ExprError();
797     break;
798   case Builtin::BI__assume:
799   case Builtin::BI__builtin_assume:
800     if (SemaBuiltinAssume(TheCall))
801       return ExprError();
802     break;
803   case Builtin::BI__builtin_assume_aligned:
804     if (SemaBuiltinAssumeAligned(TheCall))
805       return ExprError();
806     break;
807   case Builtin::BI__builtin_object_size:
808     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
809       return ExprError();
810     break;
811   case Builtin::BI__builtin_longjmp:
812     if (SemaBuiltinLongjmp(TheCall))
813       return ExprError();
814     break;
815   case Builtin::BI__builtin_setjmp:
816     if (SemaBuiltinSetjmp(TheCall))
817       return ExprError();
818     break;
819   case Builtin::BI_setjmp:
820   case Builtin::BI_setjmpex:
821     if (checkArgCount(*this, TheCall, 1))
822       return true;
823     break;
824 
825   case Builtin::BI__builtin_classify_type:
826     if (checkArgCount(*this, TheCall, 1)) return true;
827     TheCall->setType(Context.IntTy);
828     break;
829   case Builtin::BI__builtin_constant_p:
830     if (checkArgCount(*this, TheCall, 1)) return true;
831     TheCall->setType(Context.IntTy);
832     break;
833   case Builtin::BI__sync_fetch_and_add:
834   case Builtin::BI__sync_fetch_and_add_1:
835   case Builtin::BI__sync_fetch_and_add_2:
836   case Builtin::BI__sync_fetch_and_add_4:
837   case Builtin::BI__sync_fetch_and_add_8:
838   case Builtin::BI__sync_fetch_and_add_16:
839   case Builtin::BI__sync_fetch_and_sub:
840   case Builtin::BI__sync_fetch_and_sub_1:
841   case Builtin::BI__sync_fetch_and_sub_2:
842   case Builtin::BI__sync_fetch_and_sub_4:
843   case Builtin::BI__sync_fetch_and_sub_8:
844   case Builtin::BI__sync_fetch_and_sub_16:
845   case Builtin::BI__sync_fetch_and_or:
846   case Builtin::BI__sync_fetch_and_or_1:
847   case Builtin::BI__sync_fetch_and_or_2:
848   case Builtin::BI__sync_fetch_and_or_4:
849   case Builtin::BI__sync_fetch_and_or_8:
850   case Builtin::BI__sync_fetch_and_or_16:
851   case Builtin::BI__sync_fetch_and_and:
852   case Builtin::BI__sync_fetch_and_and_1:
853   case Builtin::BI__sync_fetch_and_and_2:
854   case Builtin::BI__sync_fetch_and_and_4:
855   case Builtin::BI__sync_fetch_and_and_8:
856   case Builtin::BI__sync_fetch_and_and_16:
857   case Builtin::BI__sync_fetch_and_xor:
858   case Builtin::BI__sync_fetch_and_xor_1:
859   case Builtin::BI__sync_fetch_and_xor_2:
860   case Builtin::BI__sync_fetch_and_xor_4:
861   case Builtin::BI__sync_fetch_and_xor_8:
862   case Builtin::BI__sync_fetch_and_xor_16:
863   case Builtin::BI__sync_fetch_and_nand:
864   case Builtin::BI__sync_fetch_and_nand_1:
865   case Builtin::BI__sync_fetch_and_nand_2:
866   case Builtin::BI__sync_fetch_and_nand_4:
867   case Builtin::BI__sync_fetch_and_nand_8:
868   case Builtin::BI__sync_fetch_and_nand_16:
869   case Builtin::BI__sync_add_and_fetch:
870   case Builtin::BI__sync_add_and_fetch_1:
871   case Builtin::BI__sync_add_and_fetch_2:
872   case Builtin::BI__sync_add_and_fetch_4:
873   case Builtin::BI__sync_add_and_fetch_8:
874   case Builtin::BI__sync_add_and_fetch_16:
875   case Builtin::BI__sync_sub_and_fetch:
876   case Builtin::BI__sync_sub_and_fetch_1:
877   case Builtin::BI__sync_sub_and_fetch_2:
878   case Builtin::BI__sync_sub_and_fetch_4:
879   case Builtin::BI__sync_sub_and_fetch_8:
880   case Builtin::BI__sync_sub_and_fetch_16:
881   case Builtin::BI__sync_and_and_fetch:
882   case Builtin::BI__sync_and_and_fetch_1:
883   case Builtin::BI__sync_and_and_fetch_2:
884   case Builtin::BI__sync_and_and_fetch_4:
885   case Builtin::BI__sync_and_and_fetch_8:
886   case Builtin::BI__sync_and_and_fetch_16:
887   case Builtin::BI__sync_or_and_fetch:
888   case Builtin::BI__sync_or_and_fetch_1:
889   case Builtin::BI__sync_or_and_fetch_2:
890   case Builtin::BI__sync_or_and_fetch_4:
891   case Builtin::BI__sync_or_and_fetch_8:
892   case Builtin::BI__sync_or_and_fetch_16:
893   case Builtin::BI__sync_xor_and_fetch:
894   case Builtin::BI__sync_xor_and_fetch_1:
895   case Builtin::BI__sync_xor_and_fetch_2:
896   case Builtin::BI__sync_xor_and_fetch_4:
897   case Builtin::BI__sync_xor_and_fetch_8:
898   case Builtin::BI__sync_xor_and_fetch_16:
899   case Builtin::BI__sync_nand_and_fetch:
900   case Builtin::BI__sync_nand_and_fetch_1:
901   case Builtin::BI__sync_nand_and_fetch_2:
902   case Builtin::BI__sync_nand_and_fetch_4:
903   case Builtin::BI__sync_nand_and_fetch_8:
904   case Builtin::BI__sync_nand_and_fetch_16:
905   case Builtin::BI__sync_val_compare_and_swap:
906   case Builtin::BI__sync_val_compare_and_swap_1:
907   case Builtin::BI__sync_val_compare_and_swap_2:
908   case Builtin::BI__sync_val_compare_and_swap_4:
909   case Builtin::BI__sync_val_compare_and_swap_8:
910   case Builtin::BI__sync_val_compare_and_swap_16:
911   case Builtin::BI__sync_bool_compare_and_swap:
912   case Builtin::BI__sync_bool_compare_and_swap_1:
913   case Builtin::BI__sync_bool_compare_and_swap_2:
914   case Builtin::BI__sync_bool_compare_and_swap_4:
915   case Builtin::BI__sync_bool_compare_and_swap_8:
916   case Builtin::BI__sync_bool_compare_and_swap_16:
917   case Builtin::BI__sync_lock_test_and_set:
918   case Builtin::BI__sync_lock_test_and_set_1:
919   case Builtin::BI__sync_lock_test_and_set_2:
920   case Builtin::BI__sync_lock_test_and_set_4:
921   case Builtin::BI__sync_lock_test_and_set_8:
922   case Builtin::BI__sync_lock_test_and_set_16:
923   case Builtin::BI__sync_lock_release:
924   case Builtin::BI__sync_lock_release_1:
925   case Builtin::BI__sync_lock_release_2:
926   case Builtin::BI__sync_lock_release_4:
927   case Builtin::BI__sync_lock_release_8:
928   case Builtin::BI__sync_lock_release_16:
929   case Builtin::BI__sync_swap:
930   case Builtin::BI__sync_swap_1:
931   case Builtin::BI__sync_swap_2:
932   case Builtin::BI__sync_swap_4:
933   case Builtin::BI__sync_swap_8:
934   case Builtin::BI__sync_swap_16:
935     return SemaBuiltinAtomicOverloaded(TheCallResult);
936   case Builtin::BI__builtin_nontemporal_load:
937   case Builtin::BI__builtin_nontemporal_store:
938     return SemaBuiltinNontemporalOverloaded(TheCallResult);
939 #define BUILTIN(ID, TYPE, ATTRS)
940 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
941   case Builtin::BI##ID: \
942     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
943 #include "clang/Basic/Builtins.def"
944   case Builtin::BI__builtin_annotation:
945     if (SemaBuiltinAnnotation(*this, TheCall))
946       return ExprError();
947     break;
948   case Builtin::BI__builtin_addressof:
949     if (SemaBuiltinAddressof(*this, TheCall))
950       return ExprError();
951     break;
952   case Builtin::BI__builtin_add_overflow:
953   case Builtin::BI__builtin_sub_overflow:
954   case Builtin::BI__builtin_mul_overflow:
955     if (SemaBuiltinOverflow(*this, TheCall))
956       return ExprError();
957     break;
958   case Builtin::BI__builtin_operator_new:
959   case Builtin::BI__builtin_operator_delete:
960     if (!getLangOpts().CPlusPlus) {
961       Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
962         << (BuiltinID == Builtin::BI__builtin_operator_new
963                 ? "__builtin_operator_new"
964                 : "__builtin_operator_delete")
965         << "C++";
966       return ExprError();
967     }
968     // CodeGen assumes it can find the global new and delete to call,
969     // so ensure that they are declared.
970     DeclareGlobalNewDelete();
971     break;
972 
973   // check secure string manipulation functions where overflows
974   // are detectable at compile time
975   case Builtin::BI__builtin___memcpy_chk:
976   case Builtin::BI__builtin___memmove_chk:
977   case Builtin::BI__builtin___memset_chk:
978   case Builtin::BI__builtin___strlcat_chk:
979   case Builtin::BI__builtin___strlcpy_chk:
980   case Builtin::BI__builtin___strncat_chk:
981   case Builtin::BI__builtin___strncpy_chk:
982   case Builtin::BI__builtin___stpncpy_chk:
983     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
984     break;
985   case Builtin::BI__builtin___memccpy_chk:
986     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
987     break;
988   case Builtin::BI__builtin___snprintf_chk:
989   case Builtin::BI__builtin___vsnprintf_chk:
990     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
991     break;
992   case Builtin::BI__builtin_call_with_static_chain:
993     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
994       return ExprError();
995     break;
996   case Builtin::BI__exception_code:
997   case Builtin::BI_exception_code:
998     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
999                                  diag::err_seh___except_block))
1000       return ExprError();
1001     break;
1002   case Builtin::BI__exception_info:
1003   case Builtin::BI_exception_info:
1004     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1005                                  diag::err_seh___except_filter))
1006       return ExprError();
1007     break;
1008   case Builtin::BI__GetExceptionInfo:
1009     if (checkArgCount(*this, TheCall, 1))
1010       return ExprError();
1011 
1012     if (CheckCXXThrowOperand(
1013             TheCall->getLocStart(),
1014             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1015             TheCall))
1016       return ExprError();
1017 
1018     TheCall->setType(Context.VoidPtrTy);
1019     break;
1020   // OpenCL v2.0, s6.13.16 - Pipe functions
1021   case Builtin::BIread_pipe:
1022   case Builtin::BIwrite_pipe:
1023     // Since those two functions are declared with var args, we need a semantic
1024     // check for the argument.
1025     if (SemaBuiltinRWPipe(*this, TheCall))
1026       return ExprError();
1027     TheCall->setType(Context.IntTy);
1028     break;
1029   case Builtin::BIreserve_read_pipe:
1030   case Builtin::BIreserve_write_pipe:
1031   case Builtin::BIwork_group_reserve_read_pipe:
1032   case Builtin::BIwork_group_reserve_write_pipe:
1033   case Builtin::BIsub_group_reserve_read_pipe:
1034   case Builtin::BIsub_group_reserve_write_pipe:
1035     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1036       return ExprError();
1037     // Since return type of reserve_read/write_pipe built-in function is
1038     // reserve_id_t, which is not defined in the builtin def file , we used int
1039     // as return type and need to override the return type of these functions.
1040     TheCall->setType(Context.OCLReserveIDTy);
1041     break;
1042   case Builtin::BIcommit_read_pipe:
1043   case Builtin::BIcommit_write_pipe:
1044   case Builtin::BIwork_group_commit_read_pipe:
1045   case Builtin::BIwork_group_commit_write_pipe:
1046   case Builtin::BIsub_group_commit_read_pipe:
1047   case Builtin::BIsub_group_commit_write_pipe:
1048     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1049       return ExprError();
1050     break;
1051   case Builtin::BIget_pipe_num_packets:
1052   case Builtin::BIget_pipe_max_packets:
1053     if (SemaBuiltinPipePackets(*this, TheCall))
1054       return ExprError();
1055     TheCall->setType(Context.UnsignedIntTy);
1056     break;
1057   case Builtin::BIto_global:
1058   case Builtin::BIto_local:
1059   case Builtin::BIto_private:
1060     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1061       return ExprError();
1062     break;
1063   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1064   case Builtin::BIenqueue_kernel:
1065     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1066       return ExprError();
1067     break;
1068   case Builtin::BIget_kernel_work_group_size:
1069   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1070     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1071       return ExprError();
1072     break;
1073   case Builtin::BI__builtin_os_log_format:
1074   case Builtin::BI__builtin_os_log_format_buffer_size:
1075     if (SemaBuiltinOSLogFormat(TheCall)) {
1076       return ExprError();
1077     }
1078     break;
1079   }
1080 
1081   // Since the target specific builtins for each arch overlap, only check those
1082   // of the arch we are compiling for.
1083   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1084     switch (Context.getTargetInfo().getTriple().getArch()) {
1085       case llvm::Triple::arm:
1086       case llvm::Triple::armeb:
1087       case llvm::Triple::thumb:
1088       case llvm::Triple::thumbeb:
1089         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1090           return ExprError();
1091         break;
1092       case llvm::Triple::aarch64:
1093       case llvm::Triple::aarch64_be:
1094         if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1095           return ExprError();
1096         break;
1097       case llvm::Triple::mips:
1098       case llvm::Triple::mipsel:
1099       case llvm::Triple::mips64:
1100       case llvm::Triple::mips64el:
1101         if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1102           return ExprError();
1103         break;
1104       case llvm::Triple::systemz:
1105         if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1106           return ExprError();
1107         break;
1108       case llvm::Triple::x86:
1109       case llvm::Triple::x86_64:
1110         if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1111           return ExprError();
1112         break;
1113       case llvm::Triple::ppc:
1114       case llvm::Triple::ppc64:
1115       case llvm::Triple::ppc64le:
1116         if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1117           return ExprError();
1118         break;
1119       default:
1120         break;
1121     }
1122   }
1123 
1124   return TheCallResult;
1125 }
1126 
1127 // Get the valid immediate range for the specified NEON type code.
1128 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1129   NeonTypeFlags Type(t);
1130   int IsQuad = ForceQuad ? true : Type.isQuad();
1131   switch (Type.getEltType()) {
1132   case NeonTypeFlags::Int8:
1133   case NeonTypeFlags::Poly8:
1134     return shift ? 7 : (8 << IsQuad) - 1;
1135   case NeonTypeFlags::Int16:
1136   case NeonTypeFlags::Poly16:
1137     return shift ? 15 : (4 << IsQuad) - 1;
1138   case NeonTypeFlags::Int32:
1139     return shift ? 31 : (2 << IsQuad) - 1;
1140   case NeonTypeFlags::Int64:
1141   case NeonTypeFlags::Poly64:
1142     return shift ? 63 : (1 << IsQuad) - 1;
1143   case NeonTypeFlags::Poly128:
1144     return shift ? 127 : (1 << IsQuad) - 1;
1145   case NeonTypeFlags::Float16:
1146     assert(!shift && "cannot shift float types!");
1147     return (4 << IsQuad) - 1;
1148   case NeonTypeFlags::Float32:
1149     assert(!shift && "cannot shift float types!");
1150     return (2 << IsQuad) - 1;
1151   case NeonTypeFlags::Float64:
1152     assert(!shift && "cannot shift float types!");
1153     return (1 << IsQuad) - 1;
1154   }
1155   llvm_unreachable("Invalid NeonTypeFlag!");
1156 }
1157 
1158 /// getNeonEltType - Return the QualType corresponding to the elements of
1159 /// the vector type specified by the NeonTypeFlags.  This is used to check
1160 /// the pointer arguments for Neon load/store intrinsics.
1161 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1162                                bool IsPolyUnsigned, bool IsInt64Long) {
1163   switch (Flags.getEltType()) {
1164   case NeonTypeFlags::Int8:
1165     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1166   case NeonTypeFlags::Int16:
1167     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1168   case NeonTypeFlags::Int32:
1169     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1170   case NeonTypeFlags::Int64:
1171     if (IsInt64Long)
1172       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1173     else
1174       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1175                                 : Context.LongLongTy;
1176   case NeonTypeFlags::Poly8:
1177     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1178   case NeonTypeFlags::Poly16:
1179     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1180   case NeonTypeFlags::Poly64:
1181     if (IsInt64Long)
1182       return Context.UnsignedLongTy;
1183     else
1184       return Context.UnsignedLongLongTy;
1185   case NeonTypeFlags::Poly128:
1186     break;
1187   case NeonTypeFlags::Float16:
1188     return Context.HalfTy;
1189   case NeonTypeFlags::Float32:
1190     return Context.FloatTy;
1191   case NeonTypeFlags::Float64:
1192     return Context.DoubleTy;
1193   }
1194   llvm_unreachable("Invalid NeonTypeFlag!");
1195 }
1196 
1197 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1198   llvm::APSInt Result;
1199   uint64_t mask = 0;
1200   unsigned TV = 0;
1201   int PtrArgNum = -1;
1202   bool HasConstPtr = false;
1203   switch (BuiltinID) {
1204 #define GET_NEON_OVERLOAD_CHECK
1205 #include "clang/Basic/arm_neon.inc"
1206 #undef GET_NEON_OVERLOAD_CHECK
1207   }
1208 
1209   // For NEON intrinsics which are overloaded on vector element type, validate
1210   // the immediate which specifies which variant to emit.
1211   unsigned ImmArg = TheCall->getNumArgs()-1;
1212   if (mask) {
1213     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1214       return true;
1215 
1216     TV = Result.getLimitedValue(64);
1217     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1218       return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
1219         << TheCall->getArg(ImmArg)->getSourceRange();
1220   }
1221 
1222   if (PtrArgNum >= 0) {
1223     // Check that pointer arguments have the specified type.
1224     Expr *Arg = TheCall->getArg(PtrArgNum);
1225     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1226       Arg = ICE->getSubExpr();
1227     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1228     QualType RHSTy = RHS.get()->getType();
1229 
1230     llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
1231     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
1232     bool IsInt64Long =
1233         Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1234     QualType EltTy =
1235         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
1236     if (HasConstPtr)
1237       EltTy = EltTy.withConst();
1238     QualType LHSTy = Context.getPointerType(EltTy);
1239     AssignConvertType ConvTy;
1240     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1241     if (RHS.isInvalid())
1242       return true;
1243     if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1244                                  RHS.get(), AA_Assigning))
1245       return true;
1246   }
1247 
1248   // For NEON intrinsics which take an immediate value as part of the
1249   // instruction, range check them here.
1250   unsigned i = 0, l = 0, u = 0;
1251   switch (BuiltinID) {
1252   default:
1253     return false;
1254 #define GET_NEON_IMMEDIATE_CHECK
1255 #include "clang/Basic/arm_neon.inc"
1256 #undef GET_NEON_IMMEDIATE_CHECK
1257   }
1258 
1259   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1260 }
1261 
1262 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1263                                         unsigned MaxWidth) {
1264   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1265           BuiltinID == ARM::BI__builtin_arm_ldaex ||
1266           BuiltinID == ARM::BI__builtin_arm_strex ||
1267           BuiltinID == ARM::BI__builtin_arm_stlex ||
1268           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1269           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1270           BuiltinID == AArch64::BI__builtin_arm_strex ||
1271           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1272          "unexpected ARM builtin");
1273   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1274                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1275                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1276                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
1277 
1278   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1279 
1280   // Ensure that we have the proper number of arguments.
1281   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1282     return true;
1283 
1284   // Inspect the pointer argument of the atomic builtin.  This should always be
1285   // a pointer type, whose element is an integral scalar or pointer type.
1286   // Because it is a pointer type, we don't have to worry about any implicit
1287   // casts here.
1288   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1289   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1290   if (PointerArgRes.isInvalid())
1291     return true;
1292   PointerArg = PointerArgRes.get();
1293 
1294   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1295   if (!pointerType) {
1296     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1297       << PointerArg->getType() << PointerArg->getSourceRange();
1298     return true;
1299   }
1300 
1301   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1302   // task is to insert the appropriate casts into the AST. First work out just
1303   // what the appropriate type is.
1304   QualType ValType = pointerType->getPointeeType();
1305   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1306   if (IsLdrex)
1307     AddrType.addConst();
1308 
1309   // Issue a warning if the cast is dodgy.
1310   CastKind CastNeeded = CK_NoOp;
1311   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1312     CastNeeded = CK_BitCast;
1313     Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1314       << PointerArg->getType()
1315       << Context.getPointerType(AddrType)
1316       << AA_Passing << PointerArg->getSourceRange();
1317   }
1318 
1319   // Finally, do the cast and replace the argument with the corrected version.
1320   AddrType = Context.getPointerType(AddrType);
1321   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1322   if (PointerArgRes.isInvalid())
1323     return true;
1324   PointerArg = PointerArgRes.get();
1325 
1326   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1327 
1328   // In general, we allow ints, floats and pointers to be loaded and stored.
1329   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1330       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1331     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1332       << PointerArg->getType() << PointerArg->getSourceRange();
1333     return true;
1334   }
1335 
1336   // But ARM doesn't have instructions to deal with 128-bit versions.
1337   if (Context.getTypeSize(ValType) > MaxWidth) {
1338     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
1339     Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1340       << PointerArg->getType() << PointerArg->getSourceRange();
1341     return true;
1342   }
1343 
1344   switch (ValType.getObjCLifetime()) {
1345   case Qualifiers::OCL_None:
1346   case Qualifiers::OCL_ExplicitNone:
1347     // okay
1348     break;
1349 
1350   case Qualifiers::OCL_Weak:
1351   case Qualifiers::OCL_Strong:
1352   case Qualifiers::OCL_Autoreleasing:
1353     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1354       << ValType << PointerArg->getSourceRange();
1355     return true;
1356   }
1357 
1358   if (IsLdrex) {
1359     TheCall->setType(ValType);
1360     return false;
1361   }
1362 
1363   // Initialize the argument to be stored.
1364   ExprResult ValArg = TheCall->getArg(0);
1365   InitializedEntity Entity = InitializedEntity::InitializeParameter(
1366       Context, ValType, /*consume*/ false);
1367   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1368   if (ValArg.isInvalid())
1369     return true;
1370   TheCall->setArg(0, ValArg.get());
1371 
1372   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1373   // but the custom checker bypasses all default analysis.
1374   TheCall->setType(Context.IntTy);
1375   return false;
1376 }
1377 
1378 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1379   llvm::APSInt Result;
1380 
1381   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1382       BuiltinID == ARM::BI__builtin_arm_ldaex ||
1383       BuiltinID == ARM::BI__builtin_arm_strex ||
1384       BuiltinID == ARM::BI__builtin_arm_stlex) {
1385     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1386   }
1387 
1388   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1389     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1390       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1391   }
1392 
1393   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1394       BuiltinID == ARM::BI__builtin_arm_wsr64)
1395     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1396 
1397   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1398       BuiltinID == ARM::BI__builtin_arm_rsrp ||
1399       BuiltinID == ARM::BI__builtin_arm_wsr ||
1400       BuiltinID == ARM::BI__builtin_arm_wsrp)
1401     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1402 
1403   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1404     return true;
1405 
1406   // For intrinsics which take an immediate value as part of the instruction,
1407   // range check them here.
1408   unsigned i = 0, l = 0, u = 0;
1409   switch (BuiltinID) {
1410   default: return false;
1411   case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1412   case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
1413   case ARM::BI__builtin_arm_vcvtr_f:
1414   case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
1415   case ARM::BI__builtin_arm_dmb:
1416   case ARM::BI__builtin_arm_dsb:
1417   case ARM::BI__builtin_arm_isb:
1418   case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
1419   }
1420 
1421   // FIXME: VFP Intrinsics should error if VFP not present.
1422   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1423 }
1424 
1425 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1426                                          CallExpr *TheCall) {
1427   llvm::APSInt Result;
1428 
1429   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1430       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1431       BuiltinID == AArch64::BI__builtin_arm_strex ||
1432       BuiltinID == AArch64::BI__builtin_arm_stlex) {
1433     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1434   }
1435 
1436   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1437     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1438       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1439       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1440       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1441   }
1442 
1443   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1444       BuiltinID == AArch64::BI__builtin_arm_wsr64)
1445     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1446 
1447   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1448       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1449       BuiltinID == AArch64::BI__builtin_arm_wsr ||
1450       BuiltinID == AArch64::BI__builtin_arm_wsrp)
1451     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1452 
1453   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1454     return true;
1455 
1456   // For intrinsics which take an immediate value as part of the instruction,
1457   // range check them here.
1458   unsigned i = 0, l = 0, u = 0;
1459   switch (BuiltinID) {
1460   default: return false;
1461   case AArch64::BI__builtin_arm_dmb:
1462   case AArch64::BI__builtin_arm_dsb:
1463   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1464   }
1465 
1466   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1467 }
1468 
1469 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1470 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1471 // ordering for DSP is unspecified. MSA is ordered by the data format used
1472 // by the underlying instruction i.e., df/m, df/n and then by size.
1473 //
1474 // FIXME: The size tests here should instead be tablegen'd along with the
1475 //        definitions from include/clang/Basic/BuiltinsMips.def.
1476 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
1477 //        be too.
1478 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1479   unsigned i = 0, l = 0, u = 0, m = 0;
1480   switch (BuiltinID) {
1481   default: return false;
1482   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1483   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
1484   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1485   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1486   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1487   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1488   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
1489   // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1490   // df/m field.
1491   // These intrinsics take an unsigned 3 bit immediate.
1492   case Mips::BI__builtin_msa_bclri_b:
1493   case Mips::BI__builtin_msa_bnegi_b:
1494   case Mips::BI__builtin_msa_bseti_b:
1495   case Mips::BI__builtin_msa_sat_s_b:
1496   case Mips::BI__builtin_msa_sat_u_b:
1497   case Mips::BI__builtin_msa_slli_b:
1498   case Mips::BI__builtin_msa_srai_b:
1499   case Mips::BI__builtin_msa_srari_b:
1500   case Mips::BI__builtin_msa_srli_b:
1501   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1502   case Mips::BI__builtin_msa_binsli_b:
1503   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1504   // These intrinsics take an unsigned 4 bit immediate.
1505   case Mips::BI__builtin_msa_bclri_h:
1506   case Mips::BI__builtin_msa_bnegi_h:
1507   case Mips::BI__builtin_msa_bseti_h:
1508   case Mips::BI__builtin_msa_sat_s_h:
1509   case Mips::BI__builtin_msa_sat_u_h:
1510   case Mips::BI__builtin_msa_slli_h:
1511   case Mips::BI__builtin_msa_srai_h:
1512   case Mips::BI__builtin_msa_srari_h:
1513   case Mips::BI__builtin_msa_srli_h:
1514   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1515   case Mips::BI__builtin_msa_binsli_h:
1516   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
1517   // These intrinsics take an unsigned 5 bit immedate.
1518   // The first block of intrinsics actually have an unsigned 5 bit field,
1519   // not a df/n field.
1520   case Mips::BI__builtin_msa_clei_u_b:
1521   case Mips::BI__builtin_msa_clei_u_h:
1522   case Mips::BI__builtin_msa_clei_u_w:
1523   case Mips::BI__builtin_msa_clei_u_d:
1524   case Mips::BI__builtin_msa_clti_u_b:
1525   case Mips::BI__builtin_msa_clti_u_h:
1526   case Mips::BI__builtin_msa_clti_u_w:
1527   case Mips::BI__builtin_msa_clti_u_d:
1528   case Mips::BI__builtin_msa_maxi_u_b:
1529   case Mips::BI__builtin_msa_maxi_u_h:
1530   case Mips::BI__builtin_msa_maxi_u_w:
1531   case Mips::BI__builtin_msa_maxi_u_d:
1532   case Mips::BI__builtin_msa_mini_u_b:
1533   case Mips::BI__builtin_msa_mini_u_h:
1534   case Mips::BI__builtin_msa_mini_u_w:
1535   case Mips::BI__builtin_msa_mini_u_d:
1536   case Mips::BI__builtin_msa_addvi_b:
1537   case Mips::BI__builtin_msa_addvi_h:
1538   case Mips::BI__builtin_msa_addvi_w:
1539   case Mips::BI__builtin_msa_addvi_d:
1540   case Mips::BI__builtin_msa_bclri_w:
1541   case Mips::BI__builtin_msa_bnegi_w:
1542   case Mips::BI__builtin_msa_bseti_w:
1543   case Mips::BI__builtin_msa_sat_s_w:
1544   case Mips::BI__builtin_msa_sat_u_w:
1545   case Mips::BI__builtin_msa_slli_w:
1546   case Mips::BI__builtin_msa_srai_w:
1547   case Mips::BI__builtin_msa_srari_w:
1548   case Mips::BI__builtin_msa_srli_w:
1549   case Mips::BI__builtin_msa_srlri_w:
1550   case Mips::BI__builtin_msa_subvi_b:
1551   case Mips::BI__builtin_msa_subvi_h:
1552   case Mips::BI__builtin_msa_subvi_w:
1553   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1554   case Mips::BI__builtin_msa_binsli_w:
1555   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1556   // These intrinsics take an unsigned 6 bit immediate.
1557   case Mips::BI__builtin_msa_bclri_d:
1558   case Mips::BI__builtin_msa_bnegi_d:
1559   case Mips::BI__builtin_msa_bseti_d:
1560   case Mips::BI__builtin_msa_sat_s_d:
1561   case Mips::BI__builtin_msa_sat_u_d:
1562   case Mips::BI__builtin_msa_slli_d:
1563   case Mips::BI__builtin_msa_srai_d:
1564   case Mips::BI__builtin_msa_srari_d:
1565   case Mips::BI__builtin_msa_srli_d:
1566   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1567   case Mips::BI__builtin_msa_binsli_d:
1568   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1569   // These intrinsics take a signed 5 bit immediate.
1570   case Mips::BI__builtin_msa_ceqi_b:
1571   case Mips::BI__builtin_msa_ceqi_h:
1572   case Mips::BI__builtin_msa_ceqi_w:
1573   case Mips::BI__builtin_msa_ceqi_d:
1574   case Mips::BI__builtin_msa_clti_s_b:
1575   case Mips::BI__builtin_msa_clti_s_h:
1576   case Mips::BI__builtin_msa_clti_s_w:
1577   case Mips::BI__builtin_msa_clti_s_d:
1578   case Mips::BI__builtin_msa_clei_s_b:
1579   case Mips::BI__builtin_msa_clei_s_h:
1580   case Mips::BI__builtin_msa_clei_s_w:
1581   case Mips::BI__builtin_msa_clei_s_d:
1582   case Mips::BI__builtin_msa_maxi_s_b:
1583   case Mips::BI__builtin_msa_maxi_s_h:
1584   case Mips::BI__builtin_msa_maxi_s_w:
1585   case Mips::BI__builtin_msa_maxi_s_d:
1586   case Mips::BI__builtin_msa_mini_s_b:
1587   case Mips::BI__builtin_msa_mini_s_h:
1588   case Mips::BI__builtin_msa_mini_s_w:
1589   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
1590   // These intrinsics take an unsigned 8 bit immediate.
1591   case Mips::BI__builtin_msa_andi_b:
1592   case Mips::BI__builtin_msa_nori_b:
1593   case Mips::BI__builtin_msa_ori_b:
1594   case Mips::BI__builtin_msa_shf_b:
1595   case Mips::BI__builtin_msa_shf_h:
1596   case Mips::BI__builtin_msa_shf_w:
1597   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
1598   case Mips::BI__builtin_msa_bseli_b:
1599   case Mips::BI__builtin_msa_bmnzi_b:
1600   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
1601   // df/n format
1602   // These intrinsics take an unsigned 4 bit immediate.
1603   case Mips::BI__builtin_msa_copy_s_b:
1604   case Mips::BI__builtin_msa_copy_u_b:
1605   case Mips::BI__builtin_msa_insve_b:
1606   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
1607   case Mips::BI__builtin_msa_sld_b:
1608   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
1609   // These intrinsics take an unsigned 3 bit immediate.
1610   case Mips::BI__builtin_msa_copy_s_h:
1611   case Mips::BI__builtin_msa_copy_u_h:
1612   case Mips::BI__builtin_msa_insve_h:
1613   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
1614   case Mips::BI__builtin_msa_sld_h:
1615   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1616   // These intrinsics take an unsigned 2 bit immediate.
1617   case Mips::BI__builtin_msa_copy_s_w:
1618   case Mips::BI__builtin_msa_copy_u_w:
1619   case Mips::BI__builtin_msa_insve_w:
1620   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
1621   case Mips::BI__builtin_msa_sld_w:
1622   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1623   // These intrinsics take an unsigned 1 bit immediate.
1624   case Mips::BI__builtin_msa_copy_s_d:
1625   case Mips::BI__builtin_msa_copy_u_d:
1626   case Mips::BI__builtin_msa_insve_d:
1627   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
1628   case Mips::BI__builtin_msa_sld_d:
1629   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1630   // Memory offsets and immediate loads.
1631   // These intrinsics take a signed 10 bit immediate.
1632   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 127; break;
1633   case Mips::BI__builtin_msa_ldi_h:
1634   case Mips::BI__builtin_msa_ldi_w:
1635   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1636   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1637   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1638   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1639   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1640   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1641   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1642   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1643   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
1644   }
1645 
1646   if (!m)
1647     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1648 
1649   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1650          SemaBuiltinConstantArgMultiple(TheCall, i, m);
1651 }
1652 
1653 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1654   unsigned i = 0, l = 0, u = 0;
1655   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1656                       BuiltinID == PPC::BI__builtin_divdeu ||
1657                       BuiltinID == PPC::BI__builtin_bpermd;
1658   bool IsTarget64Bit = Context.getTargetInfo()
1659                               .getTypeWidth(Context
1660                                             .getTargetInfo()
1661                                             .getIntPtrType()) == 64;
1662   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1663                        BuiltinID == PPC::BI__builtin_divweu ||
1664                        BuiltinID == PPC::BI__builtin_divde ||
1665                        BuiltinID == PPC::BI__builtin_divdeu;
1666 
1667   if (Is64BitBltin && !IsTarget64Bit)
1668       return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1669              << TheCall->getSourceRange();
1670 
1671   if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1672       (BuiltinID == PPC::BI__builtin_bpermd &&
1673        !Context.getTargetInfo().hasFeature("bpermd")))
1674     return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1675            << TheCall->getSourceRange();
1676 
1677   switch (BuiltinID) {
1678   default: return false;
1679   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1680   case PPC::BI__builtin_altivec_crypto_vshasigmad:
1681     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1682            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1683   case PPC::BI__builtin_tbegin:
1684   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1685   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1686   case PPC::BI__builtin_tabortwc:
1687   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1688   case PPC::BI__builtin_tabortwci:
1689   case PPC::BI__builtin_tabortdci:
1690     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1691            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1692   }
1693   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1694 }
1695 
1696 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1697                                            CallExpr *TheCall) {
1698   if (BuiltinID == SystemZ::BI__builtin_tabort) {
1699     Expr *Arg = TheCall->getArg(0);
1700     llvm::APSInt AbortCode(32);
1701     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1702         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1703       return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1704              << Arg->getSourceRange();
1705   }
1706 
1707   // For intrinsics which take an immediate value as part of the instruction,
1708   // range check them here.
1709   unsigned i = 0, l = 0, u = 0;
1710   switch (BuiltinID) {
1711   default: return false;
1712   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1713   case SystemZ::BI__builtin_s390_verimb:
1714   case SystemZ::BI__builtin_s390_verimh:
1715   case SystemZ::BI__builtin_s390_verimf:
1716   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1717   case SystemZ::BI__builtin_s390_vfaeb:
1718   case SystemZ::BI__builtin_s390_vfaeh:
1719   case SystemZ::BI__builtin_s390_vfaef:
1720   case SystemZ::BI__builtin_s390_vfaebs:
1721   case SystemZ::BI__builtin_s390_vfaehs:
1722   case SystemZ::BI__builtin_s390_vfaefs:
1723   case SystemZ::BI__builtin_s390_vfaezb:
1724   case SystemZ::BI__builtin_s390_vfaezh:
1725   case SystemZ::BI__builtin_s390_vfaezf:
1726   case SystemZ::BI__builtin_s390_vfaezbs:
1727   case SystemZ::BI__builtin_s390_vfaezhs:
1728   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1729   case SystemZ::BI__builtin_s390_vfidb:
1730     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1731            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1732   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1733   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1734   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1735   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1736   case SystemZ::BI__builtin_s390_vstrcb:
1737   case SystemZ::BI__builtin_s390_vstrch:
1738   case SystemZ::BI__builtin_s390_vstrcf:
1739   case SystemZ::BI__builtin_s390_vstrczb:
1740   case SystemZ::BI__builtin_s390_vstrczh:
1741   case SystemZ::BI__builtin_s390_vstrczf:
1742   case SystemZ::BI__builtin_s390_vstrcbs:
1743   case SystemZ::BI__builtin_s390_vstrchs:
1744   case SystemZ::BI__builtin_s390_vstrcfs:
1745   case SystemZ::BI__builtin_s390_vstrczbs:
1746   case SystemZ::BI__builtin_s390_vstrczhs:
1747   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1748   }
1749   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1750 }
1751 
1752 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1753 /// This checks that the target supports __builtin_cpu_supports and
1754 /// that the string argument is constant and valid.
1755 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1756   Expr *Arg = TheCall->getArg(0);
1757 
1758   // Check if the argument is a string literal.
1759   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1760     return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1761            << Arg->getSourceRange();
1762 
1763   // Check the contents of the string.
1764   StringRef Feature =
1765       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1766   if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1767     return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1768            << Arg->getSourceRange();
1769   return false;
1770 }
1771 
1772 // Check if the rounding mode is legal.
1773 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
1774   // Indicates if this instruction has rounding control or just SAE.
1775   bool HasRC = false;
1776 
1777   unsigned ArgNum = 0;
1778   switch (BuiltinID) {
1779   default:
1780     return false;
1781   case X86::BI__builtin_ia32_vcvttsd2si32:
1782   case X86::BI__builtin_ia32_vcvttsd2si64:
1783   case X86::BI__builtin_ia32_vcvttsd2usi32:
1784   case X86::BI__builtin_ia32_vcvttsd2usi64:
1785   case X86::BI__builtin_ia32_vcvttss2si32:
1786   case X86::BI__builtin_ia32_vcvttss2si64:
1787   case X86::BI__builtin_ia32_vcvttss2usi32:
1788   case X86::BI__builtin_ia32_vcvttss2usi64:
1789     ArgNum = 1;
1790     break;
1791   case X86::BI__builtin_ia32_cvtps2pd512_mask:
1792   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1793   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1794   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1795   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1796   case X86::BI__builtin_ia32_cvttps2dq512_mask:
1797   case X86::BI__builtin_ia32_cvttps2qq512_mask:
1798   case X86::BI__builtin_ia32_cvttps2udq512_mask:
1799   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1800   case X86::BI__builtin_ia32_exp2pd_mask:
1801   case X86::BI__builtin_ia32_exp2ps_mask:
1802   case X86::BI__builtin_ia32_getexppd512_mask:
1803   case X86::BI__builtin_ia32_getexpps512_mask:
1804   case X86::BI__builtin_ia32_rcp28pd_mask:
1805   case X86::BI__builtin_ia32_rcp28ps_mask:
1806   case X86::BI__builtin_ia32_rsqrt28pd_mask:
1807   case X86::BI__builtin_ia32_rsqrt28ps_mask:
1808   case X86::BI__builtin_ia32_vcomisd:
1809   case X86::BI__builtin_ia32_vcomiss:
1810   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1811     ArgNum = 3;
1812     break;
1813   case X86::BI__builtin_ia32_cmppd512_mask:
1814   case X86::BI__builtin_ia32_cmpps512_mask:
1815   case X86::BI__builtin_ia32_cmpsd_mask:
1816   case X86::BI__builtin_ia32_cmpss_mask:
1817   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
1818   case X86::BI__builtin_ia32_getexpsd128_round_mask:
1819   case X86::BI__builtin_ia32_getexpss128_round_mask:
1820   case X86::BI__builtin_ia32_maxpd512_mask:
1821   case X86::BI__builtin_ia32_maxps512_mask:
1822   case X86::BI__builtin_ia32_maxsd_round_mask:
1823   case X86::BI__builtin_ia32_maxss_round_mask:
1824   case X86::BI__builtin_ia32_minpd512_mask:
1825   case X86::BI__builtin_ia32_minps512_mask:
1826   case X86::BI__builtin_ia32_minsd_round_mask:
1827   case X86::BI__builtin_ia32_minss_round_mask:
1828   case X86::BI__builtin_ia32_rcp28sd_round_mask:
1829   case X86::BI__builtin_ia32_rcp28ss_round_mask:
1830   case X86::BI__builtin_ia32_reducepd512_mask:
1831   case X86::BI__builtin_ia32_reduceps512_mask:
1832   case X86::BI__builtin_ia32_rndscalepd_mask:
1833   case X86::BI__builtin_ia32_rndscaleps_mask:
1834   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
1835   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
1836     ArgNum = 4;
1837     break;
1838   case X86::BI__builtin_ia32_fixupimmpd512_mask:
1839   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
1840   case X86::BI__builtin_ia32_fixupimmps512_mask:
1841   case X86::BI__builtin_ia32_fixupimmps512_maskz:
1842   case X86::BI__builtin_ia32_fixupimmsd_mask:
1843   case X86::BI__builtin_ia32_fixupimmsd_maskz:
1844   case X86::BI__builtin_ia32_fixupimmss_mask:
1845   case X86::BI__builtin_ia32_fixupimmss_maskz:
1846   case X86::BI__builtin_ia32_rangepd512_mask:
1847   case X86::BI__builtin_ia32_rangeps512_mask:
1848   case X86::BI__builtin_ia32_rangesd128_round_mask:
1849   case X86::BI__builtin_ia32_rangess128_round_mask:
1850   case X86::BI__builtin_ia32_reducesd_mask:
1851   case X86::BI__builtin_ia32_reducess_mask:
1852   case X86::BI__builtin_ia32_rndscalesd_round_mask:
1853   case X86::BI__builtin_ia32_rndscaless_round_mask:
1854     ArgNum = 5;
1855     break;
1856   case X86::BI__builtin_ia32_vcvtsd2si64:
1857   case X86::BI__builtin_ia32_vcvtsd2si32:
1858   case X86::BI__builtin_ia32_vcvtsd2usi32:
1859   case X86::BI__builtin_ia32_vcvtsd2usi64:
1860   case X86::BI__builtin_ia32_vcvtss2si32:
1861   case X86::BI__builtin_ia32_vcvtss2si64:
1862   case X86::BI__builtin_ia32_vcvtss2usi32:
1863   case X86::BI__builtin_ia32_vcvtss2usi64:
1864     ArgNum = 1;
1865     HasRC = true;
1866     break;
1867   case X86::BI__builtin_ia32_cvtsi2sd64:
1868   case X86::BI__builtin_ia32_cvtsi2ss32:
1869   case X86::BI__builtin_ia32_cvtsi2ss64:
1870   case X86::BI__builtin_ia32_cvtusi2sd64:
1871   case X86::BI__builtin_ia32_cvtusi2ss32:
1872   case X86::BI__builtin_ia32_cvtusi2ss64:
1873     ArgNum = 2;
1874     HasRC = true;
1875     break;
1876   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
1877   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
1878   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
1879   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
1880   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
1881   case X86::BI__builtin_ia32_cvtps2qq512_mask:
1882   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
1883   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
1884   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
1885   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
1886   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
1887   case X86::BI__builtin_ia32_sqrtpd512_mask:
1888   case X86::BI__builtin_ia32_sqrtps512_mask:
1889     ArgNum = 3;
1890     HasRC = true;
1891     break;
1892   case X86::BI__builtin_ia32_addpd512_mask:
1893   case X86::BI__builtin_ia32_addps512_mask:
1894   case X86::BI__builtin_ia32_divpd512_mask:
1895   case X86::BI__builtin_ia32_divps512_mask:
1896   case X86::BI__builtin_ia32_mulpd512_mask:
1897   case X86::BI__builtin_ia32_mulps512_mask:
1898   case X86::BI__builtin_ia32_subpd512_mask:
1899   case X86::BI__builtin_ia32_subps512_mask:
1900   case X86::BI__builtin_ia32_addss_round_mask:
1901   case X86::BI__builtin_ia32_addsd_round_mask:
1902   case X86::BI__builtin_ia32_divss_round_mask:
1903   case X86::BI__builtin_ia32_divsd_round_mask:
1904   case X86::BI__builtin_ia32_mulss_round_mask:
1905   case X86::BI__builtin_ia32_mulsd_round_mask:
1906   case X86::BI__builtin_ia32_subss_round_mask:
1907   case X86::BI__builtin_ia32_subsd_round_mask:
1908   case X86::BI__builtin_ia32_scalefpd512_mask:
1909   case X86::BI__builtin_ia32_scalefps512_mask:
1910   case X86::BI__builtin_ia32_scalefsd_round_mask:
1911   case X86::BI__builtin_ia32_scalefss_round_mask:
1912   case X86::BI__builtin_ia32_getmantpd512_mask:
1913   case X86::BI__builtin_ia32_getmantps512_mask:
1914   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
1915   case X86::BI__builtin_ia32_sqrtsd_round_mask:
1916   case X86::BI__builtin_ia32_sqrtss_round_mask:
1917   case X86::BI__builtin_ia32_vfmaddpd512_mask:
1918   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
1919   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
1920   case X86::BI__builtin_ia32_vfmaddps512_mask:
1921   case X86::BI__builtin_ia32_vfmaddps512_mask3:
1922   case X86::BI__builtin_ia32_vfmaddps512_maskz:
1923   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
1924   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
1925   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
1926   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
1927   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
1928   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
1929   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
1930   case X86::BI__builtin_ia32_vfmsubps512_mask3:
1931   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
1932   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
1933   case X86::BI__builtin_ia32_vfnmaddpd512_mask:
1934   case X86::BI__builtin_ia32_vfnmaddps512_mask:
1935   case X86::BI__builtin_ia32_vfnmsubpd512_mask:
1936   case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
1937   case X86::BI__builtin_ia32_vfnmsubps512_mask:
1938   case X86::BI__builtin_ia32_vfnmsubps512_mask3:
1939   case X86::BI__builtin_ia32_vfmaddsd3_mask:
1940   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
1941   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
1942   case X86::BI__builtin_ia32_vfmaddss3_mask:
1943   case X86::BI__builtin_ia32_vfmaddss3_maskz:
1944   case X86::BI__builtin_ia32_vfmaddss3_mask3:
1945     ArgNum = 4;
1946     HasRC = true;
1947     break;
1948   case X86::BI__builtin_ia32_getmantsd_round_mask:
1949   case X86::BI__builtin_ia32_getmantss_round_mask:
1950     ArgNum = 5;
1951     HasRC = true;
1952     break;
1953   }
1954 
1955   llvm::APSInt Result;
1956 
1957   // We can't check the value of a dependent argument.
1958   Expr *Arg = TheCall->getArg(ArgNum);
1959   if (Arg->isTypeDependent() || Arg->isValueDependent())
1960     return false;
1961 
1962   // Check constant-ness first.
1963   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
1964     return true;
1965 
1966   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
1967   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
1968   // combined with ROUND_NO_EXC.
1969   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
1970       Result == 8/*ROUND_NO_EXC*/ ||
1971       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
1972     return false;
1973 
1974   return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
1975     << Arg->getSourceRange();
1976 }
1977 
1978 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1979   if (BuiltinID == X86::BI__builtin_cpu_supports)
1980     return SemaBuiltinCpuSupports(*this, TheCall);
1981 
1982   if (BuiltinID == X86::BI__builtin_ms_va_start)
1983     return SemaBuiltinMSVAStart(TheCall);
1984 
1985   // If the intrinsic has rounding or SAE make sure its valid.
1986   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
1987     return true;
1988 
1989   // For intrinsics which take an immediate value as part of the instruction,
1990   // range check them here.
1991   int i = 0, l = 0, u = 0;
1992   switch (BuiltinID) {
1993   default:
1994     return false;
1995   case X86::BI_mm_prefetch:
1996     i = 1; l = 0; u = 3;
1997     break;
1998   case X86::BI__builtin_ia32_sha1rnds4:
1999   case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2000   case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2001   case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2002   case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
2003     i = 2; l = 0; u = 3;
2004     break;
2005   case X86::BI__builtin_ia32_vpermil2pd:
2006   case X86::BI__builtin_ia32_vpermil2pd256:
2007   case X86::BI__builtin_ia32_vpermil2ps:
2008   case X86::BI__builtin_ia32_vpermil2ps256:
2009     i = 3; l = 0; u = 3;
2010     break;
2011   case X86::BI__builtin_ia32_cmpb128_mask:
2012   case X86::BI__builtin_ia32_cmpw128_mask:
2013   case X86::BI__builtin_ia32_cmpd128_mask:
2014   case X86::BI__builtin_ia32_cmpq128_mask:
2015   case X86::BI__builtin_ia32_cmpb256_mask:
2016   case X86::BI__builtin_ia32_cmpw256_mask:
2017   case X86::BI__builtin_ia32_cmpd256_mask:
2018   case X86::BI__builtin_ia32_cmpq256_mask:
2019   case X86::BI__builtin_ia32_cmpb512_mask:
2020   case X86::BI__builtin_ia32_cmpw512_mask:
2021   case X86::BI__builtin_ia32_cmpd512_mask:
2022   case X86::BI__builtin_ia32_cmpq512_mask:
2023   case X86::BI__builtin_ia32_ucmpb128_mask:
2024   case X86::BI__builtin_ia32_ucmpw128_mask:
2025   case X86::BI__builtin_ia32_ucmpd128_mask:
2026   case X86::BI__builtin_ia32_ucmpq128_mask:
2027   case X86::BI__builtin_ia32_ucmpb256_mask:
2028   case X86::BI__builtin_ia32_ucmpw256_mask:
2029   case X86::BI__builtin_ia32_ucmpd256_mask:
2030   case X86::BI__builtin_ia32_ucmpq256_mask:
2031   case X86::BI__builtin_ia32_ucmpb512_mask:
2032   case X86::BI__builtin_ia32_ucmpw512_mask:
2033   case X86::BI__builtin_ia32_ucmpd512_mask:
2034   case X86::BI__builtin_ia32_ucmpq512_mask:
2035   case X86::BI__builtin_ia32_vpcomub:
2036   case X86::BI__builtin_ia32_vpcomuw:
2037   case X86::BI__builtin_ia32_vpcomud:
2038   case X86::BI__builtin_ia32_vpcomuq:
2039   case X86::BI__builtin_ia32_vpcomb:
2040   case X86::BI__builtin_ia32_vpcomw:
2041   case X86::BI__builtin_ia32_vpcomd:
2042   case X86::BI__builtin_ia32_vpcomq:
2043     i = 2; l = 0; u = 7;
2044     break;
2045   case X86::BI__builtin_ia32_roundps:
2046   case X86::BI__builtin_ia32_roundpd:
2047   case X86::BI__builtin_ia32_roundps256:
2048   case X86::BI__builtin_ia32_roundpd256:
2049     i = 1; l = 0; u = 15;
2050     break;
2051   case X86::BI__builtin_ia32_roundss:
2052   case X86::BI__builtin_ia32_roundsd:
2053   case X86::BI__builtin_ia32_rangepd128_mask:
2054   case X86::BI__builtin_ia32_rangepd256_mask:
2055   case X86::BI__builtin_ia32_rangepd512_mask:
2056   case X86::BI__builtin_ia32_rangeps128_mask:
2057   case X86::BI__builtin_ia32_rangeps256_mask:
2058   case X86::BI__builtin_ia32_rangeps512_mask:
2059   case X86::BI__builtin_ia32_getmantsd_round_mask:
2060   case X86::BI__builtin_ia32_getmantss_round_mask:
2061     i = 2; l = 0; u = 15;
2062     break;
2063   case X86::BI__builtin_ia32_cmpps:
2064   case X86::BI__builtin_ia32_cmpss:
2065   case X86::BI__builtin_ia32_cmppd:
2066   case X86::BI__builtin_ia32_cmpsd:
2067   case X86::BI__builtin_ia32_cmpps256:
2068   case X86::BI__builtin_ia32_cmppd256:
2069   case X86::BI__builtin_ia32_cmpps128_mask:
2070   case X86::BI__builtin_ia32_cmppd128_mask:
2071   case X86::BI__builtin_ia32_cmpps256_mask:
2072   case X86::BI__builtin_ia32_cmppd256_mask:
2073   case X86::BI__builtin_ia32_cmpps512_mask:
2074   case X86::BI__builtin_ia32_cmppd512_mask:
2075   case X86::BI__builtin_ia32_cmpsd_mask:
2076   case X86::BI__builtin_ia32_cmpss_mask:
2077     i = 2; l = 0; u = 31;
2078     break;
2079   case X86::BI__builtin_ia32_xabort:
2080     i = 0; l = -128; u = 255;
2081     break;
2082   case X86::BI__builtin_ia32_pshufw:
2083   case X86::BI__builtin_ia32_aeskeygenassist128:
2084     i = 1; l = -128; u = 255;
2085     break;
2086   case X86::BI__builtin_ia32_vcvtps2ph:
2087   case X86::BI__builtin_ia32_vcvtps2ph256:
2088   case X86::BI__builtin_ia32_rndscaleps_128_mask:
2089   case X86::BI__builtin_ia32_rndscalepd_128_mask:
2090   case X86::BI__builtin_ia32_rndscaleps_256_mask:
2091   case X86::BI__builtin_ia32_rndscalepd_256_mask:
2092   case X86::BI__builtin_ia32_rndscaleps_mask:
2093   case X86::BI__builtin_ia32_rndscalepd_mask:
2094   case X86::BI__builtin_ia32_reducepd128_mask:
2095   case X86::BI__builtin_ia32_reducepd256_mask:
2096   case X86::BI__builtin_ia32_reducepd512_mask:
2097   case X86::BI__builtin_ia32_reduceps128_mask:
2098   case X86::BI__builtin_ia32_reduceps256_mask:
2099   case X86::BI__builtin_ia32_reduceps512_mask:
2100   case X86::BI__builtin_ia32_prold512_mask:
2101   case X86::BI__builtin_ia32_prolq512_mask:
2102   case X86::BI__builtin_ia32_prold128_mask:
2103   case X86::BI__builtin_ia32_prold256_mask:
2104   case X86::BI__builtin_ia32_prolq128_mask:
2105   case X86::BI__builtin_ia32_prolq256_mask:
2106   case X86::BI__builtin_ia32_prord128_mask:
2107   case X86::BI__builtin_ia32_prord256_mask:
2108   case X86::BI__builtin_ia32_prorq128_mask:
2109   case X86::BI__builtin_ia32_prorq256_mask:
2110   case X86::BI__builtin_ia32_fpclasspd128_mask:
2111   case X86::BI__builtin_ia32_fpclasspd256_mask:
2112   case X86::BI__builtin_ia32_fpclassps128_mask:
2113   case X86::BI__builtin_ia32_fpclassps256_mask:
2114   case X86::BI__builtin_ia32_fpclassps512_mask:
2115   case X86::BI__builtin_ia32_fpclasspd512_mask:
2116   case X86::BI__builtin_ia32_fpclasssd_mask:
2117   case X86::BI__builtin_ia32_fpclassss_mask:
2118     i = 1; l = 0; u = 255;
2119     break;
2120   case X86::BI__builtin_ia32_palignr:
2121   case X86::BI__builtin_ia32_insertps128:
2122   case X86::BI__builtin_ia32_dpps:
2123   case X86::BI__builtin_ia32_dppd:
2124   case X86::BI__builtin_ia32_dpps256:
2125   case X86::BI__builtin_ia32_mpsadbw128:
2126   case X86::BI__builtin_ia32_mpsadbw256:
2127   case X86::BI__builtin_ia32_pcmpistrm128:
2128   case X86::BI__builtin_ia32_pcmpistri128:
2129   case X86::BI__builtin_ia32_pcmpistria128:
2130   case X86::BI__builtin_ia32_pcmpistric128:
2131   case X86::BI__builtin_ia32_pcmpistrio128:
2132   case X86::BI__builtin_ia32_pcmpistris128:
2133   case X86::BI__builtin_ia32_pcmpistriz128:
2134   case X86::BI__builtin_ia32_pclmulqdq128:
2135   case X86::BI__builtin_ia32_vperm2f128_pd256:
2136   case X86::BI__builtin_ia32_vperm2f128_ps256:
2137   case X86::BI__builtin_ia32_vperm2f128_si256:
2138   case X86::BI__builtin_ia32_permti256:
2139     i = 2; l = -128; u = 255;
2140     break;
2141   case X86::BI__builtin_ia32_palignr128:
2142   case X86::BI__builtin_ia32_palignr256:
2143   case X86::BI__builtin_ia32_palignr512_mask:
2144   case X86::BI__builtin_ia32_alignq512_mask:
2145   case X86::BI__builtin_ia32_alignd512_mask:
2146   case X86::BI__builtin_ia32_alignd128_mask:
2147   case X86::BI__builtin_ia32_alignd256_mask:
2148   case X86::BI__builtin_ia32_alignq128_mask:
2149   case X86::BI__builtin_ia32_alignq256_mask:
2150   case X86::BI__builtin_ia32_vcomisd:
2151   case X86::BI__builtin_ia32_vcomiss:
2152   case X86::BI__builtin_ia32_shuf_f32x4_mask:
2153   case X86::BI__builtin_ia32_shuf_f64x2_mask:
2154   case X86::BI__builtin_ia32_shuf_i32x4_mask:
2155   case X86::BI__builtin_ia32_shuf_i64x2_mask:
2156   case X86::BI__builtin_ia32_dbpsadbw128_mask:
2157   case X86::BI__builtin_ia32_dbpsadbw256_mask:
2158   case X86::BI__builtin_ia32_dbpsadbw512_mask:
2159     i = 2; l = 0; u = 255;
2160     break;
2161   case X86::BI__builtin_ia32_fixupimmpd512_mask:
2162   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2163   case X86::BI__builtin_ia32_fixupimmps512_mask:
2164   case X86::BI__builtin_ia32_fixupimmps512_maskz:
2165   case X86::BI__builtin_ia32_fixupimmsd_mask:
2166   case X86::BI__builtin_ia32_fixupimmsd_maskz:
2167   case X86::BI__builtin_ia32_fixupimmss_mask:
2168   case X86::BI__builtin_ia32_fixupimmss_maskz:
2169   case X86::BI__builtin_ia32_fixupimmpd128_mask:
2170   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2171   case X86::BI__builtin_ia32_fixupimmpd256_mask:
2172   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2173   case X86::BI__builtin_ia32_fixupimmps128_mask:
2174   case X86::BI__builtin_ia32_fixupimmps128_maskz:
2175   case X86::BI__builtin_ia32_fixupimmps256_mask:
2176   case X86::BI__builtin_ia32_fixupimmps256_maskz:
2177   case X86::BI__builtin_ia32_pternlogd512_mask:
2178   case X86::BI__builtin_ia32_pternlogd512_maskz:
2179   case X86::BI__builtin_ia32_pternlogq512_mask:
2180   case X86::BI__builtin_ia32_pternlogq512_maskz:
2181   case X86::BI__builtin_ia32_pternlogd128_mask:
2182   case X86::BI__builtin_ia32_pternlogd128_maskz:
2183   case X86::BI__builtin_ia32_pternlogd256_mask:
2184   case X86::BI__builtin_ia32_pternlogd256_maskz:
2185   case X86::BI__builtin_ia32_pternlogq128_mask:
2186   case X86::BI__builtin_ia32_pternlogq128_maskz:
2187   case X86::BI__builtin_ia32_pternlogq256_mask:
2188   case X86::BI__builtin_ia32_pternlogq256_maskz:
2189     i = 3; l = 0; u = 255;
2190     break;
2191   case X86::BI__builtin_ia32_pcmpestrm128:
2192   case X86::BI__builtin_ia32_pcmpestri128:
2193   case X86::BI__builtin_ia32_pcmpestria128:
2194   case X86::BI__builtin_ia32_pcmpestric128:
2195   case X86::BI__builtin_ia32_pcmpestrio128:
2196   case X86::BI__builtin_ia32_pcmpestris128:
2197   case X86::BI__builtin_ia32_pcmpestriz128:
2198     i = 4; l = -128; u = 255;
2199     break;
2200   case X86::BI__builtin_ia32_rndscalesd_round_mask:
2201   case X86::BI__builtin_ia32_rndscaless_round_mask:
2202     i = 4; l = 0; u = 255;
2203     break;
2204   }
2205   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2206 }
2207 
2208 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2209 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
2210 /// Returns true when the format fits the function and the FormatStringInfo has
2211 /// been populated.
2212 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2213                                FormatStringInfo *FSI) {
2214   FSI->HasVAListArg = Format->getFirstArg() == 0;
2215   FSI->FormatIdx = Format->getFormatIdx() - 1;
2216   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
2217 
2218   // The way the format attribute works in GCC, the implicit this argument
2219   // of member functions is counted. However, it doesn't appear in our own
2220   // lists, so decrement format_idx in that case.
2221   if (IsCXXMember) {
2222     if(FSI->FormatIdx == 0)
2223       return false;
2224     --FSI->FormatIdx;
2225     if (FSI->FirstDataArg != 0)
2226       --FSI->FirstDataArg;
2227   }
2228   return true;
2229 }
2230 
2231 /// Checks if a the given expression evaluates to null.
2232 ///
2233 /// \brief Returns true if the value evaluates to null.
2234 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
2235   // If the expression has non-null type, it doesn't evaluate to null.
2236   if (auto nullability
2237         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2238     if (*nullability == NullabilityKind::NonNull)
2239       return false;
2240   }
2241 
2242   // As a special case, transparent unions initialized with zero are
2243   // considered null for the purposes of the nonnull attribute.
2244   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
2245     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2246       if (const CompoundLiteralExpr *CLE =
2247           dyn_cast<CompoundLiteralExpr>(Expr))
2248         if (const InitListExpr *ILE =
2249             dyn_cast<InitListExpr>(CLE->getInitializer()))
2250           Expr = ILE->getInit(0);
2251   }
2252 
2253   bool Result;
2254   return (!Expr->isValueDependent() &&
2255           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2256           !Result);
2257 }
2258 
2259 static void CheckNonNullArgument(Sema &S,
2260                                  const Expr *ArgExpr,
2261                                  SourceLocation CallSiteLoc) {
2262   if (CheckNonNullExpr(S, ArgExpr))
2263     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2264            S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
2265 }
2266 
2267 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2268   FormatStringInfo FSI;
2269   if ((GetFormatStringType(Format) == FST_NSString) &&
2270       getFormatStringInfo(Format, false, &FSI)) {
2271     Idx = FSI.FormatIdx;
2272     return true;
2273   }
2274   return false;
2275 }
2276 /// \brief Diagnose use of %s directive in an NSString which is being passed
2277 /// as formatting string to formatting method.
2278 static void
2279 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2280                                         const NamedDecl *FDecl,
2281                                         Expr **Args,
2282                                         unsigned NumArgs) {
2283   unsigned Idx = 0;
2284   bool Format = false;
2285   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2286   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
2287     Idx = 2;
2288     Format = true;
2289   }
2290   else
2291     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2292       if (S.GetFormatNSStringIdx(I, Idx)) {
2293         Format = true;
2294         break;
2295       }
2296     }
2297   if (!Format || NumArgs <= Idx)
2298     return;
2299   const Expr *FormatExpr = Args[Idx];
2300   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2301     FormatExpr = CSCE->getSubExpr();
2302   const StringLiteral *FormatString;
2303   if (const ObjCStringLiteral *OSL =
2304       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2305     FormatString = OSL->getString();
2306   else
2307     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2308   if (!FormatString)
2309     return;
2310   if (S.FormatStringHasSArg(FormatString)) {
2311     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2312       << "%s" << 1 << 1;
2313     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2314       << FDecl->getDeclName();
2315   }
2316 }
2317 
2318 /// Determine whether the given type has a non-null nullability annotation.
2319 static bool isNonNullType(ASTContext &ctx, QualType type) {
2320   if (auto nullability = type->getNullability(ctx))
2321     return *nullability == NullabilityKind::NonNull;
2322 
2323   return false;
2324 }
2325 
2326 static void CheckNonNullArguments(Sema &S,
2327                                   const NamedDecl *FDecl,
2328                                   const FunctionProtoType *Proto,
2329                                   ArrayRef<const Expr *> Args,
2330                                   SourceLocation CallSiteLoc) {
2331   assert((FDecl || Proto) && "Need a function declaration or prototype");
2332 
2333   // Check the attributes attached to the method/function itself.
2334   llvm::SmallBitVector NonNullArgs;
2335   if (FDecl) {
2336     // Handle the nonnull attribute on the function/method declaration itself.
2337     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2338       if (!NonNull->args_size()) {
2339         // Easy case: all pointer arguments are nonnull.
2340         for (const auto *Arg : Args)
2341           if (S.isValidPointerAttrType(Arg->getType()))
2342             CheckNonNullArgument(S, Arg, CallSiteLoc);
2343         return;
2344       }
2345 
2346       for (unsigned Val : NonNull->args()) {
2347         if (Val >= Args.size())
2348           continue;
2349         if (NonNullArgs.empty())
2350           NonNullArgs.resize(Args.size());
2351         NonNullArgs.set(Val);
2352       }
2353     }
2354   }
2355 
2356   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2357     // Handle the nonnull attribute on the parameters of the
2358     // function/method.
2359     ArrayRef<ParmVarDecl*> parms;
2360     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2361       parms = FD->parameters();
2362     else
2363       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2364 
2365     unsigned ParamIndex = 0;
2366     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2367          I != E; ++I, ++ParamIndex) {
2368       const ParmVarDecl *PVD = *I;
2369       if (PVD->hasAttr<NonNullAttr>() ||
2370           isNonNullType(S.Context, PVD->getType())) {
2371         if (NonNullArgs.empty())
2372           NonNullArgs.resize(Args.size());
2373 
2374         NonNullArgs.set(ParamIndex);
2375       }
2376     }
2377   } else {
2378     // If we have a non-function, non-method declaration but no
2379     // function prototype, try to dig out the function prototype.
2380     if (!Proto) {
2381       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2382         QualType type = VD->getType().getNonReferenceType();
2383         if (auto pointerType = type->getAs<PointerType>())
2384           type = pointerType->getPointeeType();
2385         else if (auto blockType = type->getAs<BlockPointerType>())
2386           type = blockType->getPointeeType();
2387         // FIXME: data member pointers?
2388 
2389         // Dig out the function prototype, if there is one.
2390         Proto = type->getAs<FunctionProtoType>();
2391       }
2392     }
2393 
2394     // Fill in non-null argument information from the nullability
2395     // information on the parameter types (if we have them).
2396     if (Proto) {
2397       unsigned Index = 0;
2398       for (auto paramType : Proto->getParamTypes()) {
2399         if (isNonNullType(S.Context, paramType)) {
2400           if (NonNullArgs.empty())
2401             NonNullArgs.resize(Args.size());
2402 
2403           NonNullArgs.set(Index);
2404         }
2405 
2406         ++Index;
2407       }
2408     }
2409   }
2410 
2411   // Check for non-null arguments.
2412   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2413        ArgIndex != ArgIndexEnd; ++ArgIndex) {
2414     if (NonNullArgs[ArgIndex])
2415       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
2416   }
2417 }
2418 
2419 /// Handles the checks for format strings, non-POD arguments to vararg
2420 /// functions, and NULL arguments passed to non-NULL parameters.
2421 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2422                      ArrayRef<const Expr *> Args, bool IsMemberFunction,
2423                      SourceLocation Loc, SourceRange Range,
2424                      VariadicCallType CallType) {
2425   // FIXME: We should check as much as we can in the template definition.
2426   if (CurContext->isDependentContext())
2427     return;
2428 
2429   // Printf and scanf checking.
2430   llvm::SmallBitVector CheckedVarArgs;
2431   if (FDecl) {
2432     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2433       // Only create vector if there are format attributes.
2434       CheckedVarArgs.resize(Args.size());
2435 
2436       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
2437                            CheckedVarArgs);
2438     }
2439   }
2440 
2441   // Refuse POD arguments that weren't caught by the format string
2442   // checks above.
2443   if (CallType != VariadicDoesNotApply) {
2444     unsigned NumParams = Proto ? Proto->getNumParams()
2445                        : FDecl && isa<FunctionDecl>(FDecl)
2446                            ? cast<FunctionDecl>(FDecl)->getNumParams()
2447                        : FDecl && isa<ObjCMethodDecl>(FDecl)
2448                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
2449                        : 0;
2450 
2451     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
2452       // Args[ArgIdx] can be null in malformed code.
2453       if (const Expr *Arg = Args[ArgIdx]) {
2454         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2455           checkVariadicArgument(Arg, CallType);
2456       }
2457     }
2458   }
2459 
2460   if (FDecl || Proto) {
2461     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
2462 
2463     // Type safety checking.
2464     if (FDecl) {
2465       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2466         CheckArgumentWithTypeTag(I, Args.data());
2467     }
2468   }
2469 }
2470 
2471 /// CheckConstructorCall - Check a constructor call for correctness and safety
2472 /// properties not enforced by the C type system.
2473 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2474                                 ArrayRef<const Expr *> Args,
2475                                 const FunctionProtoType *Proto,
2476                                 SourceLocation Loc) {
2477   VariadicCallType CallType =
2478     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
2479   checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
2480             CallType);
2481 }
2482 
2483 /// CheckFunctionCall - Check a direct function call for various correctness
2484 /// and safety properties not strictly enforced by the C type system.
2485 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2486                              const FunctionProtoType *Proto) {
2487   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2488                               isa<CXXMethodDecl>(FDecl);
2489   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2490                           IsMemberOperatorCall;
2491   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2492                                                   TheCall->getCallee());
2493   Expr** Args = TheCall->getArgs();
2494   unsigned NumArgs = TheCall->getNumArgs();
2495   if (IsMemberOperatorCall) {
2496     // If this is a call to a member operator, hide the first argument
2497     // from checkCall.
2498     // FIXME: Our choice of AST representation here is less than ideal.
2499     ++Args;
2500     --NumArgs;
2501   }
2502   checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
2503             IsMemberFunction, TheCall->getRParenLoc(),
2504             TheCall->getCallee()->getSourceRange(), CallType);
2505 
2506   IdentifierInfo *FnInfo = FDecl->getIdentifier();
2507   // None of the checks below are needed for functions that don't have
2508   // simple names (e.g., C++ conversion functions).
2509   if (!FnInfo)
2510     return false;
2511 
2512   CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
2513   if (getLangOpts().ObjC1)
2514     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
2515 
2516   unsigned CMId = FDecl->getMemoryFunctionKind();
2517   if (CMId == 0)
2518     return false;
2519 
2520   // Handle memory setting and copying functions.
2521   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
2522     CheckStrlcpycatArguments(TheCall, FnInfo);
2523   else if (CMId == Builtin::BIstrncat)
2524     CheckStrncatArguments(TheCall, FnInfo);
2525   else
2526     CheckMemaccessArguments(TheCall, CMId, FnInfo);
2527 
2528   return false;
2529 }
2530 
2531 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
2532                                ArrayRef<const Expr *> Args) {
2533   VariadicCallType CallType =
2534       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
2535 
2536   checkCall(Method, nullptr, Args,
2537             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
2538             CallType);
2539 
2540   return false;
2541 }
2542 
2543 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2544                             const FunctionProtoType *Proto) {
2545   QualType Ty;
2546   if (const auto *V = dyn_cast<VarDecl>(NDecl))
2547     Ty = V->getType().getNonReferenceType();
2548   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
2549     Ty = F->getType().getNonReferenceType();
2550   else
2551     return false;
2552 
2553   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2554       !Ty->isFunctionProtoType())
2555     return false;
2556 
2557   VariadicCallType CallType;
2558   if (!Proto || !Proto->isVariadic()) {
2559     CallType = VariadicDoesNotApply;
2560   } else if (Ty->isBlockPointerType()) {
2561     CallType = VariadicBlock;
2562   } else { // Ty->isFunctionPointerType()
2563     CallType = VariadicFunction;
2564   }
2565 
2566   checkCall(NDecl, Proto,
2567             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2568             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2569             TheCall->getCallee()->getSourceRange(), CallType);
2570 
2571   return false;
2572 }
2573 
2574 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2575 /// such as function pointers returned from functions.
2576 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
2577   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
2578                                                   TheCall->getCallee());
2579   checkCall(/*FDecl=*/nullptr, Proto,
2580             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2581             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2582             TheCall->getCallee()->getSourceRange(), CallType);
2583 
2584   return false;
2585 }
2586 
2587 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
2588   if (!llvm::isValidAtomicOrderingCABI(Ordering))
2589     return false;
2590 
2591   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
2592   switch (Op) {
2593   case AtomicExpr::AO__c11_atomic_init:
2594     llvm_unreachable("There is no ordering argument for an init");
2595 
2596   case AtomicExpr::AO__c11_atomic_load:
2597   case AtomicExpr::AO__atomic_load_n:
2598   case AtomicExpr::AO__atomic_load:
2599     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2600            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2601 
2602   case AtomicExpr::AO__c11_atomic_store:
2603   case AtomicExpr::AO__atomic_store:
2604   case AtomicExpr::AO__atomic_store_n:
2605     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2606            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2607            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2608 
2609   default:
2610     return true;
2611   }
2612 }
2613 
2614 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2615                                          AtomicExpr::AtomicOp Op) {
2616   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2617   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2618 
2619   // All these operations take one of the following forms:
2620   enum {
2621     // C    __c11_atomic_init(A *, C)
2622     Init,
2623     // C    __c11_atomic_load(A *, int)
2624     Load,
2625     // void __atomic_load(A *, CP, int)
2626     LoadCopy,
2627     // void __atomic_store(A *, CP, int)
2628     Copy,
2629     // C    __c11_atomic_add(A *, M, int)
2630     Arithmetic,
2631     // C    __atomic_exchange_n(A *, CP, int)
2632     Xchg,
2633     // void __atomic_exchange(A *, C *, CP, int)
2634     GNUXchg,
2635     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2636     C11CmpXchg,
2637     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2638     GNUCmpXchg
2639   } Form = Init;
2640   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2641   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
2642   // where:
2643   //   C is an appropriate type,
2644   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2645   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2646   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2647   //   the int parameters are for orderings.
2648 
2649   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2650                     AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2651                         AtomicExpr::AO__atomic_load,
2652                 "need to update code for modified C11 atomics");
2653   bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
2654                Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
2655   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2656              Op == AtomicExpr::AO__atomic_store_n ||
2657              Op == AtomicExpr::AO__atomic_exchange_n ||
2658              Op == AtomicExpr::AO__atomic_compare_exchange_n;
2659   bool IsAddSub = false;
2660 
2661   switch (Op) {
2662   case AtomicExpr::AO__c11_atomic_init:
2663     Form = Init;
2664     break;
2665 
2666   case AtomicExpr::AO__c11_atomic_load:
2667   case AtomicExpr::AO__atomic_load_n:
2668     Form = Load;
2669     break;
2670 
2671   case AtomicExpr::AO__atomic_load:
2672     Form = LoadCopy;
2673     break;
2674 
2675   case AtomicExpr::AO__c11_atomic_store:
2676   case AtomicExpr::AO__atomic_store:
2677   case AtomicExpr::AO__atomic_store_n:
2678     Form = Copy;
2679     break;
2680 
2681   case AtomicExpr::AO__c11_atomic_fetch_add:
2682   case AtomicExpr::AO__c11_atomic_fetch_sub:
2683   case AtomicExpr::AO__atomic_fetch_add:
2684   case AtomicExpr::AO__atomic_fetch_sub:
2685   case AtomicExpr::AO__atomic_add_fetch:
2686   case AtomicExpr::AO__atomic_sub_fetch:
2687     IsAddSub = true;
2688     // Fall through.
2689   case AtomicExpr::AO__c11_atomic_fetch_and:
2690   case AtomicExpr::AO__c11_atomic_fetch_or:
2691   case AtomicExpr::AO__c11_atomic_fetch_xor:
2692   case AtomicExpr::AO__atomic_fetch_and:
2693   case AtomicExpr::AO__atomic_fetch_or:
2694   case AtomicExpr::AO__atomic_fetch_xor:
2695   case AtomicExpr::AO__atomic_fetch_nand:
2696   case AtomicExpr::AO__atomic_and_fetch:
2697   case AtomicExpr::AO__atomic_or_fetch:
2698   case AtomicExpr::AO__atomic_xor_fetch:
2699   case AtomicExpr::AO__atomic_nand_fetch:
2700     Form = Arithmetic;
2701     break;
2702 
2703   case AtomicExpr::AO__c11_atomic_exchange:
2704   case AtomicExpr::AO__atomic_exchange_n:
2705     Form = Xchg;
2706     break;
2707 
2708   case AtomicExpr::AO__atomic_exchange:
2709     Form = GNUXchg;
2710     break;
2711 
2712   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2713   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2714     Form = C11CmpXchg;
2715     break;
2716 
2717   case AtomicExpr::AO__atomic_compare_exchange:
2718   case AtomicExpr::AO__atomic_compare_exchange_n:
2719     Form = GNUCmpXchg;
2720     break;
2721   }
2722 
2723   // Check we have the right number of arguments.
2724   if (TheCall->getNumArgs() < NumArgs[Form]) {
2725     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
2726       << 0 << NumArgs[Form] << TheCall->getNumArgs()
2727       << TheCall->getCallee()->getSourceRange();
2728     return ExprError();
2729   } else if (TheCall->getNumArgs() > NumArgs[Form]) {
2730     Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
2731          diag::err_typecheck_call_too_many_args)
2732       << 0 << NumArgs[Form] << TheCall->getNumArgs()
2733       << TheCall->getCallee()->getSourceRange();
2734     return ExprError();
2735   }
2736 
2737   // Inspect the first argument of the atomic operation.
2738   Expr *Ptr = TheCall->getArg(0);
2739   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
2740   if (ConvertedPtr.isInvalid())
2741     return ExprError();
2742 
2743   Ptr = ConvertedPtr.get();
2744   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
2745   if (!pointerType) {
2746     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
2747       << Ptr->getType() << Ptr->getSourceRange();
2748     return ExprError();
2749   }
2750 
2751   // For a __c11 builtin, this should be a pointer to an _Atomic type.
2752   QualType AtomTy = pointerType->getPointeeType(); // 'A'
2753   QualType ValType = AtomTy; // 'C'
2754   if (IsC11) {
2755     if (!AtomTy->isAtomicType()) {
2756       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
2757         << Ptr->getType() << Ptr->getSourceRange();
2758       return ExprError();
2759     }
2760     if (AtomTy.isConstQualified()) {
2761       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
2762         << Ptr->getType() << Ptr->getSourceRange();
2763       return ExprError();
2764     }
2765     ValType = AtomTy->getAs<AtomicType>()->getValueType();
2766   } else if (Form != Load && Form != LoadCopy) {
2767     if (ValType.isConstQualified()) {
2768       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
2769         << Ptr->getType() << Ptr->getSourceRange();
2770       return ExprError();
2771     }
2772   }
2773 
2774   // For an arithmetic operation, the implied arithmetic must be well-formed.
2775   if (Form == Arithmetic) {
2776     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
2777     if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
2778       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2779         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2780       return ExprError();
2781     }
2782     if (!IsAddSub && !ValType->isIntegerType()) {
2783       Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
2784         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2785       return ExprError();
2786     }
2787     if (IsC11 && ValType->isPointerType() &&
2788         RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
2789                             diag::err_incomplete_type)) {
2790       return ExprError();
2791     }
2792   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
2793     // For __atomic_*_n operations, the value type must be a scalar integral or
2794     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
2795     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2796       << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2797     return ExprError();
2798   }
2799 
2800   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
2801       !AtomTy->isScalarType()) {
2802     // For GNU atomics, require a trivially-copyable type. This is not part of
2803     // the GNU atomics specification, but we enforce it for sanity.
2804     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
2805       << Ptr->getType() << Ptr->getSourceRange();
2806     return ExprError();
2807   }
2808 
2809   switch (ValType.getObjCLifetime()) {
2810   case Qualifiers::OCL_None:
2811   case Qualifiers::OCL_ExplicitNone:
2812     // okay
2813     break;
2814 
2815   case Qualifiers::OCL_Weak:
2816   case Qualifiers::OCL_Strong:
2817   case Qualifiers::OCL_Autoreleasing:
2818     // FIXME: Can this happen? By this point, ValType should be known
2819     // to be trivially copyable.
2820     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2821       << ValType << Ptr->getSourceRange();
2822     return ExprError();
2823   }
2824 
2825   // atomic_fetch_or takes a pointer to a volatile 'A'.  We shouldn't let the
2826   // volatile-ness of the pointee-type inject itself into the result or the
2827   // other operands. Similarly atomic_load can take a pointer to a const 'A'.
2828   ValType.removeLocalVolatile();
2829   ValType.removeLocalConst();
2830   QualType ResultType = ValType;
2831   if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init)
2832     ResultType = Context.VoidTy;
2833   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
2834     ResultType = Context.BoolTy;
2835 
2836   // The type of a parameter passed 'by value'. In the GNU atomics, such
2837   // arguments are actually passed as pointers.
2838   QualType ByValType = ValType; // 'CP'
2839   if (!IsC11 && !IsN)
2840     ByValType = Ptr->getType();
2841 
2842   // The first argument --- the pointer --- has a fixed type; we
2843   // deduce the types of the rest of the arguments accordingly.  Walk
2844   // the remaining arguments, converting them to the deduced value type.
2845   for (unsigned i = 1; i != NumArgs[Form]; ++i) {
2846     QualType Ty;
2847     if (i < NumVals[Form] + 1) {
2848       switch (i) {
2849       case 1:
2850         // The second argument is the non-atomic operand. For arithmetic, this
2851         // is always passed by value, and for a compare_exchange it is always
2852         // passed by address. For the rest, GNU uses by-address and C11 uses
2853         // by-value.
2854         assert(Form != Load);
2855         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2856           Ty = ValType;
2857         else if (Form == Copy || Form == Xchg)
2858           Ty = ByValType;
2859         else if (Form == Arithmetic)
2860           Ty = Context.getPointerDiffType();
2861         else {
2862           Expr *ValArg = TheCall->getArg(i);
2863           unsigned AS = 0;
2864           // Keep address space of non-atomic pointer type.
2865           if (const PointerType *PtrTy =
2866                   ValArg->getType()->getAs<PointerType>()) {
2867             AS = PtrTy->getPointeeType().getAddressSpace();
2868           }
2869           Ty = Context.getPointerType(
2870               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
2871         }
2872         break;
2873       case 2:
2874         // The third argument to compare_exchange / GNU exchange is a
2875         // (pointer to a) desired value.
2876         Ty = ByValType;
2877         break;
2878       case 3:
2879         // The fourth argument to GNU compare_exchange is a 'weak' flag.
2880         Ty = Context.BoolTy;
2881         break;
2882       }
2883     } else {
2884       // The order(s) are always converted to int.
2885       Ty = Context.IntTy;
2886     }
2887 
2888     InitializedEntity Entity =
2889         InitializedEntity::InitializeParameter(Context, Ty, false);
2890     ExprResult Arg = TheCall->getArg(i);
2891     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2892     if (Arg.isInvalid())
2893       return true;
2894     TheCall->setArg(i, Arg.get());
2895   }
2896 
2897   // Permute the arguments into a 'consistent' order.
2898   SmallVector<Expr*, 5> SubExprs;
2899   SubExprs.push_back(Ptr);
2900   switch (Form) {
2901   case Init:
2902     // Note, AtomicExpr::getVal1() has a special case for this atomic.
2903     SubExprs.push_back(TheCall->getArg(1)); // Val1
2904     break;
2905   case Load:
2906     SubExprs.push_back(TheCall->getArg(1)); // Order
2907     break;
2908   case LoadCopy:
2909   case Copy:
2910   case Arithmetic:
2911   case Xchg:
2912     SubExprs.push_back(TheCall->getArg(2)); // Order
2913     SubExprs.push_back(TheCall->getArg(1)); // Val1
2914     break;
2915   case GNUXchg:
2916     // Note, AtomicExpr::getVal2() has a special case for this atomic.
2917     SubExprs.push_back(TheCall->getArg(3)); // Order
2918     SubExprs.push_back(TheCall->getArg(1)); // Val1
2919     SubExprs.push_back(TheCall->getArg(2)); // Val2
2920     break;
2921   case C11CmpXchg:
2922     SubExprs.push_back(TheCall->getArg(3)); // Order
2923     SubExprs.push_back(TheCall->getArg(1)); // Val1
2924     SubExprs.push_back(TheCall->getArg(4)); // OrderFail
2925     SubExprs.push_back(TheCall->getArg(2)); // Val2
2926     break;
2927   case GNUCmpXchg:
2928     SubExprs.push_back(TheCall->getArg(4)); // Order
2929     SubExprs.push_back(TheCall->getArg(1)); // Val1
2930     SubExprs.push_back(TheCall->getArg(5)); // OrderFail
2931     SubExprs.push_back(TheCall->getArg(2)); // Val2
2932     SubExprs.push_back(TheCall->getArg(3)); // Weak
2933     break;
2934   }
2935 
2936   if (SubExprs.size() >= 2 && Form != Init) {
2937     llvm::APSInt Result(32);
2938     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
2939         !isValidOrderingForOp(Result.getSExtValue(), Op))
2940       Diag(SubExprs[1]->getLocStart(),
2941            diag::warn_atomic_op_has_invalid_memory_order)
2942           << SubExprs[1]->getSourceRange();
2943   }
2944 
2945   AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
2946                                             SubExprs, ResultType, Op,
2947                                             TheCall->getRParenLoc());
2948 
2949   if ((Op == AtomicExpr::AO__c11_atomic_load ||
2950        (Op == AtomicExpr::AO__c11_atomic_store)) &&
2951       Context.AtomicUsesUnsupportedLibcall(AE))
2952     Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
2953     ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
2954 
2955   return AE;
2956 }
2957 
2958 /// checkBuiltinArgument - Given a call to a builtin function, perform
2959 /// normal type-checking on the given argument, updating the call in
2960 /// place.  This is useful when a builtin function requires custom
2961 /// type-checking for some of its arguments but not necessarily all of
2962 /// them.
2963 ///
2964 /// Returns true on error.
2965 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
2966   FunctionDecl *Fn = E->getDirectCallee();
2967   assert(Fn && "builtin call without direct callee!");
2968 
2969   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
2970   InitializedEntity Entity =
2971     InitializedEntity::InitializeParameter(S.Context, Param);
2972 
2973   ExprResult Arg = E->getArg(0);
2974   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
2975   if (Arg.isInvalid())
2976     return true;
2977 
2978   E->setArg(ArgIndex, Arg.get());
2979   return false;
2980 }
2981 
2982 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
2983 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
2984 /// type of its first argument.  The main ActOnCallExpr routines have already
2985 /// promoted the types of arguments because all of these calls are prototyped as
2986 /// void(...).
2987 ///
2988 /// This function goes through and does final semantic checking for these
2989 /// builtins,
2990 ExprResult
2991 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
2992   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
2993   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2994   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2995 
2996   // Ensure that we have at least one argument to do type inference from.
2997   if (TheCall->getNumArgs() < 1) {
2998     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2999       << 0 << 1 << TheCall->getNumArgs()
3000       << TheCall->getCallee()->getSourceRange();
3001     return ExprError();
3002   }
3003 
3004   // Inspect the first argument of the atomic builtin.  This should always be
3005   // a pointer type, whose element is an integral scalar or pointer type.
3006   // Because it is a pointer type, we don't have to worry about any implicit
3007   // casts here.
3008   // FIXME: We don't allow floating point scalars as input.
3009   Expr *FirstArg = TheCall->getArg(0);
3010   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3011   if (FirstArgResult.isInvalid())
3012     return ExprError();
3013   FirstArg = FirstArgResult.get();
3014   TheCall->setArg(0, FirstArg);
3015 
3016   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3017   if (!pointerType) {
3018     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3019       << FirstArg->getType() << FirstArg->getSourceRange();
3020     return ExprError();
3021   }
3022 
3023   QualType ValType = pointerType->getPointeeType();
3024   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3025       !ValType->isBlockPointerType()) {
3026     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3027       << FirstArg->getType() << FirstArg->getSourceRange();
3028     return ExprError();
3029   }
3030 
3031   switch (ValType.getObjCLifetime()) {
3032   case Qualifiers::OCL_None:
3033   case Qualifiers::OCL_ExplicitNone:
3034     // okay
3035     break;
3036 
3037   case Qualifiers::OCL_Weak:
3038   case Qualifiers::OCL_Strong:
3039   case Qualifiers::OCL_Autoreleasing:
3040     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3041       << ValType << FirstArg->getSourceRange();
3042     return ExprError();
3043   }
3044 
3045   // Strip any qualifiers off ValType.
3046   ValType = ValType.getUnqualifiedType();
3047 
3048   // The majority of builtins return a value, but a few have special return
3049   // types, so allow them to override appropriately below.
3050   QualType ResultType = ValType;
3051 
3052   // We need to figure out which concrete builtin this maps onto.  For example,
3053   // __sync_fetch_and_add with a 2 byte object turns into
3054   // __sync_fetch_and_add_2.
3055 #define BUILTIN_ROW(x) \
3056   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3057     Builtin::BI##x##_8, Builtin::BI##x##_16 }
3058 
3059   static const unsigned BuiltinIndices[][5] = {
3060     BUILTIN_ROW(__sync_fetch_and_add),
3061     BUILTIN_ROW(__sync_fetch_and_sub),
3062     BUILTIN_ROW(__sync_fetch_and_or),
3063     BUILTIN_ROW(__sync_fetch_and_and),
3064     BUILTIN_ROW(__sync_fetch_and_xor),
3065     BUILTIN_ROW(__sync_fetch_and_nand),
3066 
3067     BUILTIN_ROW(__sync_add_and_fetch),
3068     BUILTIN_ROW(__sync_sub_and_fetch),
3069     BUILTIN_ROW(__sync_and_and_fetch),
3070     BUILTIN_ROW(__sync_or_and_fetch),
3071     BUILTIN_ROW(__sync_xor_and_fetch),
3072     BUILTIN_ROW(__sync_nand_and_fetch),
3073 
3074     BUILTIN_ROW(__sync_val_compare_and_swap),
3075     BUILTIN_ROW(__sync_bool_compare_and_swap),
3076     BUILTIN_ROW(__sync_lock_test_and_set),
3077     BUILTIN_ROW(__sync_lock_release),
3078     BUILTIN_ROW(__sync_swap)
3079   };
3080 #undef BUILTIN_ROW
3081 
3082   // Determine the index of the size.
3083   unsigned SizeIndex;
3084   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
3085   case 1: SizeIndex = 0; break;
3086   case 2: SizeIndex = 1; break;
3087   case 4: SizeIndex = 2; break;
3088   case 8: SizeIndex = 3; break;
3089   case 16: SizeIndex = 4; break;
3090   default:
3091     Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3092       << FirstArg->getType() << FirstArg->getSourceRange();
3093     return ExprError();
3094   }
3095 
3096   // Each of these builtins has one pointer argument, followed by some number of
3097   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3098   // that we ignore.  Find out which row of BuiltinIndices to read from as well
3099   // as the number of fixed args.
3100   unsigned BuiltinID = FDecl->getBuiltinID();
3101   unsigned BuiltinIndex, NumFixed = 1;
3102   bool WarnAboutSemanticsChange = false;
3103   switch (BuiltinID) {
3104   default: llvm_unreachable("Unknown overloaded atomic builtin!");
3105   case Builtin::BI__sync_fetch_and_add:
3106   case Builtin::BI__sync_fetch_and_add_1:
3107   case Builtin::BI__sync_fetch_and_add_2:
3108   case Builtin::BI__sync_fetch_and_add_4:
3109   case Builtin::BI__sync_fetch_and_add_8:
3110   case Builtin::BI__sync_fetch_and_add_16:
3111     BuiltinIndex = 0;
3112     break;
3113 
3114   case Builtin::BI__sync_fetch_and_sub:
3115   case Builtin::BI__sync_fetch_and_sub_1:
3116   case Builtin::BI__sync_fetch_and_sub_2:
3117   case Builtin::BI__sync_fetch_and_sub_4:
3118   case Builtin::BI__sync_fetch_and_sub_8:
3119   case Builtin::BI__sync_fetch_and_sub_16:
3120     BuiltinIndex = 1;
3121     break;
3122 
3123   case Builtin::BI__sync_fetch_and_or:
3124   case Builtin::BI__sync_fetch_and_or_1:
3125   case Builtin::BI__sync_fetch_and_or_2:
3126   case Builtin::BI__sync_fetch_and_or_4:
3127   case Builtin::BI__sync_fetch_and_or_8:
3128   case Builtin::BI__sync_fetch_and_or_16:
3129     BuiltinIndex = 2;
3130     break;
3131 
3132   case Builtin::BI__sync_fetch_and_and:
3133   case Builtin::BI__sync_fetch_and_and_1:
3134   case Builtin::BI__sync_fetch_and_and_2:
3135   case Builtin::BI__sync_fetch_and_and_4:
3136   case Builtin::BI__sync_fetch_and_and_8:
3137   case Builtin::BI__sync_fetch_and_and_16:
3138     BuiltinIndex = 3;
3139     break;
3140 
3141   case Builtin::BI__sync_fetch_and_xor:
3142   case Builtin::BI__sync_fetch_and_xor_1:
3143   case Builtin::BI__sync_fetch_and_xor_2:
3144   case Builtin::BI__sync_fetch_and_xor_4:
3145   case Builtin::BI__sync_fetch_and_xor_8:
3146   case Builtin::BI__sync_fetch_and_xor_16:
3147     BuiltinIndex = 4;
3148     break;
3149 
3150   case Builtin::BI__sync_fetch_and_nand:
3151   case Builtin::BI__sync_fetch_and_nand_1:
3152   case Builtin::BI__sync_fetch_and_nand_2:
3153   case Builtin::BI__sync_fetch_and_nand_4:
3154   case Builtin::BI__sync_fetch_and_nand_8:
3155   case Builtin::BI__sync_fetch_and_nand_16:
3156     BuiltinIndex = 5;
3157     WarnAboutSemanticsChange = true;
3158     break;
3159 
3160   case Builtin::BI__sync_add_and_fetch:
3161   case Builtin::BI__sync_add_and_fetch_1:
3162   case Builtin::BI__sync_add_and_fetch_2:
3163   case Builtin::BI__sync_add_and_fetch_4:
3164   case Builtin::BI__sync_add_and_fetch_8:
3165   case Builtin::BI__sync_add_and_fetch_16:
3166     BuiltinIndex = 6;
3167     break;
3168 
3169   case Builtin::BI__sync_sub_and_fetch:
3170   case Builtin::BI__sync_sub_and_fetch_1:
3171   case Builtin::BI__sync_sub_and_fetch_2:
3172   case Builtin::BI__sync_sub_and_fetch_4:
3173   case Builtin::BI__sync_sub_and_fetch_8:
3174   case Builtin::BI__sync_sub_and_fetch_16:
3175     BuiltinIndex = 7;
3176     break;
3177 
3178   case Builtin::BI__sync_and_and_fetch:
3179   case Builtin::BI__sync_and_and_fetch_1:
3180   case Builtin::BI__sync_and_and_fetch_2:
3181   case Builtin::BI__sync_and_and_fetch_4:
3182   case Builtin::BI__sync_and_and_fetch_8:
3183   case Builtin::BI__sync_and_and_fetch_16:
3184     BuiltinIndex = 8;
3185     break;
3186 
3187   case Builtin::BI__sync_or_and_fetch:
3188   case Builtin::BI__sync_or_and_fetch_1:
3189   case Builtin::BI__sync_or_and_fetch_2:
3190   case Builtin::BI__sync_or_and_fetch_4:
3191   case Builtin::BI__sync_or_and_fetch_8:
3192   case Builtin::BI__sync_or_and_fetch_16:
3193     BuiltinIndex = 9;
3194     break;
3195 
3196   case Builtin::BI__sync_xor_and_fetch:
3197   case Builtin::BI__sync_xor_and_fetch_1:
3198   case Builtin::BI__sync_xor_and_fetch_2:
3199   case Builtin::BI__sync_xor_and_fetch_4:
3200   case Builtin::BI__sync_xor_and_fetch_8:
3201   case Builtin::BI__sync_xor_and_fetch_16:
3202     BuiltinIndex = 10;
3203     break;
3204 
3205   case Builtin::BI__sync_nand_and_fetch:
3206   case Builtin::BI__sync_nand_and_fetch_1:
3207   case Builtin::BI__sync_nand_and_fetch_2:
3208   case Builtin::BI__sync_nand_and_fetch_4:
3209   case Builtin::BI__sync_nand_and_fetch_8:
3210   case Builtin::BI__sync_nand_and_fetch_16:
3211     BuiltinIndex = 11;
3212     WarnAboutSemanticsChange = true;
3213     break;
3214 
3215   case Builtin::BI__sync_val_compare_and_swap:
3216   case Builtin::BI__sync_val_compare_and_swap_1:
3217   case Builtin::BI__sync_val_compare_and_swap_2:
3218   case Builtin::BI__sync_val_compare_and_swap_4:
3219   case Builtin::BI__sync_val_compare_and_swap_8:
3220   case Builtin::BI__sync_val_compare_and_swap_16:
3221     BuiltinIndex = 12;
3222     NumFixed = 2;
3223     break;
3224 
3225   case Builtin::BI__sync_bool_compare_and_swap:
3226   case Builtin::BI__sync_bool_compare_and_swap_1:
3227   case Builtin::BI__sync_bool_compare_and_swap_2:
3228   case Builtin::BI__sync_bool_compare_and_swap_4:
3229   case Builtin::BI__sync_bool_compare_and_swap_8:
3230   case Builtin::BI__sync_bool_compare_and_swap_16:
3231     BuiltinIndex = 13;
3232     NumFixed = 2;
3233     ResultType = Context.BoolTy;
3234     break;
3235 
3236   case Builtin::BI__sync_lock_test_and_set:
3237   case Builtin::BI__sync_lock_test_and_set_1:
3238   case Builtin::BI__sync_lock_test_and_set_2:
3239   case Builtin::BI__sync_lock_test_and_set_4:
3240   case Builtin::BI__sync_lock_test_and_set_8:
3241   case Builtin::BI__sync_lock_test_and_set_16:
3242     BuiltinIndex = 14;
3243     break;
3244 
3245   case Builtin::BI__sync_lock_release:
3246   case Builtin::BI__sync_lock_release_1:
3247   case Builtin::BI__sync_lock_release_2:
3248   case Builtin::BI__sync_lock_release_4:
3249   case Builtin::BI__sync_lock_release_8:
3250   case Builtin::BI__sync_lock_release_16:
3251     BuiltinIndex = 15;
3252     NumFixed = 0;
3253     ResultType = Context.VoidTy;
3254     break;
3255 
3256   case Builtin::BI__sync_swap:
3257   case Builtin::BI__sync_swap_1:
3258   case Builtin::BI__sync_swap_2:
3259   case Builtin::BI__sync_swap_4:
3260   case Builtin::BI__sync_swap_8:
3261   case Builtin::BI__sync_swap_16:
3262     BuiltinIndex = 16;
3263     break;
3264   }
3265 
3266   // Now that we know how many fixed arguments we expect, first check that we
3267   // have at least that many.
3268   if (TheCall->getNumArgs() < 1+NumFixed) {
3269     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3270       << 0 << 1+NumFixed << TheCall->getNumArgs()
3271       << TheCall->getCallee()->getSourceRange();
3272     return ExprError();
3273   }
3274 
3275   if (WarnAboutSemanticsChange) {
3276     Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3277       << TheCall->getCallee()->getSourceRange();
3278   }
3279 
3280   // Get the decl for the concrete builtin from this, we can tell what the
3281   // concrete integer type we should convert to is.
3282   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
3283   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
3284   FunctionDecl *NewBuiltinDecl;
3285   if (NewBuiltinID == BuiltinID)
3286     NewBuiltinDecl = FDecl;
3287   else {
3288     // Perform builtin lookup to avoid redeclaring it.
3289     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3290     LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3291     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3292     assert(Res.getFoundDecl());
3293     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
3294     if (!NewBuiltinDecl)
3295       return ExprError();
3296   }
3297 
3298   // The first argument --- the pointer --- has a fixed type; we
3299   // deduce the types of the rest of the arguments accordingly.  Walk
3300   // the remaining arguments, converting them to the deduced value type.
3301   for (unsigned i = 0; i != NumFixed; ++i) {
3302     ExprResult Arg = TheCall->getArg(i+1);
3303 
3304     // GCC does an implicit conversion to the pointer or integer ValType.  This
3305     // can fail in some cases (1i -> int**), check for this error case now.
3306     // Initialize the argument.
3307     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3308                                                    ValType, /*consume*/ false);
3309     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3310     if (Arg.isInvalid())
3311       return ExprError();
3312 
3313     // Okay, we have something that *can* be converted to the right type.  Check
3314     // to see if there is a potentially weird extension going on here.  This can
3315     // happen when you do an atomic operation on something like an char* and
3316     // pass in 42.  The 42 gets converted to char.  This is even more strange
3317     // for things like 45.123 -> char, etc.
3318     // FIXME: Do this check.
3319     TheCall->setArg(i+1, Arg.get());
3320   }
3321 
3322   ASTContext& Context = this->getASTContext();
3323 
3324   // Create a new DeclRefExpr to refer to the new decl.
3325   DeclRefExpr* NewDRE = DeclRefExpr::Create(
3326       Context,
3327       DRE->getQualifierLoc(),
3328       SourceLocation(),
3329       NewBuiltinDecl,
3330       /*enclosing*/ false,
3331       DRE->getLocation(),
3332       Context.BuiltinFnTy,
3333       DRE->getValueKind());
3334 
3335   // Set the callee in the CallExpr.
3336   // FIXME: This loses syntactic information.
3337   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3338   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3339                                               CK_BuiltinFnToFnPtr);
3340   TheCall->setCallee(PromotedCall.get());
3341 
3342   // Change the result type of the call to match the original value type. This
3343   // is arbitrary, but the codegen for these builtins ins design to handle it
3344   // gracefully.
3345   TheCall->setType(ResultType);
3346 
3347   return TheCallResult;
3348 }
3349 
3350 /// SemaBuiltinNontemporalOverloaded - We have a call to
3351 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3352 /// overloaded function based on the pointer type of its last argument.
3353 ///
3354 /// This function goes through and does final semantic checking for these
3355 /// builtins.
3356 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3357   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3358   DeclRefExpr *DRE =
3359       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3360   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3361   unsigned BuiltinID = FDecl->getBuiltinID();
3362   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3363           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3364          "Unexpected nontemporal load/store builtin!");
3365   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3366   unsigned numArgs = isStore ? 2 : 1;
3367 
3368   // Ensure that we have the proper number of arguments.
3369   if (checkArgCount(*this, TheCall, numArgs))
3370     return ExprError();
3371 
3372   // Inspect the last argument of the nontemporal builtin.  This should always
3373   // be a pointer type, from which we imply the type of the memory access.
3374   // Because it is a pointer type, we don't have to worry about any implicit
3375   // casts here.
3376   Expr *PointerArg = TheCall->getArg(numArgs - 1);
3377   ExprResult PointerArgResult =
3378       DefaultFunctionArrayLvalueConversion(PointerArg);
3379 
3380   if (PointerArgResult.isInvalid())
3381     return ExprError();
3382   PointerArg = PointerArgResult.get();
3383   TheCall->setArg(numArgs - 1, PointerArg);
3384 
3385   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3386   if (!pointerType) {
3387     Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3388         << PointerArg->getType() << PointerArg->getSourceRange();
3389     return ExprError();
3390   }
3391 
3392   QualType ValType = pointerType->getPointeeType();
3393 
3394   // Strip any qualifiers off ValType.
3395   ValType = ValType.getUnqualifiedType();
3396   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3397       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3398       !ValType->isVectorType()) {
3399     Diag(DRE->getLocStart(),
3400          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3401         << PointerArg->getType() << PointerArg->getSourceRange();
3402     return ExprError();
3403   }
3404 
3405   if (!isStore) {
3406     TheCall->setType(ValType);
3407     return TheCallResult;
3408   }
3409 
3410   ExprResult ValArg = TheCall->getArg(0);
3411   InitializedEntity Entity = InitializedEntity::InitializeParameter(
3412       Context, ValType, /*consume*/ false);
3413   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3414   if (ValArg.isInvalid())
3415     return ExprError();
3416 
3417   TheCall->setArg(0, ValArg.get());
3418   TheCall->setType(Context.VoidTy);
3419   return TheCallResult;
3420 }
3421 
3422 /// CheckObjCString - Checks that the argument to the builtin
3423 /// CFString constructor is correct
3424 /// Note: It might also make sense to do the UTF-16 conversion here (would
3425 /// simplify the backend).
3426 bool Sema::CheckObjCString(Expr *Arg) {
3427   Arg = Arg->IgnoreParenCasts();
3428   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3429 
3430   if (!Literal || !Literal->isAscii()) {
3431     Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3432       << Arg->getSourceRange();
3433     return true;
3434   }
3435 
3436   if (Literal->containsNonAsciiOrNull()) {
3437     StringRef String = Literal->getString();
3438     unsigned NumBytes = String.size();
3439     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3440     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3441     llvm::UTF16 *ToPtr = &ToBuf[0];
3442 
3443     llvm::ConversionResult Result =
3444         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3445                                  ToPtr + NumBytes, llvm::strictConversion);
3446     // Check for conversion failure.
3447     if (Result != llvm::conversionOK)
3448       Diag(Arg->getLocStart(),
3449            diag::warn_cfstring_truncated) << Arg->getSourceRange();
3450   }
3451   return false;
3452 }
3453 
3454 /// CheckObjCString - Checks that the format string argument to the os_log()
3455 /// and os_trace() functions is correct, and converts it to const char *.
3456 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3457   Arg = Arg->IgnoreParenCasts();
3458   auto *Literal = dyn_cast<StringLiteral>(Arg);
3459   if (!Literal) {
3460     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3461       Literal = ObjcLiteral->getString();
3462     }
3463   }
3464 
3465   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3466     return ExprError(
3467         Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3468         << Arg->getSourceRange());
3469   }
3470 
3471   ExprResult Result(Literal);
3472   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3473   InitializedEntity Entity =
3474       InitializedEntity::InitializeParameter(Context, ResultTy, false);
3475   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3476   return Result;
3477 }
3478 
3479 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3480 /// for validity.  Emit an error and return true on failure; return false
3481 /// on success.
3482 bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
3483   Expr *Fn = TheCall->getCallee();
3484   if (TheCall->getNumArgs() > 2) {
3485     Diag(TheCall->getArg(2)->getLocStart(),
3486          diag::err_typecheck_call_too_many_args)
3487       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3488       << Fn->getSourceRange()
3489       << SourceRange(TheCall->getArg(2)->getLocStart(),
3490                      (*(TheCall->arg_end()-1))->getLocEnd());
3491     return true;
3492   }
3493 
3494   if (TheCall->getNumArgs() < 2) {
3495     return Diag(TheCall->getLocEnd(),
3496       diag::err_typecheck_call_too_few_args_at_least)
3497       << 0 /*function call*/ << 2 << TheCall->getNumArgs();
3498   }
3499 
3500   // Type-check the first argument normally.
3501   if (checkBuiltinArgument(*this, TheCall, 0))
3502     return true;
3503 
3504   // Determine whether the current function is variadic or not.
3505   BlockScopeInfo *CurBlock = getCurBlock();
3506   bool isVariadic;
3507   if (CurBlock)
3508     isVariadic = CurBlock->TheDecl->isVariadic();
3509   else if (FunctionDecl *FD = getCurFunctionDecl())
3510     isVariadic = FD->isVariadic();
3511   else
3512     isVariadic = getCurMethodDecl()->isVariadic();
3513 
3514   if (!isVariadic) {
3515     Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3516     return true;
3517   }
3518 
3519   // Verify that the second argument to the builtin is the last argument of the
3520   // current function or method.
3521   bool SecondArgIsLastNamedArgument = false;
3522   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
3523 
3524   // These are valid if SecondArgIsLastNamedArgument is false after the next
3525   // block.
3526   QualType Type;
3527   SourceLocation ParamLoc;
3528   bool IsCRegister = false;
3529 
3530   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3531     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
3532       // FIXME: This isn't correct for methods (results in bogus warning).
3533       // Get the last formal in the current function.
3534       const ParmVarDecl *LastArg;
3535       if (CurBlock)
3536         LastArg = CurBlock->TheDecl->parameters().back();
3537       else if (FunctionDecl *FD = getCurFunctionDecl())
3538         LastArg = FD->parameters().back();
3539       else
3540         LastArg = getCurMethodDecl()->parameters().back();
3541       SecondArgIsLastNamedArgument = PV == LastArg;
3542 
3543       Type = PV->getType();
3544       ParamLoc = PV->getLocation();
3545       IsCRegister =
3546           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
3547     }
3548   }
3549 
3550   if (!SecondArgIsLastNamedArgument)
3551     Diag(TheCall->getArg(1)->getLocStart(),
3552          diag::warn_second_arg_of_va_start_not_last_named_param);
3553   else if (IsCRegister || Type->isReferenceType() ||
3554            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3555              // Promotable integers are UB, but enumerations need a bit of
3556              // extra checking to see what their promotable type actually is.
3557              if (!Type->isPromotableIntegerType())
3558                return false;
3559              if (!Type->isEnumeralType())
3560                return true;
3561              const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3562              return !(ED &&
3563                       Context.typesAreCompatible(ED->getPromotionType(), Type));
3564            }()) {
3565     unsigned Reason = 0;
3566     if (Type->isReferenceType())  Reason = 1;
3567     else if (IsCRegister)         Reason = 2;
3568     Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
3569     Diag(ParamLoc, diag::note_parameter_type) << Type;
3570   }
3571 
3572   TheCall->setType(Context.VoidTy);
3573   return false;
3574 }
3575 
3576 /// Check the arguments to '__builtin_va_start' for validity, and that
3577 /// it was called from a function of the native ABI.
3578 /// Emit an error and return true on failure; return false on success.
3579 bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
3580   // On x86-64 Unix, don't allow this in Win64 ABI functions.
3581   // On x64 Windows, don't allow this in System V ABI functions.
3582   // (Yes, that means there's no corresponding way to support variadic
3583   // System V ABI functions on Windows.)
3584   if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
3585     unsigned OS = Context.getTargetInfo().getTriple().getOS();
3586     clang::CallingConv CC = CC_C;
3587     if (const FunctionDecl *FD = getCurFunctionDecl())
3588       CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3589     if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
3590         (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
3591       return Diag(TheCall->getCallee()->getLocStart(),
3592                   diag::err_va_start_used_in_wrong_abi_function)
3593              << (OS != llvm::Triple::Win32);
3594   }
3595   return SemaBuiltinVAStartImpl(TheCall);
3596 }
3597 
3598 /// Check the arguments to '__builtin_ms_va_start' for validity, and that
3599 /// it was called from a Win64 ABI function.
3600 /// Emit an error and return true on failure; return false on success.
3601 bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
3602   // This only makes sense for x86-64.
3603   const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3604   Expr *Callee = TheCall->getCallee();
3605   if (TT.getArch() != llvm::Triple::x86_64)
3606     return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
3607   // Don't allow this in System V ABI functions.
3608   clang::CallingConv CC = CC_C;
3609   if (const FunctionDecl *FD = getCurFunctionDecl())
3610     CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3611   if (CC == CC_X86_64SysV ||
3612       (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
3613     return Diag(Callee->getLocStart(),
3614                 diag::err_ms_va_start_used_in_sysv_function);
3615   return SemaBuiltinVAStartImpl(TheCall);
3616 }
3617 
3618 bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
3619   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3620   //                 const char *named_addr);
3621 
3622   Expr *Func = Call->getCallee();
3623 
3624   if (Call->getNumArgs() < 3)
3625     return Diag(Call->getLocEnd(),
3626                 diag::err_typecheck_call_too_few_args_at_least)
3627            << 0 /*function call*/ << 3 << Call->getNumArgs();
3628 
3629   // Determine whether the current function is variadic or not.
3630   bool IsVariadic;
3631   if (BlockScopeInfo *CurBlock = getCurBlock())
3632     IsVariadic = CurBlock->TheDecl->isVariadic();
3633   else if (FunctionDecl *FD = getCurFunctionDecl())
3634     IsVariadic = FD->isVariadic();
3635   else if (ObjCMethodDecl *MD = getCurMethodDecl())
3636     IsVariadic = MD->isVariadic();
3637   else
3638     llvm_unreachable("unexpected statement type");
3639 
3640   if (!IsVariadic) {
3641     Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3642     return true;
3643   }
3644 
3645   // Type-check the first argument normally.
3646   if (checkBuiltinArgument(*this, Call, 0))
3647     return true;
3648 
3649   const struct {
3650     unsigned ArgNo;
3651     QualType Type;
3652   } ArgumentTypes[] = {
3653     { 1, Context.getPointerType(Context.CharTy.withConst()) },
3654     { 2, Context.getSizeType() },
3655   };
3656 
3657   for (const auto &AT : ArgumentTypes) {
3658     const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
3659     if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
3660       continue;
3661     Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
3662       << Arg->getType() << AT.Type << 1 /* different class */
3663       << 0 /* qualifier difference */ << 3 /* parameter mismatch */
3664       << AT.ArgNo + 1 << Arg->getType() << AT.Type;
3665   }
3666 
3667   return false;
3668 }
3669 
3670 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3671 /// friends.  This is declared to take (...), so we have to check everything.
3672 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3673   if (TheCall->getNumArgs() < 2)
3674     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3675       << 0 << 2 << TheCall->getNumArgs()/*function call*/;
3676   if (TheCall->getNumArgs() > 2)
3677     return Diag(TheCall->getArg(2)->getLocStart(),
3678                 diag::err_typecheck_call_too_many_args)
3679       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3680       << SourceRange(TheCall->getArg(2)->getLocStart(),
3681                      (*(TheCall->arg_end()-1))->getLocEnd());
3682 
3683   ExprResult OrigArg0 = TheCall->getArg(0);
3684   ExprResult OrigArg1 = TheCall->getArg(1);
3685 
3686   // Do standard promotions between the two arguments, returning their common
3687   // type.
3688   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
3689   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
3690     return true;
3691 
3692   // Make sure any conversions are pushed back into the call; this is
3693   // type safe since unordered compare builtins are declared as "_Bool
3694   // foo(...)".
3695   TheCall->setArg(0, OrigArg0.get());
3696   TheCall->setArg(1, OrigArg1.get());
3697 
3698   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
3699     return false;
3700 
3701   // If the common type isn't a real floating type, then the arguments were
3702   // invalid for this operation.
3703   if (Res.isNull() || !Res->isRealFloatingType())
3704     return Diag(OrigArg0.get()->getLocStart(),
3705                 diag::err_typecheck_call_invalid_ordered_compare)
3706       << OrigArg0.get()->getType() << OrigArg1.get()->getType()
3707       << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
3708 
3709   return false;
3710 }
3711 
3712 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
3713 /// __builtin_isnan and friends.  This is declared to take (...), so we have
3714 /// to check everything. We expect the last argument to be a floating point
3715 /// value.
3716 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
3717   if (TheCall->getNumArgs() < NumArgs)
3718     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3719       << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
3720   if (TheCall->getNumArgs() > NumArgs)
3721     return Diag(TheCall->getArg(NumArgs)->getLocStart(),
3722                 diag::err_typecheck_call_too_many_args)
3723       << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
3724       << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
3725                      (*(TheCall->arg_end()-1))->getLocEnd());
3726 
3727   Expr *OrigArg = TheCall->getArg(NumArgs-1);
3728 
3729   if (OrigArg->isTypeDependent())
3730     return false;
3731 
3732   // This operation requires a non-_Complex floating-point number.
3733   if (!OrigArg->getType()->isRealFloatingType())
3734     return Diag(OrigArg->getLocStart(),
3735                 diag::err_typecheck_call_invalid_unary_fp)
3736       << OrigArg->getType() << OrigArg->getSourceRange();
3737 
3738   // If this is an implicit conversion from float -> double, remove it.
3739   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
3740     Expr *CastArg = Cast->getSubExpr();
3741     if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
3742       assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
3743              "promotion from float to double is the only expected cast here");
3744       Cast->setSubExpr(nullptr);
3745       TheCall->setArg(NumArgs-1, CastArg);
3746     }
3747   }
3748 
3749   return false;
3750 }
3751 
3752 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
3753 // This is declared to take (...), so we have to check everything.
3754 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
3755   if (TheCall->getNumArgs() < 2)
3756     return ExprError(Diag(TheCall->getLocEnd(),
3757                           diag::err_typecheck_call_too_few_args_at_least)
3758                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3759                      << TheCall->getSourceRange());
3760 
3761   // Determine which of the following types of shufflevector we're checking:
3762   // 1) unary, vector mask: (lhs, mask)
3763   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
3764   QualType resType = TheCall->getArg(0)->getType();
3765   unsigned numElements = 0;
3766 
3767   if (!TheCall->getArg(0)->isTypeDependent() &&
3768       !TheCall->getArg(1)->isTypeDependent()) {
3769     QualType LHSType = TheCall->getArg(0)->getType();
3770     QualType RHSType = TheCall->getArg(1)->getType();
3771 
3772     if (!LHSType->isVectorType() || !RHSType->isVectorType())
3773       return ExprError(Diag(TheCall->getLocStart(),
3774                             diag::err_shufflevector_non_vector)
3775                        << SourceRange(TheCall->getArg(0)->getLocStart(),
3776                                       TheCall->getArg(1)->getLocEnd()));
3777 
3778     numElements = LHSType->getAs<VectorType>()->getNumElements();
3779     unsigned numResElements = TheCall->getNumArgs() - 2;
3780 
3781     // Check to see if we have a call with 2 vector arguments, the unary shuffle
3782     // with mask.  If so, verify that RHS is an integer vector type with the
3783     // same number of elts as lhs.
3784     if (TheCall->getNumArgs() == 2) {
3785       if (!RHSType->hasIntegerRepresentation() ||
3786           RHSType->getAs<VectorType>()->getNumElements() != numElements)
3787         return ExprError(Diag(TheCall->getLocStart(),
3788                               diag::err_shufflevector_incompatible_vector)
3789                          << SourceRange(TheCall->getArg(1)->getLocStart(),
3790                                         TheCall->getArg(1)->getLocEnd()));
3791     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
3792       return ExprError(Diag(TheCall->getLocStart(),
3793                             diag::err_shufflevector_incompatible_vector)
3794                        << SourceRange(TheCall->getArg(0)->getLocStart(),
3795                                       TheCall->getArg(1)->getLocEnd()));
3796     } else if (numElements != numResElements) {
3797       QualType eltType = LHSType->getAs<VectorType>()->getElementType();
3798       resType = Context.getVectorType(eltType, numResElements,
3799                                       VectorType::GenericVector);
3800     }
3801   }
3802 
3803   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
3804     if (TheCall->getArg(i)->isTypeDependent() ||
3805         TheCall->getArg(i)->isValueDependent())
3806       continue;
3807 
3808     llvm::APSInt Result(32);
3809     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
3810       return ExprError(Diag(TheCall->getLocStart(),
3811                             diag::err_shufflevector_nonconstant_argument)
3812                        << TheCall->getArg(i)->getSourceRange());
3813 
3814     // Allow -1 which will be translated to undef in the IR.
3815     if (Result.isSigned() && Result.isAllOnesValue())
3816       continue;
3817 
3818     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
3819       return ExprError(Diag(TheCall->getLocStart(),
3820                             diag::err_shufflevector_argument_too_large)
3821                        << TheCall->getArg(i)->getSourceRange());
3822   }
3823 
3824   SmallVector<Expr*, 32> exprs;
3825 
3826   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
3827     exprs.push_back(TheCall->getArg(i));
3828     TheCall->setArg(i, nullptr);
3829   }
3830 
3831   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
3832                                          TheCall->getCallee()->getLocStart(),
3833                                          TheCall->getRParenLoc());
3834 }
3835 
3836 /// SemaConvertVectorExpr - Handle __builtin_convertvector
3837 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
3838                                        SourceLocation BuiltinLoc,
3839                                        SourceLocation RParenLoc) {
3840   ExprValueKind VK = VK_RValue;
3841   ExprObjectKind OK = OK_Ordinary;
3842   QualType DstTy = TInfo->getType();
3843   QualType SrcTy = E->getType();
3844 
3845   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
3846     return ExprError(Diag(BuiltinLoc,
3847                           diag::err_convertvector_non_vector)
3848                      << E->getSourceRange());
3849   if (!DstTy->isVectorType() && !DstTy->isDependentType())
3850     return ExprError(Diag(BuiltinLoc,
3851                           diag::err_convertvector_non_vector_type));
3852 
3853   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
3854     unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
3855     unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
3856     if (SrcElts != DstElts)
3857       return ExprError(Diag(BuiltinLoc,
3858                             diag::err_convertvector_incompatible_vector)
3859                        << E->getSourceRange());
3860   }
3861 
3862   return new (Context)
3863       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
3864 }
3865 
3866 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
3867 // This is declared to take (const void*, ...) and can take two
3868 // optional constant int args.
3869 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
3870   unsigned NumArgs = TheCall->getNumArgs();
3871 
3872   if (NumArgs > 3)
3873     return Diag(TheCall->getLocEnd(),
3874              diag::err_typecheck_call_too_many_args_at_most)
3875              << 0 /*function call*/ << 3 << NumArgs
3876              << TheCall->getSourceRange();
3877 
3878   // Argument 0 is checked for us and the remaining arguments must be
3879   // constant integers.
3880   for (unsigned i = 1; i != NumArgs; ++i)
3881     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
3882       return true;
3883 
3884   return false;
3885 }
3886 
3887 /// SemaBuiltinAssume - Handle __assume (MS Extension).
3888 // __assume does not evaluate its arguments, and should warn if its argument
3889 // has side effects.
3890 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
3891   Expr *Arg = TheCall->getArg(0);
3892   if (Arg->isInstantiationDependent()) return false;
3893 
3894   if (Arg->HasSideEffects(Context))
3895     Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
3896       << Arg->getSourceRange()
3897       << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
3898 
3899   return false;
3900 }
3901 
3902 /// Handle __builtin_alloca_with_align. This is declared
3903 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
3904 /// than 8.
3905 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
3906   // The alignment must be a constant integer.
3907   Expr *Arg = TheCall->getArg(1);
3908 
3909   // We can't check the value of a dependent argument.
3910   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3911     if (const auto *UE =
3912             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
3913       if (UE->getKind() == UETT_AlignOf)
3914         Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
3915           << Arg->getSourceRange();
3916 
3917     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
3918 
3919     if (!Result.isPowerOf2())
3920       return Diag(TheCall->getLocStart(),
3921                   diag::err_alignment_not_power_of_two)
3922            << Arg->getSourceRange();
3923 
3924     if (Result < Context.getCharWidth())
3925       return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
3926            << (unsigned)Context.getCharWidth()
3927            << Arg->getSourceRange();
3928 
3929     if (Result > INT32_MAX)
3930       return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
3931            << INT32_MAX
3932            << Arg->getSourceRange();
3933   }
3934 
3935   return false;
3936 }
3937 
3938 /// Handle __builtin_assume_aligned. This is declared
3939 /// as (const void*, size_t, ...) and can take one optional constant int arg.
3940 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
3941   unsigned NumArgs = TheCall->getNumArgs();
3942 
3943   if (NumArgs > 3)
3944     return Diag(TheCall->getLocEnd(),
3945              diag::err_typecheck_call_too_many_args_at_most)
3946              << 0 /*function call*/ << 3 << NumArgs
3947              << TheCall->getSourceRange();
3948 
3949   // The alignment must be a constant integer.
3950   Expr *Arg = TheCall->getArg(1);
3951 
3952   // We can't check the value of a dependent argument.
3953   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3954     llvm::APSInt Result;
3955     if (SemaBuiltinConstantArg(TheCall, 1, Result))
3956       return true;
3957 
3958     if (!Result.isPowerOf2())
3959       return Diag(TheCall->getLocStart(),
3960                   diag::err_alignment_not_power_of_two)
3961            << Arg->getSourceRange();
3962   }
3963 
3964   if (NumArgs > 2) {
3965     ExprResult Arg(TheCall->getArg(2));
3966     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3967       Context.getSizeType(), false);
3968     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3969     if (Arg.isInvalid()) return true;
3970     TheCall->setArg(2, Arg.get());
3971   }
3972 
3973   return false;
3974 }
3975 
3976 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
3977   unsigned BuiltinID =
3978       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
3979   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
3980 
3981   unsigned NumArgs = TheCall->getNumArgs();
3982   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
3983   if (NumArgs < NumRequiredArgs) {
3984     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3985            << 0 /* function call */ << NumRequiredArgs << NumArgs
3986            << TheCall->getSourceRange();
3987   }
3988   if (NumArgs >= NumRequiredArgs + 0x100) {
3989     return Diag(TheCall->getLocEnd(),
3990                 diag::err_typecheck_call_too_many_args_at_most)
3991            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
3992            << TheCall->getSourceRange();
3993   }
3994   unsigned i = 0;
3995 
3996   // For formatting call, check buffer arg.
3997   if (!IsSizeCall) {
3998     ExprResult Arg(TheCall->getArg(i));
3999     InitializedEntity Entity = InitializedEntity::InitializeParameter(
4000         Context, Context.VoidPtrTy, false);
4001     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4002     if (Arg.isInvalid())
4003       return true;
4004     TheCall->setArg(i, Arg.get());
4005     i++;
4006   }
4007 
4008   // Check string literal arg.
4009   unsigned FormatIdx = i;
4010   {
4011     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4012     if (Arg.isInvalid())
4013       return true;
4014     TheCall->setArg(i, Arg.get());
4015     i++;
4016   }
4017 
4018   // Make sure variadic args are scalar.
4019   unsigned FirstDataArg = i;
4020   while (i < NumArgs) {
4021     ExprResult Arg = DefaultVariadicArgumentPromotion(
4022         TheCall->getArg(i), VariadicFunction, nullptr);
4023     if (Arg.isInvalid())
4024       return true;
4025     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4026     if (ArgSize.getQuantity() >= 0x100) {
4027       return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4028              << i << (int)ArgSize.getQuantity() << 0xff
4029              << TheCall->getSourceRange();
4030     }
4031     TheCall->setArg(i, Arg.get());
4032     i++;
4033   }
4034 
4035   // Check formatting specifiers. NOTE: We're only doing this for the non-size
4036   // call to avoid duplicate diagnostics.
4037   if (!IsSizeCall) {
4038     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4039     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4040     bool Success = CheckFormatArguments(
4041         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4042         VariadicFunction, TheCall->getLocStart(), SourceRange(),
4043         CheckedVarArgs);
4044     if (!Success)
4045       return true;
4046   }
4047 
4048   if (IsSizeCall) {
4049     TheCall->setType(Context.getSizeType());
4050   } else {
4051     TheCall->setType(Context.VoidPtrTy);
4052   }
4053   return false;
4054 }
4055 
4056 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4057 /// TheCall is a constant expression.
4058 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4059                                   llvm::APSInt &Result) {
4060   Expr *Arg = TheCall->getArg(ArgNum);
4061   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4062   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4063 
4064   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4065 
4066   if (!Arg->isIntegerConstantExpr(Result, Context))
4067     return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
4068                 << FDecl->getDeclName() <<  Arg->getSourceRange();
4069 
4070   return false;
4071 }
4072 
4073 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4074 /// TheCall is a constant expression in the range [Low, High].
4075 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4076                                        int Low, int High) {
4077   llvm::APSInt Result;
4078 
4079   // We can't check the value of a dependent argument.
4080   Expr *Arg = TheCall->getArg(ArgNum);
4081   if (Arg->isTypeDependent() || Arg->isValueDependent())
4082     return false;
4083 
4084   // Check constant-ness first.
4085   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4086     return true;
4087 
4088   if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
4089     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
4090       << Low << High << Arg->getSourceRange();
4091 
4092   return false;
4093 }
4094 
4095 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4096 /// TheCall is a constant expression is a multiple of Num..
4097 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4098                                           unsigned Num) {
4099   llvm::APSInt Result;
4100 
4101   // We can't check the value of a dependent argument.
4102   Expr *Arg = TheCall->getArg(ArgNum);
4103   if (Arg->isTypeDependent() || Arg->isValueDependent())
4104     return false;
4105 
4106   // Check constant-ness first.
4107   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4108     return true;
4109 
4110   if (Result.getSExtValue() % Num != 0)
4111     return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4112       << Num << Arg->getSourceRange();
4113 
4114   return false;
4115 }
4116 
4117 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4118 /// TheCall is an ARM/AArch64 special register string literal.
4119 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4120                                     int ArgNum, unsigned ExpectedFieldNum,
4121                                     bool AllowName) {
4122   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4123                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4124                       BuiltinID == ARM::BI__builtin_arm_rsr ||
4125                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
4126                       BuiltinID == ARM::BI__builtin_arm_wsr ||
4127                       BuiltinID == ARM::BI__builtin_arm_wsrp;
4128   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4129                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4130                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
4131                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4132                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
4133                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
4134   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4135 
4136   // We can't check the value of a dependent argument.
4137   Expr *Arg = TheCall->getArg(ArgNum);
4138   if (Arg->isTypeDependent() || Arg->isValueDependent())
4139     return false;
4140 
4141   // Check if the argument is a string literal.
4142   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4143     return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4144            << Arg->getSourceRange();
4145 
4146   // Check the type of special register given.
4147   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4148   SmallVector<StringRef, 6> Fields;
4149   Reg.split(Fields, ":");
4150 
4151   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4152     return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4153            << Arg->getSourceRange();
4154 
4155   // If the string is the name of a register then we cannot check that it is
4156   // valid here but if the string is of one the forms described in ACLE then we
4157   // can check that the supplied fields are integers and within the valid
4158   // ranges.
4159   if (Fields.size() > 1) {
4160     bool FiveFields = Fields.size() == 5;
4161 
4162     bool ValidString = true;
4163     if (IsARMBuiltin) {
4164       ValidString &= Fields[0].startswith_lower("cp") ||
4165                      Fields[0].startswith_lower("p");
4166       if (ValidString)
4167         Fields[0] =
4168           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4169 
4170       ValidString &= Fields[2].startswith_lower("c");
4171       if (ValidString)
4172         Fields[2] = Fields[2].drop_front(1);
4173 
4174       if (FiveFields) {
4175         ValidString &= Fields[3].startswith_lower("c");
4176         if (ValidString)
4177           Fields[3] = Fields[3].drop_front(1);
4178       }
4179     }
4180 
4181     SmallVector<int, 5> Ranges;
4182     if (FiveFields)
4183       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
4184     else
4185       Ranges.append({15, 7, 15});
4186 
4187     for (unsigned i=0; i<Fields.size(); ++i) {
4188       int IntField;
4189       ValidString &= !Fields[i].getAsInteger(10, IntField);
4190       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4191     }
4192 
4193     if (!ValidString)
4194       return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4195              << Arg->getSourceRange();
4196 
4197   } else if (IsAArch64Builtin && Fields.size() == 1) {
4198     // If the register name is one of those that appear in the condition below
4199     // and the special register builtin being used is one of the write builtins,
4200     // then we require that the argument provided for writing to the register
4201     // is an integer constant expression. This is because it will be lowered to
4202     // an MSR (immediate) instruction, so we need to know the immediate at
4203     // compile time.
4204     if (TheCall->getNumArgs() != 2)
4205       return false;
4206 
4207     std::string RegLower = Reg.lower();
4208     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4209         RegLower != "pan" && RegLower != "uao")
4210       return false;
4211 
4212     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4213   }
4214 
4215   return false;
4216 }
4217 
4218 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
4219 /// This checks that the target supports __builtin_longjmp and
4220 /// that val is a constant 1.
4221 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
4222   if (!Context.getTargetInfo().hasSjLjLowering())
4223     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4224              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4225 
4226   Expr *Arg = TheCall->getArg(1);
4227   llvm::APSInt Result;
4228 
4229   // TODO: This is less than ideal. Overload this to take a value.
4230   if (SemaBuiltinConstantArg(TheCall, 1, Result))
4231     return true;
4232 
4233   if (Result != 1)
4234     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4235              << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4236 
4237   return false;
4238 }
4239 
4240 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4241 /// This checks that the target supports __builtin_setjmp.
4242 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4243   if (!Context.getTargetInfo().hasSjLjLowering())
4244     return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4245              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4246   return false;
4247 }
4248 
4249 namespace {
4250 class UncoveredArgHandler {
4251   enum { Unknown = -1, AllCovered = -2 };
4252   signed FirstUncoveredArg;
4253   SmallVector<const Expr *, 4> DiagnosticExprs;
4254 
4255 public:
4256   UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
4257 
4258   bool hasUncoveredArg() const {
4259     return (FirstUncoveredArg >= 0);
4260   }
4261 
4262   unsigned getUncoveredArg() const {
4263     assert(hasUncoveredArg() && "no uncovered argument");
4264     return FirstUncoveredArg;
4265   }
4266 
4267   void setAllCovered() {
4268     // A string has been found with all arguments covered, so clear out
4269     // the diagnostics.
4270     DiagnosticExprs.clear();
4271     FirstUncoveredArg = AllCovered;
4272   }
4273 
4274   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4275     assert(NewFirstUncoveredArg >= 0 && "Outside range");
4276 
4277     // Don't update if a previous string covers all arguments.
4278     if (FirstUncoveredArg == AllCovered)
4279       return;
4280 
4281     // UncoveredArgHandler tracks the highest uncovered argument index
4282     // and with it all the strings that match this index.
4283     if (NewFirstUncoveredArg == FirstUncoveredArg)
4284       DiagnosticExprs.push_back(StrExpr);
4285     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4286       DiagnosticExprs.clear();
4287       DiagnosticExprs.push_back(StrExpr);
4288       FirstUncoveredArg = NewFirstUncoveredArg;
4289     }
4290   }
4291 
4292   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4293 };
4294 
4295 enum StringLiteralCheckType {
4296   SLCT_NotALiteral,
4297   SLCT_UncheckedLiteral,
4298   SLCT_CheckedLiteral
4299 };
4300 } // end anonymous namespace
4301 
4302 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4303                                      BinaryOperatorKind BinOpKind,
4304                                      bool AddendIsRight) {
4305   unsigned BitWidth = Offset.getBitWidth();
4306   unsigned AddendBitWidth = Addend.getBitWidth();
4307   // There might be negative interim results.
4308   if (Addend.isUnsigned()) {
4309     Addend = Addend.zext(++AddendBitWidth);
4310     Addend.setIsSigned(true);
4311   }
4312   // Adjust the bit width of the APSInts.
4313   if (AddendBitWidth > BitWidth) {
4314     Offset = Offset.sext(AddendBitWidth);
4315     BitWidth = AddendBitWidth;
4316   } else if (BitWidth > AddendBitWidth) {
4317     Addend = Addend.sext(BitWidth);
4318   }
4319 
4320   bool Ov = false;
4321   llvm::APSInt ResOffset = Offset;
4322   if (BinOpKind == BO_Add)
4323     ResOffset = Offset.sadd_ov(Addend, Ov);
4324   else {
4325     assert(AddendIsRight && BinOpKind == BO_Sub &&
4326            "operator must be add or sub with addend on the right");
4327     ResOffset = Offset.ssub_ov(Addend, Ov);
4328   }
4329 
4330   // We add an offset to a pointer here so we should support an offset as big as
4331   // possible.
4332   if (Ov) {
4333     assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big");
4334     Offset = Offset.sext(2 * BitWidth);
4335     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4336     return;
4337   }
4338 
4339   Offset = ResOffset;
4340 }
4341 
4342 namespace {
4343 // This is a wrapper class around StringLiteral to support offsetted string
4344 // literals as format strings. It takes the offset into account when returning
4345 // the string and its length or the source locations to display notes correctly.
4346 class FormatStringLiteral {
4347   const StringLiteral *FExpr;
4348   int64_t Offset;
4349 
4350  public:
4351   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4352       : FExpr(fexpr), Offset(Offset) {}
4353 
4354   StringRef getString() const {
4355     return FExpr->getString().drop_front(Offset);
4356   }
4357 
4358   unsigned getByteLength() const {
4359     return FExpr->getByteLength() - getCharByteWidth() * Offset;
4360   }
4361   unsigned getLength() const { return FExpr->getLength() - Offset; }
4362   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4363 
4364   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4365 
4366   QualType getType() const { return FExpr->getType(); }
4367 
4368   bool isAscii() const { return FExpr->isAscii(); }
4369   bool isWide() const { return FExpr->isWide(); }
4370   bool isUTF8() const { return FExpr->isUTF8(); }
4371   bool isUTF16() const { return FExpr->isUTF16(); }
4372   bool isUTF32() const { return FExpr->isUTF32(); }
4373   bool isPascal() const { return FExpr->isPascal(); }
4374 
4375   SourceLocation getLocationOfByte(
4376       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4377       const TargetInfo &Target, unsigned *StartToken = nullptr,
4378       unsigned *StartTokenByteOffset = nullptr) const {
4379     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4380                                     StartToken, StartTokenByteOffset);
4381   }
4382 
4383   SourceLocation getLocStart() const LLVM_READONLY {
4384     return FExpr->getLocStart().getLocWithOffset(Offset);
4385   }
4386   SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4387 };
4388 }  // end anonymous namespace
4389 
4390 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
4391                               const Expr *OrigFormatExpr,
4392                               ArrayRef<const Expr *> Args,
4393                               bool HasVAListArg, unsigned format_idx,
4394                               unsigned firstDataArg,
4395                               Sema::FormatStringType Type,
4396                               bool inFunctionCall,
4397                               Sema::VariadicCallType CallType,
4398                               llvm::SmallBitVector &CheckedVarArgs,
4399                               UncoveredArgHandler &UncoveredArg);
4400 
4401 // Determine if an expression is a string literal or constant string.
4402 // If this function returns false on the arguments to a function expecting a
4403 // format string, we will usually need to emit a warning.
4404 // True string literals are then checked by CheckFormatString.
4405 static StringLiteralCheckType
4406 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4407                       bool HasVAListArg, unsigned format_idx,
4408                       unsigned firstDataArg, Sema::FormatStringType Type,
4409                       Sema::VariadicCallType CallType, bool InFunctionCall,
4410                       llvm::SmallBitVector &CheckedVarArgs,
4411                       UncoveredArgHandler &UncoveredArg,
4412                       llvm::APSInt Offset) {
4413  tryAgain:
4414   assert(Offset.isSigned() && "invalid offset");
4415 
4416   if (E->isTypeDependent() || E->isValueDependent())
4417     return SLCT_NotALiteral;
4418 
4419   E = E->IgnoreParenCasts();
4420 
4421   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
4422     // Technically -Wformat-nonliteral does not warn about this case.
4423     // The behavior of printf and friends in this case is implementation
4424     // dependent.  Ideally if the format string cannot be null then
4425     // it should have a 'nonnull' attribute in the function prototype.
4426     return SLCT_UncheckedLiteral;
4427 
4428   switch (E->getStmtClass()) {
4429   case Stmt::BinaryConditionalOperatorClass:
4430   case Stmt::ConditionalOperatorClass: {
4431     // The expression is a literal if both sub-expressions were, and it was
4432     // completely checked only if both sub-expressions were checked.
4433     const AbstractConditionalOperator *C =
4434         cast<AbstractConditionalOperator>(E);
4435 
4436     // Determine whether it is necessary to check both sub-expressions, for
4437     // example, because the condition expression is a constant that can be
4438     // evaluated at compile time.
4439     bool CheckLeft = true, CheckRight = true;
4440 
4441     bool Cond;
4442     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4443       if (Cond)
4444         CheckRight = false;
4445       else
4446         CheckLeft = false;
4447     }
4448 
4449     // We need to maintain the offsets for the right and the left hand side
4450     // separately to check if every possible indexed expression is a valid
4451     // string literal. They might have different offsets for different string
4452     // literals in the end.
4453     StringLiteralCheckType Left;
4454     if (!CheckLeft)
4455       Left = SLCT_UncheckedLiteral;
4456     else {
4457       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4458                                    HasVAListArg, format_idx, firstDataArg,
4459                                    Type, CallType, InFunctionCall,
4460                                    CheckedVarArgs, UncoveredArg, Offset);
4461       if (Left == SLCT_NotALiteral || !CheckRight) {
4462         return Left;
4463       }
4464     }
4465 
4466     StringLiteralCheckType Right =
4467         checkFormatStringExpr(S, C->getFalseExpr(), Args,
4468                               HasVAListArg, format_idx, firstDataArg,
4469                               Type, CallType, InFunctionCall, CheckedVarArgs,
4470                               UncoveredArg, Offset);
4471 
4472     return (CheckLeft && Left < Right) ? Left : Right;
4473   }
4474 
4475   case Stmt::ImplicitCastExprClass: {
4476     E = cast<ImplicitCastExpr>(E)->getSubExpr();
4477     goto tryAgain;
4478   }
4479 
4480   case Stmt::OpaqueValueExprClass:
4481     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4482       E = src;
4483       goto tryAgain;
4484     }
4485     return SLCT_NotALiteral;
4486 
4487   case Stmt::PredefinedExprClass:
4488     // While __func__, etc., are technically not string literals, they
4489     // cannot contain format specifiers and thus are not a security
4490     // liability.
4491     return SLCT_UncheckedLiteral;
4492 
4493   case Stmt::DeclRefExprClass: {
4494     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
4495 
4496     // As an exception, do not flag errors for variables binding to
4497     // const string literals.
4498     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4499       bool isConstant = false;
4500       QualType T = DR->getType();
4501 
4502       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4503         isConstant = AT->getElementType().isConstant(S.Context);
4504       } else if (const PointerType *PT = T->getAs<PointerType>()) {
4505         isConstant = T.isConstant(S.Context) &&
4506                      PT->getPointeeType().isConstant(S.Context);
4507       } else if (T->isObjCObjectPointerType()) {
4508         // In ObjC, there is usually no "const ObjectPointer" type,
4509         // so don't check if the pointee type is constant.
4510         isConstant = T.isConstant(S.Context);
4511       }
4512 
4513       if (isConstant) {
4514         if (const Expr *Init = VD->getAnyInitializer()) {
4515           // Look through initializers like const char c[] = { "foo" }
4516           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4517             if (InitList->isStringLiteralInit())
4518               Init = InitList->getInit(0)->IgnoreParenImpCasts();
4519           }
4520           return checkFormatStringExpr(S, Init, Args,
4521                                        HasVAListArg, format_idx,
4522                                        firstDataArg, Type, CallType,
4523                                        /*InFunctionCall*/ false, CheckedVarArgs,
4524                                        UncoveredArg, Offset);
4525         }
4526       }
4527 
4528       // For vprintf* functions (i.e., HasVAListArg==true), we add a
4529       // special check to see if the format string is a function parameter
4530       // of the function calling the printf function.  If the function
4531       // has an attribute indicating it is a printf-like function, then we
4532       // should suppress warnings concerning non-literals being used in a call
4533       // to a vprintf function.  For example:
4534       //
4535       // void
4536       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4537       //      va_list ap;
4538       //      va_start(ap, fmt);
4539       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
4540       //      ...
4541       // }
4542       if (HasVAListArg) {
4543         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4544           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4545             int PVIndex = PV->getFunctionScopeIndex() + 1;
4546             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
4547               // adjust for implicit parameter
4548               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4549                 if (MD->isInstance())
4550                   ++PVIndex;
4551               // We also check if the formats are compatible.
4552               // We can't pass a 'scanf' string to a 'printf' function.
4553               if (PVIndex == PVFormat->getFormatIdx() &&
4554                   Type == S.GetFormatStringType(PVFormat))
4555                 return SLCT_UncheckedLiteral;
4556             }
4557           }
4558         }
4559       }
4560     }
4561 
4562     return SLCT_NotALiteral;
4563   }
4564 
4565   case Stmt::CallExprClass:
4566   case Stmt::CXXMemberCallExprClass: {
4567     const CallExpr *CE = cast<CallExpr>(E);
4568     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
4569       if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
4570         unsigned ArgIndex = FA->getFormatIdx();
4571         if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4572           if (MD->isInstance())
4573             --ArgIndex;
4574         const Expr *Arg = CE->getArg(ArgIndex - 1);
4575 
4576         return checkFormatStringExpr(S, Arg, Args,
4577                                      HasVAListArg, format_idx, firstDataArg,
4578                                      Type, CallType, InFunctionCall,
4579                                      CheckedVarArgs, UncoveredArg, Offset);
4580       } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4581         unsigned BuiltinID = FD->getBuiltinID();
4582         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
4583             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
4584           const Expr *Arg = CE->getArg(0);
4585           return checkFormatStringExpr(S, Arg, Args,
4586                                        HasVAListArg, format_idx,
4587                                        firstDataArg, Type, CallType,
4588                                        InFunctionCall, CheckedVarArgs,
4589                                        UncoveredArg, Offset);
4590         }
4591       }
4592     }
4593 
4594     return SLCT_NotALiteral;
4595   }
4596   case Stmt::ObjCMessageExprClass: {
4597     const auto *ME = cast<ObjCMessageExpr>(E);
4598     if (const auto *ND = ME->getMethodDecl()) {
4599       if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
4600         unsigned ArgIndex = FA->getFormatIdx();
4601         const Expr *Arg = ME->getArg(ArgIndex - 1);
4602         return checkFormatStringExpr(
4603             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
4604             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
4605       }
4606     }
4607 
4608     return SLCT_NotALiteral;
4609   }
4610   case Stmt::ObjCStringLiteralClass:
4611   case Stmt::StringLiteralClass: {
4612     const StringLiteral *StrE = nullptr;
4613 
4614     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
4615       StrE = ObjCFExpr->getString();
4616     else
4617       StrE = cast<StringLiteral>(E);
4618 
4619     if (StrE) {
4620       if (Offset.isNegative() || Offset > StrE->getLength()) {
4621         // TODO: It would be better to have an explicit warning for out of
4622         // bounds literals.
4623         return SLCT_NotALiteral;
4624       }
4625       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
4626       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
4627                         firstDataArg, Type, InFunctionCall, CallType,
4628                         CheckedVarArgs, UncoveredArg);
4629       return SLCT_CheckedLiteral;
4630     }
4631 
4632     return SLCT_NotALiteral;
4633   }
4634   case Stmt::BinaryOperatorClass: {
4635     llvm::APSInt LResult;
4636     llvm::APSInt RResult;
4637 
4638     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
4639 
4640     // A string literal + an int offset is still a string literal.
4641     if (BinOp->isAdditiveOp()) {
4642       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
4643       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
4644 
4645       if (LIsInt != RIsInt) {
4646         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
4647 
4648         if (LIsInt) {
4649           if (BinOpKind == BO_Add) {
4650             sumOffsets(Offset, LResult, BinOpKind, RIsInt);
4651             E = BinOp->getRHS();
4652             goto tryAgain;
4653           }
4654         } else {
4655           sumOffsets(Offset, RResult, BinOpKind, RIsInt);
4656           E = BinOp->getLHS();
4657           goto tryAgain;
4658         }
4659       }
4660     }
4661 
4662     return SLCT_NotALiteral;
4663   }
4664   case Stmt::UnaryOperatorClass: {
4665     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
4666     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
4667     if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) {
4668       llvm::APSInt IndexResult;
4669       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
4670         sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
4671         E = ASE->getBase();
4672         goto tryAgain;
4673       }
4674     }
4675 
4676     return SLCT_NotALiteral;
4677   }
4678 
4679   default:
4680     return SLCT_NotALiteral;
4681   }
4682 }
4683 
4684 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
4685   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
4686       .Case("scanf", FST_Scanf)
4687       .Cases("printf", "printf0", FST_Printf)
4688       .Cases("NSString", "CFString", FST_NSString)
4689       .Case("strftime", FST_Strftime)
4690       .Case("strfmon", FST_Strfmon)
4691       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
4692       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
4693       .Case("os_trace", FST_OSLog)
4694       .Case("os_log", FST_OSLog)
4695       .Default(FST_Unknown);
4696 }
4697 
4698 /// CheckFormatArguments - Check calls to printf and scanf (and similar
4699 /// functions) for correct use of format strings.
4700 /// Returns true if a format string has been fully checked.
4701 bool Sema::CheckFormatArguments(const FormatAttr *Format,
4702                                 ArrayRef<const Expr *> Args,
4703                                 bool IsCXXMember,
4704                                 VariadicCallType CallType,
4705                                 SourceLocation Loc, SourceRange Range,
4706                                 llvm::SmallBitVector &CheckedVarArgs) {
4707   FormatStringInfo FSI;
4708   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
4709     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
4710                                 FSI.FirstDataArg, GetFormatStringType(Format),
4711                                 CallType, Loc, Range, CheckedVarArgs);
4712   return false;
4713 }
4714 
4715 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
4716                                 bool HasVAListArg, unsigned format_idx,
4717                                 unsigned firstDataArg, FormatStringType Type,
4718                                 VariadicCallType CallType,
4719                                 SourceLocation Loc, SourceRange Range,
4720                                 llvm::SmallBitVector &CheckedVarArgs) {
4721   // CHECK: printf/scanf-like function is called with no format string.
4722   if (format_idx >= Args.size()) {
4723     Diag(Loc, diag::warn_missing_format_string) << Range;
4724     return false;
4725   }
4726 
4727   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
4728 
4729   // CHECK: format string is not a string literal.
4730   //
4731   // Dynamically generated format strings are difficult to
4732   // automatically vet at compile time.  Requiring that format strings
4733   // are string literals: (1) permits the checking of format strings by
4734   // the compiler and thereby (2) can practically remove the source of
4735   // many format string exploits.
4736 
4737   // Format string can be either ObjC string (e.g. @"%d") or
4738   // C string (e.g. "%d")
4739   // ObjC string uses the same format specifiers as C string, so we can use
4740   // the same format string checking logic for both ObjC and C strings.
4741   UncoveredArgHandler UncoveredArg;
4742   StringLiteralCheckType CT =
4743       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
4744                             format_idx, firstDataArg, Type, CallType,
4745                             /*IsFunctionCall*/ true, CheckedVarArgs,
4746                             UncoveredArg,
4747                             /*no string offset*/ llvm::APSInt(64, false) = 0);
4748 
4749   // Generate a diagnostic where an uncovered argument is detected.
4750   if (UncoveredArg.hasUncoveredArg()) {
4751     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
4752     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
4753     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
4754   }
4755 
4756   if (CT != SLCT_NotALiteral)
4757     // Literal format string found, check done!
4758     return CT == SLCT_CheckedLiteral;
4759 
4760   // Strftime is particular as it always uses a single 'time' argument,
4761   // so it is safe to pass a non-literal string.
4762   if (Type == FST_Strftime)
4763     return false;
4764 
4765   // Do not emit diag when the string param is a macro expansion and the
4766   // format is either NSString or CFString. This is a hack to prevent
4767   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
4768   // which are usually used in place of NS and CF string literals.
4769   SourceLocation FormatLoc = Args[format_idx]->getLocStart();
4770   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
4771     return false;
4772 
4773   // If there are no arguments specified, warn with -Wformat-security, otherwise
4774   // warn only with -Wformat-nonliteral.
4775   if (Args.size() == firstDataArg) {
4776     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
4777       << OrigFormatExpr->getSourceRange();
4778     switch (Type) {
4779     default:
4780       break;
4781     case FST_Kprintf:
4782     case FST_FreeBSDKPrintf:
4783     case FST_Printf:
4784       Diag(FormatLoc, diag::note_format_security_fixit)
4785         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
4786       break;
4787     case FST_NSString:
4788       Diag(FormatLoc, diag::note_format_security_fixit)
4789         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
4790       break;
4791     }
4792   } else {
4793     Diag(FormatLoc, diag::warn_format_nonliteral)
4794       << OrigFormatExpr->getSourceRange();
4795   }
4796   return false;
4797 }
4798 
4799 namespace {
4800 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
4801 protected:
4802   Sema &S;
4803   const FormatStringLiteral *FExpr;
4804   const Expr *OrigFormatExpr;
4805   const Sema::FormatStringType FSType;
4806   const unsigned FirstDataArg;
4807   const unsigned NumDataArgs;
4808   const char *Beg; // Start of format string.
4809   const bool HasVAListArg;
4810   ArrayRef<const Expr *> Args;
4811   unsigned FormatIdx;
4812   llvm::SmallBitVector CoveredArgs;
4813   bool usesPositionalArgs;
4814   bool atFirstArg;
4815   bool inFunctionCall;
4816   Sema::VariadicCallType CallType;
4817   llvm::SmallBitVector &CheckedVarArgs;
4818   UncoveredArgHandler &UncoveredArg;
4819 
4820 public:
4821   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
4822                      const Expr *origFormatExpr,
4823                      const Sema::FormatStringType type, unsigned firstDataArg,
4824                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
4825                      ArrayRef<const Expr *> Args, unsigned formatIdx,
4826                      bool inFunctionCall, Sema::VariadicCallType callType,
4827                      llvm::SmallBitVector &CheckedVarArgs,
4828                      UncoveredArgHandler &UncoveredArg)
4829       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
4830         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
4831         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
4832         usesPositionalArgs(false), atFirstArg(true),
4833         inFunctionCall(inFunctionCall), CallType(callType),
4834         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
4835     CoveredArgs.resize(numDataArgs);
4836     CoveredArgs.reset();
4837   }
4838 
4839   void DoneProcessing();
4840 
4841   void HandleIncompleteSpecifier(const char *startSpecifier,
4842                                  unsigned specifierLen) override;
4843 
4844   void HandleInvalidLengthModifier(
4845                            const analyze_format_string::FormatSpecifier &FS,
4846                            const analyze_format_string::ConversionSpecifier &CS,
4847                            const char *startSpecifier, unsigned specifierLen,
4848                            unsigned DiagID);
4849 
4850   void HandleNonStandardLengthModifier(
4851                     const analyze_format_string::FormatSpecifier &FS,
4852                     const char *startSpecifier, unsigned specifierLen);
4853 
4854   void HandleNonStandardConversionSpecifier(
4855                     const analyze_format_string::ConversionSpecifier &CS,
4856                     const char *startSpecifier, unsigned specifierLen);
4857 
4858   void HandlePosition(const char *startPos, unsigned posLen) override;
4859 
4860   void HandleInvalidPosition(const char *startSpecifier,
4861                              unsigned specifierLen,
4862                              analyze_format_string::PositionContext p) override;
4863 
4864   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
4865 
4866   void HandleNullChar(const char *nullCharacter) override;
4867 
4868   template <typename Range>
4869   static void
4870   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
4871                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
4872                        bool IsStringLocation, Range StringRange,
4873                        ArrayRef<FixItHint> Fixit = None);
4874 
4875 protected:
4876   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
4877                                         const char *startSpec,
4878                                         unsigned specifierLen,
4879                                         const char *csStart, unsigned csLen);
4880 
4881   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
4882                                          const char *startSpec,
4883                                          unsigned specifierLen);
4884 
4885   SourceRange getFormatStringRange();
4886   CharSourceRange getSpecifierRange(const char *startSpecifier,
4887                                     unsigned specifierLen);
4888   SourceLocation getLocationOfByte(const char *x);
4889 
4890   const Expr *getDataArg(unsigned i) const;
4891 
4892   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
4893                     const analyze_format_string::ConversionSpecifier &CS,
4894                     const char *startSpecifier, unsigned specifierLen,
4895                     unsigned argIndex);
4896 
4897   template <typename Range>
4898   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4899                             bool IsStringLocation, Range StringRange,
4900                             ArrayRef<FixItHint> Fixit = None);
4901 };
4902 } // end anonymous namespace
4903 
4904 SourceRange CheckFormatHandler::getFormatStringRange() {
4905   return OrigFormatExpr->getSourceRange();
4906 }
4907 
4908 CharSourceRange CheckFormatHandler::
4909 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
4910   SourceLocation Start = getLocationOfByte(startSpecifier);
4911   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
4912 
4913   // Advance the end SourceLocation by one due to half-open ranges.
4914   End = End.getLocWithOffset(1);
4915 
4916   return CharSourceRange::getCharRange(Start, End);
4917 }
4918 
4919 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
4920   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
4921                                   S.getLangOpts(), S.Context.getTargetInfo());
4922 }
4923 
4924 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
4925                                                    unsigned specifierLen){
4926   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
4927                        getLocationOfByte(startSpecifier),
4928                        /*IsStringLocation*/true,
4929                        getSpecifierRange(startSpecifier, specifierLen));
4930 }
4931 
4932 void CheckFormatHandler::HandleInvalidLengthModifier(
4933     const analyze_format_string::FormatSpecifier &FS,
4934     const analyze_format_string::ConversionSpecifier &CS,
4935     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
4936   using namespace analyze_format_string;
4937 
4938   const LengthModifier &LM = FS.getLengthModifier();
4939   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4940 
4941   // See if we know how to fix this length modifier.
4942   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
4943   if (FixedLM) {
4944     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
4945                          getLocationOfByte(LM.getStart()),
4946                          /*IsStringLocation*/true,
4947                          getSpecifierRange(startSpecifier, specifierLen));
4948 
4949     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4950       << FixedLM->toString()
4951       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4952 
4953   } else {
4954     FixItHint Hint;
4955     if (DiagID == diag::warn_format_nonsensical_length)
4956       Hint = FixItHint::CreateRemoval(LMRange);
4957 
4958     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
4959                          getLocationOfByte(LM.getStart()),
4960                          /*IsStringLocation*/true,
4961                          getSpecifierRange(startSpecifier, specifierLen),
4962                          Hint);
4963   }
4964 }
4965 
4966 void CheckFormatHandler::HandleNonStandardLengthModifier(
4967     const analyze_format_string::FormatSpecifier &FS,
4968     const char *startSpecifier, unsigned specifierLen) {
4969   using namespace analyze_format_string;
4970 
4971   const LengthModifier &LM = FS.getLengthModifier();
4972   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4973 
4974   // See if we know how to fix this length modifier.
4975   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
4976   if (FixedLM) {
4977     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4978                            << LM.toString() << 0,
4979                          getLocationOfByte(LM.getStart()),
4980                          /*IsStringLocation*/true,
4981                          getSpecifierRange(startSpecifier, specifierLen));
4982 
4983     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4984       << FixedLM->toString()
4985       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4986 
4987   } else {
4988     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4989                            << LM.toString() << 0,
4990                          getLocationOfByte(LM.getStart()),
4991                          /*IsStringLocation*/true,
4992                          getSpecifierRange(startSpecifier, specifierLen));
4993   }
4994 }
4995 
4996 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
4997     const analyze_format_string::ConversionSpecifier &CS,
4998     const char *startSpecifier, unsigned specifierLen) {
4999   using namespace analyze_format_string;
5000 
5001   // See if we know how to fix this conversion specifier.
5002   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
5003   if (FixedCS) {
5004     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5005                           << CS.toString() << /*conversion specifier*/1,
5006                          getLocationOfByte(CS.getStart()),
5007                          /*IsStringLocation*/true,
5008                          getSpecifierRange(startSpecifier, specifierLen));
5009 
5010     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5011     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5012       << FixedCS->toString()
5013       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5014   } else {
5015     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5016                           << CS.toString() << /*conversion specifier*/1,
5017                          getLocationOfByte(CS.getStart()),
5018                          /*IsStringLocation*/true,
5019                          getSpecifierRange(startSpecifier, specifierLen));
5020   }
5021 }
5022 
5023 void CheckFormatHandler::HandlePosition(const char *startPos,
5024                                         unsigned posLen) {
5025   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5026                                getLocationOfByte(startPos),
5027                                /*IsStringLocation*/true,
5028                                getSpecifierRange(startPos, posLen));
5029 }
5030 
5031 void
5032 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5033                                      analyze_format_string::PositionContext p) {
5034   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5035                          << (unsigned) p,
5036                        getLocationOfByte(startPos), /*IsStringLocation*/true,
5037                        getSpecifierRange(startPos, posLen));
5038 }
5039 
5040 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
5041                                             unsigned posLen) {
5042   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5043                                getLocationOfByte(startPos),
5044                                /*IsStringLocation*/true,
5045                                getSpecifierRange(startPos, posLen));
5046 }
5047 
5048 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
5049   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
5050     // The presence of a null character is likely an error.
5051     EmitFormatDiagnostic(
5052       S.PDiag(diag::warn_printf_format_string_contains_null_char),
5053       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5054       getFormatStringRange());
5055   }
5056 }
5057 
5058 // Note that this may return NULL if there was an error parsing or building
5059 // one of the argument expressions.
5060 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
5061   return Args[FirstDataArg + i];
5062 }
5063 
5064 void CheckFormatHandler::DoneProcessing() {
5065   // Does the number of data arguments exceed the number of
5066   // format conversions in the format string?
5067   if (!HasVAListArg) {
5068       // Find any arguments that weren't covered.
5069     CoveredArgs.flip();
5070     signed notCoveredArg = CoveredArgs.find_first();
5071     if (notCoveredArg >= 0) {
5072       assert((unsigned)notCoveredArg < NumDataArgs);
5073       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5074     } else {
5075       UncoveredArg.setAllCovered();
5076     }
5077   }
5078 }
5079 
5080 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5081                                    const Expr *ArgExpr) {
5082   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5083          "Invalid state");
5084 
5085   if (!ArgExpr)
5086     return;
5087 
5088   SourceLocation Loc = ArgExpr->getLocStart();
5089 
5090   if (S.getSourceManager().isInSystemMacro(Loc))
5091     return;
5092 
5093   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5094   for (auto E : DiagnosticExprs)
5095     PDiag << E->getSourceRange();
5096 
5097   CheckFormatHandler::EmitFormatDiagnostic(
5098                                   S, IsFunctionCall, DiagnosticExprs[0],
5099                                   PDiag, Loc, /*IsStringLocation*/false,
5100                                   DiagnosticExprs[0]->getSourceRange());
5101 }
5102 
5103 bool
5104 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5105                                                      SourceLocation Loc,
5106                                                      const char *startSpec,
5107                                                      unsigned specifierLen,
5108                                                      const char *csStart,
5109                                                      unsigned csLen) {
5110   bool keepGoing = true;
5111   if (argIndex < NumDataArgs) {
5112     // Consider the argument coverered, even though the specifier doesn't
5113     // make sense.
5114     CoveredArgs.set(argIndex);
5115   }
5116   else {
5117     // If argIndex exceeds the number of data arguments we
5118     // don't issue a warning because that is just a cascade of warnings (and
5119     // they may have intended '%%' anyway). We don't want to continue processing
5120     // the format string after this point, however, as we will like just get
5121     // gibberish when trying to match arguments.
5122     keepGoing = false;
5123   }
5124 
5125   StringRef Specifier(csStart, csLen);
5126 
5127   // If the specifier in non-printable, it could be the first byte of a UTF-8
5128   // sequence. In that case, print the UTF-8 code point. If not, print the byte
5129   // hex value.
5130   std::string CodePointStr;
5131   if (!llvm::sys::locale::isPrint(*csStart)) {
5132     llvm::UTF32 CodePoint;
5133     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5134     const llvm::UTF8 *E =
5135         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5136     llvm::ConversionResult Result =
5137         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
5138 
5139     if (Result != llvm::conversionOK) {
5140       unsigned char FirstChar = *csStart;
5141       CodePoint = (llvm::UTF32)FirstChar;
5142     }
5143 
5144     llvm::raw_string_ostream OS(CodePointStr);
5145     if (CodePoint < 256)
5146       OS << "\\x" << llvm::format("%02x", CodePoint);
5147     else if (CodePoint <= 0xFFFF)
5148       OS << "\\u" << llvm::format("%04x", CodePoint);
5149     else
5150       OS << "\\U" << llvm::format("%08x", CodePoint);
5151     OS.flush();
5152     Specifier = CodePointStr;
5153   }
5154 
5155   EmitFormatDiagnostic(
5156       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5157       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5158 
5159   return keepGoing;
5160 }
5161 
5162 void
5163 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5164                                                       const char *startSpec,
5165                                                       unsigned specifierLen) {
5166   EmitFormatDiagnostic(
5167     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5168     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5169 }
5170 
5171 bool
5172 CheckFormatHandler::CheckNumArgs(
5173   const analyze_format_string::FormatSpecifier &FS,
5174   const analyze_format_string::ConversionSpecifier &CS,
5175   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5176 
5177   if (argIndex >= NumDataArgs) {
5178     PartialDiagnostic PDiag = FS.usesPositionalArg()
5179       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5180            << (argIndex+1) << NumDataArgs)
5181       : S.PDiag(diag::warn_printf_insufficient_data_args);
5182     EmitFormatDiagnostic(
5183       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5184       getSpecifierRange(startSpecifier, specifierLen));
5185 
5186     // Since more arguments than conversion tokens are given, by extension
5187     // all arguments are covered, so mark this as so.
5188     UncoveredArg.setAllCovered();
5189     return false;
5190   }
5191   return true;
5192 }
5193 
5194 template<typename Range>
5195 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5196                                               SourceLocation Loc,
5197                                               bool IsStringLocation,
5198                                               Range StringRange,
5199                                               ArrayRef<FixItHint> FixIt) {
5200   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
5201                        Loc, IsStringLocation, StringRange, FixIt);
5202 }
5203 
5204 /// \brief If the format string is not within the funcion call, emit a note
5205 /// so that the function call and string are in diagnostic messages.
5206 ///
5207 /// \param InFunctionCall if true, the format string is within the function
5208 /// call and only one diagnostic message will be produced.  Otherwise, an
5209 /// extra note will be emitted pointing to location of the format string.
5210 ///
5211 /// \param ArgumentExpr the expression that is passed as the format string
5212 /// argument in the function call.  Used for getting locations when two
5213 /// diagnostics are emitted.
5214 ///
5215 /// \param PDiag the callee should already have provided any strings for the
5216 /// diagnostic message.  This function only adds locations and fixits
5217 /// to diagnostics.
5218 ///
5219 /// \param Loc primary location for diagnostic.  If two diagnostics are
5220 /// required, one will be at Loc and a new SourceLocation will be created for
5221 /// the other one.
5222 ///
5223 /// \param IsStringLocation if true, Loc points to the format string should be
5224 /// used for the note.  Otherwise, Loc points to the argument list and will
5225 /// be used with PDiag.
5226 ///
5227 /// \param StringRange some or all of the string to highlight.  This is
5228 /// templated so it can accept either a CharSourceRange or a SourceRange.
5229 ///
5230 /// \param FixIt optional fix it hint for the format string.
5231 template <typename Range>
5232 void CheckFormatHandler::EmitFormatDiagnostic(
5233     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5234     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5235     Range StringRange, ArrayRef<FixItHint> FixIt) {
5236   if (InFunctionCall) {
5237     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5238     D << StringRange;
5239     D << FixIt;
5240   } else {
5241     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5242       << ArgumentExpr->getSourceRange();
5243 
5244     const Sema::SemaDiagnosticBuilder &Note =
5245       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5246              diag::note_format_string_defined);
5247 
5248     Note << StringRange;
5249     Note << FixIt;
5250   }
5251 }
5252 
5253 //===--- CHECK: Printf format string checking ------------------------------===//
5254 
5255 namespace {
5256 class CheckPrintfHandler : public CheckFormatHandler {
5257 public:
5258   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
5259                      const Expr *origFormatExpr,
5260                      const Sema::FormatStringType type, unsigned firstDataArg,
5261                      unsigned numDataArgs, bool isObjC, const char *beg,
5262                      bool hasVAListArg, ArrayRef<const Expr *> Args,
5263                      unsigned formatIdx, bool inFunctionCall,
5264                      Sema::VariadicCallType CallType,
5265                      llvm::SmallBitVector &CheckedVarArgs,
5266                      UncoveredArgHandler &UncoveredArg)
5267       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5268                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
5269                            inFunctionCall, CallType, CheckedVarArgs,
5270                            UncoveredArg) {}
5271 
5272   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5273 
5274   /// Returns true if '%@' specifiers are allowed in the format string.
5275   bool allowsObjCArg() const {
5276     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5277            FSType == Sema::FST_OSTrace;
5278   }
5279 
5280   bool HandleInvalidPrintfConversionSpecifier(
5281                                       const analyze_printf::PrintfSpecifier &FS,
5282                                       const char *startSpecifier,
5283                                       unsigned specifierLen) override;
5284 
5285   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5286                              const char *startSpecifier,
5287                              unsigned specifierLen) override;
5288   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5289                        const char *StartSpecifier,
5290                        unsigned SpecifierLen,
5291                        const Expr *E);
5292 
5293   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5294                     const char *startSpecifier, unsigned specifierLen);
5295   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5296                            const analyze_printf::OptionalAmount &Amt,
5297                            unsigned type,
5298                            const char *startSpecifier, unsigned specifierLen);
5299   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5300                   const analyze_printf::OptionalFlag &flag,
5301                   const char *startSpecifier, unsigned specifierLen);
5302   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5303                          const analyze_printf::OptionalFlag &ignoredFlag,
5304                          const analyze_printf::OptionalFlag &flag,
5305                          const char *startSpecifier, unsigned specifierLen);
5306   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
5307                            const Expr *E);
5308 
5309   void HandleEmptyObjCModifierFlag(const char *startFlag,
5310                                    unsigned flagLen) override;
5311 
5312   void HandleInvalidObjCModifierFlag(const char *startFlag,
5313                                             unsigned flagLen) override;
5314 
5315   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5316                                            const char *flagsEnd,
5317                                            const char *conversionPosition)
5318                                              override;
5319 };
5320 } // end anonymous namespace
5321 
5322 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5323                                       const analyze_printf::PrintfSpecifier &FS,
5324                                       const char *startSpecifier,
5325                                       unsigned specifierLen) {
5326   const analyze_printf::PrintfConversionSpecifier &CS =
5327     FS.getConversionSpecifier();
5328 
5329   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5330                                           getLocationOfByte(CS.getStart()),
5331                                           startSpecifier, specifierLen,
5332                                           CS.getStart(), CS.getLength());
5333 }
5334 
5335 bool CheckPrintfHandler::HandleAmount(
5336                                const analyze_format_string::OptionalAmount &Amt,
5337                                unsigned k, const char *startSpecifier,
5338                                unsigned specifierLen) {
5339   if (Amt.hasDataArgument()) {
5340     if (!HasVAListArg) {
5341       unsigned argIndex = Amt.getArgIndex();
5342       if (argIndex >= NumDataArgs) {
5343         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5344                                << k,
5345                              getLocationOfByte(Amt.getStart()),
5346                              /*IsStringLocation*/true,
5347                              getSpecifierRange(startSpecifier, specifierLen));
5348         // Don't do any more checking.  We will just emit
5349         // spurious errors.
5350         return false;
5351       }
5352 
5353       // Type check the data argument.  It should be an 'int'.
5354       // Although not in conformance with C99, we also allow the argument to be
5355       // an 'unsigned int' as that is a reasonably safe case.  GCC also
5356       // doesn't emit a warning for that case.
5357       CoveredArgs.set(argIndex);
5358       const Expr *Arg = getDataArg(argIndex);
5359       if (!Arg)
5360         return false;
5361 
5362       QualType T = Arg->getType();
5363 
5364       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5365       assert(AT.isValid());
5366 
5367       if (!AT.matchesType(S.Context, T)) {
5368         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
5369                                << k << AT.getRepresentativeTypeName(S.Context)
5370                                << T << Arg->getSourceRange(),
5371                              getLocationOfByte(Amt.getStart()),
5372                              /*IsStringLocation*/true,
5373                              getSpecifierRange(startSpecifier, specifierLen));
5374         // Don't do any more checking.  We will just emit
5375         // spurious errors.
5376         return false;
5377       }
5378     }
5379   }
5380   return true;
5381 }
5382 
5383 void CheckPrintfHandler::HandleInvalidAmount(
5384                                       const analyze_printf::PrintfSpecifier &FS,
5385                                       const analyze_printf::OptionalAmount &Amt,
5386                                       unsigned type,
5387                                       const char *startSpecifier,
5388                                       unsigned specifierLen) {
5389   const analyze_printf::PrintfConversionSpecifier &CS =
5390     FS.getConversionSpecifier();
5391 
5392   FixItHint fixit =
5393     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5394       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5395                                  Amt.getConstantLength()))
5396       : FixItHint();
5397 
5398   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5399                          << type << CS.toString(),
5400                        getLocationOfByte(Amt.getStart()),
5401                        /*IsStringLocation*/true,
5402                        getSpecifierRange(startSpecifier, specifierLen),
5403                        fixit);
5404 }
5405 
5406 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5407                                     const analyze_printf::OptionalFlag &flag,
5408                                     const char *startSpecifier,
5409                                     unsigned specifierLen) {
5410   // Warn about pointless flag with a fixit removal.
5411   const analyze_printf::PrintfConversionSpecifier &CS =
5412     FS.getConversionSpecifier();
5413   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5414                          << flag.toString() << CS.toString(),
5415                        getLocationOfByte(flag.getPosition()),
5416                        /*IsStringLocation*/true,
5417                        getSpecifierRange(startSpecifier, specifierLen),
5418                        FixItHint::CreateRemoval(
5419                          getSpecifierRange(flag.getPosition(), 1)));
5420 }
5421 
5422 void CheckPrintfHandler::HandleIgnoredFlag(
5423                                 const analyze_printf::PrintfSpecifier &FS,
5424                                 const analyze_printf::OptionalFlag &ignoredFlag,
5425                                 const analyze_printf::OptionalFlag &flag,
5426                                 const char *startSpecifier,
5427                                 unsigned specifierLen) {
5428   // Warn about ignored flag with a fixit removal.
5429   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5430                          << ignoredFlag.toString() << flag.toString(),
5431                        getLocationOfByte(ignoredFlag.getPosition()),
5432                        /*IsStringLocation*/true,
5433                        getSpecifierRange(startSpecifier, specifierLen),
5434                        FixItHint::CreateRemoval(
5435                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
5436 }
5437 
5438 //  void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5439 //                            bool IsStringLocation, Range StringRange,
5440 //                            ArrayRef<FixItHint> Fixit = None);
5441 
5442 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5443                                                      unsigned flagLen) {
5444   // Warn about an empty flag.
5445   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5446                        getLocationOfByte(startFlag),
5447                        /*IsStringLocation*/true,
5448                        getSpecifierRange(startFlag, flagLen));
5449 }
5450 
5451 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5452                                                        unsigned flagLen) {
5453   // Warn about an invalid flag.
5454   auto Range = getSpecifierRange(startFlag, flagLen);
5455   StringRef flag(startFlag, flagLen);
5456   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5457                       getLocationOfByte(startFlag),
5458                       /*IsStringLocation*/true,
5459                       Range, FixItHint::CreateRemoval(Range));
5460 }
5461 
5462 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5463     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5464     // Warn about using '[...]' without a '@' conversion.
5465     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5466     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5467     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5468                          getLocationOfByte(conversionPosition),
5469                          /*IsStringLocation*/true,
5470                          Range, FixItHint::CreateRemoval(Range));
5471 }
5472 
5473 // Determines if the specified is a C++ class or struct containing
5474 // a member with the specified name and kind (e.g. a CXXMethodDecl named
5475 // "c_str()").
5476 template<typename MemberKind>
5477 static llvm::SmallPtrSet<MemberKind*, 1>
5478 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5479   const RecordType *RT = Ty->getAs<RecordType>();
5480   llvm::SmallPtrSet<MemberKind*, 1> Results;
5481 
5482   if (!RT)
5483     return Results;
5484   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
5485   if (!RD || !RD->getDefinition())
5486     return Results;
5487 
5488   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
5489                  Sema::LookupMemberName);
5490   R.suppressDiagnostics();
5491 
5492   // We just need to include all members of the right kind turned up by the
5493   // filter, at this point.
5494   if (S.LookupQualifiedName(R, RT->getDecl()))
5495     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5496       NamedDecl *decl = (*I)->getUnderlyingDecl();
5497       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5498         Results.insert(FK);
5499     }
5500   return Results;
5501 }
5502 
5503 /// Check if we could call '.c_str()' on an object.
5504 ///
5505 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5506 /// allow the call, or if it would be ambiguous).
5507 bool Sema::hasCStrMethod(const Expr *E) {
5508   typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5509   MethodSet Results =
5510       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5511   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5512        MI != ME; ++MI)
5513     if ((*MI)->getMinRequiredArguments() == 0)
5514       return true;
5515   return false;
5516 }
5517 
5518 // Check if a (w)string was passed when a (w)char* was needed, and offer a
5519 // better diagnostic if so. AT is assumed to be valid.
5520 // Returns true when a c_str() conversion method is found.
5521 bool CheckPrintfHandler::checkForCStrMembers(
5522     const analyze_printf::ArgType &AT, const Expr *E) {
5523   typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5524 
5525   MethodSet Results =
5526       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5527 
5528   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5529        MI != ME; ++MI) {
5530     const CXXMethodDecl *Method = *MI;
5531     if (Method->getMinRequiredArguments() == 0 &&
5532         AT.matchesType(S.Context, Method->getReturnType())) {
5533       // FIXME: Suggest parens if the expression needs them.
5534       SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
5535       S.Diag(E->getLocStart(), diag::note_printf_c_str)
5536           << "c_str()"
5537           << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5538       return true;
5539     }
5540   }
5541 
5542   return false;
5543 }
5544 
5545 bool
5546 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
5547                                             &FS,
5548                                           const char *startSpecifier,
5549                                           unsigned specifierLen) {
5550   using namespace analyze_format_string;
5551   using namespace analyze_printf;
5552   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
5553 
5554   if (FS.consumesDataArgument()) {
5555     if (atFirstArg) {
5556         atFirstArg = false;
5557         usesPositionalArgs = FS.usesPositionalArg();
5558     }
5559     else if (usesPositionalArgs != FS.usesPositionalArg()) {
5560       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5561                                         startSpecifier, specifierLen);
5562       return false;
5563     }
5564   }
5565 
5566   // First check if the field width, precision, and conversion specifier
5567   // have matching data arguments.
5568   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
5569                     startSpecifier, specifierLen)) {
5570     return false;
5571   }
5572 
5573   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
5574                     startSpecifier, specifierLen)) {
5575     return false;
5576   }
5577 
5578   if (!CS.consumesDataArgument()) {
5579     // FIXME: Technically specifying a precision or field width here
5580     // makes no sense.  Worth issuing a warning at some point.
5581     return true;
5582   }
5583 
5584   // Consume the argument.
5585   unsigned argIndex = FS.getArgIndex();
5586   if (argIndex < NumDataArgs) {
5587     // The check to see if the argIndex is valid will come later.
5588     // We set the bit here because we may exit early from this
5589     // function if we encounter some other error.
5590     CoveredArgs.set(argIndex);
5591   }
5592 
5593   // FreeBSD kernel extensions.
5594   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
5595       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
5596     // We need at least two arguments.
5597     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
5598       return false;
5599 
5600     // Claim the second argument.
5601     CoveredArgs.set(argIndex + 1);
5602 
5603     // Type check the first argument (int for %b, pointer for %D)
5604     const Expr *Ex = getDataArg(argIndex);
5605     const analyze_printf::ArgType &AT =
5606       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
5607         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
5608     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
5609       EmitFormatDiagnostic(
5610         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5611         << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
5612         << false << Ex->getSourceRange(),
5613         Ex->getLocStart(), /*IsStringLocation*/false,
5614         getSpecifierRange(startSpecifier, specifierLen));
5615 
5616     // Type check the second argument (char * for both %b and %D)
5617     Ex = getDataArg(argIndex + 1);
5618     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
5619     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
5620       EmitFormatDiagnostic(
5621         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5622         << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
5623         << false << Ex->getSourceRange(),
5624         Ex->getLocStart(), /*IsStringLocation*/false,
5625         getSpecifierRange(startSpecifier, specifierLen));
5626 
5627      return true;
5628   }
5629 
5630   // Check for using an Objective-C specific conversion specifier
5631   // in a non-ObjC literal.
5632   if (!allowsObjCArg() && CS.isObjCArg()) {
5633     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5634                                                   specifierLen);
5635   }
5636 
5637   // %P can only be used with os_log.
5638   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
5639     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5640                                                   specifierLen);
5641   }
5642 
5643   // %n is not allowed with os_log.
5644   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
5645     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
5646                          getLocationOfByte(CS.getStart()),
5647                          /*IsStringLocation*/ false,
5648                          getSpecifierRange(startSpecifier, specifierLen));
5649 
5650     return true;
5651   }
5652 
5653   // Only scalars are allowed for os_trace.
5654   if (FSType == Sema::FST_OSTrace &&
5655       (CS.getKind() == ConversionSpecifier::PArg ||
5656        CS.getKind() == ConversionSpecifier::sArg ||
5657        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
5658     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5659                                                   specifierLen);
5660   }
5661 
5662   // Check for use of public/private annotation outside of os_log().
5663   if (FSType != Sema::FST_OSLog) {
5664     if (FS.isPublic().isSet()) {
5665       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5666                                << "public",
5667                            getLocationOfByte(FS.isPublic().getPosition()),
5668                            /*IsStringLocation*/ false,
5669                            getSpecifierRange(startSpecifier, specifierLen));
5670     }
5671     if (FS.isPrivate().isSet()) {
5672       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5673                                << "private",
5674                            getLocationOfByte(FS.isPrivate().getPosition()),
5675                            /*IsStringLocation*/ false,
5676                            getSpecifierRange(startSpecifier, specifierLen));
5677     }
5678   }
5679 
5680   // Check for invalid use of field width
5681   if (!FS.hasValidFieldWidth()) {
5682     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
5683         startSpecifier, specifierLen);
5684   }
5685 
5686   // Check for invalid use of precision
5687   if (!FS.hasValidPrecision()) {
5688     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
5689         startSpecifier, specifierLen);
5690   }
5691 
5692   // Precision is mandatory for %P specifier.
5693   if (CS.getKind() == ConversionSpecifier::PArg &&
5694       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
5695     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
5696                          getLocationOfByte(startSpecifier),
5697                          /*IsStringLocation*/ false,
5698                          getSpecifierRange(startSpecifier, specifierLen));
5699   }
5700 
5701   // Check each flag does not conflict with any other component.
5702   if (!FS.hasValidThousandsGroupingPrefix())
5703     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
5704   if (!FS.hasValidLeadingZeros())
5705     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
5706   if (!FS.hasValidPlusPrefix())
5707     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
5708   if (!FS.hasValidSpacePrefix())
5709     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
5710   if (!FS.hasValidAlternativeForm())
5711     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
5712   if (!FS.hasValidLeftJustified())
5713     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
5714 
5715   // Check that flags are not ignored by another flag
5716   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
5717     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
5718         startSpecifier, specifierLen);
5719   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
5720     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
5721             startSpecifier, specifierLen);
5722 
5723   // Check the length modifier is valid with the given conversion specifier.
5724   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
5725     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5726                                 diag::warn_format_nonsensical_length);
5727   else if (!FS.hasStandardLengthModifier())
5728     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
5729   else if (!FS.hasStandardLengthConversionCombination())
5730     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5731                                 diag::warn_format_non_standard_conversion_spec);
5732 
5733   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5734     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5735 
5736   // The remaining checks depend on the data arguments.
5737   if (HasVAListArg)
5738     return true;
5739 
5740   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
5741     return false;
5742 
5743   const Expr *Arg = getDataArg(argIndex);
5744   if (!Arg)
5745     return true;
5746 
5747   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
5748 }
5749 
5750 static bool requiresParensToAddCast(const Expr *E) {
5751   // FIXME: We should have a general way to reason about operator
5752   // precedence and whether parens are actually needed here.
5753   // Take care of a few common cases where they aren't.
5754   const Expr *Inside = E->IgnoreImpCasts();
5755   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
5756     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
5757 
5758   switch (Inside->getStmtClass()) {
5759   case Stmt::ArraySubscriptExprClass:
5760   case Stmt::CallExprClass:
5761   case Stmt::CharacterLiteralClass:
5762   case Stmt::CXXBoolLiteralExprClass:
5763   case Stmt::DeclRefExprClass:
5764   case Stmt::FloatingLiteralClass:
5765   case Stmt::IntegerLiteralClass:
5766   case Stmt::MemberExprClass:
5767   case Stmt::ObjCArrayLiteralClass:
5768   case Stmt::ObjCBoolLiteralExprClass:
5769   case Stmt::ObjCBoxedExprClass:
5770   case Stmt::ObjCDictionaryLiteralClass:
5771   case Stmt::ObjCEncodeExprClass:
5772   case Stmt::ObjCIvarRefExprClass:
5773   case Stmt::ObjCMessageExprClass:
5774   case Stmt::ObjCPropertyRefExprClass:
5775   case Stmt::ObjCStringLiteralClass:
5776   case Stmt::ObjCSubscriptRefExprClass:
5777   case Stmt::ParenExprClass:
5778   case Stmt::StringLiteralClass:
5779   case Stmt::UnaryOperatorClass:
5780     return false;
5781   default:
5782     return true;
5783   }
5784 }
5785 
5786 static std::pair<QualType, StringRef>
5787 shouldNotPrintDirectly(const ASTContext &Context,
5788                        QualType IntendedTy,
5789                        const Expr *E) {
5790   // Use a 'while' to peel off layers of typedefs.
5791   QualType TyTy = IntendedTy;
5792   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
5793     StringRef Name = UserTy->getDecl()->getName();
5794     QualType CastTy = llvm::StringSwitch<QualType>(Name)
5795       .Case("NSInteger", Context.LongTy)
5796       .Case("NSUInteger", Context.UnsignedLongTy)
5797       .Case("SInt32", Context.IntTy)
5798       .Case("UInt32", Context.UnsignedIntTy)
5799       .Default(QualType());
5800 
5801     if (!CastTy.isNull())
5802       return std::make_pair(CastTy, Name);
5803 
5804     TyTy = UserTy->desugar();
5805   }
5806 
5807   // Strip parens if necessary.
5808   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
5809     return shouldNotPrintDirectly(Context,
5810                                   PE->getSubExpr()->getType(),
5811                                   PE->getSubExpr());
5812 
5813   // If this is a conditional expression, then its result type is constructed
5814   // via usual arithmetic conversions and thus there might be no necessary
5815   // typedef sugar there.  Recurse to operands to check for NSInteger &
5816   // Co. usage condition.
5817   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5818     QualType TrueTy, FalseTy;
5819     StringRef TrueName, FalseName;
5820 
5821     std::tie(TrueTy, TrueName) =
5822       shouldNotPrintDirectly(Context,
5823                              CO->getTrueExpr()->getType(),
5824                              CO->getTrueExpr());
5825     std::tie(FalseTy, FalseName) =
5826       shouldNotPrintDirectly(Context,
5827                              CO->getFalseExpr()->getType(),
5828                              CO->getFalseExpr());
5829 
5830     if (TrueTy == FalseTy)
5831       return std::make_pair(TrueTy, TrueName);
5832     else if (TrueTy.isNull())
5833       return std::make_pair(FalseTy, FalseName);
5834     else if (FalseTy.isNull())
5835       return std::make_pair(TrueTy, TrueName);
5836   }
5837 
5838   return std::make_pair(QualType(), StringRef());
5839 }
5840 
5841 bool
5842 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5843                                     const char *StartSpecifier,
5844                                     unsigned SpecifierLen,
5845                                     const Expr *E) {
5846   using namespace analyze_format_string;
5847   using namespace analyze_printf;
5848   // Now type check the data expression that matches the
5849   // format specifier.
5850   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
5851   if (!AT.isValid())
5852     return true;
5853 
5854   QualType ExprTy = E->getType();
5855   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
5856     ExprTy = TET->getUnderlyingExpr()->getType();
5857   }
5858 
5859   analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
5860 
5861   if (match == analyze_printf::ArgType::Match) {
5862     return true;
5863   }
5864 
5865   // Look through argument promotions for our error message's reported type.
5866   // This includes the integral and floating promotions, but excludes array
5867   // and function pointer decay; seeing that an argument intended to be a
5868   // string has type 'char [6]' is probably more confusing than 'char *'.
5869   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5870     if (ICE->getCastKind() == CK_IntegralCast ||
5871         ICE->getCastKind() == CK_FloatingCast) {
5872       E = ICE->getSubExpr();
5873       ExprTy = E->getType();
5874 
5875       // Check if we didn't match because of an implicit cast from a 'char'
5876       // or 'short' to an 'int'.  This is done because printf is a varargs
5877       // function.
5878       if (ICE->getType() == S.Context.IntTy ||
5879           ICE->getType() == S.Context.UnsignedIntTy) {
5880         // All further checking is done on the subexpression.
5881         if (AT.matchesType(S.Context, ExprTy))
5882           return true;
5883       }
5884     }
5885   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
5886     // Special case for 'a', which has type 'int' in C.
5887     // Note, however, that we do /not/ want to treat multibyte constants like
5888     // 'MooV' as characters! This form is deprecated but still exists.
5889     if (ExprTy == S.Context.IntTy)
5890       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
5891         ExprTy = S.Context.CharTy;
5892   }
5893 
5894   // Look through enums to their underlying type.
5895   bool IsEnum = false;
5896   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
5897     ExprTy = EnumTy->getDecl()->getIntegerType();
5898     IsEnum = true;
5899   }
5900 
5901   // %C in an Objective-C context prints a unichar, not a wchar_t.
5902   // If the argument is an integer of some kind, believe the %C and suggest
5903   // a cast instead of changing the conversion specifier.
5904   QualType IntendedTy = ExprTy;
5905   if (isObjCContext() &&
5906       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
5907     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
5908         !ExprTy->isCharType()) {
5909       // 'unichar' is defined as a typedef of unsigned short, but we should
5910       // prefer using the typedef if it is visible.
5911       IntendedTy = S.Context.UnsignedShortTy;
5912 
5913       // While we are here, check if the value is an IntegerLiteral that happens
5914       // to be within the valid range.
5915       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
5916         const llvm::APInt &V = IL->getValue();
5917         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
5918           return true;
5919       }
5920 
5921       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
5922                           Sema::LookupOrdinaryName);
5923       if (S.LookupName(Result, S.getCurScope())) {
5924         NamedDecl *ND = Result.getFoundDecl();
5925         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
5926           if (TD->getUnderlyingType() == IntendedTy)
5927             IntendedTy = S.Context.getTypedefType(TD);
5928       }
5929     }
5930   }
5931 
5932   // Special-case some of Darwin's platform-independence types by suggesting
5933   // casts to primitive types that are known to be large enough.
5934   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
5935   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
5936     QualType CastTy;
5937     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
5938     if (!CastTy.isNull()) {
5939       IntendedTy = CastTy;
5940       ShouldNotPrintDirectly = true;
5941     }
5942   }
5943 
5944   // We may be able to offer a FixItHint if it is a supported type.
5945   PrintfSpecifier fixedFS = FS;
5946   bool success =
5947       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
5948 
5949   if (success) {
5950     // Get the fix string from the fixed format specifier
5951     SmallString<16> buf;
5952     llvm::raw_svector_ostream os(buf);
5953     fixedFS.toString(os);
5954 
5955     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
5956 
5957     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
5958       unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5959       if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5960         diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5961       }
5962       // In this case, the specifier is wrong and should be changed to match
5963       // the argument.
5964       EmitFormatDiagnostic(S.PDiag(diag)
5965                                << AT.getRepresentativeTypeName(S.Context)
5966                                << IntendedTy << IsEnum << E->getSourceRange(),
5967                            E->getLocStart(),
5968                            /*IsStringLocation*/ false, SpecRange,
5969                            FixItHint::CreateReplacement(SpecRange, os.str()));
5970     } else {
5971       // The canonical type for formatting this value is different from the
5972       // actual type of the expression. (This occurs, for example, with Darwin's
5973       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
5974       // should be printed as 'long' for 64-bit compatibility.)
5975       // Rather than emitting a normal format/argument mismatch, we want to
5976       // add a cast to the recommended type (and correct the format string
5977       // if necessary).
5978       SmallString<16> CastBuf;
5979       llvm::raw_svector_ostream CastFix(CastBuf);
5980       CastFix << "(";
5981       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
5982       CastFix << ")";
5983 
5984       SmallVector<FixItHint,4> Hints;
5985       if (!AT.matchesType(S.Context, IntendedTy))
5986         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
5987 
5988       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
5989         // If there's already a cast present, just replace it.
5990         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
5991         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
5992 
5993       } else if (!requiresParensToAddCast(E)) {
5994         // If the expression has high enough precedence,
5995         // just write the C-style cast.
5996         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
5997                                                    CastFix.str()));
5998       } else {
5999         // Otherwise, add parens around the expression as well as the cast.
6000         CastFix << "(";
6001         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6002                                                    CastFix.str()));
6003 
6004         SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
6005         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6006       }
6007 
6008       if (ShouldNotPrintDirectly) {
6009         // The expression has a type that should not be printed directly.
6010         // We extract the name from the typedef because we don't want to show
6011         // the underlying type in the diagnostic.
6012         StringRef Name;
6013         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6014           Name = TypedefTy->getDecl()->getName();
6015         else
6016           Name = CastTyName;
6017         EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
6018                                << Name << IntendedTy << IsEnum
6019                                << E->getSourceRange(),
6020                              E->getLocStart(), /*IsStringLocation=*/false,
6021                              SpecRange, Hints);
6022       } else {
6023         // In this case, the expression could be printed using a different
6024         // specifier, but we've decided that the specifier is probably correct
6025         // and we should cast instead. Just use the normal warning message.
6026         EmitFormatDiagnostic(
6027           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6028             << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
6029             << E->getSourceRange(),
6030           E->getLocStart(), /*IsStringLocation*/false,
6031           SpecRange, Hints);
6032       }
6033     }
6034   } else {
6035     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6036                                                    SpecifierLen);
6037     // Since the warning for passing non-POD types to variadic functions
6038     // was deferred until now, we emit a warning for non-POD
6039     // arguments here.
6040     switch (S.isValidVarArgType(ExprTy)) {
6041     case Sema::VAK_Valid:
6042     case Sema::VAK_ValidInCXX11: {
6043       unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6044       if (match == analyze_printf::ArgType::NoMatchPedantic) {
6045         diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6046       }
6047 
6048       EmitFormatDiagnostic(
6049           S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6050                         << IsEnum << CSR << E->getSourceRange(),
6051           E->getLocStart(), /*IsStringLocation*/ false, CSR);
6052       break;
6053     }
6054     case Sema::VAK_Undefined:
6055     case Sema::VAK_MSVCUndefined:
6056       EmitFormatDiagnostic(
6057         S.PDiag(diag::warn_non_pod_vararg_with_format_string)
6058           << S.getLangOpts().CPlusPlus11
6059           << ExprTy
6060           << CallType
6061           << AT.getRepresentativeTypeName(S.Context)
6062           << CSR
6063           << E->getSourceRange(),
6064         E->getLocStart(), /*IsStringLocation*/false, CSR);
6065       checkForCStrMembers(AT, E);
6066       break;
6067 
6068     case Sema::VAK_Invalid:
6069       if (ExprTy->isObjCObjectType())
6070         EmitFormatDiagnostic(
6071           S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6072             << S.getLangOpts().CPlusPlus11
6073             << ExprTy
6074             << CallType
6075             << AT.getRepresentativeTypeName(S.Context)
6076             << CSR
6077             << E->getSourceRange(),
6078           E->getLocStart(), /*IsStringLocation*/false, CSR);
6079       else
6080         // FIXME: If this is an initializer list, suggest removing the braces
6081         // or inserting a cast to the target type.
6082         S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6083           << isa<InitListExpr>(E) << ExprTy << CallType
6084           << AT.getRepresentativeTypeName(S.Context)
6085           << E->getSourceRange();
6086       break;
6087     }
6088 
6089     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6090            "format string specifier index out of range");
6091     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
6092   }
6093 
6094   return true;
6095 }
6096 
6097 //===--- CHECK: Scanf format string checking ------------------------------===//
6098 
6099 namespace {
6100 class CheckScanfHandler : public CheckFormatHandler {
6101 public:
6102   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
6103                     const Expr *origFormatExpr, Sema::FormatStringType type,
6104                     unsigned firstDataArg, unsigned numDataArgs,
6105                     const char *beg, bool hasVAListArg,
6106                     ArrayRef<const Expr *> Args, unsigned formatIdx,
6107                     bool inFunctionCall, Sema::VariadicCallType CallType,
6108                     llvm::SmallBitVector &CheckedVarArgs,
6109                     UncoveredArgHandler &UncoveredArg)
6110       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6111                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
6112                            inFunctionCall, CallType, CheckedVarArgs,
6113                            UncoveredArg) {}
6114 
6115   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6116                             const char *startSpecifier,
6117                             unsigned specifierLen) override;
6118 
6119   bool HandleInvalidScanfConversionSpecifier(
6120           const analyze_scanf::ScanfSpecifier &FS,
6121           const char *startSpecifier,
6122           unsigned specifierLen) override;
6123 
6124   void HandleIncompleteScanList(const char *start, const char *end) override;
6125 };
6126 } // end anonymous namespace
6127 
6128 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6129                                                  const char *end) {
6130   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6131                        getLocationOfByte(end), /*IsStringLocation*/true,
6132                        getSpecifierRange(start, end - start));
6133 }
6134 
6135 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6136                                         const analyze_scanf::ScanfSpecifier &FS,
6137                                         const char *startSpecifier,
6138                                         unsigned specifierLen) {
6139 
6140   const analyze_scanf::ScanfConversionSpecifier &CS =
6141     FS.getConversionSpecifier();
6142 
6143   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6144                                           getLocationOfByte(CS.getStart()),
6145                                           startSpecifier, specifierLen,
6146                                           CS.getStart(), CS.getLength());
6147 }
6148 
6149 bool CheckScanfHandler::HandleScanfSpecifier(
6150                                        const analyze_scanf::ScanfSpecifier &FS,
6151                                        const char *startSpecifier,
6152                                        unsigned specifierLen) {
6153   using namespace analyze_scanf;
6154   using namespace analyze_format_string;
6155 
6156   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
6157 
6158   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
6159   // be used to decide if we are using positional arguments consistently.
6160   if (FS.consumesDataArgument()) {
6161     if (atFirstArg) {
6162       atFirstArg = false;
6163       usesPositionalArgs = FS.usesPositionalArg();
6164     }
6165     else if (usesPositionalArgs != FS.usesPositionalArg()) {
6166       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6167                                         startSpecifier, specifierLen);
6168       return false;
6169     }
6170   }
6171 
6172   // Check if the field with is non-zero.
6173   const OptionalAmount &Amt = FS.getFieldWidth();
6174   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6175     if (Amt.getConstantAmount() == 0) {
6176       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6177                                                    Amt.getConstantLength());
6178       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6179                            getLocationOfByte(Amt.getStart()),
6180                            /*IsStringLocation*/true, R,
6181                            FixItHint::CreateRemoval(R));
6182     }
6183   }
6184 
6185   if (!FS.consumesDataArgument()) {
6186     // FIXME: Technically specifying a precision or field width here
6187     // makes no sense.  Worth issuing a warning at some point.
6188     return true;
6189   }
6190 
6191   // Consume the argument.
6192   unsigned argIndex = FS.getArgIndex();
6193   if (argIndex < NumDataArgs) {
6194       // The check to see if the argIndex is valid will come later.
6195       // We set the bit here because we may exit early from this
6196       // function if we encounter some other error.
6197     CoveredArgs.set(argIndex);
6198   }
6199 
6200   // Check the length modifier is valid with the given conversion specifier.
6201   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
6202     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6203                                 diag::warn_format_nonsensical_length);
6204   else if (!FS.hasStandardLengthModifier())
6205     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
6206   else if (!FS.hasStandardLengthConversionCombination())
6207     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6208                                 diag::warn_format_non_standard_conversion_spec);
6209 
6210   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6211     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6212 
6213   // The remaining checks depend on the data arguments.
6214   if (HasVAListArg)
6215     return true;
6216 
6217   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
6218     return false;
6219 
6220   // Check that the argument type matches the format specifier.
6221   const Expr *Ex = getDataArg(argIndex);
6222   if (!Ex)
6223     return true;
6224 
6225   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
6226 
6227   if (!AT.isValid()) {
6228     return true;
6229   }
6230 
6231   analyze_format_string::ArgType::MatchKind match =
6232       AT.matchesType(S.Context, Ex->getType());
6233   if (match == analyze_format_string::ArgType::Match) {
6234     return true;
6235   }
6236 
6237   ScanfSpecifier fixedFS = FS;
6238   bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6239                                  S.getLangOpts(), S.Context);
6240 
6241   unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6242   if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6243     diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6244   }
6245 
6246   if (success) {
6247     // Get the fix string from the fixed format specifier.
6248     SmallString<128> buf;
6249     llvm::raw_svector_ostream os(buf);
6250     fixedFS.toString(os);
6251 
6252     EmitFormatDiagnostic(
6253         S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6254                       << Ex->getType() << false << Ex->getSourceRange(),
6255         Ex->getLocStart(),
6256         /*IsStringLocation*/ false,
6257         getSpecifierRange(startSpecifier, specifierLen),
6258         FixItHint::CreateReplacement(
6259             getSpecifierRange(startSpecifier, specifierLen), os.str()));
6260   } else {
6261     EmitFormatDiagnostic(S.PDiag(diag)
6262                              << AT.getRepresentativeTypeName(S.Context)
6263                              << Ex->getType() << false << Ex->getSourceRange(),
6264                          Ex->getLocStart(),
6265                          /*IsStringLocation*/ false,
6266                          getSpecifierRange(startSpecifier, specifierLen));
6267   }
6268 
6269   return true;
6270 }
6271 
6272 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6273                               const Expr *OrigFormatExpr,
6274                               ArrayRef<const Expr *> Args,
6275                               bool HasVAListArg, unsigned format_idx,
6276                               unsigned firstDataArg,
6277                               Sema::FormatStringType Type,
6278                               bool inFunctionCall,
6279                               Sema::VariadicCallType CallType,
6280                               llvm::SmallBitVector &CheckedVarArgs,
6281                               UncoveredArgHandler &UncoveredArg) {
6282   // CHECK: is the format string a wide literal?
6283   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
6284     CheckFormatHandler::EmitFormatDiagnostic(
6285       S, inFunctionCall, Args[format_idx],
6286       S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
6287       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
6288     return;
6289   }
6290 
6291   // Str - The format string.  NOTE: this is NOT null-terminated!
6292   StringRef StrRef = FExpr->getString();
6293   const char *Str = StrRef.data();
6294   // Account for cases where the string literal is truncated in a declaration.
6295   const ConstantArrayType *T =
6296     S.Context.getAsConstantArrayType(FExpr->getType());
6297   assert(T && "String literal not of constant array type!");
6298   size_t TypeSize = T->getSize().getZExtValue();
6299   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6300   const unsigned numDataArgs = Args.size() - firstDataArg;
6301 
6302   // Emit a warning if the string literal is truncated and does not contain an
6303   // embedded null character.
6304   if (TypeSize <= StrRef.size() &&
6305       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6306     CheckFormatHandler::EmitFormatDiagnostic(
6307         S, inFunctionCall, Args[format_idx],
6308         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
6309         FExpr->getLocStart(),
6310         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6311     return;
6312   }
6313 
6314   // CHECK: empty format string?
6315   if (StrLen == 0 && numDataArgs > 0) {
6316     CheckFormatHandler::EmitFormatDiagnostic(
6317       S, inFunctionCall, Args[format_idx],
6318       S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
6319       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
6320     return;
6321   }
6322 
6323   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
6324       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6325       Type == Sema::FST_OSTrace) {
6326     CheckPrintfHandler H(
6327         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6328         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6329         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6330         CheckedVarArgs, UncoveredArg);
6331 
6332     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
6333                                                   S.getLangOpts(),
6334                                                   S.Context.getTargetInfo(),
6335                                             Type == Sema::FST_FreeBSDKPrintf))
6336       H.DoneProcessing();
6337   } else if (Type == Sema::FST_Scanf) {
6338     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6339                         numDataArgs, Str, HasVAListArg, Args, format_idx,
6340                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
6341 
6342     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
6343                                                  S.getLangOpts(),
6344                                                  S.Context.getTargetInfo()))
6345       H.DoneProcessing();
6346   } // TODO: handle other formats
6347 }
6348 
6349 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6350   // Str - The format string.  NOTE: this is NOT null-terminated!
6351   StringRef StrRef = FExpr->getString();
6352   const char *Str = StrRef.data();
6353   // Account for cases where the string literal is truncated in a declaration.
6354   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6355   assert(T && "String literal not of constant array type!");
6356   size_t TypeSize = T->getSize().getZExtValue();
6357   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6358   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6359                                                          getLangOpts(),
6360                                                          Context.getTargetInfo());
6361 }
6362 
6363 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6364 
6365 // Returns the related absolute value function that is larger, of 0 if one
6366 // does not exist.
6367 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6368   switch (AbsFunction) {
6369   default:
6370     return 0;
6371 
6372   case Builtin::BI__builtin_abs:
6373     return Builtin::BI__builtin_labs;
6374   case Builtin::BI__builtin_labs:
6375     return Builtin::BI__builtin_llabs;
6376   case Builtin::BI__builtin_llabs:
6377     return 0;
6378 
6379   case Builtin::BI__builtin_fabsf:
6380     return Builtin::BI__builtin_fabs;
6381   case Builtin::BI__builtin_fabs:
6382     return Builtin::BI__builtin_fabsl;
6383   case Builtin::BI__builtin_fabsl:
6384     return 0;
6385 
6386   case Builtin::BI__builtin_cabsf:
6387     return Builtin::BI__builtin_cabs;
6388   case Builtin::BI__builtin_cabs:
6389     return Builtin::BI__builtin_cabsl;
6390   case Builtin::BI__builtin_cabsl:
6391     return 0;
6392 
6393   case Builtin::BIabs:
6394     return Builtin::BIlabs;
6395   case Builtin::BIlabs:
6396     return Builtin::BIllabs;
6397   case Builtin::BIllabs:
6398     return 0;
6399 
6400   case Builtin::BIfabsf:
6401     return Builtin::BIfabs;
6402   case Builtin::BIfabs:
6403     return Builtin::BIfabsl;
6404   case Builtin::BIfabsl:
6405     return 0;
6406 
6407   case Builtin::BIcabsf:
6408    return Builtin::BIcabs;
6409   case Builtin::BIcabs:
6410     return Builtin::BIcabsl;
6411   case Builtin::BIcabsl:
6412     return 0;
6413   }
6414 }
6415 
6416 // Returns the argument type of the absolute value function.
6417 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6418                                              unsigned AbsType) {
6419   if (AbsType == 0)
6420     return QualType();
6421 
6422   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6423   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6424   if (Error != ASTContext::GE_None)
6425     return QualType();
6426 
6427   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6428   if (!FT)
6429     return QualType();
6430 
6431   if (FT->getNumParams() != 1)
6432     return QualType();
6433 
6434   return FT->getParamType(0);
6435 }
6436 
6437 // Returns the best absolute value function, or zero, based on type and
6438 // current absolute value function.
6439 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6440                                    unsigned AbsFunctionKind) {
6441   unsigned BestKind = 0;
6442   uint64_t ArgSize = Context.getTypeSize(ArgType);
6443   for (unsigned Kind = AbsFunctionKind; Kind != 0;
6444        Kind = getLargerAbsoluteValueFunction(Kind)) {
6445     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6446     if (Context.getTypeSize(ParamType) >= ArgSize) {
6447       if (BestKind == 0)
6448         BestKind = Kind;
6449       else if (Context.hasSameType(ParamType, ArgType)) {
6450         BestKind = Kind;
6451         break;
6452       }
6453     }
6454   }
6455   return BestKind;
6456 }
6457 
6458 enum AbsoluteValueKind {
6459   AVK_Integer,
6460   AVK_Floating,
6461   AVK_Complex
6462 };
6463 
6464 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6465   if (T->isIntegralOrEnumerationType())
6466     return AVK_Integer;
6467   if (T->isRealFloatingType())
6468     return AVK_Floating;
6469   if (T->isAnyComplexType())
6470     return AVK_Complex;
6471 
6472   llvm_unreachable("Type not integer, floating, or complex");
6473 }
6474 
6475 // Changes the absolute value function to a different type.  Preserves whether
6476 // the function is a builtin.
6477 static unsigned changeAbsFunction(unsigned AbsKind,
6478                                   AbsoluteValueKind ValueKind) {
6479   switch (ValueKind) {
6480   case AVK_Integer:
6481     switch (AbsKind) {
6482     default:
6483       return 0;
6484     case Builtin::BI__builtin_fabsf:
6485     case Builtin::BI__builtin_fabs:
6486     case Builtin::BI__builtin_fabsl:
6487     case Builtin::BI__builtin_cabsf:
6488     case Builtin::BI__builtin_cabs:
6489     case Builtin::BI__builtin_cabsl:
6490       return Builtin::BI__builtin_abs;
6491     case Builtin::BIfabsf:
6492     case Builtin::BIfabs:
6493     case Builtin::BIfabsl:
6494     case Builtin::BIcabsf:
6495     case Builtin::BIcabs:
6496     case Builtin::BIcabsl:
6497       return Builtin::BIabs;
6498     }
6499   case AVK_Floating:
6500     switch (AbsKind) {
6501     default:
6502       return 0;
6503     case Builtin::BI__builtin_abs:
6504     case Builtin::BI__builtin_labs:
6505     case Builtin::BI__builtin_llabs:
6506     case Builtin::BI__builtin_cabsf:
6507     case Builtin::BI__builtin_cabs:
6508     case Builtin::BI__builtin_cabsl:
6509       return Builtin::BI__builtin_fabsf;
6510     case Builtin::BIabs:
6511     case Builtin::BIlabs:
6512     case Builtin::BIllabs:
6513     case Builtin::BIcabsf:
6514     case Builtin::BIcabs:
6515     case Builtin::BIcabsl:
6516       return Builtin::BIfabsf;
6517     }
6518   case AVK_Complex:
6519     switch (AbsKind) {
6520     default:
6521       return 0;
6522     case Builtin::BI__builtin_abs:
6523     case Builtin::BI__builtin_labs:
6524     case Builtin::BI__builtin_llabs:
6525     case Builtin::BI__builtin_fabsf:
6526     case Builtin::BI__builtin_fabs:
6527     case Builtin::BI__builtin_fabsl:
6528       return Builtin::BI__builtin_cabsf;
6529     case Builtin::BIabs:
6530     case Builtin::BIlabs:
6531     case Builtin::BIllabs:
6532     case Builtin::BIfabsf:
6533     case Builtin::BIfabs:
6534     case Builtin::BIfabsl:
6535       return Builtin::BIcabsf;
6536     }
6537   }
6538   llvm_unreachable("Unable to convert function");
6539 }
6540 
6541 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
6542   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6543   if (!FnInfo)
6544     return 0;
6545 
6546   switch (FDecl->getBuiltinID()) {
6547   default:
6548     return 0;
6549   case Builtin::BI__builtin_abs:
6550   case Builtin::BI__builtin_fabs:
6551   case Builtin::BI__builtin_fabsf:
6552   case Builtin::BI__builtin_fabsl:
6553   case Builtin::BI__builtin_labs:
6554   case Builtin::BI__builtin_llabs:
6555   case Builtin::BI__builtin_cabs:
6556   case Builtin::BI__builtin_cabsf:
6557   case Builtin::BI__builtin_cabsl:
6558   case Builtin::BIabs:
6559   case Builtin::BIlabs:
6560   case Builtin::BIllabs:
6561   case Builtin::BIfabs:
6562   case Builtin::BIfabsf:
6563   case Builtin::BIfabsl:
6564   case Builtin::BIcabs:
6565   case Builtin::BIcabsf:
6566   case Builtin::BIcabsl:
6567     return FDecl->getBuiltinID();
6568   }
6569   llvm_unreachable("Unknown Builtin type");
6570 }
6571 
6572 // If the replacement is valid, emit a note with replacement function.
6573 // Additionally, suggest including the proper header if not already included.
6574 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
6575                             unsigned AbsKind, QualType ArgType) {
6576   bool EmitHeaderHint = true;
6577   const char *HeaderName = nullptr;
6578   const char *FunctionName = nullptr;
6579   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
6580     FunctionName = "std::abs";
6581     if (ArgType->isIntegralOrEnumerationType()) {
6582       HeaderName = "cstdlib";
6583     } else if (ArgType->isRealFloatingType()) {
6584       HeaderName = "cmath";
6585     } else {
6586       llvm_unreachable("Invalid Type");
6587     }
6588 
6589     // Lookup all std::abs
6590     if (NamespaceDecl *Std = S.getStdNamespace()) {
6591       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
6592       R.suppressDiagnostics();
6593       S.LookupQualifiedName(R, Std);
6594 
6595       for (const auto *I : R) {
6596         const FunctionDecl *FDecl = nullptr;
6597         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
6598           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
6599         } else {
6600           FDecl = dyn_cast<FunctionDecl>(I);
6601         }
6602         if (!FDecl)
6603           continue;
6604 
6605         // Found std::abs(), check that they are the right ones.
6606         if (FDecl->getNumParams() != 1)
6607           continue;
6608 
6609         // Check that the parameter type can handle the argument.
6610         QualType ParamType = FDecl->getParamDecl(0)->getType();
6611         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
6612             S.Context.getTypeSize(ArgType) <=
6613                 S.Context.getTypeSize(ParamType)) {
6614           // Found a function, don't need the header hint.
6615           EmitHeaderHint = false;
6616           break;
6617         }
6618       }
6619     }
6620   } else {
6621     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
6622     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
6623 
6624     if (HeaderName) {
6625       DeclarationName DN(&S.Context.Idents.get(FunctionName));
6626       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
6627       R.suppressDiagnostics();
6628       S.LookupName(R, S.getCurScope());
6629 
6630       if (R.isSingleResult()) {
6631         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
6632         if (FD && FD->getBuiltinID() == AbsKind) {
6633           EmitHeaderHint = false;
6634         } else {
6635           return;
6636         }
6637       } else if (!R.empty()) {
6638         return;
6639       }
6640     }
6641   }
6642 
6643   S.Diag(Loc, diag::note_replace_abs_function)
6644       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
6645 
6646   if (!HeaderName)
6647     return;
6648 
6649   if (!EmitHeaderHint)
6650     return;
6651 
6652   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
6653                                                     << FunctionName;
6654 }
6655 
6656 static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
6657   if (!FDecl)
6658     return false;
6659 
6660   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
6661     return false;
6662 
6663   const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
6664 
6665   while (ND && ND->isInlineNamespace()) {
6666     ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
6667   }
6668 
6669   if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
6670     return false;
6671 
6672   if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
6673     return false;
6674 
6675   return true;
6676 }
6677 
6678 // Warn when using the wrong abs() function.
6679 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
6680                                       const FunctionDecl *FDecl,
6681                                       IdentifierInfo *FnInfo) {
6682   if (Call->getNumArgs() != 1)
6683     return;
6684 
6685   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
6686   bool IsStdAbs = IsFunctionStdAbs(FDecl);
6687   if (AbsKind == 0 && !IsStdAbs)
6688     return;
6689 
6690   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6691   QualType ParamType = Call->getArg(0)->getType();
6692 
6693   // Unsigned types cannot be negative.  Suggest removing the absolute value
6694   // function call.
6695   if (ArgType->isUnsignedIntegerType()) {
6696     const char *FunctionName =
6697         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
6698     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
6699     Diag(Call->getExprLoc(), diag::note_remove_abs)
6700         << FunctionName
6701         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
6702     return;
6703   }
6704 
6705   // Taking the absolute value of a pointer is very suspicious, they probably
6706   // wanted to index into an array, dereference a pointer, call a function, etc.
6707   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
6708     unsigned DiagType = 0;
6709     if (ArgType->isFunctionType())
6710       DiagType = 1;
6711     else if (ArgType->isArrayType())
6712       DiagType = 2;
6713 
6714     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
6715     return;
6716   }
6717 
6718   // std::abs has overloads which prevent most of the absolute value problems
6719   // from occurring.
6720   if (IsStdAbs)
6721     return;
6722 
6723   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
6724   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
6725 
6726   // The argument and parameter are the same kind.  Check if they are the right
6727   // size.
6728   if (ArgValueKind == ParamValueKind) {
6729     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
6730       return;
6731 
6732     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
6733     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
6734         << FDecl << ArgType << ParamType;
6735 
6736     if (NewAbsKind == 0)
6737       return;
6738 
6739     emitReplacement(*this, Call->getExprLoc(),
6740                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
6741     return;
6742   }
6743 
6744   // ArgValueKind != ParamValueKind
6745   // The wrong type of absolute value function was used.  Attempt to find the
6746   // proper one.
6747   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
6748   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
6749   if (NewAbsKind == 0)
6750     return;
6751 
6752   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
6753       << FDecl << ParamValueKind << ArgValueKind;
6754 
6755   emitReplacement(*this, Call->getExprLoc(),
6756                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
6757 }
6758 
6759 //===--- CHECK: Standard memory functions ---------------------------------===//
6760 
6761 /// \brief Takes the expression passed to the size_t parameter of functions
6762 /// such as memcmp, strncat, etc and warns if it's a comparison.
6763 ///
6764 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
6765 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
6766                                            IdentifierInfo *FnName,
6767                                            SourceLocation FnLoc,
6768                                            SourceLocation RParenLoc) {
6769   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
6770   if (!Size)
6771     return false;
6772 
6773   // if E is binop and op is >, <, >=, <=, ==, &&, ||:
6774   if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
6775     return false;
6776 
6777   SourceRange SizeRange = Size->getSourceRange();
6778   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
6779       << SizeRange << FnName;
6780   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
6781       << FnName << FixItHint::CreateInsertion(
6782                        S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
6783       << FixItHint::CreateRemoval(RParenLoc);
6784   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
6785       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
6786       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
6787                                     ")");
6788 
6789   return true;
6790 }
6791 
6792 /// \brief Determine whether the given type is or contains a dynamic class type
6793 /// (e.g., whether it has a vtable).
6794 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
6795                                                      bool &IsContained) {
6796   // Look through array types while ignoring qualifiers.
6797   const Type *Ty = T->getBaseElementTypeUnsafe();
6798   IsContained = false;
6799 
6800   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
6801   RD = RD ? RD->getDefinition() : nullptr;
6802   if (!RD || RD->isInvalidDecl())
6803     return nullptr;
6804 
6805   if (RD->isDynamicClass())
6806     return RD;
6807 
6808   // Check all the fields.  If any bases were dynamic, the class is dynamic.
6809   // It's impossible for a class to transitively contain itself by value, so
6810   // infinite recursion is impossible.
6811   for (auto *FD : RD->fields()) {
6812     bool SubContained;
6813     if (const CXXRecordDecl *ContainedRD =
6814             getContainedDynamicClass(FD->getType(), SubContained)) {
6815       IsContained = true;
6816       return ContainedRD;
6817     }
6818   }
6819 
6820   return nullptr;
6821 }
6822 
6823 /// \brief If E is a sizeof expression, returns its argument expression,
6824 /// otherwise returns NULL.
6825 static const Expr *getSizeOfExprArg(const Expr *E) {
6826   if (const UnaryExprOrTypeTraitExpr *SizeOf =
6827       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6828     if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
6829       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
6830 
6831   return nullptr;
6832 }
6833 
6834 /// \brief If E is a sizeof expression, returns its argument type.
6835 static QualType getSizeOfArgType(const Expr *E) {
6836   if (const UnaryExprOrTypeTraitExpr *SizeOf =
6837       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6838     if (SizeOf->getKind() == clang::UETT_SizeOf)
6839       return SizeOf->getTypeOfArgument();
6840 
6841   return QualType();
6842 }
6843 
6844 /// \brief Check for dangerous or invalid arguments to memset().
6845 ///
6846 /// This issues warnings on known problematic, dangerous or unspecified
6847 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
6848 /// function calls.
6849 ///
6850 /// \param Call The call expression to diagnose.
6851 void Sema::CheckMemaccessArguments(const CallExpr *Call,
6852                                    unsigned BId,
6853                                    IdentifierInfo *FnName) {
6854   assert(BId != 0);
6855 
6856   // It is possible to have a non-standard definition of memset.  Validate
6857   // we have enough arguments, and if not, abort further checking.
6858   unsigned ExpectedNumArgs =
6859       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
6860   if (Call->getNumArgs() < ExpectedNumArgs)
6861     return;
6862 
6863   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
6864                       BId == Builtin::BIstrndup ? 1 : 2);
6865   unsigned LenArg =
6866       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
6867   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
6868 
6869   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
6870                                      Call->getLocStart(), Call->getRParenLoc()))
6871     return;
6872 
6873   // We have special checking when the length is a sizeof expression.
6874   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
6875   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
6876   llvm::FoldingSetNodeID SizeOfArgID;
6877 
6878   // Although widely used, 'bzero' is not a standard function. Be more strict
6879   // with the argument types before allowing diagnostics and only allow the
6880   // form bzero(ptr, sizeof(...)).
6881   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6882   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
6883     return;
6884 
6885   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
6886     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
6887     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
6888 
6889     QualType DestTy = Dest->getType();
6890     QualType PointeeTy;
6891     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
6892       PointeeTy = DestPtrTy->getPointeeType();
6893 
6894       // Never warn about void type pointers. This can be used to suppress
6895       // false positives.
6896       if (PointeeTy->isVoidType())
6897         continue;
6898 
6899       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
6900       // actually comparing the expressions for equality. Because computing the
6901       // expression IDs can be expensive, we only do this if the diagnostic is
6902       // enabled.
6903       if (SizeOfArg &&
6904           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
6905                            SizeOfArg->getExprLoc())) {
6906         // We only compute IDs for expressions if the warning is enabled, and
6907         // cache the sizeof arg's ID.
6908         if (SizeOfArgID == llvm::FoldingSetNodeID())
6909           SizeOfArg->Profile(SizeOfArgID, Context, true);
6910         llvm::FoldingSetNodeID DestID;
6911         Dest->Profile(DestID, Context, true);
6912         if (DestID == SizeOfArgID) {
6913           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
6914           //       over sizeof(src) as well.
6915           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
6916           StringRef ReadableName = FnName->getName();
6917 
6918           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
6919             if (UnaryOp->getOpcode() == UO_AddrOf)
6920               ActionIdx = 1; // If its an address-of operator, just remove it.
6921           if (!PointeeTy->isIncompleteType() &&
6922               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
6923             ActionIdx = 2; // If the pointee's size is sizeof(char),
6924                            // suggest an explicit length.
6925 
6926           // If the function is defined as a builtin macro, do not show macro
6927           // expansion.
6928           SourceLocation SL = SizeOfArg->getExprLoc();
6929           SourceRange DSR = Dest->getSourceRange();
6930           SourceRange SSR = SizeOfArg->getSourceRange();
6931           SourceManager &SM = getSourceManager();
6932 
6933           if (SM.isMacroArgExpansion(SL)) {
6934             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
6935             SL = SM.getSpellingLoc(SL);
6936             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
6937                              SM.getSpellingLoc(DSR.getEnd()));
6938             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
6939                              SM.getSpellingLoc(SSR.getEnd()));
6940           }
6941 
6942           DiagRuntimeBehavior(SL, SizeOfArg,
6943                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
6944                                 << ReadableName
6945                                 << PointeeTy
6946                                 << DestTy
6947                                 << DSR
6948                                 << SSR);
6949           DiagRuntimeBehavior(SL, SizeOfArg,
6950                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
6951                                 << ActionIdx
6952                                 << SSR);
6953 
6954           break;
6955         }
6956       }
6957 
6958       // Also check for cases where the sizeof argument is the exact same
6959       // type as the memory argument, and where it points to a user-defined
6960       // record type.
6961       if (SizeOfArgTy != QualType()) {
6962         if (PointeeTy->isRecordType() &&
6963             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
6964           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
6965                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
6966                                 << FnName << SizeOfArgTy << ArgIdx
6967                                 << PointeeTy << Dest->getSourceRange()
6968                                 << LenExpr->getSourceRange());
6969           break;
6970         }
6971       }
6972     } else if (DestTy->isArrayType()) {
6973       PointeeTy = DestTy;
6974     }
6975 
6976     if (PointeeTy == QualType())
6977       continue;
6978 
6979     // Always complain about dynamic classes.
6980     bool IsContained;
6981     if (const CXXRecordDecl *ContainedRD =
6982             getContainedDynamicClass(PointeeTy, IsContained)) {
6983 
6984       unsigned OperationType = 0;
6985       // "overwritten" if we're warning about the destination for any call
6986       // but memcmp; otherwise a verb appropriate to the call.
6987       if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
6988         if (BId == Builtin::BImemcpy)
6989           OperationType = 1;
6990         else if(BId == Builtin::BImemmove)
6991           OperationType = 2;
6992         else if (BId == Builtin::BImemcmp)
6993           OperationType = 3;
6994       }
6995 
6996       DiagRuntimeBehavior(
6997         Dest->getExprLoc(), Dest,
6998         PDiag(diag::warn_dyn_class_memaccess)
6999           << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7000           << FnName << IsContained << ContainedRD << OperationType
7001           << Call->getCallee()->getSourceRange());
7002     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7003              BId != Builtin::BImemset)
7004       DiagRuntimeBehavior(
7005         Dest->getExprLoc(), Dest,
7006         PDiag(diag::warn_arc_object_memaccess)
7007           << ArgIdx << FnName << PointeeTy
7008           << Call->getCallee()->getSourceRange());
7009     else
7010       continue;
7011 
7012     DiagRuntimeBehavior(
7013       Dest->getExprLoc(), Dest,
7014       PDiag(diag::note_bad_memaccess_silence)
7015         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7016     break;
7017   }
7018 }
7019 
7020 // A little helper routine: ignore addition and subtraction of integer literals.
7021 // This intentionally does not ignore all integer constant expressions because
7022 // we don't want to remove sizeof().
7023 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7024   Ex = Ex->IgnoreParenCasts();
7025 
7026   for (;;) {
7027     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7028     if (!BO || !BO->isAdditiveOp())
7029       break;
7030 
7031     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7032     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7033 
7034     if (isa<IntegerLiteral>(RHS))
7035       Ex = LHS;
7036     else if (isa<IntegerLiteral>(LHS))
7037       Ex = RHS;
7038     else
7039       break;
7040   }
7041 
7042   return Ex;
7043 }
7044 
7045 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7046                                                       ASTContext &Context) {
7047   // Only handle constant-sized or VLAs, but not flexible members.
7048   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7049     // Only issue the FIXIT for arrays of size > 1.
7050     if (CAT->getSize().getSExtValue() <= 1)
7051       return false;
7052   } else if (!Ty->isVariableArrayType()) {
7053     return false;
7054   }
7055   return true;
7056 }
7057 
7058 // Warn if the user has made the 'size' argument to strlcpy or strlcat
7059 // be the size of the source, instead of the destination.
7060 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7061                                     IdentifierInfo *FnName) {
7062 
7063   // Don't crash if the user has the wrong number of arguments
7064   unsigned NumArgs = Call->getNumArgs();
7065   if ((NumArgs != 3) && (NumArgs != 4))
7066     return;
7067 
7068   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7069   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
7070   const Expr *CompareWithSrc = nullptr;
7071 
7072   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7073                                      Call->getLocStart(), Call->getRParenLoc()))
7074     return;
7075 
7076   // Look for 'strlcpy(dst, x, sizeof(x))'
7077   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7078     CompareWithSrc = Ex;
7079   else {
7080     // Look for 'strlcpy(dst, x, strlen(x))'
7081     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
7082       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7083           SizeCall->getNumArgs() == 1)
7084         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7085     }
7086   }
7087 
7088   if (!CompareWithSrc)
7089     return;
7090 
7091   // Determine if the argument to sizeof/strlen is equal to the source
7092   // argument.  In principle there's all kinds of things you could do
7093   // here, for instance creating an == expression and evaluating it with
7094   // EvaluateAsBooleanCondition, but this uses a more direct technique:
7095   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7096   if (!SrcArgDRE)
7097     return;
7098 
7099   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7100   if (!CompareWithSrcDRE ||
7101       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7102     return;
7103 
7104   const Expr *OriginalSizeArg = Call->getArg(2);
7105   Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7106     << OriginalSizeArg->getSourceRange() << FnName;
7107 
7108   // Output a FIXIT hint if the destination is an array (rather than a
7109   // pointer to an array).  This could be enhanced to handle some
7110   // pointers if we know the actual size, like if DstArg is 'array+2'
7111   // we could say 'sizeof(array)-2'.
7112   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
7113   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
7114     return;
7115 
7116   SmallString<128> sizeString;
7117   llvm::raw_svector_ostream OS(sizeString);
7118   OS << "sizeof(";
7119   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7120   OS << ")";
7121 
7122   Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7123     << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7124                                     OS.str());
7125 }
7126 
7127 /// Check if two expressions refer to the same declaration.
7128 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7129   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7130     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7131       return D1->getDecl() == D2->getDecl();
7132   return false;
7133 }
7134 
7135 static const Expr *getStrlenExprArg(const Expr *E) {
7136   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7137     const FunctionDecl *FD = CE->getDirectCallee();
7138     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
7139       return nullptr;
7140     return CE->getArg(0)->IgnoreParenCasts();
7141   }
7142   return nullptr;
7143 }
7144 
7145 // Warn on anti-patterns as the 'size' argument to strncat.
7146 // The correct size argument should look like following:
7147 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7148 void Sema::CheckStrncatArguments(const CallExpr *CE,
7149                                  IdentifierInfo *FnName) {
7150   // Don't crash if the user has the wrong number of arguments.
7151   if (CE->getNumArgs() < 3)
7152     return;
7153   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7154   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7155   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7156 
7157   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7158                                      CE->getRParenLoc()))
7159     return;
7160 
7161   // Identify common expressions, which are wrongly used as the size argument
7162   // to strncat and may lead to buffer overflows.
7163   unsigned PatternType = 0;
7164   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7165     // - sizeof(dst)
7166     if (referToTheSameDecl(SizeOfArg, DstArg))
7167       PatternType = 1;
7168     // - sizeof(src)
7169     else if (referToTheSameDecl(SizeOfArg, SrcArg))
7170       PatternType = 2;
7171   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7172     if (BE->getOpcode() == BO_Sub) {
7173       const Expr *L = BE->getLHS()->IgnoreParenCasts();
7174       const Expr *R = BE->getRHS()->IgnoreParenCasts();
7175       // - sizeof(dst) - strlen(dst)
7176       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7177           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7178         PatternType = 1;
7179       // - sizeof(src) - (anything)
7180       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7181         PatternType = 2;
7182     }
7183   }
7184 
7185   if (PatternType == 0)
7186     return;
7187 
7188   // Generate the diagnostic.
7189   SourceLocation SL = LenArg->getLocStart();
7190   SourceRange SR = LenArg->getSourceRange();
7191   SourceManager &SM = getSourceManager();
7192 
7193   // If the function is defined as a builtin macro, do not show macro expansion.
7194   if (SM.isMacroArgExpansion(SL)) {
7195     SL = SM.getSpellingLoc(SL);
7196     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7197                      SM.getSpellingLoc(SR.getEnd()));
7198   }
7199 
7200   // Check if the destination is an array (rather than a pointer to an array).
7201   QualType DstTy = DstArg->getType();
7202   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7203                                                                     Context);
7204   if (!isKnownSizeArray) {
7205     if (PatternType == 1)
7206       Diag(SL, diag::warn_strncat_wrong_size) << SR;
7207     else
7208       Diag(SL, diag::warn_strncat_src_size) << SR;
7209     return;
7210   }
7211 
7212   if (PatternType == 1)
7213     Diag(SL, diag::warn_strncat_large_size) << SR;
7214   else
7215     Diag(SL, diag::warn_strncat_src_size) << SR;
7216 
7217   SmallString<128> sizeString;
7218   llvm::raw_svector_ostream OS(sizeString);
7219   OS << "sizeof(";
7220   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7221   OS << ") - ";
7222   OS << "strlen(";
7223   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7224   OS << ") - 1";
7225 
7226   Diag(SL, diag::note_strncat_wrong_size)
7227     << FixItHint::CreateReplacement(SR, OS.str());
7228 }
7229 
7230 //===--- CHECK: Return Address of Stack Variable --------------------------===//
7231 
7232 static const Expr *EvalVal(const Expr *E,
7233                            SmallVectorImpl<const DeclRefExpr *> &refVars,
7234                            const Decl *ParentDecl);
7235 static const Expr *EvalAddr(const Expr *E,
7236                             SmallVectorImpl<const DeclRefExpr *> &refVars,
7237                             const Decl *ParentDecl);
7238 
7239 /// CheckReturnStackAddr - Check if a return statement returns the address
7240 ///   of a stack variable.
7241 static void
7242 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7243                      SourceLocation ReturnLoc) {
7244 
7245   const Expr *stackE = nullptr;
7246   SmallVector<const DeclRefExpr *, 8> refVars;
7247 
7248   // Perform checking for returned stack addresses, local blocks,
7249   // label addresses or references to temporaries.
7250   if (lhsType->isPointerType() ||
7251       (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
7252     stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
7253   } else if (lhsType->isReferenceType()) {
7254     stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
7255   }
7256 
7257   if (!stackE)
7258     return; // Nothing suspicious was found.
7259 
7260   // Parameters are initalized in the calling scope, so taking the address
7261   // of a parameter reference doesn't need a warning.
7262   for (auto *DRE : refVars)
7263     if (isa<ParmVarDecl>(DRE->getDecl()))
7264       return;
7265 
7266   SourceLocation diagLoc;
7267   SourceRange diagRange;
7268   if (refVars.empty()) {
7269     diagLoc = stackE->getLocStart();
7270     diagRange = stackE->getSourceRange();
7271   } else {
7272     // We followed through a reference variable. 'stackE' contains the
7273     // problematic expression but we will warn at the return statement pointing
7274     // at the reference variable. We will later display the "trail" of
7275     // reference variables using notes.
7276     diagLoc = refVars[0]->getLocStart();
7277     diagRange = refVars[0]->getSourceRange();
7278   }
7279 
7280   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7281     // address of local var
7282     S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
7283      << DR->getDecl()->getDeclName() << diagRange;
7284   } else if (isa<BlockExpr>(stackE)) { // local block.
7285     S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
7286   } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
7287     S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
7288   } else { // local temporary.
7289     // If there is an LValue->RValue conversion, then the value of the
7290     // reference type is used, not the reference.
7291     if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7292       if (ICE->getCastKind() == CK_LValueToRValue) {
7293         return;
7294       }
7295     }
7296     S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7297      << lhsType->isReferenceType() << diagRange;
7298   }
7299 
7300   // Display the "trail" of reference variables that we followed until we
7301   // found the problematic expression using notes.
7302   for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
7303     const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
7304     // If this var binds to another reference var, show the range of the next
7305     // var, otherwise the var binds to the problematic expression, in which case
7306     // show the range of the expression.
7307     SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7308                                     : stackE->getSourceRange();
7309     S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7310         << VD->getDeclName() << range;
7311   }
7312 }
7313 
7314 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7315 ///  check if the expression in a return statement evaluates to an address
7316 ///  to a location on the stack, a local block, an address of a label, or a
7317 ///  reference to local temporary. The recursion is used to traverse the
7318 ///  AST of the return expression, with recursion backtracking when we
7319 ///  encounter a subexpression that (1) clearly does not lead to one of the
7320 ///  above problematic expressions (2) is something we cannot determine leads to
7321 ///  a problematic expression based on such local checking.
7322 ///
7323 ///  Both EvalAddr and EvalVal follow through reference variables to evaluate
7324 ///  the expression that they point to. Such variables are added to the
7325 ///  'refVars' vector so that we know what the reference variable "trail" was.
7326 ///
7327 ///  EvalAddr processes expressions that are pointers that are used as
7328 ///  references (and not L-values).  EvalVal handles all other values.
7329 ///  At the base case of the recursion is a check for the above problematic
7330 ///  expressions.
7331 ///
7332 ///  This implementation handles:
7333 ///
7334 ///   * pointer-to-pointer casts
7335 ///   * implicit conversions from array references to pointers
7336 ///   * taking the address of fields
7337 ///   * arbitrary interplay between "&" and "*" operators
7338 ///   * pointer arithmetic from an address of a stack variable
7339 ///   * taking the address of an array element where the array is on the stack
7340 static const Expr *EvalAddr(const Expr *E,
7341                             SmallVectorImpl<const DeclRefExpr *> &refVars,
7342                             const Decl *ParentDecl) {
7343   if (E->isTypeDependent())
7344     return nullptr;
7345 
7346   // We should only be called for evaluating pointer expressions.
7347   assert((E->getType()->isAnyPointerType() ||
7348           E->getType()->isBlockPointerType() ||
7349           E->getType()->isObjCQualifiedIdType()) &&
7350          "EvalAddr only works on pointers");
7351 
7352   E = E->IgnoreParens();
7353 
7354   // Our "symbolic interpreter" is just a dispatch off the currently
7355   // viewed AST node.  We then recursively traverse the AST by calling
7356   // EvalAddr and EvalVal appropriately.
7357   switch (E->getStmtClass()) {
7358   case Stmt::DeclRefExprClass: {
7359     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7360 
7361     // If we leave the immediate function, the lifetime isn't about to end.
7362     if (DR->refersToEnclosingVariableOrCapture())
7363       return nullptr;
7364 
7365     if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
7366       // If this is a reference variable, follow through to the expression that
7367       // it points to.
7368       if (V->hasLocalStorage() &&
7369           V->getType()->isReferenceType() && V->hasInit()) {
7370         // Add the reference variable to the "trail".
7371         refVars.push_back(DR);
7372         return EvalAddr(V->getInit(), refVars, ParentDecl);
7373       }
7374 
7375     return nullptr;
7376   }
7377 
7378   case Stmt::UnaryOperatorClass: {
7379     // The only unary operator that make sense to handle here
7380     // is AddrOf.  All others don't make sense as pointers.
7381     const UnaryOperator *U = cast<UnaryOperator>(E);
7382 
7383     if (U->getOpcode() == UO_AddrOf)
7384       return EvalVal(U->getSubExpr(), refVars, ParentDecl);
7385     return nullptr;
7386   }
7387 
7388   case Stmt::BinaryOperatorClass: {
7389     // Handle pointer arithmetic.  All other binary operators are not valid
7390     // in this context.
7391     const BinaryOperator *B = cast<BinaryOperator>(E);
7392     BinaryOperatorKind op = B->getOpcode();
7393 
7394     if (op != BO_Add && op != BO_Sub)
7395       return nullptr;
7396 
7397     const Expr *Base = B->getLHS();
7398 
7399     // Determine which argument is the real pointer base.  It could be
7400     // the RHS argument instead of the LHS.
7401     if (!Base->getType()->isPointerType())
7402       Base = B->getRHS();
7403 
7404     assert(Base->getType()->isPointerType());
7405     return EvalAddr(Base, refVars, ParentDecl);
7406   }
7407 
7408   // For conditional operators we need to see if either the LHS or RHS are
7409   // valid DeclRefExpr*s.  If one of them is valid, we return it.
7410   case Stmt::ConditionalOperatorClass: {
7411     const ConditionalOperator *C = cast<ConditionalOperator>(E);
7412 
7413     // Handle the GNU extension for missing LHS.
7414     // FIXME: That isn't a ConditionalOperator, so doesn't get here.
7415     if (const Expr *LHSExpr = C->getLHS()) {
7416       // In C++, we can have a throw-expression, which has 'void' type.
7417       if (!LHSExpr->getType()->isVoidType())
7418         if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
7419           return LHS;
7420     }
7421 
7422     // In C++, we can have a throw-expression, which has 'void' type.
7423     if (C->getRHS()->getType()->isVoidType())
7424       return nullptr;
7425 
7426     return EvalAddr(C->getRHS(), refVars, ParentDecl);
7427   }
7428 
7429   case Stmt::BlockExprClass:
7430     if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
7431       return E; // local block.
7432     return nullptr;
7433 
7434   case Stmt::AddrLabelExprClass:
7435     return E; // address of label.
7436 
7437   case Stmt::ExprWithCleanupsClass:
7438     return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7439                     ParentDecl);
7440 
7441   // For casts, we need to handle conversions from arrays to
7442   // pointer values, and pointer-to-pointer conversions.
7443   case Stmt::ImplicitCastExprClass:
7444   case Stmt::CStyleCastExprClass:
7445   case Stmt::CXXFunctionalCastExprClass:
7446   case Stmt::ObjCBridgedCastExprClass:
7447   case Stmt::CXXStaticCastExprClass:
7448   case Stmt::CXXDynamicCastExprClass:
7449   case Stmt::CXXConstCastExprClass:
7450   case Stmt::CXXReinterpretCastExprClass: {
7451     const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
7452     switch (cast<CastExpr>(E)->getCastKind()) {
7453     case CK_LValueToRValue:
7454     case CK_NoOp:
7455     case CK_BaseToDerived:
7456     case CK_DerivedToBase:
7457     case CK_UncheckedDerivedToBase:
7458     case CK_Dynamic:
7459     case CK_CPointerToObjCPointerCast:
7460     case CK_BlockPointerToObjCPointerCast:
7461     case CK_AnyPointerToBlockPointerCast:
7462       return EvalAddr(SubExpr, refVars, ParentDecl);
7463 
7464     case CK_ArrayToPointerDecay:
7465       return EvalVal(SubExpr, refVars, ParentDecl);
7466 
7467     case CK_BitCast:
7468       if (SubExpr->getType()->isAnyPointerType() ||
7469           SubExpr->getType()->isBlockPointerType() ||
7470           SubExpr->getType()->isObjCQualifiedIdType())
7471         return EvalAddr(SubExpr, refVars, ParentDecl);
7472       else
7473         return nullptr;
7474 
7475     default:
7476       return nullptr;
7477     }
7478   }
7479 
7480   case Stmt::MaterializeTemporaryExprClass:
7481     if (const Expr *Result =
7482             EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7483                      refVars, ParentDecl))
7484       return Result;
7485     return E;
7486 
7487   // Everything else: we simply don't reason about them.
7488   default:
7489     return nullptr;
7490   }
7491 }
7492 
7493 ///  EvalVal - This function is complements EvalAddr in the mutual recursion.
7494 ///   See the comments for EvalAddr for more details.
7495 static const Expr *EvalVal(const Expr *E,
7496                            SmallVectorImpl<const DeclRefExpr *> &refVars,
7497                            const Decl *ParentDecl) {
7498   do {
7499     // We should only be called for evaluating non-pointer expressions, or
7500     // expressions with a pointer type that are not used as references but
7501     // instead
7502     // are l-values (e.g., DeclRefExpr with a pointer type).
7503 
7504     // Our "symbolic interpreter" is just a dispatch off the currently
7505     // viewed AST node.  We then recursively traverse the AST by calling
7506     // EvalAddr and EvalVal appropriately.
7507 
7508     E = E->IgnoreParens();
7509     switch (E->getStmtClass()) {
7510     case Stmt::ImplicitCastExprClass: {
7511       const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
7512       if (IE->getValueKind() == VK_LValue) {
7513         E = IE->getSubExpr();
7514         continue;
7515       }
7516       return nullptr;
7517     }
7518 
7519     case Stmt::ExprWithCleanupsClass:
7520       return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7521                      ParentDecl);
7522 
7523     case Stmt::DeclRefExprClass: {
7524       // When we hit a DeclRefExpr we are looking at code that refers to a
7525       // variable's name. If it's not a reference variable we check if it has
7526       // local storage within the function, and if so, return the expression.
7527       const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7528 
7529       // If we leave the immediate function, the lifetime isn't about to end.
7530       if (DR->refersToEnclosingVariableOrCapture())
7531         return nullptr;
7532 
7533       if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
7534         // Check if it refers to itself, e.g. "int& i = i;".
7535         if (V == ParentDecl)
7536           return DR;
7537 
7538         if (V->hasLocalStorage()) {
7539           if (!V->getType()->isReferenceType())
7540             return DR;
7541 
7542           // Reference variable, follow through to the expression that
7543           // it points to.
7544           if (V->hasInit()) {
7545             // Add the reference variable to the "trail".
7546             refVars.push_back(DR);
7547             return EvalVal(V->getInit(), refVars, V);
7548           }
7549         }
7550       }
7551 
7552       return nullptr;
7553     }
7554 
7555     case Stmt::UnaryOperatorClass: {
7556       // The only unary operator that make sense to handle here
7557       // is Deref.  All others don't resolve to a "name."  This includes
7558       // handling all sorts of rvalues passed to a unary operator.
7559       const UnaryOperator *U = cast<UnaryOperator>(E);
7560 
7561       if (U->getOpcode() == UO_Deref)
7562         return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
7563 
7564       return nullptr;
7565     }
7566 
7567     case Stmt::ArraySubscriptExprClass: {
7568       // Array subscripts are potential references to data on the stack.  We
7569       // retrieve the DeclRefExpr* for the array variable if it indeed
7570       // has local storage.
7571       const auto *ASE = cast<ArraySubscriptExpr>(E);
7572       if (ASE->isTypeDependent())
7573         return nullptr;
7574       return EvalAddr(ASE->getBase(), refVars, ParentDecl);
7575     }
7576 
7577     case Stmt::OMPArraySectionExprClass: {
7578       return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
7579                       ParentDecl);
7580     }
7581 
7582     case Stmt::ConditionalOperatorClass: {
7583       // For conditional operators we need to see if either the LHS or RHS are
7584       // non-NULL Expr's.  If one is non-NULL, we return it.
7585       const ConditionalOperator *C = cast<ConditionalOperator>(E);
7586 
7587       // Handle the GNU extension for missing LHS.
7588       if (const Expr *LHSExpr = C->getLHS()) {
7589         // In C++, we can have a throw-expression, which has 'void' type.
7590         if (!LHSExpr->getType()->isVoidType())
7591           if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
7592             return LHS;
7593       }
7594 
7595       // In C++, we can have a throw-expression, which has 'void' type.
7596       if (C->getRHS()->getType()->isVoidType())
7597         return nullptr;
7598 
7599       return EvalVal(C->getRHS(), refVars, ParentDecl);
7600     }
7601 
7602     // Accesses to members are potential references to data on the stack.
7603     case Stmt::MemberExprClass: {
7604       const MemberExpr *M = cast<MemberExpr>(E);
7605 
7606       // Check for indirect access.  We only want direct field accesses.
7607       if (M->isArrow())
7608         return nullptr;
7609 
7610       // Check whether the member type is itself a reference, in which case
7611       // we're not going to refer to the member, but to what the member refers
7612       // to.
7613       if (M->getMemberDecl()->getType()->isReferenceType())
7614         return nullptr;
7615 
7616       return EvalVal(M->getBase(), refVars, ParentDecl);
7617     }
7618 
7619     case Stmt::MaterializeTemporaryExprClass:
7620       if (const Expr *Result =
7621               EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7622                       refVars, ParentDecl))
7623         return Result;
7624       return E;
7625 
7626     default:
7627       // Check that we don't return or take the address of a reference to a
7628       // temporary. This is only useful in C++.
7629       if (!E->isTypeDependent() && E->isRValue())
7630         return E;
7631 
7632       // Everything else: we simply don't reason about them.
7633       return nullptr;
7634     }
7635   } while (true);
7636 }
7637 
7638 void
7639 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
7640                          SourceLocation ReturnLoc,
7641                          bool isObjCMethod,
7642                          const AttrVec *Attrs,
7643                          const FunctionDecl *FD) {
7644   CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
7645 
7646   // Check if the return value is null but should not be.
7647   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
7648        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
7649       CheckNonNullExpr(*this, RetValExp))
7650     Diag(ReturnLoc, diag::warn_null_ret)
7651       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
7652 
7653   // C++11 [basic.stc.dynamic.allocation]p4:
7654   //   If an allocation function declared with a non-throwing
7655   //   exception-specification fails to allocate storage, it shall return
7656   //   a null pointer. Any other allocation function that fails to allocate
7657   //   storage shall indicate failure only by throwing an exception [...]
7658   if (FD) {
7659     OverloadedOperatorKind Op = FD->getOverloadedOperator();
7660     if (Op == OO_New || Op == OO_Array_New) {
7661       const FunctionProtoType *Proto
7662         = FD->getType()->castAs<FunctionProtoType>();
7663       if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
7664           CheckNonNullExpr(*this, RetValExp))
7665         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
7666           << FD << getLangOpts().CPlusPlus11;
7667     }
7668   }
7669 }
7670 
7671 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
7672 
7673 /// Check for comparisons of floating point operands using != and ==.
7674 /// Issue a warning if these are no self-comparisons, as they are not likely
7675 /// to do what the programmer intended.
7676 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
7677   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
7678   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
7679 
7680   // Special case: check for x == x (which is OK).
7681   // Do not emit warnings for such cases.
7682   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
7683     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
7684       if (DRL->getDecl() == DRR->getDecl())
7685         return;
7686 
7687   // Special case: check for comparisons against literals that can be exactly
7688   //  represented by APFloat.  In such cases, do not emit a warning.  This
7689   //  is a heuristic: often comparison against such literals are used to
7690   //  detect if a value in a variable has not changed.  This clearly can
7691   //  lead to false negatives.
7692   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
7693     if (FLL->isExact())
7694       return;
7695   } else
7696     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
7697       if (FLR->isExact())
7698         return;
7699 
7700   // Check for comparisons with builtin types.
7701   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
7702     if (CL->getBuiltinCallee())
7703       return;
7704 
7705   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
7706     if (CR->getBuiltinCallee())
7707       return;
7708 
7709   // Emit the diagnostic.
7710   Diag(Loc, diag::warn_floatingpoint_eq)
7711     << LHS->getSourceRange() << RHS->getSourceRange();
7712 }
7713 
7714 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
7715 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
7716 
7717 namespace {
7718 
7719 /// Structure recording the 'active' range of an integer-valued
7720 /// expression.
7721 struct IntRange {
7722   /// The number of bits active in the int.
7723   unsigned Width;
7724 
7725   /// True if the int is known not to have negative values.
7726   bool NonNegative;
7727 
7728   IntRange(unsigned Width, bool NonNegative)
7729     : Width(Width), NonNegative(NonNegative)
7730   {}
7731 
7732   /// Returns the range of the bool type.
7733   static IntRange forBoolType() {
7734     return IntRange(1, true);
7735   }
7736 
7737   /// Returns the range of an opaque value of the given integral type.
7738   static IntRange forValueOfType(ASTContext &C, QualType T) {
7739     return forValueOfCanonicalType(C,
7740                           T->getCanonicalTypeInternal().getTypePtr());
7741   }
7742 
7743   /// Returns the range of an opaque value of a canonical integral type.
7744   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
7745     assert(T->isCanonicalUnqualified());
7746 
7747     if (const VectorType *VT = dyn_cast<VectorType>(T))
7748       T = VT->getElementType().getTypePtr();
7749     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7750       T = CT->getElementType().getTypePtr();
7751     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7752       T = AT->getValueType().getTypePtr();
7753 
7754     // For enum types, use the known bit width of the enumerators.
7755     if (const EnumType *ET = dyn_cast<EnumType>(T)) {
7756       EnumDecl *Enum = ET->getDecl();
7757       if (!Enum->isCompleteDefinition())
7758         return IntRange(C.getIntWidth(QualType(T, 0)), false);
7759 
7760       unsigned NumPositive = Enum->getNumPositiveBits();
7761       unsigned NumNegative = Enum->getNumNegativeBits();
7762 
7763       if (NumNegative == 0)
7764         return IntRange(NumPositive, true/*NonNegative*/);
7765       else
7766         return IntRange(std::max(NumPositive + 1, NumNegative),
7767                         false/*NonNegative*/);
7768     }
7769 
7770     const BuiltinType *BT = cast<BuiltinType>(T);
7771     assert(BT->isInteger());
7772 
7773     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7774   }
7775 
7776   /// Returns the "target" range of a canonical integral type, i.e.
7777   /// the range of values expressible in the type.
7778   ///
7779   /// This matches forValueOfCanonicalType except that enums have the
7780   /// full range of their type, not the range of their enumerators.
7781   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
7782     assert(T->isCanonicalUnqualified());
7783 
7784     if (const VectorType *VT = dyn_cast<VectorType>(T))
7785       T = VT->getElementType().getTypePtr();
7786     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7787       T = CT->getElementType().getTypePtr();
7788     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7789       T = AT->getValueType().getTypePtr();
7790     if (const EnumType *ET = dyn_cast<EnumType>(T))
7791       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
7792 
7793     const BuiltinType *BT = cast<BuiltinType>(T);
7794     assert(BT->isInteger());
7795 
7796     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7797   }
7798 
7799   /// Returns the supremum of two ranges: i.e. their conservative merge.
7800   static IntRange join(IntRange L, IntRange R) {
7801     return IntRange(std::max(L.Width, R.Width),
7802                     L.NonNegative && R.NonNegative);
7803   }
7804 
7805   /// Returns the infinum of two ranges: i.e. their aggressive merge.
7806   static IntRange meet(IntRange L, IntRange R) {
7807     return IntRange(std::min(L.Width, R.Width),
7808                     L.NonNegative || R.NonNegative);
7809   }
7810 };
7811 
7812 IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
7813   if (value.isSigned() && value.isNegative())
7814     return IntRange(value.getMinSignedBits(), false);
7815 
7816   if (value.getBitWidth() > MaxWidth)
7817     value = value.trunc(MaxWidth);
7818 
7819   // isNonNegative() just checks the sign bit without considering
7820   // signedness.
7821   return IntRange(value.getActiveBits(), true);
7822 }
7823 
7824 IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
7825                        unsigned MaxWidth) {
7826   if (result.isInt())
7827     return GetValueRange(C, result.getInt(), MaxWidth);
7828 
7829   if (result.isVector()) {
7830     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
7831     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
7832       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
7833       R = IntRange::join(R, El);
7834     }
7835     return R;
7836   }
7837 
7838   if (result.isComplexInt()) {
7839     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
7840     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
7841     return IntRange::join(R, I);
7842   }
7843 
7844   // This can happen with lossless casts to intptr_t of "based" lvalues.
7845   // Assume it might use arbitrary bits.
7846   // FIXME: The only reason we need to pass the type in here is to get
7847   // the sign right on this one case.  It would be nice if APValue
7848   // preserved this.
7849   assert(result.isLValue() || result.isAddrLabelDiff());
7850   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
7851 }
7852 
7853 QualType GetExprType(const Expr *E) {
7854   QualType Ty = E->getType();
7855   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
7856     Ty = AtomicRHS->getValueType();
7857   return Ty;
7858 }
7859 
7860 /// Pseudo-evaluate the given integer expression, estimating the
7861 /// range of values it might take.
7862 ///
7863 /// \param MaxWidth - the width to which the value will be truncated
7864 IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
7865   E = E->IgnoreParens();
7866 
7867   // Try a full evaluation first.
7868   Expr::EvalResult result;
7869   if (E->EvaluateAsRValue(result, C))
7870     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
7871 
7872   // I think we only want to look through implicit casts here; if the
7873   // user has an explicit widening cast, we should treat the value as
7874   // being of the new, wider type.
7875   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
7876     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
7877       return GetExprRange(C, CE->getSubExpr(), MaxWidth);
7878 
7879     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
7880 
7881     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
7882                          CE->getCastKind() == CK_BooleanToSignedIntegral;
7883 
7884     // Assume that non-integer casts can span the full range of the type.
7885     if (!isIntegerCast)
7886       return OutputTypeRange;
7887 
7888     IntRange SubRange
7889       = GetExprRange(C, CE->getSubExpr(),
7890                      std::min(MaxWidth, OutputTypeRange.Width));
7891 
7892     // Bail out if the subexpr's range is as wide as the cast type.
7893     if (SubRange.Width >= OutputTypeRange.Width)
7894       return OutputTypeRange;
7895 
7896     // Otherwise, we take the smaller width, and we're non-negative if
7897     // either the output type or the subexpr is.
7898     return IntRange(SubRange.Width,
7899                     SubRange.NonNegative || OutputTypeRange.NonNegative);
7900   }
7901 
7902   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
7903     // If we can fold the condition, just take that operand.
7904     bool CondResult;
7905     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
7906       return GetExprRange(C, CondResult ? CO->getTrueExpr()
7907                                         : CO->getFalseExpr(),
7908                           MaxWidth);
7909 
7910     // Otherwise, conservatively merge.
7911     IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
7912     IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
7913     return IntRange::join(L, R);
7914   }
7915 
7916   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
7917     switch (BO->getOpcode()) {
7918 
7919     // Boolean-valued operations are single-bit and positive.
7920     case BO_LAnd:
7921     case BO_LOr:
7922     case BO_LT:
7923     case BO_GT:
7924     case BO_LE:
7925     case BO_GE:
7926     case BO_EQ:
7927     case BO_NE:
7928       return IntRange::forBoolType();
7929 
7930     // The type of the assignments is the type of the LHS, so the RHS
7931     // is not necessarily the same type.
7932     case BO_MulAssign:
7933     case BO_DivAssign:
7934     case BO_RemAssign:
7935     case BO_AddAssign:
7936     case BO_SubAssign:
7937     case BO_XorAssign:
7938     case BO_OrAssign:
7939       // TODO: bitfields?
7940       return IntRange::forValueOfType(C, GetExprType(E));
7941 
7942     // Simple assignments just pass through the RHS, which will have
7943     // been coerced to the LHS type.
7944     case BO_Assign:
7945       // TODO: bitfields?
7946       return GetExprRange(C, BO->getRHS(), MaxWidth);
7947 
7948     // Operations with opaque sources are black-listed.
7949     case BO_PtrMemD:
7950     case BO_PtrMemI:
7951       return IntRange::forValueOfType(C, GetExprType(E));
7952 
7953     // Bitwise-and uses the *infinum* of the two source ranges.
7954     case BO_And:
7955     case BO_AndAssign:
7956       return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
7957                             GetExprRange(C, BO->getRHS(), MaxWidth));
7958 
7959     // Left shift gets black-listed based on a judgement call.
7960     case BO_Shl:
7961       // ...except that we want to treat '1 << (blah)' as logically
7962       // positive.  It's an important idiom.
7963       if (IntegerLiteral *I
7964             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
7965         if (I->getValue() == 1) {
7966           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
7967           return IntRange(R.Width, /*NonNegative*/ true);
7968         }
7969       }
7970       // fallthrough
7971 
7972     case BO_ShlAssign:
7973       return IntRange::forValueOfType(C, GetExprType(E));
7974 
7975     // Right shift by a constant can narrow its left argument.
7976     case BO_Shr:
7977     case BO_ShrAssign: {
7978       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
7979 
7980       // If the shift amount is a positive constant, drop the width by
7981       // that much.
7982       llvm::APSInt shift;
7983       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
7984           shift.isNonNegative()) {
7985         unsigned zext = shift.getZExtValue();
7986         if (zext >= L.Width)
7987           L.Width = (L.NonNegative ? 0 : 1);
7988         else
7989           L.Width -= zext;
7990       }
7991 
7992       return L;
7993     }
7994 
7995     // Comma acts as its right operand.
7996     case BO_Comma:
7997       return GetExprRange(C, BO->getRHS(), MaxWidth);
7998 
7999     // Black-list pointer subtractions.
8000     case BO_Sub:
8001       if (BO->getLHS()->getType()->isPointerType())
8002         return IntRange::forValueOfType(C, GetExprType(E));
8003       break;
8004 
8005     // The width of a division result is mostly determined by the size
8006     // of the LHS.
8007     case BO_Div: {
8008       // Don't 'pre-truncate' the operands.
8009       unsigned opWidth = C.getIntWidth(GetExprType(E));
8010       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8011 
8012       // If the divisor is constant, use that.
8013       llvm::APSInt divisor;
8014       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8015         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8016         if (log2 >= L.Width)
8017           L.Width = (L.NonNegative ? 0 : 1);
8018         else
8019           L.Width = std::min(L.Width - log2, MaxWidth);
8020         return L;
8021       }
8022 
8023       // Otherwise, just use the LHS's width.
8024       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8025       return IntRange(L.Width, L.NonNegative && R.NonNegative);
8026     }
8027 
8028     // The result of a remainder can't be larger than the result of
8029     // either side.
8030     case BO_Rem: {
8031       // Don't 'pre-truncate' the operands.
8032       unsigned opWidth = C.getIntWidth(GetExprType(E));
8033       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8034       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8035 
8036       IntRange meet = IntRange::meet(L, R);
8037       meet.Width = std::min(meet.Width, MaxWidth);
8038       return meet;
8039     }
8040 
8041     // The default behavior is okay for these.
8042     case BO_Mul:
8043     case BO_Add:
8044     case BO_Xor:
8045     case BO_Or:
8046       break;
8047     }
8048 
8049     // The default case is to treat the operation as if it were closed
8050     // on the narrowest type that encompasses both operands.
8051     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8052     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8053     return IntRange::join(L, R);
8054   }
8055 
8056   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
8057     switch (UO->getOpcode()) {
8058     // Boolean-valued operations are white-listed.
8059     case UO_LNot:
8060       return IntRange::forBoolType();
8061 
8062     // Operations with opaque sources are black-listed.
8063     case UO_Deref:
8064     case UO_AddrOf: // should be impossible
8065       return IntRange::forValueOfType(C, GetExprType(E));
8066 
8067     default:
8068       return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8069     }
8070   }
8071 
8072   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
8073     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8074 
8075   if (const auto *BitField = E->getSourceBitField())
8076     return IntRange(BitField->getBitWidthValue(C),
8077                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
8078 
8079   return IntRange::forValueOfType(C, GetExprType(E));
8080 }
8081 
8082 IntRange GetExprRange(ASTContext &C, const Expr *E) {
8083   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
8084 }
8085 
8086 /// Checks whether the given value, which currently has the given
8087 /// source semantics, has the same value when coerced through the
8088 /// target semantics.
8089 bool IsSameFloatAfterCast(const llvm::APFloat &value,
8090                           const llvm::fltSemantics &Src,
8091                           const llvm::fltSemantics &Tgt) {
8092   llvm::APFloat truncated = value;
8093 
8094   bool ignored;
8095   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8096   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8097 
8098   return truncated.bitwiseIsEqual(value);
8099 }
8100 
8101 /// Checks whether the given value, which currently has the given
8102 /// source semantics, has the same value when coerced through the
8103 /// target semantics.
8104 ///
8105 /// The value might be a vector of floats (or a complex number).
8106 bool IsSameFloatAfterCast(const APValue &value,
8107                           const llvm::fltSemantics &Src,
8108                           const llvm::fltSemantics &Tgt) {
8109   if (value.isFloat())
8110     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8111 
8112   if (value.isVector()) {
8113     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8114       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8115         return false;
8116     return true;
8117   }
8118 
8119   assert(value.isComplexFloat());
8120   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8121           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8122 }
8123 
8124 void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
8125 
8126 bool IsZero(Sema &S, Expr *E) {
8127   // Suppress cases where we are comparing against an enum constant.
8128   if (const DeclRefExpr *DR =
8129       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8130     if (isa<EnumConstantDecl>(DR->getDecl()))
8131       return false;
8132 
8133   // Suppress cases where the '0' value is expanded from a macro.
8134   if (E->getLocStart().isMacroID())
8135     return false;
8136 
8137   llvm::APSInt Value;
8138   return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
8139 }
8140 
8141 bool HasEnumType(Expr *E) {
8142   // Strip off implicit integral promotions.
8143   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8144     if (ICE->getCastKind() != CK_IntegralCast &&
8145         ICE->getCastKind() != CK_NoOp)
8146       break;
8147     E = ICE->getSubExpr();
8148   }
8149 
8150   return E->getType()->isEnumeralType();
8151 }
8152 
8153 void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
8154   // Disable warning in template instantiations.
8155   if (!S.ActiveTemplateInstantiations.empty())
8156     return;
8157 
8158   BinaryOperatorKind op = E->getOpcode();
8159   if (E->isValueDependent())
8160     return;
8161 
8162   if (op == BO_LT && IsZero(S, E->getRHS())) {
8163     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
8164       << "< 0" << "false" << HasEnumType(E->getLHS())
8165       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8166   } else if (op == BO_GE && IsZero(S, E->getRHS())) {
8167     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
8168       << ">= 0" << "true" << HasEnumType(E->getLHS())
8169       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8170   } else if (op == BO_GT && IsZero(S, E->getLHS())) {
8171     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
8172       << "0 >" << "false" << HasEnumType(E->getRHS())
8173       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8174   } else if (op == BO_LE && IsZero(S, E->getLHS())) {
8175     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
8176       << "0 <=" << "true" << HasEnumType(E->getRHS())
8177       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8178   }
8179 }
8180 
8181 void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
8182                                   Expr *Other, const llvm::APSInt &Value,
8183                                   bool RhsConstant) {
8184   // Disable warning in template instantiations.
8185   if (!S.ActiveTemplateInstantiations.empty())
8186     return;
8187 
8188   // TODO: Investigate using GetExprRange() to get tighter bounds
8189   // on the bit ranges.
8190   QualType OtherT = Other->getType();
8191   if (const auto *AT = OtherT->getAs<AtomicType>())
8192     OtherT = AT->getValueType();
8193   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8194   unsigned OtherWidth = OtherRange.Width;
8195 
8196   bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
8197 
8198   // 0 values are handled later by CheckTrivialUnsignedComparison().
8199   if ((Value == 0) && (!OtherIsBooleanType))
8200     return;
8201 
8202   BinaryOperatorKind op = E->getOpcode();
8203   bool IsTrue = true;
8204 
8205   // Used for diagnostic printout.
8206   enum {
8207     LiteralConstant = 0,
8208     CXXBoolLiteralTrue,
8209     CXXBoolLiteralFalse
8210   } LiteralOrBoolConstant = LiteralConstant;
8211 
8212   if (!OtherIsBooleanType) {
8213     QualType ConstantT = Constant->getType();
8214     QualType CommonT = E->getLHS()->getType();
8215 
8216     if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
8217       return;
8218     assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
8219            "comparison with non-integer type");
8220 
8221     bool ConstantSigned = ConstantT->isSignedIntegerType();
8222     bool CommonSigned = CommonT->isSignedIntegerType();
8223 
8224     bool EqualityOnly = false;
8225 
8226     if (CommonSigned) {
8227       // The common type is signed, therefore no signed to unsigned conversion.
8228       if (!OtherRange.NonNegative) {
8229         // Check that the constant is representable in type OtherT.
8230         if (ConstantSigned) {
8231           if (OtherWidth >= Value.getMinSignedBits())
8232             return;
8233         } else { // !ConstantSigned
8234           if (OtherWidth >= Value.getActiveBits() + 1)
8235             return;
8236         }
8237       } else { // !OtherSigned
8238                // Check that the constant is representable in type OtherT.
8239         // Negative values are out of range.
8240         if (ConstantSigned) {
8241           if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
8242             return;
8243         } else { // !ConstantSigned
8244           if (OtherWidth >= Value.getActiveBits())
8245             return;
8246         }
8247       }
8248     } else { // !CommonSigned
8249       if (OtherRange.NonNegative) {
8250         if (OtherWidth >= Value.getActiveBits())
8251           return;
8252       } else { // OtherSigned
8253         assert(!ConstantSigned &&
8254                "Two signed types converted to unsigned types.");
8255         // Check to see if the constant is representable in OtherT.
8256         if (OtherWidth > Value.getActiveBits())
8257           return;
8258         // Check to see if the constant is equivalent to a negative value
8259         // cast to CommonT.
8260         if (S.Context.getIntWidth(ConstantT) ==
8261                 S.Context.getIntWidth(CommonT) &&
8262             Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
8263           return;
8264         // The constant value rests between values that OtherT can represent
8265         // after conversion.  Relational comparison still works, but equality
8266         // comparisons will be tautological.
8267         EqualityOnly = true;
8268       }
8269     }
8270 
8271     bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
8272 
8273     if (op == BO_EQ || op == BO_NE) {
8274       IsTrue = op == BO_NE;
8275     } else if (EqualityOnly) {
8276       return;
8277     } else if (RhsConstant) {
8278       if (op == BO_GT || op == BO_GE)
8279         IsTrue = !PositiveConstant;
8280       else // op == BO_LT || op == BO_LE
8281         IsTrue = PositiveConstant;
8282     } else {
8283       if (op == BO_LT || op == BO_LE)
8284         IsTrue = !PositiveConstant;
8285       else // op == BO_GT || op == BO_GE
8286         IsTrue = PositiveConstant;
8287     }
8288   } else {
8289     // Other isKnownToHaveBooleanValue
8290     enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
8291     enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
8292     enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
8293 
8294     static const struct LinkedConditions {
8295       CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
8296       CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
8297       CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
8298       CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
8299       CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
8300       CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
8301 
8302     } TruthTable = {
8303         // Constant on LHS.              | Constant on RHS.              |
8304         // LT_Zero| Zero  | One   |GT_One| LT_Zero| Zero  | One   |GT_One|
8305         { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
8306         { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
8307         { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
8308         { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
8309         { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
8310         { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
8311       };
8312 
8313     bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
8314 
8315     enum ConstantValue ConstVal = Zero;
8316     if (Value.isUnsigned() || Value.isNonNegative()) {
8317       if (Value == 0) {
8318         LiteralOrBoolConstant =
8319             ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
8320         ConstVal = Zero;
8321       } else if (Value == 1) {
8322         LiteralOrBoolConstant =
8323             ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
8324         ConstVal = One;
8325       } else {
8326         LiteralOrBoolConstant = LiteralConstant;
8327         ConstVal = GT_One;
8328       }
8329     } else {
8330       ConstVal = LT_Zero;
8331     }
8332 
8333     CompareBoolWithConstantResult CmpRes;
8334 
8335     switch (op) {
8336     case BO_LT:
8337       CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
8338       break;
8339     case BO_GT:
8340       CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
8341       break;
8342     case BO_LE:
8343       CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
8344       break;
8345     case BO_GE:
8346       CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
8347       break;
8348     case BO_EQ:
8349       CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
8350       break;
8351     case BO_NE:
8352       CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
8353       break;
8354     default:
8355       CmpRes = Unkwn;
8356       break;
8357     }
8358 
8359     if (CmpRes == AFals) {
8360       IsTrue = false;
8361     } else if (CmpRes == ATrue) {
8362       IsTrue = true;
8363     } else {
8364       return;
8365     }
8366   }
8367 
8368   // If this is a comparison to an enum constant, include that
8369   // constant in the diagnostic.
8370   const EnumConstantDecl *ED = nullptr;
8371   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8372     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8373 
8374   SmallString<64> PrettySourceValue;
8375   llvm::raw_svector_ostream OS(PrettySourceValue);
8376   if (ED)
8377     OS << '\'' << *ED << "' (" << Value << ")";
8378   else
8379     OS << Value;
8380 
8381   S.DiagRuntimeBehavior(
8382     E->getOperatorLoc(), E,
8383     S.PDiag(diag::warn_out_of_range_compare)
8384         << OS.str() << LiteralOrBoolConstant
8385         << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
8386         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
8387 }
8388 
8389 /// Analyze the operands of the given comparison.  Implements the
8390 /// fallback case from AnalyzeComparison.
8391 void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
8392   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8393   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8394 }
8395 
8396 /// \brief Implements -Wsign-compare.
8397 ///
8398 /// \param E the binary operator to check for warnings
8399 void AnalyzeComparison(Sema &S, BinaryOperator *E) {
8400   // The type the comparison is being performed in.
8401   QualType T = E->getLHS()->getType();
8402 
8403   // Only analyze comparison operators where both sides have been converted to
8404   // the same type.
8405   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8406     return AnalyzeImpConvsInComparison(S, E);
8407 
8408   // Don't analyze value-dependent comparisons directly.
8409   if (E->isValueDependent())
8410     return AnalyzeImpConvsInComparison(S, E);
8411 
8412   Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
8413   Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
8414 
8415   bool IsComparisonConstant = false;
8416 
8417   // Check whether an integer constant comparison results in a value
8418   // of 'true' or 'false'.
8419   if (T->isIntegralType(S.Context)) {
8420     llvm::APSInt RHSValue;
8421     bool IsRHSIntegralLiteral =
8422       RHS->isIntegerConstantExpr(RHSValue, S.Context);
8423     llvm::APSInt LHSValue;
8424     bool IsLHSIntegralLiteral =
8425       LHS->isIntegerConstantExpr(LHSValue, S.Context);
8426     if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
8427         DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
8428     else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8429       DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
8430     else
8431       IsComparisonConstant =
8432         (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
8433   } else if (!T->hasUnsignedIntegerRepresentation())
8434       IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
8435 
8436   // We don't do anything special if this isn't an unsigned integral
8437   // comparison:  we're only interested in integral comparisons, and
8438   // signed comparisons only happen in cases we don't care to warn about.
8439   //
8440   // We also don't care about value-dependent expressions or expressions
8441   // whose result is a constant.
8442   if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
8443     return AnalyzeImpConvsInComparison(S, E);
8444 
8445   // Check to see if one of the (unmodified) operands is of different
8446   // signedness.
8447   Expr *signedOperand, *unsignedOperand;
8448   if (LHS->getType()->hasSignedIntegerRepresentation()) {
8449     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
8450            "unsigned comparison between two signed integer expressions?");
8451     signedOperand = LHS;
8452     unsignedOperand = RHS;
8453   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
8454     signedOperand = RHS;
8455     unsignedOperand = LHS;
8456   } else {
8457     CheckTrivialUnsignedComparison(S, E);
8458     return AnalyzeImpConvsInComparison(S, E);
8459   }
8460 
8461   // Otherwise, calculate the effective range of the signed operand.
8462   IntRange signedRange = GetExprRange(S.Context, signedOperand);
8463 
8464   // Go ahead and analyze implicit conversions in the operands.  Note
8465   // that we skip the implicit conversions on both sides.
8466   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
8467   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
8468 
8469   // If the signed range is non-negative, -Wsign-compare won't fire,
8470   // but we should still check for comparisons which are always true
8471   // or false.
8472   if (signedRange.NonNegative)
8473     return CheckTrivialUnsignedComparison(S, E);
8474 
8475   // For (in)equality comparisons, if the unsigned operand is a
8476   // constant which cannot collide with a overflowed signed operand,
8477   // then reinterpreting the signed operand as unsigned will not
8478   // change the result of the comparison.
8479   if (E->isEqualityOp()) {
8480     unsigned comparisonWidth = S.Context.getIntWidth(T);
8481     IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
8482 
8483     // We should never be unable to prove that the unsigned operand is
8484     // non-negative.
8485     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
8486 
8487     if (unsignedRange.Width < comparisonWidth)
8488       return;
8489   }
8490 
8491   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
8492     S.PDiag(diag::warn_mixed_sign_comparison)
8493       << LHS->getType() << RHS->getType()
8494       << LHS->getSourceRange() << RHS->getSourceRange());
8495 }
8496 
8497 /// Analyzes an attempt to assign the given value to a bitfield.
8498 ///
8499 /// Returns true if there was something fishy about the attempt.
8500 bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
8501                                SourceLocation InitLoc) {
8502   assert(Bitfield->isBitField());
8503   if (Bitfield->isInvalidDecl())
8504     return false;
8505 
8506   // White-list bool bitfields.
8507   if (Bitfield->getType()->isBooleanType())
8508     return false;
8509 
8510   // Ignore value- or type-dependent expressions.
8511   if (Bitfield->getBitWidth()->isValueDependent() ||
8512       Bitfield->getBitWidth()->isTypeDependent() ||
8513       Init->isValueDependent() ||
8514       Init->isTypeDependent())
8515     return false;
8516 
8517   Expr *OriginalInit = Init->IgnoreParenImpCasts();
8518 
8519   llvm::APSInt Value;
8520   if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
8521     return false;
8522 
8523   unsigned OriginalWidth = Value.getBitWidth();
8524   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
8525 
8526   if (!Value.isSigned() || Value.isNegative())
8527     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
8528       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
8529         OriginalWidth = Value.getMinSignedBits();
8530 
8531   if (OriginalWidth <= FieldWidth)
8532     return false;
8533 
8534   // Compute the value which the bitfield will contain.
8535   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
8536   TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
8537 
8538   // Check whether the stored value is equal to the original value.
8539   TruncatedValue = TruncatedValue.extend(OriginalWidth);
8540   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
8541     return false;
8542 
8543   // Special-case bitfields of width 1: booleans are naturally 0/1, and
8544   // therefore don't strictly fit into a signed bitfield of width 1.
8545   if (FieldWidth == 1 && Value == 1)
8546     return false;
8547 
8548   std::string PrettyValue = Value.toString(10);
8549   std::string PrettyTrunc = TruncatedValue.toString(10);
8550 
8551   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
8552     << PrettyValue << PrettyTrunc << OriginalInit->getType()
8553     << Init->getSourceRange();
8554 
8555   return true;
8556 }
8557 
8558 /// Analyze the given simple or compound assignment for warning-worthy
8559 /// operations.
8560 void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
8561   // Just recurse on the LHS.
8562   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8563 
8564   // We want to recurse on the RHS as normal unless we're assigning to
8565   // a bitfield.
8566   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
8567     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
8568                                   E->getOperatorLoc())) {
8569       // Recurse, ignoring any implicit conversions on the RHS.
8570       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
8571                                         E->getOperatorLoc());
8572     }
8573   }
8574 
8575   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8576 }
8577 
8578 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
8579 void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
8580                      SourceLocation CContext, unsigned diag,
8581                      bool pruneControlFlow = false) {
8582   if (pruneControlFlow) {
8583     S.DiagRuntimeBehavior(E->getExprLoc(), E,
8584                           S.PDiag(diag)
8585                             << SourceType << T << E->getSourceRange()
8586                             << SourceRange(CContext));
8587     return;
8588   }
8589   S.Diag(E->getExprLoc(), diag)
8590     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
8591 }
8592 
8593 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
8594 void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
8595                      unsigned diag, bool pruneControlFlow = false) {
8596   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
8597 }
8598 
8599 
8600 /// Diagnose an implicit cast from a floating point value to an integer value.
8601 void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
8602 
8603                              SourceLocation CContext) {
8604   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
8605   const bool PruneWarnings = !S.ActiveTemplateInstantiations.empty();
8606 
8607   Expr *InnerE = E->IgnoreParenImpCasts();
8608   // We also want to warn on, e.g., "int i = -1.234"
8609   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
8610     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
8611       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
8612 
8613   const bool IsLiteral =
8614       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
8615 
8616   llvm::APFloat Value(0.0);
8617   bool IsConstant =
8618     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
8619   if (!IsConstant) {
8620     return DiagnoseImpCast(S, E, T, CContext,
8621                            diag::warn_impcast_float_integer, PruneWarnings);
8622   }
8623 
8624   bool isExact = false;
8625 
8626   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
8627                             T->hasUnsignedIntegerRepresentation());
8628   if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
8629                              &isExact) == llvm::APFloat::opOK &&
8630       isExact) {
8631     if (IsLiteral) return;
8632     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
8633                            PruneWarnings);
8634   }
8635 
8636   unsigned DiagID = 0;
8637   if (IsLiteral) {
8638     // Warn on floating point literal to integer.
8639     DiagID = diag::warn_impcast_literal_float_to_integer;
8640   } else if (IntegerValue == 0) {
8641     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
8642       return DiagnoseImpCast(S, E, T, CContext,
8643                              diag::warn_impcast_float_integer, PruneWarnings);
8644     }
8645     // Warn on non-zero to zero conversion.
8646     DiagID = diag::warn_impcast_float_to_integer_zero;
8647   } else {
8648     if (IntegerValue.isUnsigned()) {
8649       if (!IntegerValue.isMaxValue()) {
8650         return DiagnoseImpCast(S, E, T, CContext,
8651                                diag::warn_impcast_float_integer, PruneWarnings);
8652       }
8653     } else {  // IntegerValue.isSigned()
8654       if (!IntegerValue.isMaxSignedValue() &&
8655           !IntegerValue.isMinSignedValue()) {
8656         return DiagnoseImpCast(S, E, T, CContext,
8657                                diag::warn_impcast_float_integer, PruneWarnings);
8658       }
8659     }
8660     // Warn on evaluatable floating point expression to integer conversion.
8661     DiagID = diag::warn_impcast_float_to_integer;
8662   }
8663 
8664   // FIXME: Force the precision of the source value down so we don't print
8665   // digits which are usually useless (we don't really care here if we
8666   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
8667   // would automatically print the shortest representation, but it's a bit
8668   // tricky to implement.
8669   SmallString<16> PrettySourceValue;
8670   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
8671   precision = (precision * 59 + 195) / 196;
8672   Value.toString(PrettySourceValue, precision);
8673 
8674   SmallString<16> PrettyTargetValue;
8675   if (IsBool)
8676     PrettyTargetValue = Value.isZero() ? "false" : "true";
8677   else
8678     IntegerValue.toString(PrettyTargetValue);
8679 
8680   if (PruneWarnings) {
8681     S.DiagRuntimeBehavior(E->getExprLoc(), E,
8682                           S.PDiag(DiagID)
8683                               << E->getType() << T.getUnqualifiedType()
8684                               << PrettySourceValue << PrettyTargetValue
8685                               << E->getSourceRange() << SourceRange(CContext));
8686   } else {
8687     S.Diag(E->getExprLoc(), DiagID)
8688         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
8689         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
8690   }
8691 }
8692 
8693 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
8694   if (!Range.Width) return "0";
8695 
8696   llvm::APSInt ValueInRange = Value;
8697   ValueInRange.setIsSigned(!Range.NonNegative);
8698   ValueInRange = ValueInRange.trunc(Range.Width);
8699   return ValueInRange.toString(10);
8700 }
8701 
8702 bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
8703   if (!isa<ImplicitCastExpr>(Ex))
8704     return false;
8705 
8706   Expr *InnerE = Ex->IgnoreParenImpCasts();
8707   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
8708   const Type *Source =
8709     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
8710   if (Target->isDependentType())
8711     return false;
8712 
8713   const BuiltinType *FloatCandidateBT =
8714     dyn_cast<BuiltinType>(ToBool ? Source : Target);
8715   const Type *BoolCandidateType = ToBool ? Target : Source;
8716 
8717   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
8718           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
8719 }
8720 
8721 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
8722                                       SourceLocation CC) {
8723   unsigned NumArgs = TheCall->getNumArgs();
8724   for (unsigned i = 0; i < NumArgs; ++i) {
8725     Expr *CurrA = TheCall->getArg(i);
8726     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
8727       continue;
8728 
8729     bool IsSwapped = ((i > 0) &&
8730         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
8731     IsSwapped |= ((i < (NumArgs - 1)) &&
8732         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
8733     if (IsSwapped) {
8734       // Warn on this floating-point to bool conversion.
8735       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
8736                       CurrA->getType(), CC,
8737                       diag::warn_impcast_floating_point_to_bool);
8738     }
8739   }
8740 }
8741 
8742 void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
8743   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
8744                         E->getExprLoc()))
8745     return;
8746 
8747   // Don't warn on functions which have return type nullptr_t.
8748   if (isa<CallExpr>(E))
8749     return;
8750 
8751   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
8752   const Expr::NullPointerConstantKind NullKind =
8753       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
8754   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
8755     return;
8756 
8757   // Return if target type is a safe conversion.
8758   if (T->isAnyPointerType() || T->isBlockPointerType() ||
8759       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
8760     return;
8761 
8762   SourceLocation Loc = E->getSourceRange().getBegin();
8763 
8764   // Venture through the macro stacks to get to the source of macro arguments.
8765   // The new location is a better location than the complete location that was
8766   // passed in.
8767   while (S.SourceMgr.isMacroArgExpansion(Loc))
8768     Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
8769 
8770   while (S.SourceMgr.isMacroArgExpansion(CC))
8771     CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
8772 
8773   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
8774   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
8775     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
8776         Loc, S.SourceMgr, S.getLangOpts());
8777     if (MacroName == "NULL")
8778       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
8779   }
8780 
8781   // Only warn if the null and context location are in the same macro expansion.
8782   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
8783     return;
8784 
8785   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
8786       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
8787       << FixItHint::CreateReplacement(Loc,
8788                                       S.getFixItZeroLiteralForType(T, Loc));
8789 }
8790 
8791 void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8792                            ObjCArrayLiteral *ArrayLiteral);
8793 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8794                                 ObjCDictionaryLiteral *DictionaryLiteral);
8795 
8796 /// Check a single element within a collection literal against the
8797 /// target element type.
8798 void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
8799                                        Expr *Element, unsigned ElementKind) {
8800   // Skip a bitcast to 'id' or qualified 'id'.
8801   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
8802     if (ICE->getCastKind() == CK_BitCast &&
8803         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
8804       Element = ICE->getSubExpr();
8805   }
8806 
8807   QualType ElementType = Element->getType();
8808   ExprResult ElementResult(Element);
8809   if (ElementType->getAs<ObjCObjectPointerType>() &&
8810       S.CheckSingleAssignmentConstraints(TargetElementType,
8811                                          ElementResult,
8812                                          false, false)
8813         != Sema::Compatible) {
8814     S.Diag(Element->getLocStart(),
8815            diag::warn_objc_collection_literal_element)
8816       << ElementType << ElementKind << TargetElementType
8817       << Element->getSourceRange();
8818   }
8819 
8820   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
8821     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
8822   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
8823     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
8824 }
8825 
8826 /// Check an Objective-C array literal being converted to the given
8827 /// target type.
8828 void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8829                            ObjCArrayLiteral *ArrayLiteral) {
8830   if (!S.NSArrayDecl)
8831     return;
8832 
8833   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8834   if (!TargetObjCPtr)
8835     return;
8836 
8837   if (TargetObjCPtr->isUnspecialized() ||
8838       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8839         != S.NSArrayDecl->getCanonicalDecl())
8840     return;
8841 
8842   auto TypeArgs = TargetObjCPtr->getTypeArgs();
8843   if (TypeArgs.size() != 1)
8844     return;
8845 
8846   QualType TargetElementType = TypeArgs[0];
8847   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
8848     checkObjCCollectionLiteralElement(S, TargetElementType,
8849                                       ArrayLiteral->getElement(I),
8850                                       0);
8851   }
8852 }
8853 
8854 /// Check an Objective-C dictionary literal being converted to the given
8855 /// target type.
8856 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8857                                 ObjCDictionaryLiteral *DictionaryLiteral) {
8858   if (!S.NSDictionaryDecl)
8859     return;
8860 
8861   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8862   if (!TargetObjCPtr)
8863     return;
8864 
8865   if (TargetObjCPtr->isUnspecialized() ||
8866       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8867         != S.NSDictionaryDecl->getCanonicalDecl())
8868     return;
8869 
8870   auto TypeArgs = TargetObjCPtr->getTypeArgs();
8871   if (TypeArgs.size() != 2)
8872     return;
8873 
8874   QualType TargetKeyType = TypeArgs[0];
8875   QualType TargetObjectType = TypeArgs[1];
8876   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
8877     auto Element = DictionaryLiteral->getKeyValueElement(I);
8878     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
8879     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
8880   }
8881 }
8882 
8883 // Helper function to filter out cases for constant width constant conversion.
8884 // Don't warn on char array initialization or for non-decimal values.
8885 bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
8886                                    SourceLocation CC) {
8887   // If initializing from a constant, and the constant starts with '0',
8888   // then it is a binary, octal, or hexadecimal.  Allow these constants
8889   // to fill all the bits, even if there is a sign change.
8890   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
8891     const char FirstLiteralCharacter =
8892         S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
8893     if (FirstLiteralCharacter == '0')
8894       return false;
8895   }
8896 
8897   // If the CC location points to a '{', and the type is char, then assume
8898   // assume it is an array initialization.
8899   if (CC.isValid() && T->isCharType()) {
8900     const char FirstContextCharacter =
8901         S.getSourceManager().getCharacterData(CC)[0];
8902     if (FirstContextCharacter == '{')
8903       return false;
8904   }
8905 
8906   return true;
8907 }
8908 
8909 void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
8910                              SourceLocation CC, bool *ICContext = nullptr) {
8911   if (E->isTypeDependent() || E->isValueDependent()) return;
8912 
8913   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
8914   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
8915   if (Source == Target) return;
8916   if (Target->isDependentType()) return;
8917 
8918   // If the conversion context location is invalid don't complain. We also
8919   // don't want to emit a warning if the issue occurs from the expansion of
8920   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
8921   // delay this check as long as possible. Once we detect we are in that
8922   // scenario, we just return.
8923   if (CC.isInvalid())
8924     return;
8925 
8926   // Diagnose implicit casts to bool.
8927   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
8928     if (isa<StringLiteral>(E))
8929       // Warn on string literal to bool.  Checks for string literals in logical
8930       // and expressions, for instance, assert(0 && "error here"), are
8931       // prevented by a check in AnalyzeImplicitConversions().
8932       return DiagnoseImpCast(S, E, T, CC,
8933                              diag::warn_impcast_string_literal_to_bool);
8934     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
8935         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
8936       // This covers the literal expressions that evaluate to Objective-C
8937       // objects.
8938       return DiagnoseImpCast(S, E, T, CC,
8939                              diag::warn_impcast_objective_c_literal_to_bool);
8940     }
8941     if (Source->isPointerType() || Source->canDecayToPointerType()) {
8942       // Warn on pointer to bool conversion that is always true.
8943       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
8944                                      SourceRange(CC));
8945     }
8946   }
8947 
8948   // Check implicit casts from Objective-C collection literals to specialized
8949   // collection types, e.g., NSArray<NSString *> *.
8950   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
8951     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
8952   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
8953     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
8954 
8955   // Strip vector types.
8956   if (isa<VectorType>(Source)) {
8957     if (!isa<VectorType>(Target)) {
8958       if (S.SourceMgr.isInSystemMacro(CC))
8959         return;
8960       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
8961     }
8962 
8963     // If the vector cast is cast between two vectors of the same size, it is
8964     // a bitcast, not a conversion.
8965     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
8966       return;
8967 
8968     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
8969     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
8970   }
8971   if (auto VecTy = dyn_cast<VectorType>(Target))
8972     Target = VecTy->getElementType().getTypePtr();
8973 
8974   // Strip complex types.
8975   if (isa<ComplexType>(Source)) {
8976     if (!isa<ComplexType>(Target)) {
8977       if (S.SourceMgr.isInSystemMacro(CC))
8978         return;
8979 
8980       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
8981     }
8982 
8983     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
8984     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
8985   }
8986 
8987   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
8988   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
8989 
8990   // If the source is floating point...
8991   if (SourceBT && SourceBT->isFloatingPoint()) {
8992     // ...and the target is floating point...
8993     if (TargetBT && TargetBT->isFloatingPoint()) {
8994       // ...then warn if we're dropping FP rank.
8995 
8996       // Builtin FP kinds are ordered by increasing FP rank.
8997       if (SourceBT->getKind() > TargetBT->getKind()) {
8998         // Don't warn about float constants that are precisely
8999         // representable in the target type.
9000         Expr::EvalResult result;
9001         if (E->EvaluateAsRValue(result, S.Context)) {
9002           // Value might be a float, a float vector, or a float complex.
9003           if (IsSameFloatAfterCast(result.Val,
9004                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9005                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
9006             return;
9007         }
9008 
9009         if (S.SourceMgr.isInSystemMacro(CC))
9010           return;
9011 
9012         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
9013       }
9014       // ... or possibly if we're increasing rank, too
9015       else if (TargetBT->getKind() > SourceBT->getKind()) {
9016         if (S.SourceMgr.isInSystemMacro(CC))
9017           return;
9018 
9019         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
9020       }
9021       return;
9022     }
9023 
9024     // If the target is integral, always warn.
9025     if (TargetBT && TargetBT->isInteger()) {
9026       if (S.SourceMgr.isInSystemMacro(CC))
9027         return;
9028 
9029       DiagnoseFloatingImpCast(S, E, T, CC);
9030     }
9031 
9032     // Detect the case where a call result is converted from floating-point to
9033     // to bool, and the final argument to the call is converted from bool, to
9034     // discover this typo:
9035     //
9036     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
9037     //
9038     // FIXME: This is an incredibly special case; is there some more general
9039     // way to detect this class of misplaced-parentheses bug?
9040     if (Target->isBooleanType() && isa<CallExpr>(E)) {
9041       // Check last argument of function call to see if it is an
9042       // implicit cast from a type matching the type the result
9043       // is being cast to.
9044       CallExpr *CEx = cast<CallExpr>(E);
9045       if (unsigned NumArgs = CEx->getNumArgs()) {
9046         Expr *LastA = CEx->getArg(NumArgs - 1);
9047         Expr *InnerE = LastA->IgnoreParenImpCasts();
9048         if (isa<ImplicitCastExpr>(LastA) &&
9049             InnerE->getType()->isBooleanType()) {
9050           // Warn on this floating-point to bool conversion
9051           DiagnoseImpCast(S, E, T, CC,
9052                           diag::warn_impcast_floating_point_to_bool);
9053         }
9054       }
9055     }
9056     return;
9057   }
9058 
9059   DiagnoseNullConversion(S, E, T, CC);
9060 
9061   S.DiscardMisalignedMemberAddress(Target, E);
9062 
9063   if (!Source->isIntegerType() || !Target->isIntegerType())
9064     return;
9065 
9066   // TODO: remove this early return once the false positives for constant->bool
9067   // in templates, macros, etc, are reduced or removed.
9068   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9069     return;
9070 
9071   IntRange SourceRange = GetExprRange(S.Context, E);
9072   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
9073 
9074   if (SourceRange.Width > TargetRange.Width) {
9075     // If the source is a constant, use a default-on diagnostic.
9076     // TODO: this should happen for bitfield stores, too.
9077     llvm::APSInt Value(32);
9078     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
9079       if (S.SourceMgr.isInSystemMacro(CC))
9080         return;
9081 
9082       std::string PrettySourceValue = Value.toString(10);
9083       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
9084 
9085       S.DiagRuntimeBehavior(E->getExprLoc(), E,
9086         S.PDiag(diag::warn_impcast_integer_precision_constant)
9087             << PrettySourceValue << PrettyTargetValue
9088             << E->getType() << T << E->getSourceRange()
9089             << clang::SourceRange(CC));
9090       return;
9091     }
9092 
9093     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9094     if (S.SourceMgr.isInSystemMacro(CC))
9095       return;
9096 
9097     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
9098       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9099                              /* pruneControlFlow */ true);
9100     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
9101   }
9102 
9103   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9104       SourceRange.NonNegative && Source->isSignedIntegerType()) {
9105     // Warn when doing a signed to signed conversion, warn if the positive
9106     // source value is exactly the width of the target type, which will
9107     // cause a negative value to be stored.
9108 
9109     llvm::APSInt Value;
9110     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9111         !S.SourceMgr.isInSystemMacro(CC)) {
9112       if (isSameWidthConstantConversion(S, E, T, CC)) {
9113         std::string PrettySourceValue = Value.toString(10);
9114         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
9115 
9116         S.DiagRuntimeBehavior(
9117             E->getExprLoc(), E,
9118             S.PDiag(diag::warn_impcast_integer_precision_constant)
9119                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
9120                 << E->getSourceRange() << clang::SourceRange(CC));
9121         return;
9122       }
9123     }
9124 
9125     // Fall through for non-constants to give a sign conversion warning.
9126   }
9127 
9128   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9129       (!TargetRange.NonNegative && SourceRange.NonNegative &&
9130        SourceRange.Width == TargetRange.Width)) {
9131     if (S.SourceMgr.isInSystemMacro(CC))
9132       return;
9133 
9134     unsigned DiagID = diag::warn_impcast_integer_sign;
9135 
9136     // Traditionally, gcc has warned about this under -Wsign-compare.
9137     // We also want to warn about it in -Wconversion.
9138     // So if -Wconversion is off, use a completely identical diagnostic
9139     // in the sign-compare group.
9140     // The conditional-checking code will
9141     if (ICContext) {
9142       DiagID = diag::warn_impcast_integer_sign_conditional;
9143       *ICContext = true;
9144     }
9145 
9146     return DiagnoseImpCast(S, E, T, CC, DiagID);
9147   }
9148 
9149   // Diagnose conversions between different enumeration types.
9150   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9151   // type, to give us better diagnostics.
9152   QualType SourceType = E->getType();
9153   if (!S.getLangOpts().CPlusPlus) {
9154     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9155       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9156         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9157         SourceType = S.Context.getTypeDeclType(Enum);
9158         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9159       }
9160   }
9161 
9162   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9163     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
9164       if (SourceEnum->getDecl()->hasNameForLinkage() &&
9165           TargetEnum->getDecl()->hasNameForLinkage() &&
9166           SourceEnum != TargetEnum) {
9167         if (S.SourceMgr.isInSystemMacro(CC))
9168           return;
9169 
9170         return DiagnoseImpCast(S, E, SourceType, T, CC,
9171                                diag::warn_impcast_different_enum_types);
9172       }
9173 }
9174 
9175 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9176                               SourceLocation CC, QualType T);
9177 
9178 void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
9179                              SourceLocation CC, bool &ICContext) {
9180   E = E->IgnoreParenImpCasts();
9181 
9182   if (isa<ConditionalOperator>(E))
9183     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
9184 
9185   AnalyzeImplicitConversions(S, E, CC);
9186   if (E->getType() != T)
9187     return CheckImplicitConversion(S, E, T, CC, &ICContext);
9188 }
9189 
9190 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9191                               SourceLocation CC, QualType T) {
9192   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
9193 
9194   bool Suspicious = false;
9195   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9196   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
9197 
9198   // If -Wconversion would have warned about either of the candidates
9199   // for a signedness conversion to the context type...
9200   if (!Suspicious) return;
9201 
9202   // ...but it's currently ignored...
9203   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
9204     return;
9205 
9206   // ...then check whether it would have warned about either of the
9207   // candidates for a signedness conversion to the condition type.
9208   if (E->getType() == T) return;
9209 
9210   Suspicious = false;
9211   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
9212                           E->getType(), CC, &Suspicious);
9213   if (!Suspicious)
9214     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
9215                             E->getType(), CC, &Suspicious);
9216 }
9217 
9218 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9219 /// Input argument E is a logical expression.
9220 void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
9221   if (S.getLangOpts().Bool)
9222     return;
9223   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
9224 }
9225 
9226 /// AnalyzeImplicitConversions - Find and report any interesting
9227 /// implicit conversions in the given expression.  There are a couple
9228 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
9229 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
9230   QualType T = OrigE->getType();
9231   Expr *E = OrigE->IgnoreParenImpCasts();
9232 
9233   if (E->isTypeDependent() || E->isValueDependent())
9234     return;
9235 
9236   // For conditional operators, we analyze the arguments as if they
9237   // were being fed directly into the output.
9238   if (isa<ConditionalOperator>(E)) {
9239     ConditionalOperator *CO = cast<ConditionalOperator>(E);
9240     CheckConditionalOperator(S, CO, CC, T);
9241     return;
9242   }
9243 
9244   // Check implicit argument conversions for function calls.
9245   if (CallExpr *Call = dyn_cast<CallExpr>(E))
9246     CheckImplicitArgumentConversions(S, Call, CC);
9247 
9248   // Go ahead and check any implicit conversions we might have skipped.
9249   // The non-canonical typecheck is just an optimization;
9250   // CheckImplicitConversion will filter out dead implicit conversions.
9251   if (E->getType() != T)
9252     CheckImplicitConversion(S, E, T, CC);
9253 
9254   // Now continue drilling into this expression.
9255 
9256   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
9257     // The bound subexpressions in a PseudoObjectExpr are not reachable
9258     // as transitive children.
9259     // FIXME: Use a more uniform representation for this.
9260     for (auto *SE : POE->semantics())
9261       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9262         AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
9263   }
9264 
9265   // Skip past explicit casts.
9266   if (isa<ExplicitCastExpr>(E)) {
9267     E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
9268     return AnalyzeImplicitConversions(S, E, CC);
9269   }
9270 
9271   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9272     // Do a somewhat different check with comparison operators.
9273     if (BO->isComparisonOp())
9274       return AnalyzeComparison(S, BO);
9275 
9276     // And with simple assignments.
9277     if (BO->getOpcode() == BO_Assign)
9278       return AnalyzeAssignment(S, BO);
9279   }
9280 
9281   // These break the otherwise-useful invariant below.  Fortunately,
9282   // we don't really need to recurse into them, because any internal
9283   // expressions should have been analyzed already when they were
9284   // built into statements.
9285   if (isa<StmtExpr>(E)) return;
9286 
9287   // Don't descend into unevaluated contexts.
9288   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
9289 
9290   // Now just recurse over the expression's children.
9291   CC = E->getExprLoc();
9292   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
9293   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
9294   for (Stmt *SubStmt : E->children()) {
9295     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
9296     if (!ChildExpr)
9297       continue;
9298 
9299     if (IsLogicalAndOperator &&
9300         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
9301       // Ignore checking string literals that are in logical and operators.
9302       // This is a common pattern for asserts.
9303       continue;
9304     AnalyzeImplicitConversions(S, ChildExpr, CC);
9305   }
9306 
9307   if (BO && BO->isLogicalOp()) {
9308     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
9309     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
9310       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
9311 
9312     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
9313     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
9314       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
9315   }
9316 
9317   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
9318     if (U->getOpcode() == UO_LNot)
9319       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
9320 }
9321 
9322 } // end anonymous namespace
9323 
9324 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
9325                                             unsigned Start, unsigned End) {
9326   bool IllegalParams = false;
9327   for (unsigned I = Start; I <= End; ++I) {
9328     QualType Ty = TheCall->getArg(I)->getType();
9329     // Taking into account implicit conversions,
9330     // allow any integer within 32 bits range
9331     if (!Ty->isIntegerType() ||
9332         S.Context.getTypeSizeInChars(Ty).getQuantity() > 4) {
9333       S.Diag(TheCall->getArg(I)->getLocStart(),
9334              diag::err_opencl_enqueue_kernel_invalid_local_size_type);
9335       IllegalParams = true;
9336     }
9337     // Potentially emit standard warnings for implicit conversions if enabled
9338     // using -Wconversion.
9339     CheckImplicitConversion(S, TheCall->getArg(I), S.Context.UnsignedIntTy,
9340                             TheCall->getArg(I)->getLocStart());
9341   }
9342   return IllegalParams;
9343 }
9344 
9345 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
9346 // Returns true when emitting a warning about taking the address of a reference.
9347 static bool CheckForReference(Sema &SemaRef, const Expr *E,
9348                               const PartialDiagnostic &PD) {
9349   E = E->IgnoreParenImpCasts();
9350 
9351   const FunctionDecl *FD = nullptr;
9352 
9353   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9354     if (!DRE->getDecl()->getType()->isReferenceType())
9355       return false;
9356   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9357     if (!M->getMemberDecl()->getType()->isReferenceType())
9358       return false;
9359   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
9360     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
9361       return false;
9362     FD = Call->getDirectCallee();
9363   } else {
9364     return false;
9365   }
9366 
9367   SemaRef.Diag(E->getExprLoc(), PD);
9368 
9369   // If possible, point to location of function.
9370   if (FD) {
9371     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
9372   }
9373 
9374   return true;
9375 }
9376 
9377 // Returns true if the SourceLocation is expanded from any macro body.
9378 // Returns false if the SourceLocation is invalid, is from not in a macro
9379 // expansion, or is from expanded from a top-level macro argument.
9380 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
9381   if (Loc.isInvalid())
9382     return false;
9383 
9384   while (Loc.isMacroID()) {
9385     if (SM.isMacroBodyExpansion(Loc))
9386       return true;
9387     Loc = SM.getImmediateMacroCallerLoc(Loc);
9388   }
9389 
9390   return false;
9391 }
9392 
9393 /// \brief Diagnose pointers that are always non-null.
9394 /// \param E the expression containing the pointer
9395 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
9396 /// compared to a null pointer
9397 /// \param IsEqual True when the comparison is equal to a null pointer
9398 /// \param Range Extra SourceRange to highlight in the diagnostic
9399 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
9400                                         Expr::NullPointerConstantKind NullKind,
9401                                         bool IsEqual, SourceRange Range) {
9402   if (!E)
9403     return;
9404 
9405   // Don't warn inside macros.
9406   if (E->getExprLoc().isMacroID()) {
9407     const SourceManager &SM = getSourceManager();
9408     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
9409         IsInAnyMacroBody(SM, Range.getBegin()))
9410       return;
9411   }
9412   E = E->IgnoreImpCasts();
9413 
9414   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
9415 
9416   if (isa<CXXThisExpr>(E)) {
9417     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
9418                                 : diag::warn_this_bool_conversion;
9419     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
9420     return;
9421   }
9422 
9423   bool IsAddressOf = false;
9424 
9425   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9426     if (UO->getOpcode() != UO_AddrOf)
9427       return;
9428     IsAddressOf = true;
9429     E = UO->getSubExpr();
9430   }
9431 
9432   if (IsAddressOf) {
9433     unsigned DiagID = IsCompare
9434                           ? diag::warn_address_of_reference_null_compare
9435                           : diag::warn_address_of_reference_bool_conversion;
9436     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
9437                                          << IsEqual;
9438     if (CheckForReference(*this, E, PD)) {
9439       return;
9440     }
9441   }
9442 
9443   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
9444     bool IsParam = isa<NonNullAttr>(NonnullAttr);
9445     std::string Str;
9446     llvm::raw_string_ostream S(Str);
9447     E->printPretty(S, nullptr, getPrintingPolicy());
9448     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
9449                                 : diag::warn_cast_nonnull_to_bool;
9450     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
9451       << E->getSourceRange() << Range << IsEqual;
9452     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
9453   };
9454 
9455   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
9456   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
9457     if (auto *Callee = Call->getDirectCallee()) {
9458       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
9459         ComplainAboutNonnullParamOrCall(A);
9460         return;
9461       }
9462     }
9463   }
9464 
9465   // Expect to find a single Decl.  Skip anything more complicated.
9466   ValueDecl *D = nullptr;
9467   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
9468     D = R->getDecl();
9469   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9470     D = M->getMemberDecl();
9471   }
9472 
9473   // Weak Decls can be null.
9474   if (!D || D->isWeak())
9475     return;
9476 
9477   // Check for parameter decl with nonnull attribute
9478   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
9479     if (getCurFunction() &&
9480         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
9481       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
9482         ComplainAboutNonnullParamOrCall(A);
9483         return;
9484       }
9485 
9486       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
9487         auto ParamIter = llvm::find(FD->parameters(), PV);
9488         assert(ParamIter != FD->param_end());
9489         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
9490 
9491         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
9492           if (!NonNull->args_size()) {
9493               ComplainAboutNonnullParamOrCall(NonNull);
9494               return;
9495           }
9496 
9497           for (unsigned ArgNo : NonNull->args()) {
9498             if (ArgNo == ParamNo) {
9499               ComplainAboutNonnullParamOrCall(NonNull);
9500               return;
9501             }
9502           }
9503         }
9504       }
9505     }
9506   }
9507 
9508   QualType T = D->getType();
9509   const bool IsArray = T->isArrayType();
9510   const bool IsFunction = T->isFunctionType();
9511 
9512   // Address of function is used to silence the function warning.
9513   if (IsAddressOf && IsFunction) {
9514     return;
9515   }
9516 
9517   // Found nothing.
9518   if (!IsAddressOf && !IsFunction && !IsArray)
9519     return;
9520 
9521   // Pretty print the expression for the diagnostic.
9522   std::string Str;
9523   llvm::raw_string_ostream S(Str);
9524   E->printPretty(S, nullptr, getPrintingPolicy());
9525 
9526   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
9527                               : diag::warn_impcast_pointer_to_bool;
9528   enum {
9529     AddressOf,
9530     FunctionPointer,
9531     ArrayPointer
9532   } DiagType;
9533   if (IsAddressOf)
9534     DiagType = AddressOf;
9535   else if (IsFunction)
9536     DiagType = FunctionPointer;
9537   else if (IsArray)
9538     DiagType = ArrayPointer;
9539   else
9540     llvm_unreachable("Could not determine diagnostic.");
9541   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
9542                                 << Range << IsEqual;
9543 
9544   if (!IsFunction)
9545     return;
9546 
9547   // Suggest '&' to silence the function warning.
9548   Diag(E->getExprLoc(), diag::note_function_warning_silence)
9549       << FixItHint::CreateInsertion(E->getLocStart(), "&");
9550 
9551   // Check to see if '()' fixit should be emitted.
9552   QualType ReturnType;
9553   UnresolvedSet<4> NonTemplateOverloads;
9554   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
9555   if (ReturnType.isNull())
9556     return;
9557 
9558   if (IsCompare) {
9559     // There are two cases here.  If there is null constant, the only suggest
9560     // for a pointer return type.  If the null is 0, then suggest if the return
9561     // type is a pointer or an integer type.
9562     if (!ReturnType->isPointerType()) {
9563       if (NullKind == Expr::NPCK_ZeroExpression ||
9564           NullKind == Expr::NPCK_ZeroLiteral) {
9565         if (!ReturnType->isIntegerType())
9566           return;
9567       } else {
9568         return;
9569       }
9570     }
9571   } else { // !IsCompare
9572     // For function to bool, only suggest if the function pointer has bool
9573     // return type.
9574     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
9575       return;
9576   }
9577   Diag(E->getExprLoc(), diag::note_function_to_function_call)
9578       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
9579 }
9580 
9581 /// Diagnoses "dangerous" implicit conversions within the given
9582 /// expression (which is a full expression).  Implements -Wconversion
9583 /// and -Wsign-compare.
9584 ///
9585 /// \param CC the "context" location of the implicit conversion, i.e.
9586 ///   the most location of the syntactic entity requiring the implicit
9587 ///   conversion
9588 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
9589   // Don't diagnose in unevaluated contexts.
9590   if (isUnevaluatedContext())
9591     return;
9592 
9593   // Don't diagnose for value- or type-dependent expressions.
9594   if (E->isTypeDependent() || E->isValueDependent())
9595     return;
9596 
9597   // Check for array bounds violations in cases where the check isn't triggered
9598   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
9599   // ArraySubscriptExpr is on the RHS of a variable initialization.
9600   CheckArrayAccess(E);
9601 
9602   // This is not the right CC for (e.g.) a variable initialization.
9603   AnalyzeImplicitConversions(*this, E, CC);
9604 }
9605 
9606 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9607 /// Input argument E is a logical expression.
9608 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
9609   ::CheckBoolLikeConversion(*this, E, CC);
9610 }
9611 
9612 /// Diagnose when expression is an integer constant expression and its evaluation
9613 /// results in integer overflow
9614 void Sema::CheckForIntOverflow (Expr *E) {
9615   // Use a work list to deal with nested struct initializers.
9616   SmallVector<Expr *, 2> Exprs(1, E);
9617 
9618   do {
9619     Expr *E = Exprs.pop_back_val();
9620 
9621     if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
9622       E->IgnoreParenCasts()->EvaluateForOverflow(Context);
9623       continue;
9624     }
9625 
9626     if (auto InitList = dyn_cast<InitListExpr>(E))
9627       Exprs.append(InitList->inits().begin(), InitList->inits().end());
9628   } while (!Exprs.empty());
9629 }
9630 
9631 namespace {
9632 /// \brief Visitor for expressions which looks for unsequenced operations on the
9633 /// same object.
9634 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
9635   typedef EvaluatedExprVisitor<SequenceChecker> Base;
9636 
9637   /// \brief A tree of sequenced regions within an expression. Two regions are
9638   /// unsequenced if one is an ancestor or a descendent of the other. When we
9639   /// finish processing an expression with sequencing, such as a comma
9640   /// expression, we fold its tree nodes into its parent, since they are
9641   /// unsequenced with respect to nodes we will visit later.
9642   class SequenceTree {
9643     struct Value {
9644       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
9645       unsigned Parent : 31;
9646       unsigned Merged : 1;
9647     };
9648     SmallVector<Value, 8> Values;
9649 
9650   public:
9651     /// \brief A region within an expression which may be sequenced with respect
9652     /// to some other region.
9653     class Seq {
9654       explicit Seq(unsigned N) : Index(N) {}
9655       unsigned Index;
9656       friend class SequenceTree;
9657     public:
9658       Seq() : Index(0) {}
9659     };
9660 
9661     SequenceTree() { Values.push_back(Value(0)); }
9662     Seq root() const { return Seq(0); }
9663 
9664     /// \brief Create a new sequence of operations, which is an unsequenced
9665     /// subset of \p Parent. This sequence of operations is sequenced with
9666     /// respect to other children of \p Parent.
9667     Seq allocate(Seq Parent) {
9668       Values.push_back(Value(Parent.Index));
9669       return Seq(Values.size() - 1);
9670     }
9671 
9672     /// \brief Merge a sequence of operations into its parent.
9673     void merge(Seq S) {
9674       Values[S.Index].Merged = true;
9675     }
9676 
9677     /// \brief Determine whether two operations are unsequenced. This operation
9678     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
9679     /// should have been merged into its parent as appropriate.
9680     bool isUnsequenced(Seq Cur, Seq Old) {
9681       unsigned C = representative(Cur.Index);
9682       unsigned Target = representative(Old.Index);
9683       while (C >= Target) {
9684         if (C == Target)
9685           return true;
9686         C = Values[C].Parent;
9687       }
9688       return false;
9689     }
9690 
9691   private:
9692     /// \brief Pick a representative for a sequence.
9693     unsigned representative(unsigned K) {
9694       if (Values[K].Merged)
9695         // Perform path compression as we go.
9696         return Values[K].Parent = representative(Values[K].Parent);
9697       return K;
9698     }
9699   };
9700 
9701   /// An object for which we can track unsequenced uses.
9702   typedef NamedDecl *Object;
9703 
9704   /// Different flavors of object usage which we track. We only track the
9705   /// least-sequenced usage of each kind.
9706   enum UsageKind {
9707     /// A read of an object. Multiple unsequenced reads are OK.
9708     UK_Use,
9709     /// A modification of an object which is sequenced before the value
9710     /// computation of the expression, such as ++n in C++.
9711     UK_ModAsValue,
9712     /// A modification of an object which is not sequenced before the value
9713     /// computation of the expression, such as n++.
9714     UK_ModAsSideEffect,
9715 
9716     UK_Count = UK_ModAsSideEffect + 1
9717   };
9718 
9719   struct Usage {
9720     Usage() : Use(nullptr), Seq() {}
9721     Expr *Use;
9722     SequenceTree::Seq Seq;
9723   };
9724 
9725   struct UsageInfo {
9726     UsageInfo() : Diagnosed(false) {}
9727     Usage Uses[UK_Count];
9728     /// Have we issued a diagnostic for this variable already?
9729     bool Diagnosed;
9730   };
9731   typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
9732 
9733   Sema &SemaRef;
9734   /// Sequenced regions within the expression.
9735   SequenceTree Tree;
9736   /// Declaration modifications and references which we have seen.
9737   UsageInfoMap UsageMap;
9738   /// The region we are currently within.
9739   SequenceTree::Seq Region;
9740   /// Filled in with declarations which were modified as a side-effect
9741   /// (that is, post-increment operations).
9742   SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
9743   /// Expressions to check later. We defer checking these to reduce
9744   /// stack usage.
9745   SmallVectorImpl<Expr *> &WorkList;
9746 
9747   /// RAII object wrapping the visitation of a sequenced subexpression of an
9748   /// expression. At the end of this process, the side-effects of the evaluation
9749   /// become sequenced with respect to the value computation of the result, so
9750   /// we downgrade any UK_ModAsSideEffect within the evaluation to
9751   /// UK_ModAsValue.
9752   struct SequencedSubexpression {
9753     SequencedSubexpression(SequenceChecker &Self)
9754       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
9755       Self.ModAsSideEffect = &ModAsSideEffect;
9756     }
9757     ~SequencedSubexpression() {
9758       for (auto &M : llvm::reverse(ModAsSideEffect)) {
9759         UsageInfo &U = Self.UsageMap[M.first];
9760         auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
9761         Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
9762         SideEffectUsage = M.second;
9763       }
9764       Self.ModAsSideEffect = OldModAsSideEffect;
9765     }
9766 
9767     SequenceChecker &Self;
9768     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
9769     SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
9770   };
9771 
9772   /// RAII object wrapping the visitation of a subexpression which we might
9773   /// choose to evaluate as a constant. If any subexpression is evaluated and
9774   /// found to be non-constant, this allows us to suppress the evaluation of
9775   /// the outer expression.
9776   class EvaluationTracker {
9777   public:
9778     EvaluationTracker(SequenceChecker &Self)
9779         : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
9780       Self.EvalTracker = this;
9781     }
9782     ~EvaluationTracker() {
9783       Self.EvalTracker = Prev;
9784       if (Prev)
9785         Prev->EvalOK &= EvalOK;
9786     }
9787 
9788     bool evaluate(const Expr *E, bool &Result) {
9789       if (!EvalOK || E->isValueDependent())
9790         return false;
9791       EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
9792       return EvalOK;
9793     }
9794 
9795   private:
9796     SequenceChecker &Self;
9797     EvaluationTracker *Prev;
9798     bool EvalOK;
9799   } *EvalTracker;
9800 
9801   /// \brief Find the object which is produced by the specified expression,
9802   /// if any.
9803   Object getObject(Expr *E, bool Mod) const {
9804     E = E->IgnoreParenCasts();
9805     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9806       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
9807         return getObject(UO->getSubExpr(), Mod);
9808     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9809       if (BO->getOpcode() == BO_Comma)
9810         return getObject(BO->getRHS(), Mod);
9811       if (Mod && BO->isAssignmentOp())
9812         return getObject(BO->getLHS(), Mod);
9813     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9814       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
9815       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
9816         return ME->getMemberDecl();
9817     } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9818       // FIXME: If this is a reference, map through to its value.
9819       return DRE->getDecl();
9820     return nullptr;
9821   }
9822 
9823   /// \brief Note that an object was modified or used by an expression.
9824   void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
9825     Usage &U = UI.Uses[UK];
9826     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
9827       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
9828         ModAsSideEffect->push_back(std::make_pair(O, U));
9829       U.Use = Ref;
9830       U.Seq = Region;
9831     }
9832   }
9833   /// \brief Check whether a modification or use conflicts with a prior usage.
9834   void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
9835                   bool IsModMod) {
9836     if (UI.Diagnosed)
9837       return;
9838 
9839     const Usage &U = UI.Uses[OtherKind];
9840     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
9841       return;
9842 
9843     Expr *Mod = U.Use;
9844     Expr *ModOrUse = Ref;
9845     if (OtherKind == UK_Use)
9846       std::swap(Mod, ModOrUse);
9847 
9848     SemaRef.Diag(Mod->getExprLoc(),
9849                  IsModMod ? diag::warn_unsequenced_mod_mod
9850                           : diag::warn_unsequenced_mod_use)
9851       << O << SourceRange(ModOrUse->getExprLoc());
9852     UI.Diagnosed = true;
9853   }
9854 
9855   void notePreUse(Object O, Expr *Use) {
9856     UsageInfo &U = UsageMap[O];
9857     // Uses conflict with other modifications.
9858     checkUsage(O, U, Use, UK_ModAsValue, false);
9859   }
9860   void notePostUse(Object O, Expr *Use) {
9861     UsageInfo &U = UsageMap[O];
9862     checkUsage(O, U, Use, UK_ModAsSideEffect, false);
9863     addUsage(U, O, Use, UK_Use);
9864   }
9865 
9866   void notePreMod(Object O, Expr *Mod) {
9867     UsageInfo &U = UsageMap[O];
9868     // Modifications conflict with other modifications and with uses.
9869     checkUsage(O, U, Mod, UK_ModAsValue, true);
9870     checkUsage(O, U, Mod, UK_Use, false);
9871   }
9872   void notePostMod(Object O, Expr *Use, UsageKind UK) {
9873     UsageInfo &U = UsageMap[O];
9874     checkUsage(O, U, Use, UK_ModAsSideEffect, true);
9875     addUsage(U, O, Use, UK);
9876   }
9877 
9878 public:
9879   SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
9880       : Base(S.Context), SemaRef(S), Region(Tree.root()),
9881         ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
9882     Visit(E);
9883   }
9884 
9885   void VisitStmt(Stmt *S) {
9886     // Skip all statements which aren't expressions for now.
9887   }
9888 
9889   void VisitExpr(Expr *E) {
9890     // By default, just recurse to evaluated subexpressions.
9891     Base::VisitStmt(E);
9892   }
9893 
9894   void VisitCastExpr(CastExpr *E) {
9895     Object O = Object();
9896     if (E->getCastKind() == CK_LValueToRValue)
9897       O = getObject(E->getSubExpr(), false);
9898 
9899     if (O)
9900       notePreUse(O, E);
9901     VisitExpr(E);
9902     if (O)
9903       notePostUse(O, E);
9904   }
9905 
9906   void VisitBinComma(BinaryOperator *BO) {
9907     // C++11 [expr.comma]p1:
9908     //   Every value computation and side effect associated with the left
9909     //   expression is sequenced before every value computation and side
9910     //   effect associated with the right expression.
9911     SequenceTree::Seq LHS = Tree.allocate(Region);
9912     SequenceTree::Seq RHS = Tree.allocate(Region);
9913     SequenceTree::Seq OldRegion = Region;
9914 
9915     {
9916       SequencedSubexpression SeqLHS(*this);
9917       Region = LHS;
9918       Visit(BO->getLHS());
9919     }
9920 
9921     Region = RHS;
9922     Visit(BO->getRHS());
9923 
9924     Region = OldRegion;
9925 
9926     // Forget that LHS and RHS are sequenced. They are both unsequenced
9927     // with respect to other stuff.
9928     Tree.merge(LHS);
9929     Tree.merge(RHS);
9930   }
9931 
9932   void VisitBinAssign(BinaryOperator *BO) {
9933     // The modification is sequenced after the value computation of the LHS
9934     // and RHS, so check it before inspecting the operands and update the
9935     // map afterwards.
9936     Object O = getObject(BO->getLHS(), true);
9937     if (!O)
9938       return VisitExpr(BO);
9939 
9940     notePreMod(O, BO);
9941 
9942     // C++11 [expr.ass]p7:
9943     //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
9944     //   only once.
9945     //
9946     // Therefore, for a compound assignment operator, O is considered used
9947     // everywhere except within the evaluation of E1 itself.
9948     if (isa<CompoundAssignOperator>(BO))
9949       notePreUse(O, BO);
9950 
9951     Visit(BO->getLHS());
9952 
9953     if (isa<CompoundAssignOperator>(BO))
9954       notePostUse(O, BO);
9955 
9956     Visit(BO->getRHS());
9957 
9958     // C++11 [expr.ass]p1:
9959     //   the assignment is sequenced [...] before the value computation of the
9960     //   assignment expression.
9961     // C11 6.5.16/3 has no such rule.
9962     notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
9963                                                        : UK_ModAsSideEffect);
9964   }
9965 
9966   void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
9967     VisitBinAssign(CAO);
9968   }
9969 
9970   void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
9971   void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
9972   void VisitUnaryPreIncDec(UnaryOperator *UO) {
9973     Object O = getObject(UO->getSubExpr(), true);
9974     if (!O)
9975       return VisitExpr(UO);
9976 
9977     notePreMod(O, UO);
9978     Visit(UO->getSubExpr());
9979     // C++11 [expr.pre.incr]p1:
9980     //   the expression ++x is equivalent to x+=1
9981     notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
9982                                                        : UK_ModAsSideEffect);
9983   }
9984 
9985   void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
9986   void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
9987   void VisitUnaryPostIncDec(UnaryOperator *UO) {
9988     Object O = getObject(UO->getSubExpr(), true);
9989     if (!O)
9990       return VisitExpr(UO);
9991 
9992     notePreMod(O, UO);
9993     Visit(UO->getSubExpr());
9994     notePostMod(O, UO, UK_ModAsSideEffect);
9995   }
9996 
9997   /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
9998   void VisitBinLOr(BinaryOperator *BO) {
9999     // The side-effects of the LHS of an '&&' are sequenced before the
10000     // value computation of the RHS, and hence before the value computation
10001     // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10002     // as if they were unconditionally sequenced.
10003     EvaluationTracker Eval(*this);
10004     {
10005       SequencedSubexpression Sequenced(*this);
10006       Visit(BO->getLHS());
10007     }
10008 
10009     bool Result;
10010     if (Eval.evaluate(BO->getLHS(), Result)) {
10011       if (!Result)
10012         Visit(BO->getRHS());
10013     } else {
10014       // Check for unsequenced operations in the RHS, treating it as an
10015       // entirely separate evaluation.
10016       //
10017       // FIXME: If there are operations in the RHS which are unsequenced
10018       // with respect to operations outside the RHS, and those operations
10019       // are unconditionally evaluated, diagnose them.
10020       WorkList.push_back(BO->getRHS());
10021     }
10022   }
10023   void VisitBinLAnd(BinaryOperator *BO) {
10024     EvaluationTracker Eval(*this);
10025     {
10026       SequencedSubexpression Sequenced(*this);
10027       Visit(BO->getLHS());
10028     }
10029 
10030     bool Result;
10031     if (Eval.evaluate(BO->getLHS(), Result)) {
10032       if (Result)
10033         Visit(BO->getRHS());
10034     } else {
10035       WorkList.push_back(BO->getRHS());
10036     }
10037   }
10038 
10039   // Only visit the condition, unless we can be sure which subexpression will
10040   // be chosen.
10041   void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
10042     EvaluationTracker Eval(*this);
10043     {
10044       SequencedSubexpression Sequenced(*this);
10045       Visit(CO->getCond());
10046     }
10047 
10048     bool Result;
10049     if (Eval.evaluate(CO->getCond(), Result))
10050       Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
10051     else {
10052       WorkList.push_back(CO->getTrueExpr());
10053       WorkList.push_back(CO->getFalseExpr());
10054     }
10055   }
10056 
10057   void VisitCallExpr(CallExpr *CE) {
10058     // C++11 [intro.execution]p15:
10059     //   When calling a function [...], every value computation and side effect
10060     //   associated with any argument expression, or with the postfix expression
10061     //   designating the called function, is sequenced before execution of every
10062     //   expression or statement in the body of the function [and thus before
10063     //   the value computation of its result].
10064     SequencedSubexpression Sequenced(*this);
10065     Base::VisitCallExpr(CE);
10066 
10067     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10068   }
10069 
10070   void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
10071     // This is a call, so all subexpressions are sequenced before the result.
10072     SequencedSubexpression Sequenced(*this);
10073 
10074     if (!CCE->isListInitialization())
10075       return VisitExpr(CCE);
10076 
10077     // In C++11, list initializations are sequenced.
10078     SmallVector<SequenceTree::Seq, 32> Elts;
10079     SequenceTree::Seq Parent = Region;
10080     for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10081                                         E = CCE->arg_end();
10082          I != E; ++I) {
10083       Region = Tree.allocate(Parent);
10084       Elts.push_back(Region);
10085       Visit(*I);
10086     }
10087 
10088     // Forget that the initializers are sequenced.
10089     Region = Parent;
10090     for (unsigned I = 0; I < Elts.size(); ++I)
10091       Tree.merge(Elts[I]);
10092   }
10093 
10094   void VisitInitListExpr(InitListExpr *ILE) {
10095     if (!SemaRef.getLangOpts().CPlusPlus11)
10096       return VisitExpr(ILE);
10097 
10098     // In C++11, list initializations are sequenced.
10099     SmallVector<SequenceTree::Seq, 32> Elts;
10100     SequenceTree::Seq Parent = Region;
10101     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10102       Expr *E = ILE->getInit(I);
10103       if (!E) continue;
10104       Region = Tree.allocate(Parent);
10105       Elts.push_back(Region);
10106       Visit(E);
10107     }
10108 
10109     // Forget that the initializers are sequenced.
10110     Region = Parent;
10111     for (unsigned I = 0; I < Elts.size(); ++I)
10112       Tree.merge(Elts[I]);
10113   }
10114 };
10115 } // end anonymous namespace
10116 
10117 void Sema::CheckUnsequencedOperations(Expr *E) {
10118   SmallVector<Expr *, 8> WorkList;
10119   WorkList.push_back(E);
10120   while (!WorkList.empty()) {
10121     Expr *Item = WorkList.pop_back_val();
10122     SequenceChecker(*this, Item, WorkList);
10123   }
10124 }
10125 
10126 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10127                               bool IsConstexpr) {
10128   CheckImplicitConversions(E, CheckLoc);
10129   if (!E->isInstantiationDependent())
10130     CheckUnsequencedOperations(E);
10131   if (!IsConstexpr && !E->isValueDependent())
10132     CheckForIntOverflow(E);
10133   DiagnoseMisalignedMembers();
10134 }
10135 
10136 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10137                                        FieldDecl *BitField,
10138                                        Expr *Init) {
10139   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10140 }
10141 
10142 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
10143                                          SourceLocation Loc) {
10144   if (!PType->isVariablyModifiedType())
10145     return;
10146   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10147     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10148     return;
10149   }
10150   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10151     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10152     return;
10153   }
10154   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10155     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10156     return;
10157   }
10158 
10159   const ArrayType *AT = S.Context.getAsArrayType(PType);
10160   if (!AT)
10161     return;
10162 
10163   if (AT->getSizeModifier() != ArrayType::Star) {
10164     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
10165     return;
10166   }
10167 
10168   S.Diag(Loc, diag::err_array_star_in_function_definition);
10169 }
10170 
10171 /// CheckParmsForFunctionDef - Check that the parameters of the given
10172 /// function are appropriate for the definition of a function. This
10173 /// takes care of any checks that cannot be performed on the
10174 /// declaration itself, e.g., that the types of each of the function
10175 /// parameters are complete.
10176 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
10177                                     bool CheckParameterNames) {
10178   bool HasInvalidParm = false;
10179   for (ParmVarDecl *Param : Parameters) {
10180     // C99 6.7.5.3p4: the parameters in a parameter type list in a
10181     // function declarator that is part of a function definition of
10182     // that function shall not have incomplete type.
10183     //
10184     // This is also C++ [dcl.fct]p6.
10185     if (!Param->isInvalidDecl() &&
10186         RequireCompleteType(Param->getLocation(), Param->getType(),
10187                             diag::err_typecheck_decl_incomplete_type)) {
10188       Param->setInvalidDecl();
10189       HasInvalidParm = true;
10190     }
10191 
10192     // C99 6.9.1p5: If the declarator includes a parameter type list, the
10193     // declaration of each parameter shall include an identifier.
10194     if (CheckParameterNames &&
10195         Param->getIdentifier() == nullptr &&
10196         !Param->isImplicit() &&
10197         !getLangOpts().CPlusPlus)
10198       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
10199 
10200     // C99 6.7.5.3p12:
10201     //   If the function declarator is not part of a definition of that
10202     //   function, parameters may have incomplete type and may use the [*]
10203     //   notation in their sequences of declarator specifiers to specify
10204     //   variable length array types.
10205     QualType PType = Param->getOriginalType();
10206     // FIXME: This diagnostic should point the '[*]' if source-location
10207     // information is added for it.
10208     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
10209 
10210     // MSVC destroys objects passed by value in the callee.  Therefore a
10211     // function definition which takes such a parameter must be able to call the
10212     // object's destructor.  However, we don't perform any direct access check
10213     // on the dtor.
10214     if (getLangOpts().CPlusPlus && Context.getTargetInfo()
10215                                        .getCXXABI()
10216                                        .areArgsDestroyedLeftToRightInCallee()) {
10217       if (!Param->isInvalidDecl()) {
10218         if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
10219           CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
10220           if (!ClassDecl->isInvalidDecl() &&
10221               !ClassDecl->hasIrrelevantDestructor() &&
10222               !ClassDecl->isDependentContext()) {
10223             CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10224             MarkFunctionReferenced(Param->getLocation(), Destructor);
10225             DiagnoseUseOfDecl(Destructor, Param->getLocation());
10226           }
10227         }
10228       }
10229     }
10230 
10231     // Parameters with the pass_object_size attribute only need to be marked
10232     // constant at function definitions. Because we lack information about
10233     // whether we're on a declaration or definition when we're instantiating the
10234     // attribute, we need to check for constness here.
10235     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
10236       if (!Param->getType().isConstQualified())
10237         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10238             << Attr->getSpelling() << 1;
10239   }
10240 
10241   return HasInvalidParm;
10242 }
10243 
10244 /// CheckCastAlign - Implements -Wcast-align, which warns when a
10245 /// pointer cast increases the alignment requirements.
10246 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
10247   // This is actually a lot of work to potentially be doing on every
10248   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
10249   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
10250     return;
10251 
10252   // Ignore dependent types.
10253   if (T->isDependentType() || Op->getType()->isDependentType())
10254     return;
10255 
10256   // Require that the destination be a pointer type.
10257   const PointerType *DestPtr = T->getAs<PointerType>();
10258   if (!DestPtr) return;
10259 
10260   // If the destination has alignment 1, we're done.
10261   QualType DestPointee = DestPtr->getPointeeType();
10262   if (DestPointee->isIncompleteType()) return;
10263   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
10264   if (DestAlign.isOne()) return;
10265 
10266   // Require that the source be a pointer type.
10267   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
10268   if (!SrcPtr) return;
10269   QualType SrcPointee = SrcPtr->getPointeeType();
10270 
10271   // Whitelist casts from cv void*.  We already implicitly
10272   // whitelisted casts to cv void*, since they have alignment 1.
10273   // Also whitelist casts involving incomplete types, which implicitly
10274   // includes 'void'.
10275   if (SrcPointee->isIncompleteType()) return;
10276 
10277   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
10278   if (SrcAlign >= DestAlign) return;
10279 
10280   Diag(TRange.getBegin(), diag::warn_cast_align)
10281     << Op->getType() << T
10282     << static_cast<unsigned>(SrcAlign.getQuantity())
10283     << static_cast<unsigned>(DestAlign.getQuantity())
10284     << TRange << Op->getSourceRange();
10285 }
10286 
10287 /// \brief Check whether this array fits the idiom of a size-one tail padded
10288 /// array member of a struct.
10289 ///
10290 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
10291 /// commonly used to emulate flexible arrays in C89 code.
10292 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
10293                                     const NamedDecl *ND) {
10294   if (Size != 1 || !ND) return false;
10295 
10296   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
10297   if (!FD) return false;
10298 
10299   // Don't consider sizes resulting from macro expansions or template argument
10300   // substitution to form C89 tail-padded arrays.
10301 
10302   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
10303   while (TInfo) {
10304     TypeLoc TL = TInfo->getTypeLoc();
10305     // Look through typedefs.
10306     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
10307       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
10308       TInfo = TDL->getTypeSourceInfo();
10309       continue;
10310     }
10311     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
10312       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
10313       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
10314         return false;
10315     }
10316     break;
10317   }
10318 
10319   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
10320   if (!RD) return false;
10321   if (RD->isUnion()) return false;
10322   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10323     if (!CRD->isStandardLayout()) return false;
10324   }
10325 
10326   // See if this is the last field decl in the record.
10327   const Decl *D = FD;
10328   while ((D = D->getNextDeclInContext()))
10329     if (isa<FieldDecl>(D))
10330       return false;
10331   return true;
10332 }
10333 
10334 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
10335                             const ArraySubscriptExpr *ASE,
10336                             bool AllowOnePastEnd, bool IndexNegated) {
10337   IndexExpr = IndexExpr->IgnoreParenImpCasts();
10338   if (IndexExpr->isValueDependent())
10339     return;
10340 
10341   const Type *EffectiveType =
10342       BaseExpr->getType()->getPointeeOrArrayElementType();
10343   BaseExpr = BaseExpr->IgnoreParenCasts();
10344   const ConstantArrayType *ArrayTy =
10345     Context.getAsConstantArrayType(BaseExpr->getType());
10346   if (!ArrayTy)
10347     return;
10348 
10349   llvm::APSInt index;
10350   if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
10351     return;
10352   if (IndexNegated)
10353     index = -index;
10354 
10355   const NamedDecl *ND = nullptr;
10356   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10357     ND = dyn_cast<NamedDecl>(DRE->getDecl());
10358   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10359     ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10360 
10361   if (index.isUnsigned() || !index.isNegative()) {
10362     llvm::APInt size = ArrayTy->getSize();
10363     if (!size.isStrictlyPositive())
10364       return;
10365 
10366     const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
10367     if (BaseType != EffectiveType) {
10368       // Make sure we're comparing apples to apples when comparing index to size
10369       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
10370       uint64_t array_typesize = Context.getTypeSize(BaseType);
10371       // Handle ptrarith_typesize being zero, such as when casting to void*
10372       if (!ptrarith_typesize) ptrarith_typesize = 1;
10373       if (ptrarith_typesize != array_typesize) {
10374         // There's a cast to a different size type involved
10375         uint64_t ratio = array_typesize / ptrarith_typesize;
10376         // TODO: Be smarter about handling cases where array_typesize is not a
10377         // multiple of ptrarith_typesize
10378         if (ptrarith_typesize * ratio == array_typesize)
10379           size *= llvm::APInt(size.getBitWidth(), ratio);
10380       }
10381     }
10382 
10383     if (size.getBitWidth() > index.getBitWidth())
10384       index = index.zext(size.getBitWidth());
10385     else if (size.getBitWidth() < index.getBitWidth())
10386       size = size.zext(index.getBitWidth());
10387 
10388     // For array subscripting the index must be less than size, but for pointer
10389     // arithmetic also allow the index (offset) to be equal to size since
10390     // computing the next address after the end of the array is legal and
10391     // commonly done e.g. in C++ iterators and range-based for loops.
10392     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
10393       return;
10394 
10395     // Also don't warn for arrays of size 1 which are members of some
10396     // structure. These are often used to approximate flexible arrays in C89
10397     // code.
10398     if (IsTailPaddedMemberArray(*this, size, ND))
10399       return;
10400 
10401     // Suppress the warning if the subscript expression (as identified by the
10402     // ']' location) and the index expression are both from macro expansions
10403     // within a system header.
10404     if (ASE) {
10405       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
10406           ASE->getRBracketLoc());
10407       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
10408         SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
10409             IndexExpr->getLocStart());
10410         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
10411           return;
10412       }
10413     }
10414 
10415     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
10416     if (ASE)
10417       DiagID = diag::warn_array_index_exceeds_bounds;
10418 
10419     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10420                         PDiag(DiagID) << index.toString(10, true)
10421                           << size.toString(10, true)
10422                           << (unsigned)size.getLimitedValue(~0U)
10423                           << IndexExpr->getSourceRange());
10424   } else {
10425     unsigned DiagID = diag::warn_array_index_precedes_bounds;
10426     if (!ASE) {
10427       DiagID = diag::warn_ptr_arith_precedes_bounds;
10428       if (index.isNegative()) index = -index;
10429     }
10430 
10431     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10432                         PDiag(DiagID) << index.toString(10, true)
10433                           << IndexExpr->getSourceRange());
10434   }
10435 
10436   if (!ND) {
10437     // Try harder to find a NamedDecl to point at in the note.
10438     while (const ArraySubscriptExpr *ASE =
10439            dyn_cast<ArraySubscriptExpr>(BaseExpr))
10440       BaseExpr = ASE->getBase()->IgnoreParenCasts();
10441     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10442       ND = dyn_cast<NamedDecl>(DRE->getDecl());
10443     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10444       ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10445   }
10446 
10447   if (ND)
10448     DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
10449                         PDiag(diag::note_array_index_out_of_bounds)
10450                           << ND->getDeclName());
10451 }
10452 
10453 void Sema::CheckArrayAccess(const Expr *expr) {
10454   int AllowOnePastEnd = 0;
10455   while (expr) {
10456     expr = expr->IgnoreParenImpCasts();
10457     switch (expr->getStmtClass()) {
10458       case Stmt::ArraySubscriptExprClass: {
10459         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
10460         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
10461                          AllowOnePastEnd > 0);
10462         return;
10463       }
10464       case Stmt::OMPArraySectionExprClass: {
10465         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
10466         if (ASE->getLowerBound())
10467           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
10468                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
10469         return;
10470       }
10471       case Stmt::UnaryOperatorClass: {
10472         // Only unwrap the * and & unary operators
10473         const UnaryOperator *UO = cast<UnaryOperator>(expr);
10474         expr = UO->getSubExpr();
10475         switch (UO->getOpcode()) {
10476           case UO_AddrOf:
10477             AllowOnePastEnd++;
10478             break;
10479           case UO_Deref:
10480             AllowOnePastEnd--;
10481             break;
10482           default:
10483             return;
10484         }
10485         break;
10486       }
10487       case Stmt::ConditionalOperatorClass: {
10488         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
10489         if (const Expr *lhs = cond->getLHS())
10490           CheckArrayAccess(lhs);
10491         if (const Expr *rhs = cond->getRHS())
10492           CheckArrayAccess(rhs);
10493         return;
10494       }
10495       default:
10496         return;
10497     }
10498   }
10499 }
10500 
10501 //===--- CHECK: Objective-C retain cycles ----------------------------------//
10502 
10503 namespace {
10504   struct RetainCycleOwner {
10505     RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
10506     VarDecl *Variable;
10507     SourceRange Range;
10508     SourceLocation Loc;
10509     bool Indirect;
10510 
10511     void setLocsFrom(Expr *e) {
10512       Loc = e->getExprLoc();
10513       Range = e->getSourceRange();
10514     }
10515   };
10516 } // end anonymous namespace
10517 
10518 /// Consider whether capturing the given variable can possibly lead to
10519 /// a retain cycle.
10520 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
10521   // In ARC, it's captured strongly iff the variable has __strong
10522   // lifetime.  In MRR, it's captured strongly if the variable is
10523   // __block and has an appropriate type.
10524   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10525     return false;
10526 
10527   owner.Variable = var;
10528   if (ref)
10529     owner.setLocsFrom(ref);
10530   return true;
10531 }
10532 
10533 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
10534   while (true) {
10535     e = e->IgnoreParens();
10536     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
10537       switch (cast->getCastKind()) {
10538       case CK_BitCast:
10539       case CK_LValueBitCast:
10540       case CK_LValueToRValue:
10541       case CK_ARCReclaimReturnedObject:
10542         e = cast->getSubExpr();
10543         continue;
10544 
10545       default:
10546         return false;
10547       }
10548     }
10549 
10550     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
10551       ObjCIvarDecl *ivar = ref->getDecl();
10552       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10553         return false;
10554 
10555       // Try to find a retain cycle in the base.
10556       if (!findRetainCycleOwner(S, ref->getBase(), owner))
10557         return false;
10558 
10559       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
10560       owner.Indirect = true;
10561       return true;
10562     }
10563 
10564     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
10565       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
10566       if (!var) return false;
10567       return considerVariable(var, ref, owner);
10568     }
10569 
10570     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
10571       if (member->isArrow()) return false;
10572 
10573       // Don't count this as an indirect ownership.
10574       e = member->getBase();
10575       continue;
10576     }
10577 
10578     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
10579       // Only pay attention to pseudo-objects on property references.
10580       ObjCPropertyRefExpr *pre
10581         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
10582                                               ->IgnoreParens());
10583       if (!pre) return false;
10584       if (pre->isImplicitProperty()) return false;
10585       ObjCPropertyDecl *property = pre->getExplicitProperty();
10586       if (!property->isRetaining() &&
10587           !(property->getPropertyIvarDecl() &&
10588             property->getPropertyIvarDecl()->getType()
10589               .getObjCLifetime() == Qualifiers::OCL_Strong))
10590           return false;
10591 
10592       owner.Indirect = true;
10593       if (pre->isSuperReceiver()) {
10594         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
10595         if (!owner.Variable)
10596           return false;
10597         owner.Loc = pre->getLocation();
10598         owner.Range = pre->getSourceRange();
10599         return true;
10600       }
10601       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
10602                               ->getSourceExpr());
10603       continue;
10604     }
10605 
10606     // Array ivars?
10607 
10608     return false;
10609   }
10610 }
10611 
10612 namespace {
10613   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
10614     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
10615       : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
10616         Context(Context), Variable(variable), Capturer(nullptr),
10617         VarWillBeReased(false) {}
10618     ASTContext &Context;
10619     VarDecl *Variable;
10620     Expr *Capturer;
10621     bool VarWillBeReased;
10622 
10623     void VisitDeclRefExpr(DeclRefExpr *ref) {
10624       if (ref->getDecl() == Variable && !Capturer)
10625         Capturer = ref;
10626     }
10627 
10628     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
10629       if (Capturer) return;
10630       Visit(ref->getBase());
10631       if (Capturer && ref->isFreeIvar())
10632         Capturer = ref;
10633     }
10634 
10635     void VisitBlockExpr(BlockExpr *block) {
10636       // Look inside nested blocks
10637       if (block->getBlockDecl()->capturesVariable(Variable))
10638         Visit(block->getBlockDecl()->getBody());
10639     }
10640 
10641     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
10642       if (Capturer) return;
10643       if (OVE->getSourceExpr())
10644         Visit(OVE->getSourceExpr());
10645     }
10646     void VisitBinaryOperator(BinaryOperator *BinOp) {
10647       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
10648         return;
10649       Expr *LHS = BinOp->getLHS();
10650       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
10651         if (DRE->getDecl() != Variable)
10652           return;
10653         if (Expr *RHS = BinOp->getRHS()) {
10654           RHS = RHS->IgnoreParenCasts();
10655           llvm::APSInt Value;
10656           VarWillBeReased =
10657             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
10658         }
10659       }
10660     }
10661   };
10662 } // end anonymous namespace
10663 
10664 /// Check whether the given argument is a block which captures a
10665 /// variable.
10666 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
10667   assert(owner.Variable && owner.Loc.isValid());
10668 
10669   e = e->IgnoreParenCasts();
10670 
10671   // Look through [^{...} copy] and Block_copy(^{...}).
10672   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
10673     Selector Cmd = ME->getSelector();
10674     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
10675       e = ME->getInstanceReceiver();
10676       if (!e)
10677         return nullptr;
10678       e = e->IgnoreParenCasts();
10679     }
10680   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
10681     if (CE->getNumArgs() == 1) {
10682       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
10683       if (Fn) {
10684         const IdentifierInfo *FnI = Fn->getIdentifier();
10685         if (FnI && FnI->isStr("_Block_copy")) {
10686           e = CE->getArg(0)->IgnoreParenCasts();
10687         }
10688       }
10689     }
10690   }
10691 
10692   BlockExpr *block = dyn_cast<BlockExpr>(e);
10693   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
10694     return nullptr;
10695 
10696   FindCaptureVisitor visitor(S.Context, owner.Variable);
10697   visitor.Visit(block->getBlockDecl()->getBody());
10698   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
10699 }
10700 
10701 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
10702                                 RetainCycleOwner &owner) {
10703   assert(capturer);
10704   assert(owner.Variable && owner.Loc.isValid());
10705 
10706   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
10707     << owner.Variable << capturer->getSourceRange();
10708   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
10709     << owner.Indirect << owner.Range;
10710 }
10711 
10712 /// Check for a keyword selector that starts with the word 'add' or
10713 /// 'set'.
10714 static bool isSetterLikeSelector(Selector sel) {
10715   if (sel.isUnarySelector()) return false;
10716 
10717   StringRef str = sel.getNameForSlot(0);
10718   while (!str.empty() && str.front() == '_') str = str.substr(1);
10719   if (str.startswith("set"))
10720     str = str.substr(3);
10721   else if (str.startswith("add")) {
10722     // Specially whitelist 'addOperationWithBlock:'.
10723     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
10724       return false;
10725     str = str.substr(3);
10726   }
10727   else
10728     return false;
10729 
10730   if (str.empty()) return true;
10731   return !isLowercase(str.front());
10732 }
10733 
10734 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
10735                                                     ObjCMessageExpr *Message) {
10736   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
10737                                                 Message->getReceiverInterface(),
10738                                                 NSAPI::ClassId_NSMutableArray);
10739   if (!IsMutableArray) {
10740     return None;
10741   }
10742 
10743   Selector Sel = Message->getSelector();
10744 
10745   Optional<NSAPI::NSArrayMethodKind> MKOpt =
10746     S.NSAPIObj->getNSArrayMethodKind(Sel);
10747   if (!MKOpt) {
10748     return None;
10749   }
10750 
10751   NSAPI::NSArrayMethodKind MK = *MKOpt;
10752 
10753   switch (MK) {
10754     case NSAPI::NSMutableArr_addObject:
10755     case NSAPI::NSMutableArr_insertObjectAtIndex:
10756     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
10757       return 0;
10758     case NSAPI::NSMutableArr_replaceObjectAtIndex:
10759       return 1;
10760 
10761     default:
10762       return None;
10763   }
10764 
10765   return None;
10766 }
10767 
10768 static
10769 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
10770                                                   ObjCMessageExpr *Message) {
10771   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
10772                                             Message->getReceiverInterface(),
10773                                             NSAPI::ClassId_NSMutableDictionary);
10774   if (!IsMutableDictionary) {
10775     return None;
10776   }
10777 
10778   Selector Sel = Message->getSelector();
10779 
10780   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
10781     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
10782   if (!MKOpt) {
10783     return None;
10784   }
10785 
10786   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
10787 
10788   switch (MK) {
10789     case NSAPI::NSMutableDict_setObjectForKey:
10790     case NSAPI::NSMutableDict_setValueForKey:
10791     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
10792       return 0;
10793 
10794     default:
10795       return None;
10796   }
10797 
10798   return None;
10799 }
10800 
10801 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
10802   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
10803                                                 Message->getReceiverInterface(),
10804                                                 NSAPI::ClassId_NSMutableSet);
10805 
10806   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
10807                                             Message->getReceiverInterface(),
10808                                             NSAPI::ClassId_NSMutableOrderedSet);
10809   if (!IsMutableSet && !IsMutableOrderedSet) {
10810     return None;
10811   }
10812 
10813   Selector Sel = Message->getSelector();
10814 
10815   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
10816   if (!MKOpt) {
10817     return None;
10818   }
10819 
10820   NSAPI::NSSetMethodKind MK = *MKOpt;
10821 
10822   switch (MK) {
10823     case NSAPI::NSMutableSet_addObject:
10824     case NSAPI::NSOrderedSet_setObjectAtIndex:
10825     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
10826     case NSAPI::NSOrderedSet_insertObjectAtIndex:
10827       return 0;
10828     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
10829       return 1;
10830   }
10831 
10832   return None;
10833 }
10834 
10835 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
10836   if (!Message->isInstanceMessage()) {
10837     return;
10838   }
10839 
10840   Optional<int> ArgOpt;
10841 
10842   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
10843       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
10844       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
10845     return;
10846   }
10847 
10848   int ArgIndex = *ArgOpt;
10849 
10850   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
10851   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
10852     Arg = OE->getSourceExpr()->IgnoreImpCasts();
10853   }
10854 
10855   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
10856     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
10857       if (ArgRE->isObjCSelfExpr()) {
10858         Diag(Message->getSourceRange().getBegin(),
10859              diag::warn_objc_circular_container)
10860           << ArgRE->getDecl()->getName() << StringRef("super");
10861       }
10862     }
10863   } else {
10864     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
10865 
10866     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
10867       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
10868     }
10869 
10870     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
10871       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
10872         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
10873           ValueDecl *Decl = ReceiverRE->getDecl();
10874           Diag(Message->getSourceRange().getBegin(),
10875                diag::warn_objc_circular_container)
10876             << Decl->getName() << Decl->getName();
10877           if (!ArgRE->isObjCSelfExpr()) {
10878             Diag(Decl->getLocation(),
10879                  diag::note_objc_circular_container_declared_here)
10880               << Decl->getName();
10881           }
10882         }
10883       }
10884     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
10885       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
10886         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
10887           ObjCIvarDecl *Decl = IvarRE->getDecl();
10888           Diag(Message->getSourceRange().getBegin(),
10889                diag::warn_objc_circular_container)
10890             << Decl->getName() << Decl->getName();
10891           Diag(Decl->getLocation(),
10892                diag::note_objc_circular_container_declared_here)
10893             << Decl->getName();
10894         }
10895       }
10896     }
10897   }
10898 }
10899 
10900 /// Check a message send to see if it's likely to cause a retain cycle.
10901 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
10902   // Only check instance methods whose selector looks like a setter.
10903   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
10904     return;
10905 
10906   // Try to find a variable that the receiver is strongly owned by.
10907   RetainCycleOwner owner;
10908   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
10909     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
10910       return;
10911   } else {
10912     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
10913     owner.Variable = getCurMethodDecl()->getSelfDecl();
10914     owner.Loc = msg->getSuperLoc();
10915     owner.Range = msg->getSuperLoc();
10916   }
10917 
10918   // Check whether the receiver is captured by any of the arguments.
10919   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
10920     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
10921       return diagnoseRetainCycle(*this, capturer, owner);
10922 }
10923 
10924 /// Check a property assign to see if it's likely to cause a retain cycle.
10925 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
10926   RetainCycleOwner owner;
10927   if (!findRetainCycleOwner(*this, receiver, owner))
10928     return;
10929 
10930   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
10931     diagnoseRetainCycle(*this, capturer, owner);
10932 }
10933 
10934 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
10935   RetainCycleOwner Owner;
10936   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
10937     return;
10938 
10939   // Because we don't have an expression for the variable, we have to set the
10940   // location explicitly here.
10941   Owner.Loc = Var->getLocation();
10942   Owner.Range = Var->getSourceRange();
10943 
10944   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
10945     diagnoseRetainCycle(*this, Capturer, Owner);
10946 }
10947 
10948 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
10949                                      Expr *RHS, bool isProperty) {
10950   // Check if RHS is an Objective-C object literal, which also can get
10951   // immediately zapped in a weak reference.  Note that we explicitly
10952   // allow ObjCStringLiterals, since those are designed to never really die.
10953   RHS = RHS->IgnoreParenImpCasts();
10954 
10955   // This enum needs to match with the 'select' in
10956   // warn_objc_arc_literal_assign (off-by-1).
10957   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
10958   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
10959     return false;
10960 
10961   S.Diag(Loc, diag::warn_arc_literal_assign)
10962     << (unsigned) Kind
10963     << (isProperty ? 0 : 1)
10964     << RHS->getSourceRange();
10965 
10966   return true;
10967 }
10968 
10969 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
10970                                     Qualifiers::ObjCLifetime LT,
10971                                     Expr *RHS, bool isProperty) {
10972   // Strip off any implicit cast added to get to the one ARC-specific.
10973   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
10974     if (cast->getCastKind() == CK_ARCConsumeObject) {
10975       S.Diag(Loc, diag::warn_arc_retained_assign)
10976         << (LT == Qualifiers::OCL_ExplicitNone)
10977         << (isProperty ? 0 : 1)
10978         << RHS->getSourceRange();
10979       return true;
10980     }
10981     RHS = cast->getSubExpr();
10982   }
10983 
10984   if (LT == Qualifiers::OCL_Weak &&
10985       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
10986     return true;
10987 
10988   return false;
10989 }
10990 
10991 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
10992                               QualType LHS, Expr *RHS) {
10993   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
10994 
10995   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
10996     return false;
10997 
10998   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
10999     return true;
11000 
11001   return false;
11002 }
11003 
11004 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
11005                               Expr *LHS, Expr *RHS) {
11006   QualType LHSType;
11007   // PropertyRef on LHS type need be directly obtained from
11008   // its declaration as it has a PseudoType.
11009   ObjCPropertyRefExpr *PRE
11010     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11011   if (PRE && !PRE->isImplicitProperty()) {
11012     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11013     if (PD)
11014       LHSType = PD->getType();
11015   }
11016 
11017   if (LHSType.isNull())
11018     LHSType = LHS->getType();
11019 
11020   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
11021 
11022   if (LT == Qualifiers::OCL_Weak) {
11023     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
11024       getCurFunction()->markSafeWeakUse(LHS);
11025   }
11026 
11027   if (checkUnsafeAssigns(Loc, LHSType, RHS))
11028     return;
11029 
11030   // FIXME. Check for other life times.
11031   if (LT != Qualifiers::OCL_None)
11032     return;
11033 
11034   if (PRE) {
11035     if (PRE->isImplicitProperty())
11036       return;
11037     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11038     if (!PD)
11039       return;
11040 
11041     unsigned Attributes = PD->getPropertyAttributes();
11042     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
11043       // when 'assign' attribute was not explicitly specified
11044       // by user, ignore it and rely on property type itself
11045       // for lifetime info.
11046       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11047       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11048           LHSType->isObjCRetainableType())
11049         return;
11050 
11051       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11052         if (cast->getCastKind() == CK_ARCConsumeObject) {
11053           Diag(Loc, diag::warn_arc_retained_property_assign)
11054           << RHS->getSourceRange();
11055           return;
11056         }
11057         RHS = cast->getSubExpr();
11058       }
11059     }
11060     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
11061       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11062         return;
11063     }
11064   }
11065 }
11066 
11067 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11068 
11069 namespace {
11070 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11071                                  SourceLocation StmtLoc,
11072                                  const NullStmt *Body) {
11073   // Do not warn if the body is a macro that expands to nothing, e.g:
11074   //
11075   // #define CALL(x)
11076   // if (condition)
11077   //   CALL(0);
11078   //
11079   if (Body->hasLeadingEmptyMacro())
11080     return false;
11081 
11082   // Get line numbers of statement and body.
11083   bool StmtLineInvalid;
11084   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
11085                                                       &StmtLineInvalid);
11086   if (StmtLineInvalid)
11087     return false;
11088 
11089   bool BodyLineInvalid;
11090   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11091                                                       &BodyLineInvalid);
11092   if (BodyLineInvalid)
11093     return false;
11094 
11095   // Warn if null statement and body are on the same line.
11096   if (StmtLine != BodyLine)
11097     return false;
11098 
11099   return true;
11100 }
11101 } // end anonymous namespace
11102 
11103 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
11104                                  const Stmt *Body,
11105                                  unsigned DiagID) {
11106   // Since this is a syntactic check, don't emit diagnostic for template
11107   // instantiations, this just adds noise.
11108   if (CurrentInstantiationScope)
11109     return;
11110 
11111   // The body should be a null statement.
11112   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11113   if (!NBody)
11114     return;
11115 
11116   // Do the usual checks.
11117   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11118     return;
11119 
11120   Diag(NBody->getSemiLoc(), DiagID);
11121   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11122 }
11123 
11124 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
11125                                  const Stmt *PossibleBody) {
11126   assert(!CurrentInstantiationScope); // Ensured by caller
11127 
11128   SourceLocation StmtLoc;
11129   const Stmt *Body;
11130   unsigned DiagID;
11131   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11132     StmtLoc = FS->getRParenLoc();
11133     Body = FS->getBody();
11134     DiagID = diag::warn_empty_for_body;
11135   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11136     StmtLoc = WS->getCond()->getSourceRange().getEnd();
11137     Body = WS->getBody();
11138     DiagID = diag::warn_empty_while_body;
11139   } else
11140     return; // Neither `for' nor `while'.
11141 
11142   // The body should be a null statement.
11143   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11144   if (!NBody)
11145     return;
11146 
11147   // Skip expensive checks if diagnostic is disabled.
11148   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
11149     return;
11150 
11151   // Do the usual checks.
11152   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11153     return;
11154 
11155   // `for(...);' and `while(...);' are popular idioms, so in order to keep
11156   // noise level low, emit diagnostics only if for/while is followed by a
11157   // CompoundStmt, e.g.:
11158   //    for (int i = 0; i < n; i++);
11159   //    {
11160   //      a(i);
11161   //    }
11162   // or if for/while is followed by a statement with more indentation
11163   // than for/while itself:
11164   //    for (int i = 0; i < n; i++);
11165   //      a(i);
11166   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
11167   if (!ProbableTypo) {
11168     bool BodyColInvalid;
11169     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
11170                              PossibleBody->getLocStart(),
11171                              &BodyColInvalid);
11172     if (BodyColInvalid)
11173       return;
11174 
11175     bool StmtColInvalid;
11176     unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
11177                              S->getLocStart(),
11178                              &StmtColInvalid);
11179     if (StmtColInvalid)
11180       return;
11181 
11182     if (BodyCol > StmtCol)
11183       ProbableTypo = true;
11184   }
11185 
11186   if (ProbableTypo) {
11187     Diag(NBody->getSemiLoc(), DiagID);
11188     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11189   }
11190 }
11191 
11192 //===--- CHECK: Warn on self move with std::move. -------------------------===//
11193 
11194 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
11195 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
11196                              SourceLocation OpLoc) {
11197   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11198     return;
11199 
11200   if (!ActiveTemplateInstantiations.empty())
11201     return;
11202 
11203   // Strip parens and casts away.
11204   LHSExpr = LHSExpr->IgnoreParenImpCasts();
11205   RHSExpr = RHSExpr->IgnoreParenImpCasts();
11206 
11207   // Check for a call expression
11208   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
11209   if (!CE || CE->getNumArgs() != 1)
11210     return;
11211 
11212   // Check for a call to std::move
11213   const FunctionDecl *FD = CE->getDirectCallee();
11214   if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
11215       !FD->getIdentifier()->isStr("move"))
11216     return;
11217 
11218   // Get argument from std::move
11219   RHSExpr = CE->getArg(0);
11220 
11221   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11222   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11223 
11224   // Two DeclRefExpr's, check that the decls are the same.
11225   if (LHSDeclRef && RHSDeclRef) {
11226     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11227       return;
11228     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11229         RHSDeclRef->getDecl()->getCanonicalDecl())
11230       return;
11231 
11232     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11233                                         << LHSExpr->getSourceRange()
11234                                         << RHSExpr->getSourceRange();
11235     return;
11236   }
11237 
11238   // Member variables require a different approach to check for self moves.
11239   // MemberExpr's are the same if every nested MemberExpr refers to the same
11240   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
11241   // the base Expr's are CXXThisExpr's.
11242   const Expr *LHSBase = LHSExpr;
11243   const Expr *RHSBase = RHSExpr;
11244   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
11245   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
11246   if (!LHSME || !RHSME)
11247     return;
11248 
11249   while (LHSME && RHSME) {
11250     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
11251         RHSME->getMemberDecl()->getCanonicalDecl())
11252       return;
11253 
11254     LHSBase = LHSME->getBase();
11255     RHSBase = RHSME->getBase();
11256     LHSME = dyn_cast<MemberExpr>(LHSBase);
11257     RHSME = dyn_cast<MemberExpr>(RHSBase);
11258   }
11259 
11260   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
11261   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
11262   if (LHSDeclRef && RHSDeclRef) {
11263     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11264       return;
11265     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11266         RHSDeclRef->getDecl()->getCanonicalDecl())
11267       return;
11268 
11269     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11270                                         << LHSExpr->getSourceRange()
11271                                         << RHSExpr->getSourceRange();
11272     return;
11273   }
11274 
11275   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
11276     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11277                                         << LHSExpr->getSourceRange()
11278                                         << RHSExpr->getSourceRange();
11279 }
11280 
11281 //===--- Layout compatibility ----------------------------------------------//
11282 
11283 namespace {
11284 
11285 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
11286 
11287 /// \brief Check if two enumeration types are layout-compatible.
11288 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
11289   // C++11 [dcl.enum] p8:
11290   // Two enumeration types are layout-compatible if they have the same
11291   // underlying type.
11292   return ED1->isComplete() && ED2->isComplete() &&
11293          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
11294 }
11295 
11296 /// \brief Check if two fields are layout-compatible.
11297 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
11298   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
11299     return false;
11300 
11301   if (Field1->isBitField() != Field2->isBitField())
11302     return false;
11303 
11304   if (Field1->isBitField()) {
11305     // Make sure that the bit-fields are the same length.
11306     unsigned Bits1 = Field1->getBitWidthValue(C);
11307     unsigned Bits2 = Field2->getBitWidthValue(C);
11308 
11309     if (Bits1 != Bits2)
11310       return false;
11311   }
11312 
11313   return true;
11314 }
11315 
11316 /// \brief Check if two standard-layout structs are layout-compatible.
11317 /// (C++11 [class.mem] p17)
11318 bool isLayoutCompatibleStruct(ASTContext &C,
11319                               RecordDecl *RD1,
11320                               RecordDecl *RD2) {
11321   // If both records are C++ classes, check that base classes match.
11322   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
11323     // If one of records is a CXXRecordDecl we are in C++ mode,
11324     // thus the other one is a CXXRecordDecl, too.
11325     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
11326     // Check number of base classes.
11327     if (D1CXX->getNumBases() != D2CXX->getNumBases())
11328       return false;
11329 
11330     // Check the base classes.
11331     for (CXXRecordDecl::base_class_const_iterator
11332                Base1 = D1CXX->bases_begin(),
11333            BaseEnd1 = D1CXX->bases_end(),
11334               Base2 = D2CXX->bases_begin();
11335          Base1 != BaseEnd1;
11336          ++Base1, ++Base2) {
11337       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
11338         return false;
11339     }
11340   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
11341     // If only RD2 is a C++ class, it should have zero base classes.
11342     if (D2CXX->getNumBases() > 0)
11343       return false;
11344   }
11345 
11346   // Check the fields.
11347   RecordDecl::field_iterator Field2 = RD2->field_begin(),
11348                              Field2End = RD2->field_end(),
11349                              Field1 = RD1->field_begin(),
11350                              Field1End = RD1->field_end();
11351   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
11352     if (!isLayoutCompatible(C, *Field1, *Field2))
11353       return false;
11354   }
11355   if (Field1 != Field1End || Field2 != Field2End)
11356     return false;
11357 
11358   return true;
11359 }
11360 
11361 /// \brief Check if two standard-layout unions are layout-compatible.
11362 /// (C++11 [class.mem] p18)
11363 bool isLayoutCompatibleUnion(ASTContext &C,
11364                              RecordDecl *RD1,
11365                              RecordDecl *RD2) {
11366   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
11367   for (auto *Field2 : RD2->fields())
11368     UnmatchedFields.insert(Field2);
11369 
11370   for (auto *Field1 : RD1->fields()) {
11371     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
11372         I = UnmatchedFields.begin(),
11373         E = UnmatchedFields.end();
11374 
11375     for ( ; I != E; ++I) {
11376       if (isLayoutCompatible(C, Field1, *I)) {
11377         bool Result = UnmatchedFields.erase(*I);
11378         (void) Result;
11379         assert(Result);
11380         break;
11381       }
11382     }
11383     if (I == E)
11384       return false;
11385   }
11386 
11387   return UnmatchedFields.empty();
11388 }
11389 
11390 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
11391   if (RD1->isUnion() != RD2->isUnion())
11392     return false;
11393 
11394   if (RD1->isUnion())
11395     return isLayoutCompatibleUnion(C, RD1, RD2);
11396   else
11397     return isLayoutCompatibleStruct(C, RD1, RD2);
11398 }
11399 
11400 /// \brief Check if two types are layout-compatible in C++11 sense.
11401 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
11402   if (T1.isNull() || T2.isNull())
11403     return false;
11404 
11405   // C++11 [basic.types] p11:
11406   // If two types T1 and T2 are the same type, then T1 and T2 are
11407   // layout-compatible types.
11408   if (C.hasSameType(T1, T2))
11409     return true;
11410 
11411   T1 = T1.getCanonicalType().getUnqualifiedType();
11412   T2 = T2.getCanonicalType().getUnqualifiedType();
11413 
11414   const Type::TypeClass TC1 = T1->getTypeClass();
11415   const Type::TypeClass TC2 = T2->getTypeClass();
11416 
11417   if (TC1 != TC2)
11418     return false;
11419 
11420   if (TC1 == Type::Enum) {
11421     return isLayoutCompatible(C,
11422                               cast<EnumType>(T1)->getDecl(),
11423                               cast<EnumType>(T2)->getDecl());
11424   } else if (TC1 == Type::Record) {
11425     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
11426       return false;
11427 
11428     return isLayoutCompatible(C,
11429                               cast<RecordType>(T1)->getDecl(),
11430                               cast<RecordType>(T2)->getDecl());
11431   }
11432 
11433   return false;
11434 }
11435 } // end anonymous namespace
11436 
11437 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
11438 
11439 namespace {
11440 /// \brief Given a type tag expression find the type tag itself.
11441 ///
11442 /// \param TypeExpr Type tag expression, as it appears in user's code.
11443 ///
11444 /// \param VD Declaration of an identifier that appears in a type tag.
11445 ///
11446 /// \param MagicValue Type tag magic value.
11447 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
11448                      const ValueDecl **VD, uint64_t *MagicValue) {
11449   while(true) {
11450     if (!TypeExpr)
11451       return false;
11452 
11453     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
11454 
11455     switch (TypeExpr->getStmtClass()) {
11456     case Stmt::UnaryOperatorClass: {
11457       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
11458       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
11459         TypeExpr = UO->getSubExpr();
11460         continue;
11461       }
11462       return false;
11463     }
11464 
11465     case Stmt::DeclRefExprClass: {
11466       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
11467       *VD = DRE->getDecl();
11468       return true;
11469     }
11470 
11471     case Stmt::IntegerLiteralClass: {
11472       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
11473       llvm::APInt MagicValueAPInt = IL->getValue();
11474       if (MagicValueAPInt.getActiveBits() <= 64) {
11475         *MagicValue = MagicValueAPInt.getZExtValue();
11476         return true;
11477       } else
11478         return false;
11479     }
11480 
11481     case Stmt::BinaryConditionalOperatorClass:
11482     case Stmt::ConditionalOperatorClass: {
11483       const AbstractConditionalOperator *ACO =
11484           cast<AbstractConditionalOperator>(TypeExpr);
11485       bool Result;
11486       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
11487         if (Result)
11488           TypeExpr = ACO->getTrueExpr();
11489         else
11490           TypeExpr = ACO->getFalseExpr();
11491         continue;
11492       }
11493       return false;
11494     }
11495 
11496     case Stmt::BinaryOperatorClass: {
11497       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
11498       if (BO->getOpcode() == BO_Comma) {
11499         TypeExpr = BO->getRHS();
11500         continue;
11501       }
11502       return false;
11503     }
11504 
11505     default:
11506       return false;
11507     }
11508   }
11509 }
11510 
11511 /// \brief Retrieve the C type corresponding to type tag TypeExpr.
11512 ///
11513 /// \param TypeExpr Expression that specifies a type tag.
11514 ///
11515 /// \param MagicValues Registered magic values.
11516 ///
11517 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
11518 ///        kind.
11519 ///
11520 /// \param TypeInfo Information about the corresponding C type.
11521 ///
11522 /// \returns true if the corresponding C type was found.
11523 bool GetMatchingCType(
11524         const IdentifierInfo *ArgumentKind,
11525         const Expr *TypeExpr, const ASTContext &Ctx,
11526         const llvm::DenseMap<Sema::TypeTagMagicValue,
11527                              Sema::TypeTagData> *MagicValues,
11528         bool &FoundWrongKind,
11529         Sema::TypeTagData &TypeInfo) {
11530   FoundWrongKind = false;
11531 
11532   // Variable declaration that has type_tag_for_datatype attribute.
11533   const ValueDecl *VD = nullptr;
11534 
11535   uint64_t MagicValue;
11536 
11537   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
11538     return false;
11539 
11540   if (VD) {
11541     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
11542       if (I->getArgumentKind() != ArgumentKind) {
11543         FoundWrongKind = true;
11544         return false;
11545       }
11546       TypeInfo.Type = I->getMatchingCType();
11547       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
11548       TypeInfo.MustBeNull = I->getMustBeNull();
11549       return true;
11550     }
11551     return false;
11552   }
11553 
11554   if (!MagicValues)
11555     return false;
11556 
11557   llvm::DenseMap<Sema::TypeTagMagicValue,
11558                  Sema::TypeTagData>::const_iterator I =
11559       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
11560   if (I == MagicValues->end())
11561     return false;
11562 
11563   TypeInfo = I->second;
11564   return true;
11565 }
11566 } // end anonymous namespace
11567 
11568 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
11569                                       uint64_t MagicValue, QualType Type,
11570                                       bool LayoutCompatible,
11571                                       bool MustBeNull) {
11572   if (!TypeTagForDatatypeMagicValues)
11573     TypeTagForDatatypeMagicValues.reset(
11574         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
11575 
11576   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
11577   (*TypeTagForDatatypeMagicValues)[Magic] =
11578       TypeTagData(Type, LayoutCompatible, MustBeNull);
11579 }
11580 
11581 namespace {
11582 bool IsSameCharType(QualType T1, QualType T2) {
11583   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
11584   if (!BT1)
11585     return false;
11586 
11587   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
11588   if (!BT2)
11589     return false;
11590 
11591   BuiltinType::Kind T1Kind = BT1->getKind();
11592   BuiltinType::Kind T2Kind = BT2->getKind();
11593 
11594   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
11595          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
11596          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
11597          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
11598 }
11599 } // end anonymous namespace
11600 
11601 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
11602                                     const Expr * const *ExprArgs) {
11603   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
11604   bool IsPointerAttr = Attr->getIsPointer();
11605 
11606   const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
11607   bool FoundWrongKind;
11608   TypeTagData TypeInfo;
11609   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
11610                         TypeTagForDatatypeMagicValues.get(),
11611                         FoundWrongKind, TypeInfo)) {
11612     if (FoundWrongKind)
11613       Diag(TypeTagExpr->getExprLoc(),
11614            diag::warn_type_tag_for_datatype_wrong_kind)
11615         << TypeTagExpr->getSourceRange();
11616     return;
11617   }
11618 
11619   const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
11620   if (IsPointerAttr) {
11621     // Skip implicit cast of pointer to `void *' (as a function argument).
11622     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
11623       if (ICE->getType()->isVoidPointerType() &&
11624           ICE->getCastKind() == CK_BitCast)
11625         ArgumentExpr = ICE->getSubExpr();
11626   }
11627   QualType ArgumentType = ArgumentExpr->getType();
11628 
11629   // Passing a `void*' pointer shouldn't trigger a warning.
11630   if (IsPointerAttr && ArgumentType->isVoidPointerType())
11631     return;
11632 
11633   if (TypeInfo.MustBeNull) {
11634     // Type tag with matching void type requires a null pointer.
11635     if (!ArgumentExpr->isNullPointerConstant(Context,
11636                                              Expr::NPC_ValueDependentIsNotNull)) {
11637       Diag(ArgumentExpr->getExprLoc(),
11638            diag::warn_type_safety_null_pointer_required)
11639           << ArgumentKind->getName()
11640           << ArgumentExpr->getSourceRange()
11641           << TypeTagExpr->getSourceRange();
11642     }
11643     return;
11644   }
11645 
11646   QualType RequiredType = TypeInfo.Type;
11647   if (IsPointerAttr)
11648     RequiredType = Context.getPointerType(RequiredType);
11649 
11650   bool mismatch = false;
11651   if (!TypeInfo.LayoutCompatible) {
11652     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
11653 
11654     // C++11 [basic.fundamental] p1:
11655     // Plain char, signed char, and unsigned char are three distinct types.
11656     //
11657     // But we treat plain `char' as equivalent to `signed char' or `unsigned
11658     // char' depending on the current char signedness mode.
11659     if (mismatch)
11660       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
11661                                            RequiredType->getPointeeType())) ||
11662           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
11663         mismatch = false;
11664   } else
11665     if (IsPointerAttr)
11666       mismatch = !isLayoutCompatible(Context,
11667                                      ArgumentType->getPointeeType(),
11668                                      RequiredType->getPointeeType());
11669     else
11670       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
11671 
11672   if (mismatch)
11673     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
11674         << ArgumentType << ArgumentKind
11675         << TypeInfo.LayoutCompatible << RequiredType
11676         << ArgumentExpr->getSourceRange()
11677         << TypeTagExpr->getSourceRange();
11678 }
11679 
11680 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
11681                                          CharUnits Alignment) {
11682   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
11683 }
11684 
11685 void Sema::DiagnoseMisalignedMembers() {
11686   for (MisalignedMember &m : MisalignedMembers) {
11687     const NamedDecl *ND = m.RD;
11688     if (ND->getName().empty()) {
11689       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
11690         ND = TD;
11691     }
11692     Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
11693         << m.MD << ND << m.E->getSourceRange();
11694   }
11695   MisalignedMembers.clear();
11696 }
11697 
11698 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
11699   E = E->IgnoreParens();
11700   if (!T->isPointerType() && !T->isIntegerType())
11701     return;
11702   if (isa<UnaryOperator>(E) &&
11703       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
11704     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11705     if (isa<MemberExpr>(Op)) {
11706       auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
11707                           MisalignedMember(Op));
11708       if (MA != MisalignedMembers.end() &&
11709           (T->isIntegerType() ||
11710            (T->isPointerType() &&
11711             Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment)))
11712         MisalignedMembers.erase(MA);
11713     }
11714   }
11715 }
11716 
11717 void Sema::RefersToMemberWithReducedAlignment(
11718     Expr *E,
11719     std::function<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> Action) {
11720   const auto *ME = dyn_cast<MemberExpr>(E);
11721   if (!ME)
11722     return;
11723 
11724   // For a chain of MemberExpr like "a.b.c.d" this list
11725   // will keep FieldDecl's like [d, c, b].
11726   SmallVector<FieldDecl *, 4> ReverseMemberChain;
11727   const MemberExpr *TopME = nullptr;
11728   bool AnyIsPacked = false;
11729   do {
11730     QualType BaseType = ME->getBase()->getType();
11731     if (ME->isArrow())
11732       BaseType = BaseType->getPointeeType();
11733     RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
11734 
11735     ValueDecl *MD = ME->getMemberDecl();
11736     auto *FD = dyn_cast<FieldDecl>(MD);
11737     // We do not care about non-data members.
11738     if (!FD || FD->isInvalidDecl())
11739       return;
11740 
11741     AnyIsPacked =
11742         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
11743     ReverseMemberChain.push_back(FD);
11744 
11745     TopME = ME;
11746     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
11747   } while (ME);
11748   assert(TopME && "We did not compute a topmost MemberExpr!");
11749 
11750   // Not the scope of this diagnostic.
11751   if (!AnyIsPacked)
11752     return;
11753 
11754   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
11755   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
11756   // TODO: The innermost base of the member expression may be too complicated.
11757   // For now, just disregard these cases. This is left for future
11758   // improvement.
11759   if (!DRE && !isa<CXXThisExpr>(TopBase))
11760       return;
11761 
11762   // Alignment expected by the whole expression.
11763   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
11764 
11765   // No need to do anything else with this case.
11766   if (ExpectedAlignment.isOne())
11767     return;
11768 
11769   // Synthesize offset of the whole access.
11770   CharUnits Offset;
11771   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
11772        I++) {
11773     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
11774   }
11775 
11776   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
11777   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
11778       ReverseMemberChain.back()->getParent()->getTypeForDecl());
11779 
11780   // The base expression of the innermost MemberExpr may give
11781   // stronger guarantees than the class containing the member.
11782   if (DRE && !TopME->isArrow()) {
11783     const ValueDecl *VD = DRE->getDecl();
11784     if (!VD->getType()->isReferenceType())
11785       CompleteObjectAlignment =
11786           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
11787   }
11788 
11789   // Check if the synthesized offset fulfills the alignment.
11790   if (Offset % ExpectedAlignment != 0 ||
11791       // It may fulfill the offset it but the effective alignment may still be
11792       // lower than the expected expression alignment.
11793       CompleteObjectAlignment < ExpectedAlignment) {
11794     // If this happens, we want to determine a sensible culprit of this.
11795     // Intuitively, watching the chain of member expressions from right to
11796     // left, we start with the required alignment (as required by the field
11797     // type) but some packed attribute in that chain has reduced the alignment.
11798     // It may happen that another packed structure increases it again. But if
11799     // we are here such increase has not been enough. So pointing the first
11800     // FieldDecl that either is packed or else its RecordDecl is,
11801     // seems reasonable.
11802     FieldDecl *FD = nullptr;
11803     CharUnits Alignment;
11804     for (FieldDecl *FDI : ReverseMemberChain) {
11805       if (FDI->hasAttr<PackedAttr>() ||
11806           FDI->getParent()->hasAttr<PackedAttr>()) {
11807         FD = FDI;
11808         Alignment = std::min(
11809             Context.getTypeAlignInChars(FD->getType()),
11810             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
11811         break;
11812       }
11813     }
11814     assert(FD && "We did not find a packed FieldDecl!");
11815     Action(E, FD->getParent(), FD, Alignment);
11816   }
11817 }
11818 
11819 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
11820   using namespace std::placeholders;
11821   RefersToMemberWithReducedAlignment(
11822       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
11823                      _2, _3, _4));
11824 }
11825 
11826