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/Sema/SemaInternal.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/CharUnits.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/EvaluatedExprVisitor.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/ExprObjC.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/Preprocessor.h"
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 "llvm/ADT/STLExtras.h"
36 #include "llvm/ADT/SmallBitVector.h"
37 #include "llvm/ADT/SmallString.h"
38 #include "llvm/Support/ConvertUTF.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include <limits>
41 using namespace clang;
42 using namespace sema;
43 
44 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
45                                                     unsigned ByteNo) const {
46   return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
47                                PP.getLangOpts(), PP.getTargetInfo());
48 }
49 
50 /// Checks that a call expression's argument count is the desired number.
51 /// This is useful when doing custom type-checking.  Returns true on error.
52 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
53   unsigned argCount = call->getNumArgs();
54   if (argCount == desiredArgCount) return false;
55 
56   if (argCount < desiredArgCount)
57     return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
58         << 0 /*function call*/ << desiredArgCount << argCount
59         << call->getSourceRange();
60 
61   // Highlight all the excess arguments.
62   SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
63                     call->getArg(argCount - 1)->getLocEnd());
64 
65   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
66     << 0 /*function call*/ << desiredArgCount << argCount
67     << call->getArg(1)->getSourceRange();
68 }
69 
70 /// Check that the first argument to __builtin_annotation is an integer
71 /// and the second argument is a non-wide string literal.
72 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
73   if (checkArgCount(S, TheCall, 2))
74     return true;
75 
76   // First argument should be an integer.
77   Expr *ValArg = TheCall->getArg(0);
78   QualType Ty = ValArg->getType();
79   if (!Ty->isIntegerType()) {
80     S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
81       << ValArg->getSourceRange();
82     return true;
83   }
84 
85   // Second argument should be a constant string.
86   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
87   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
88   if (!Literal || !Literal->isAscii()) {
89     S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
90       << StrArg->getSourceRange();
91     return true;
92   }
93 
94   TheCall->setType(Ty);
95   return false;
96 }
97 
98 /// Check that the argument to __builtin_addressof is a glvalue, and set the
99 /// result type to the corresponding pointer type.
100 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
101   if (checkArgCount(S, TheCall, 1))
102     return true;
103 
104   ExprResult Arg(S.Owned(TheCall->getArg(0)));
105   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
106   if (ResultType.isNull())
107     return true;
108 
109   TheCall->setArg(0, Arg.take());
110   TheCall->setType(ResultType);
111   return false;
112 }
113 
114 ExprResult
115 Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
116   ExprResult TheCallResult(Owned(TheCall));
117 
118   // Find out if any arguments are required to be integer constant expressions.
119   unsigned ICEArguments = 0;
120   ASTContext::GetBuiltinTypeError Error;
121   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
122   if (Error != ASTContext::GE_None)
123     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
124 
125   // If any arguments are required to be ICE's, check and diagnose.
126   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
127     // Skip arguments not required to be ICE's.
128     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
129 
130     llvm::APSInt Result;
131     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
132       return true;
133     ICEArguments &= ~(1 << ArgNo);
134   }
135 
136   switch (BuiltinID) {
137   case Builtin::BI__builtin___CFStringMakeConstantString:
138     assert(TheCall->getNumArgs() == 1 &&
139            "Wrong # arguments to builtin CFStringMakeConstantString");
140     if (CheckObjCString(TheCall->getArg(0)))
141       return ExprError();
142     break;
143   case Builtin::BI__builtin_stdarg_start:
144   case Builtin::BI__builtin_va_start:
145     if (SemaBuiltinVAStart(TheCall))
146       return ExprError();
147     break;
148   case Builtin::BI__builtin_isgreater:
149   case Builtin::BI__builtin_isgreaterequal:
150   case Builtin::BI__builtin_isless:
151   case Builtin::BI__builtin_islessequal:
152   case Builtin::BI__builtin_islessgreater:
153   case Builtin::BI__builtin_isunordered:
154     if (SemaBuiltinUnorderedCompare(TheCall))
155       return ExprError();
156     break;
157   case Builtin::BI__builtin_fpclassify:
158     if (SemaBuiltinFPClassification(TheCall, 6))
159       return ExprError();
160     break;
161   case Builtin::BI__builtin_isfinite:
162   case Builtin::BI__builtin_isinf:
163   case Builtin::BI__builtin_isinf_sign:
164   case Builtin::BI__builtin_isnan:
165   case Builtin::BI__builtin_isnormal:
166     if (SemaBuiltinFPClassification(TheCall, 1))
167       return ExprError();
168     break;
169   case Builtin::BI__builtin_shufflevector:
170     return SemaBuiltinShuffleVector(TheCall);
171     // TheCall will be freed by the smart pointer here, but that's fine, since
172     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
173   case Builtin::BI__builtin_prefetch:
174     if (SemaBuiltinPrefetch(TheCall))
175       return ExprError();
176     break;
177   case Builtin::BI__builtin_object_size:
178     if (SemaBuiltinObjectSize(TheCall))
179       return ExprError();
180     break;
181   case Builtin::BI__builtin_longjmp:
182     if (SemaBuiltinLongjmp(TheCall))
183       return ExprError();
184     break;
185 
186   case Builtin::BI__builtin_classify_type:
187     if (checkArgCount(*this, TheCall, 1)) return true;
188     TheCall->setType(Context.IntTy);
189     break;
190   case Builtin::BI__builtin_constant_p:
191     if (checkArgCount(*this, TheCall, 1)) return true;
192     TheCall->setType(Context.IntTy);
193     break;
194   case Builtin::BI__sync_fetch_and_add:
195   case Builtin::BI__sync_fetch_and_add_1:
196   case Builtin::BI__sync_fetch_and_add_2:
197   case Builtin::BI__sync_fetch_and_add_4:
198   case Builtin::BI__sync_fetch_and_add_8:
199   case Builtin::BI__sync_fetch_and_add_16:
200   case Builtin::BI__sync_fetch_and_sub:
201   case Builtin::BI__sync_fetch_and_sub_1:
202   case Builtin::BI__sync_fetch_and_sub_2:
203   case Builtin::BI__sync_fetch_and_sub_4:
204   case Builtin::BI__sync_fetch_and_sub_8:
205   case Builtin::BI__sync_fetch_and_sub_16:
206   case Builtin::BI__sync_fetch_and_or:
207   case Builtin::BI__sync_fetch_and_or_1:
208   case Builtin::BI__sync_fetch_and_or_2:
209   case Builtin::BI__sync_fetch_and_or_4:
210   case Builtin::BI__sync_fetch_and_or_8:
211   case Builtin::BI__sync_fetch_and_or_16:
212   case Builtin::BI__sync_fetch_and_and:
213   case Builtin::BI__sync_fetch_and_and_1:
214   case Builtin::BI__sync_fetch_and_and_2:
215   case Builtin::BI__sync_fetch_and_and_4:
216   case Builtin::BI__sync_fetch_and_and_8:
217   case Builtin::BI__sync_fetch_and_and_16:
218   case Builtin::BI__sync_fetch_and_xor:
219   case Builtin::BI__sync_fetch_and_xor_1:
220   case Builtin::BI__sync_fetch_and_xor_2:
221   case Builtin::BI__sync_fetch_and_xor_4:
222   case Builtin::BI__sync_fetch_and_xor_8:
223   case Builtin::BI__sync_fetch_and_xor_16:
224   case Builtin::BI__sync_add_and_fetch:
225   case Builtin::BI__sync_add_and_fetch_1:
226   case Builtin::BI__sync_add_and_fetch_2:
227   case Builtin::BI__sync_add_and_fetch_4:
228   case Builtin::BI__sync_add_and_fetch_8:
229   case Builtin::BI__sync_add_and_fetch_16:
230   case Builtin::BI__sync_sub_and_fetch:
231   case Builtin::BI__sync_sub_and_fetch_1:
232   case Builtin::BI__sync_sub_and_fetch_2:
233   case Builtin::BI__sync_sub_and_fetch_4:
234   case Builtin::BI__sync_sub_and_fetch_8:
235   case Builtin::BI__sync_sub_and_fetch_16:
236   case Builtin::BI__sync_and_and_fetch:
237   case Builtin::BI__sync_and_and_fetch_1:
238   case Builtin::BI__sync_and_and_fetch_2:
239   case Builtin::BI__sync_and_and_fetch_4:
240   case Builtin::BI__sync_and_and_fetch_8:
241   case Builtin::BI__sync_and_and_fetch_16:
242   case Builtin::BI__sync_or_and_fetch:
243   case Builtin::BI__sync_or_and_fetch_1:
244   case Builtin::BI__sync_or_and_fetch_2:
245   case Builtin::BI__sync_or_and_fetch_4:
246   case Builtin::BI__sync_or_and_fetch_8:
247   case Builtin::BI__sync_or_and_fetch_16:
248   case Builtin::BI__sync_xor_and_fetch:
249   case Builtin::BI__sync_xor_and_fetch_1:
250   case Builtin::BI__sync_xor_and_fetch_2:
251   case Builtin::BI__sync_xor_and_fetch_4:
252   case Builtin::BI__sync_xor_and_fetch_8:
253   case Builtin::BI__sync_xor_and_fetch_16:
254   case Builtin::BI__sync_val_compare_and_swap:
255   case Builtin::BI__sync_val_compare_and_swap_1:
256   case Builtin::BI__sync_val_compare_and_swap_2:
257   case Builtin::BI__sync_val_compare_and_swap_4:
258   case Builtin::BI__sync_val_compare_and_swap_8:
259   case Builtin::BI__sync_val_compare_and_swap_16:
260   case Builtin::BI__sync_bool_compare_and_swap:
261   case Builtin::BI__sync_bool_compare_and_swap_1:
262   case Builtin::BI__sync_bool_compare_and_swap_2:
263   case Builtin::BI__sync_bool_compare_and_swap_4:
264   case Builtin::BI__sync_bool_compare_and_swap_8:
265   case Builtin::BI__sync_bool_compare_and_swap_16:
266   case Builtin::BI__sync_lock_test_and_set:
267   case Builtin::BI__sync_lock_test_and_set_1:
268   case Builtin::BI__sync_lock_test_and_set_2:
269   case Builtin::BI__sync_lock_test_and_set_4:
270   case Builtin::BI__sync_lock_test_and_set_8:
271   case Builtin::BI__sync_lock_test_and_set_16:
272   case Builtin::BI__sync_lock_release:
273   case Builtin::BI__sync_lock_release_1:
274   case Builtin::BI__sync_lock_release_2:
275   case Builtin::BI__sync_lock_release_4:
276   case Builtin::BI__sync_lock_release_8:
277   case Builtin::BI__sync_lock_release_16:
278   case Builtin::BI__sync_swap:
279   case Builtin::BI__sync_swap_1:
280   case Builtin::BI__sync_swap_2:
281   case Builtin::BI__sync_swap_4:
282   case Builtin::BI__sync_swap_8:
283   case Builtin::BI__sync_swap_16:
284     return SemaBuiltinAtomicOverloaded(TheCallResult);
285 #define BUILTIN(ID, TYPE, ATTRS)
286 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
287   case Builtin::BI##ID: \
288     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
289 #include "clang/Basic/Builtins.def"
290   case Builtin::BI__builtin_annotation:
291     if (SemaBuiltinAnnotation(*this, TheCall))
292       return ExprError();
293     break;
294   case Builtin::BI__builtin_addressof:
295     if (SemaBuiltinAddressof(*this, TheCall))
296       return ExprError();
297     break;
298   }
299 
300   // Since the target specific builtins for each arch overlap, only check those
301   // of the arch we are compiling for.
302   if (BuiltinID >= Builtin::FirstTSBuiltin) {
303     switch (Context.getTargetInfo().getTriple().getArch()) {
304       case llvm::Triple::arm:
305       case llvm::Triple::thumb:
306         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
307           return ExprError();
308         break;
309       case llvm::Triple::aarch64:
310       case llvm::Triple::aarch64_be:
311         if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
312           return ExprError();
313         break;
314       case llvm::Triple::mips:
315       case llvm::Triple::mipsel:
316       case llvm::Triple::mips64:
317       case llvm::Triple::mips64el:
318         if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
319           return ExprError();
320         break;
321       case llvm::Triple::x86:
322       case llvm::Triple::x86_64:
323         if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
324           return ExprError();
325         break;
326       default:
327         break;
328     }
329   }
330 
331   return TheCallResult;
332 }
333 
334 // Get the valid immediate range for the specified NEON type code.
335 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
336   NeonTypeFlags Type(t);
337   int IsQuad = ForceQuad ? true : Type.isQuad();
338   switch (Type.getEltType()) {
339   case NeonTypeFlags::Int8:
340   case NeonTypeFlags::Poly8:
341     return shift ? 7 : (8 << IsQuad) - 1;
342   case NeonTypeFlags::Int16:
343   case NeonTypeFlags::Poly16:
344     return shift ? 15 : (4 << IsQuad) - 1;
345   case NeonTypeFlags::Int32:
346     return shift ? 31 : (2 << IsQuad) - 1;
347   case NeonTypeFlags::Int64:
348   case NeonTypeFlags::Poly64:
349     return shift ? 63 : (1 << IsQuad) - 1;
350   case NeonTypeFlags::Poly128:
351     return shift ? 127 : (1 << IsQuad) - 1;
352   case NeonTypeFlags::Float16:
353     assert(!shift && "cannot shift float types!");
354     return (4 << IsQuad) - 1;
355   case NeonTypeFlags::Float32:
356     assert(!shift && "cannot shift float types!");
357     return (2 << IsQuad) - 1;
358   case NeonTypeFlags::Float64:
359     assert(!shift && "cannot shift float types!");
360     return (1 << IsQuad) - 1;
361   }
362   llvm_unreachable("Invalid NeonTypeFlag!");
363 }
364 
365 /// getNeonEltType - Return the QualType corresponding to the elements of
366 /// the vector type specified by the NeonTypeFlags.  This is used to check
367 /// the pointer arguments for Neon load/store intrinsics.
368 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
369                                bool IsAArch64) {
370   switch (Flags.getEltType()) {
371   case NeonTypeFlags::Int8:
372     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
373   case NeonTypeFlags::Int16:
374     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
375   case NeonTypeFlags::Int32:
376     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
377   case NeonTypeFlags::Int64:
378     if (IsAArch64)
379       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
380     else
381       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
382                                 : Context.LongLongTy;
383   case NeonTypeFlags::Poly8:
384     return IsAArch64 ? Context.UnsignedCharTy : Context.SignedCharTy;
385   case NeonTypeFlags::Poly16:
386     return IsAArch64 ? Context.UnsignedShortTy : Context.ShortTy;
387   case NeonTypeFlags::Poly64:
388     return Context.UnsignedLongTy;
389   case NeonTypeFlags::Poly128:
390     break;
391   case NeonTypeFlags::Float16:
392     return Context.HalfTy;
393   case NeonTypeFlags::Float32:
394     return Context.FloatTy;
395   case NeonTypeFlags::Float64:
396     return Context.DoubleTy;
397   }
398   llvm_unreachable("Invalid NeonTypeFlag!");
399 }
400 
401 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
402   llvm::APSInt Result;
403   uint64_t mask = 0;
404   unsigned TV = 0;
405   int PtrArgNum = -1;
406   bool HasConstPtr = false;
407   switch (BuiltinID) {
408 #define GET_NEON_OVERLOAD_CHECK
409 #include "clang/Basic/arm_neon.inc"
410 #undef GET_NEON_OVERLOAD_CHECK
411   }
412 
413   // For NEON intrinsics which are overloaded on vector element type, validate
414   // the immediate which specifies which variant to emit.
415   unsigned ImmArg = TheCall->getNumArgs()-1;
416   if (mask) {
417     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
418       return true;
419 
420     TV = Result.getLimitedValue(64);
421     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
422       return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
423         << TheCall->getArg(ImmArg)->getSourceRange();
424   }
425 
426   if (PtrArgNum >= 0) {
427     // Check that pointer arguments have the specified type.
428     Expr *Arg = TheCall->getArg(PtrArgNum);
429     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
430       Arg = ICE->getSubExpr();
431     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
432     QualType RHSTy = RHS.get()->getType();
433 
434     bool IsAArch64 =
435         Context.getTargetInfo().getTriple().getArch() == llvm::Triple::aarch64;
436     QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context, IsAArch64);
437     if (HasConstPtr)
438       EltTy = EltTy.withConst();
439     QualType LHSTy = Context.getPointerType(EltTy);
440     AssignConvertType ConvTy;
441     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
442     if (RHS.isInvalid())
443       return true;
444     if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
445                                  RHS.get(), AA_Assigning))
446       return true;
447   }
448 
449   // For NEON intrinsics which take an immediate value as part of the
450   // instruction, range check them here.
451   unsigned i = 0, l = 0, u = 0;
452   switch (BuiltinID) {
453   default:
454     return false;
455 #define GET_NEON_IMMEDIATE_CHECK
456 #include "clang/Basic/arm_neon.inc"
457 #undef GET_NEON_IMMEDIATE_CHECK
458   }
459   ;
460 
461   // We can't check the value of a dependent argument.
462   if (TheCall->getArg(i)->isTypeDependent() ||
463       TheCall->getArg(i)->isValueDependent())
464     return false;
465 
466   // Check that the immediate argument is actually a constant.
467   if (SemaBuiltinConstantArg(TheCall, i, Result))
468     return true;
469 
470   // Range check against the upper/lower values for this isntruction.
471   unsigned Val = Result.getZExtValue();
472   if (Val < l || Val > (u + l))
473     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
474            << l << u + l << TheCall->getArg(i)->getSourceRange();
475 
476   return false;
477 }
478 
479 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
480                                            CallExpr *TheCall) {
481   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
482     return true;
483 
484   return false;
485 }
486 
487 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall) {
488   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
489           BuiltinID == ARM::BI__builtin_arm_strex) &&
490          "unexpected ARM builtin");
491   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex;
492 
493   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
494 
495   // Ensure that we have the proper number of arguments.
496   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
497     return true;
498 
499   // Inspect the pointer argument of the atomic builtin.  This should always be
500   // a pointer type, whose element is an integral scalar or pointer type.
501   // Because it is a pointer type, we don't have to worry about any implicit
502   // casts here.
503   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
504   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
505   if (PointerArgRes.isInvalid())
506     return true;
507   PointerArg = PointerArgRes.take();
508 
509   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
510   if (!pointerType) {
511     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
512       << PointerArg->getType() << PointerArg->getSourceRange();
513     return true;
514   }
515 
516   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
517   // task is to insert the appropriate casts into the AST. First work out just
518   // what the appropriate type is.
519   QualType ValType = pointerType->getPointeeType();
520   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
521   if (IsLdrex)
522     AddrType.addConst();
523 
524   // Issue a warning if the cast is dodgy.
525   CastKind CastNeeded = CK_NoOp;
526   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
527     CastNeeded = CK_BitCast;
528     Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
529       << PointerArg->getType()
530       << Context.getPointerType(AddrType)
531       << AA_Passing << PointerArg->getSourceRange();
532   }
533 
534   // Finally, do the cast and replace the argument with the corrected version.
535   AddrType = Context.getPointerType(AddrType);
536   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
537   if (PointerArgRes.isInvalid())
538     return true;
539   PointerArg = PointerArgRes.take();
540 
541   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
542 
543   // In general, we allow ints, floats and pointers to be loaded and stored.
544   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
545       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
546     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
547       << PointerArg->getType() << PointerArg->getSourceRange();
548     return true;
549   }
550 
551   // But ARM doesn't have instructions to deal with 128-bit versions.
552   if (Context.getTypeSize(ValType) > 64) {
553     Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
554       << PointerArg->getType() << PointerArg->getSourceRange();
555     return true;
556   }
557 
558   switch (ValType.getObjCLifetime()) {
559   case Qualifiers::OCL_None:
560   case Qualifiers::OCL_ExplicitNone:
561     // okay
562     break;
563 
564   case Qualifiers::OCL_Weak:
565   case Qualifiers::OCL_Strong:
566   case Qualifiers::OCL_Autoreleasing:
567     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
568       << ValType << PointerArg->getSourceRange();
569     return true;
570   }
571 
572 
573   if (IsLdrex) {
574     TheCall->setType(ValType);
575     return false;
576   }
577 
578   // Initialize the argument to be stored.
579   ExprResult ValArg = TheCall->getArg(0);
580   InitializedEntity Entity = InitializedEntity::InitializeParameter(
581       Context, ValType, /*consume*/ false);
582   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
583   if (ValArg.isInvalid())
584     return true;
585   TheCall->setArg(0, ValArg.get());
586 
587   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
588   // but the custom checker bypasses all default analysis.
589   TheCall->setType(Context.IntTy);
590   return false;
591 }
592 
593 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
594   llvm::APSInt Result;
595 
596   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
597       BuiltinID == ARM::BI__builtin_arm_strex) {
598     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall);
599   }
600 
601   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
602     return true;
603 
604   // For NEON intrinsics which take an immediate value as part of the
605   // instruction, range check them here.
606   unsigned i = 0, l = 0, u = 0;
607   switch (BuiltinID) {
608   default: return false;
609   case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
610   case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
611   case ARM::BI__builtin_arm_vcvtr_f:
612   case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
613   case ARM::BI__builtin_arm_dmb:
614   case ARM::BI__builtin_arm_dsb: l = 0; u = 15; break;
615   };
616 
617   // We can't check the value of a dependent argument.
618   if (TheCall->getArg(i)->isTypeDependent() ||
619       TheCall->getArg(i)->isValueDependent())
620     return false;
621 
622   // Check that the immediate argument is actually a constant.
623   if (SemaBuiltinConstantArg(TheCall, i, Result))
624     return true;
625 
626   // Range check against the upper/lower values for this isntruction.
627   unsigned Val = Result.getZExtValue();
628   if (Val < l || Val > (u + l))
629     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
630       << l << u+l << TheCall->getArg(i)->getSourceRange();
631 
632   // FIXME: VFP Intrinsics should error if VFP not present.
633   return false;
634 }
635 
636 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
637   unsigned i = 0, l = 0, u = 0;
638   switch (BuiltinID) {
639   default: return false;
640   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
641   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
642   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
643   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
644   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
645   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
646   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
647   };
648 
649   // We can't check the value of a dependent argument.
650   if (TheCall->getArg(i)->isTypeDependent() ||
651       TheCall->getArg(i)->isValueDependent())
652     return false;
653 
654   // Check that the immediate argument is actually a constant.
655   llvm::APSInt Result;
656   if (SemaBuiltinConstantArg(TheCall, i, Result))
657     return true;
658 
659   // Range check against the upper/lower values for this instruction.
660   unsigned Val = Result.getZExtValue();
661   if (Val < l || Val > u)
662     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
663       << l << u << TheCall->getArg(i)->getSourceRange();
664 
665   return false;
666 }
667 
668 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
669   switch (BuiltinID) {
670   case X86::BI_mm_prefetch:
671     return SemaBuiltinMMPrefetch(TheCall);
672   }
673   return false;
674 }
675 
676 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
677 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
678 /// Returns true when the format fits the function and the FormatStringInfo has
679 /// been populated.
680 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
681                                FormatStringInfo *FSI) {
682   FSI->HasVAListArg = Format->getFirstArg() == 0;
683   FSI->FormatIdx = Format->getFormatIdx() - 1;
684   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
685 
686   // The way the format attribute works in GCC, the implicit this argument
687   // of member functions is counted. However, it doesn't appear in our own
688   // lists, so decrement format_idx in that case.
689   if (IsCXXMember) {
690     if(FSI->FormatIdx == 0)
691       return false;
692     --FSI->FormatIdx;
693     if (FSI->FirstDataArg != 0)
694       --FSI->FirstDataArg;
695   }
696   return true;
697 }
698 
699 /// Checks if a the given expression evaluates to null.
700 ///
701 /// \brief Returns true if the value evaluates to null.
702 static bool CheckNonNullExpr(Sema &S,
703                              const Expr *Expr) {
704   // As a special case, transparent unions initialized with zero are
705   // considered null for the purposes of the nonnull attribute.
706   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
707     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
708       if (const CompoundLiteralExpr *CLE =
709           dyn_cast<CompoundLiteralExpr>(Expr))
710         if (const InitListExpr *ILE =
711             dyn_cast<InitListExpr>(CLE->getInitializer()))
712           Expr = ILE->getInit(0);
713   }
714 
715   bool Result;
716   return (!Expr->isValueDependent() &&
717           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
718           !Result);
719 }
720 
721 static void CheckNonNullArgument(Sema &S,
722                                  const Expr *ArgExpr,
723                                  SourceLocation CallSiteLoc) {
724   if (CheckNonNullExpr(S, ArgExpr))
725     S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
726 }
727 
728 static void CheckNonNullArguments(Sema &S,
729                                   const NamedDecl *FDecl,
730                                   const Expr * const *ExprArgs,
731                                   SourceLocation CallSiteLoc) {
732   // Check the attributes attached to the method/function itself.
733   for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
734     for (NonNullAttr::args_iterator i = NonNull->args_begin(),
735          e = NonNull->args_end();
736          i != e; ++i) {
737       CheckNonNullArgument(S, ExprArgs[*i], CallSiteLoc);
738     }
739   }
740 
741   // Check the attributes on the parameters.
742   ArrayRef<ParmVarDecl*> parms;
743   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
744     parms = FD->parameters();
745   else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
746     parms = MD->parameters();
747 
748   unsigned argIndex = 0;
749   for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
750        I != E; ++I, ++argIndex) {
751     const ParmVarDecl *PVD = *I;
752     if (PVD->hasAttr<NonNullAttr>())
753       CheckNonNullArgument(S, ExprArgs[argIndex], CallSiteLoc);
754   }
755 }
756 
757 /// Handles the checks for format strings, non-POD arguments to vararg
758 /// functions, and NULL arguments passed to non-NULL parameters.
759 void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
760                      unsigned NumParams, bool IsMemberFunction,
761                      SourceLocation Loc, SourceRange Range,
762                      VariadicCallType CallType) {
763   // FIXME: We should check as much as we can in the template definition.
764   if (CurContext->isDependentContext())
765     return;
766 
767   // Printf and scanf checking.
768   llvm::SmallBitVector CheckedVarArgs;
769   if (FDecl) {
770     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
771       // Only create vector if there are format attributes.
772       CheckedVarArgs.resize(Args.size());
773 
774       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
775                            CheckedVarArgs);
776     }
777   }
778 
779   // Refuse POD arguments that weren't caught by the format string
780   // checks above.
781   if (CallType != VariadicDoesNotApply) {
782     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
783       // Args[ArgIdx] can be null in malformed code.
784       if (const Expr *Arg = Args[ArgIdx]) {
785         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
786           checkVariadicArgument(Arg, CallType);
787       }
788     }
789   }
790 
791   if (FDecl) {
792     CheckNonNullArguments(*this, FDecl, Args.data(), Loc);
793 
794     // Type safety checking.
795     for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
796       CheckArgumentWithTypeTag(I, Args.data());
797   }
798 }
799 
800 /// CheckConstructorCall - Check a constructor call for correctness and safety
801 /// properties not enforced by the C type system.
802 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
803                                 ArrayRef<const Expr *> Args,
804                                 const FunctionProtoType *Proto,
805                                 SourceLocation Loc) {
806   VariadicCallType CallType =
807     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
808   checkCall(FDecl, Args, Proto->getNumParams(),
809             /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
810 }
811 
812 /// CheckFunctionCall - Check a direct function call for various correctness
813 /// and safety properties not strictly enforced by the C type system.
814 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
815                              const FunctionProtoType *Proto) {
816   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
817                               isa<CXXMethodDecl>(FDecl);
818   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
819                           IsMemberOperatorCall;
820   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
821                                                   TheCall->getCallee());
822   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
823   Expr** Args = TheCall->getArgs();
824   unsigned NumArgs = TheCall->getNumArgs();
825   if (IsMemberOperatorCall) {
826     // If this is a call to a member operator, hide the first argument
827     // from checkCall.
828     // FIXME: Our choice of AST representation here is less than ideal.
829     ++Args;
830     --NumArgs;
831   }
832   checkCall(FDecl, llvm::makeArrayRef<const Expr *>(Args, NumArgs), NumParams,
833             IsMemberFunction, TheCall->getRParenLoc(),
834             TheCall->getCallee()->getSourceRange(), CallType);
835 
836   IdentifierInfo *FnInfo = FDecl->getIdentifier();
837   // None of the checks below are needed for functions that don't have
838   // simple names (e.g., C++ conversion functions).
839   if (!FnInfo)
840     return false;
841 
842   CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
843 
844   unsigned CMId = FDecl->getMemoryFunctionKind();
845   if (CMId == 0)
846     return false;
847 
848   // Handle memory setting and copying functions.
849   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
850     CheckStrlcpycatArguments(TheCall, FnInfo);
851   else if (CMId == Builtin::BIstrncat)
852     CheckStrncatArguments(TheCall, FnInfo);
853   else
854     CheckMemaccessArguments(TheCall, CMId, FnInfo);
855 
856   return false;
857 }
858 
859 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
860                                ArrayRef<const Expr *> Args) {
861   VariadicCallType CallType =
862       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
863 
864   checkCall(Method, Args, Method->param_size(),
865             /*IsMemberFunction=*/false,
866             lbrac, Method->getSourceRange(), CallType);
867 
868   return false;
869 }
870 
871 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
872                             const FunctionProtoType *Proto) {
873   const VarDecl *V = dyn_cast<VarDecl>(NDecl);
874   if (!V)
875     return false;
876 
877   QualType Ty = V->getType();
878   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
879     return false;
880 
881   VariadicCallType CallType;
882   if (!Proto || !Proto->isVariadic()) {
883     CallType = VariadicDoesNotApply;
884   } else if (Ty->isBlockPointerType()) {
885     CallType = VariadicBlock;
886   } else { // Ty->isFunctionPointerType()
887     CallType = VariadicFunction;
888   }
889   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
890 
891   checkCall(NDecl, llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
892                                                     TheCall->getNumArgs()),
893             NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
894             TheCall->getCallee()->getSourceRange(), CallType);
895 
896   return false;
897 }
898 
899 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
900 /// such as function pointers returned from functions.
901 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
902   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/0, Proto,
903                                                   TheCall->getCallee());
904   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
905 
906   checkCall(/*FDecl=*/0, llvm::makeArrayRef<const Expr *>(
907                              TheCall->getArgs(), TheCall->getNumArgs()),
908             NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
909             TheCall->getCallee()->getSourceRange(), CallType);
910 
911   return false;
912 }
913 
914 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
915                                          AtomicExpr::AtomicOp Op) {
916   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
917   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
918 
919   // All these operations take one of the following forms:
920   enum {
921     // C    __c11_atomic_init(A *, C)
922     Init,
923     // C    __c11_atomic_load(A *, int)
924     Load,
925     // void __atomic_load(A *, CP, int)
926     Copy,
927     // C    __c11_atomic_add(A *, M, int)
928     Arithmetic,
929     // C    __atomic_exchange_n(A *, CP, int)
930     Xchg,
931     // void __atomic_exchange(A *, C *, CP, int)
932     GNUXchg,
933     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
934     C11CmpXchg,
935     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
936     GNUCmpXchg
937   } Form = Init;
938   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
939   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
940   // where:
941   //   C is an appropriate type,
942   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
943   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
944   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
945   //   the int parameters are for orderings.
946 
947   assert(AtomicExpr::AO__c11_atomic_init == 0 &&
948          AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
949          && "need to update code for modified C11 atomics");
950   bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
951                Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
952   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
953              Op == AtomicExpr::AO__atomic_store_n ||
954              Op == AtomicExpr::AO__atomic_exchange_n ||
955              Op == AtomicExpr::AO__atomic_compare_exchange_n;
956   bool IsAddSub = false;
957 
958   switch (Op) {
959   case AtomicExpr::AO__c11_atomic_init:
960     Form = Init;
961     break;
962 
963   case AtomicExpr::AO__c11_atomic_load:
964   case AtomicExpr::AO__atomic_load_n:
965     Form = Load;
966     break;
967 
968   case AtomicExpr::AO__c11_atomic_store:
969   case AtomicExpr::AO__atomic_load:
970   case AtomicExpr::AO__atomic_store:
971   case AtomicExpr::AO__atomic_store_n:
972     Form = Copy;
973     break;
974 
975   case AtomicExpr::AO__c11_atomic_fetch_add:
976   case AtomicExpr::AO__c11_atomic_fetch_sub:
977   case AtomicExpr::AO__atomic_fetch_add:
978   case AtomicExpr::AO__atomic_fetch_sub:
979   case AtomicExpr::AO__atomic_add_fetch:
980   case AtomicExpr::AO__atomic_sub_fetch:
981     IsAddSub = true;
982     // Fall through.
983   case AtomicExpr::AO__c11_atomic_fetch_and:
984   case AtomicExpr::AO__c11_atomic_fetch_or:
985   case AtomicExpr::AO__c11_atomic_fetch_xor:
986   case AtomicExpr::AO__atomic_fetch_and:
987   case AtomicExpr::AO__atomic_fetch_or:
988   case AtomicExpr::AO__atomic_fetch_xor:
989   case AtomicExpr::AO__atomic_fetch_nand:
990   case AtomicExpr::AO__atomic_and_fetch:
991   case AtomicExpr::AO__atomic_or_fetch:
992   case AtomicExpr::AO__atomic_xor_fetch:
993   case AtomicExpr::AO__atomic_nand_fetch:
994     Form = Arithmetic;
995     break;
996 
997   case AtomicExpr::AO__c11_atomic_exchange:
998   case AtomicExpr::AO__atomic_exchange_n:
999     Form = Xchg;
1000     break;
1001 
1002   case AtomicExpr::AO__atomic_exchange:
1003     Form = GNUXchg;
1004     break;
1005 
1006   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1007   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1008     Form = C11CmpXchg;
1009     break;
1010 
1011   case AtomicExpr::AO__atomic_compare_exchange:
1012   case AtomicExpr::AO__atomic_compare_exchange_n:
1013     Form = GNUCmpXchg;
1014     break;
1015   }
1016 
1017   // Check we have the right number of arguments.
1018   if (TheCall->getNumArgs() < NumArgs[Form]) {
1019     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
1020       << 0 << NumArgs[Form] << TheCall->getNumArgs()
1021       << TheCall->getCallee()->getSourceRange();
1022     return ExprError();
1023   } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1024     Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
1025          diag::err_typecheck_call_too_many_args)
1026       << 0 << NumArgs[Form] << TheCall->getNumArgs()
1027       << TheCall->getCallee()->getSourceRange();
1028     return ExprError();
1029   }
1030 
1031   // Inspect the first argument of the atomic operation.
1032   Expr *Ptr = TheCall->getArg(0);
1033   Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1034   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1035   if (!pointerType) {
1036     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1037       << Ptr->getType() << Ptr->getSourceRange();
1038     return ExprError();
1039   }
1040 
1041   // For a __c11 builtin, this should be a pointer to an _Atomic type.
1042   QualType AtomTy = pointerType->getPointeeType(); // 'A'
1043   QualType ValType = AtomTy; // 'C'
1044   if (IsC11) {
1045     if (!AtomTy->isAtomicType()) {
1046       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1047         << Ptr->getType() << Ptr->getSourceRange();
1048       return ExprError();
1049     }
1050     if (AtomTy.isConstQualified()) {
1051       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1052         << Ptr->getType() << Ptr->getSourceRange();
1053       return ExprError();
1054     }
1055     ValType = AtomTy->getAs<AtomicType>()->getValueType();
1056   }
1057 
1058   // For an arithmetic operation, the implied arithmetic must be well-formed.
1059   if (Form == Arithmetic) {
1060     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1061     if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1062       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1063         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1064       return ExprError();
1065     }
1066     if (!IsAddSub && !ValType->isIntegerType()) {
1067       Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1068         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1069       return ExprError();
1070     }
1071   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1072     // For __atomic_*_n operations, the value type must be a scalar integral or
1073     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
1074     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1075       << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1076     return ExprError();
1077   }
1078 
1079   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1080       !AtomTy->isScalarType()) {
1081     // For GNU atomics, require a trivially-copyable type. This is not part of
1082     // the GNU atomics specification, but we enforce it for sanity.
1083     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
1084       << Ptr->getType() << Ptr->getSourceRange();
1085     return ExprError();
1086   }
1087 
1088   // FIXME: For any builtin other than a load, the ValType must not be
1089   // const-qualified.
1090 
1091   switch (ValType.getObjCLifetime()) {
1092   case Qualifiers::OCL_None:
1093   case Qualifiers::OCL_ExplicitNone:
1094     // okay
1095     break;
1096 
1097   case Qualifiers::OCL_Weak:
1098   case Qualifiers::OCL_Strong:
1099   case Qualifiers::OCL_Autoreleasing:
1100     // FIXME: Can this happen? By this point, ValType should be known
1101     // to be trivially copyable.
1102     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1103       << ValType << Ptr->getSourceRange();
1104     return ExprError();
1105   }
1106 
1107   QualType ResultType = ValType;
1108   if (Form == Copy || Form == GNUXchg || Form == Init)
1109     ResultType = Context.VoidTy;
1110   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
1111     ResultType = Context.BoolTy;
1112 
1113   // The type of a parameter passed 'by value'. In the GNU atomics, such
1114   // arguments are actually passed as pointers.
1115   QualType ByValType = ValType; // 'CP'
1116   if (!IsC11 && !IsN)
1117     ByValType = Ptr->getType();
1118 
1119   // The first argument --- the pointer --- has a fixed type; we
1120   // deduce the types of the rest of the arguments accordingly.  Walk
1121   // the remaining arguments, converting them to the deduced value type.
1122   for (unsigned i = 1; i != NumArgs[Form]; ++i) {
1123     QualType Ty;
1124     if (i < NumVals[Form] + 1) {
1125       switch (i) {
1126       case 1:
1127         // The second argument is the non-atomic operand. For arithmetic, this
1128         // is always passed by value, and for a compare_exchange it is always
1129         // passed by address. For the rest, GNU uses by-address and C11 uses
1130         // by-value.
1131         assert(Form != Load);
1132         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1133           Ty = ValType;
1134         else if (Form == Copy || Form == Xchg)
1135           Ty = ByValType;
1136         else if (Form == Arithmetic)
1137           Ty = Context.getPointerDiffType();
1138         else
1139           Ty = Context.getPointerType(ValType.getUnqualifiedType());
1140         break;
1141       case 2:
1142         // The third argument to compare_exchange / GNU exchange is a
1143         // (pointer to a) desired value.
1144         Ty = ByValType;
1145         break;
1146       case 3:
1147         // The fourth argument to GNU compare_exchange is a 'weak' flag.
1148         Ty = Context.BoolTy;
1149         break;
1150       }
1151     } else {
1152       // The order(s) are always converted to int.
1153       Ty = Context.IntTy;
1154     }
1155 
1156     InitializedEntity Entity =
1157         InitializedEntity::InitializeParameter(Context, Ty, false);
1158     ExprResult Arg = TheCall->getArg(i);
1159     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1160     if (Arg.isInvalid())
1161       return true;
1162     TheCall->setArg(i, Arg.get());
1163   }
1164 
1165   // Permute the arguments into a 'consistent' order.
1166   SmallVector<Expr*, 5> SubExprs;
1167   SubExprs.push_back(Ptr);
1168   switch (Form) {
1169   case Init:
1170     // Note, AtomicExpr::getVal1() has a special case for this atomic.
1171     SubExprs.push_back(TheCall->getArg(1)); // Val1
1172     break;
1173   case Load:
1174     SubExprs.push_back(TheCall->getArg(1)); // Order
1175     break;
1176   case Copy:
1177   case Arithmetic:
1178   case Xchg:
1179     SubExprs.push_back(TheCall->getArg(2)); // Order
1180     SubExprs.push_back(TheCall->getArg(1)); // Val1
1181     break;
1182   case GNUXchg:
1183     // Note, AtomicExpr::getVal2() has a special case for this atomic.
1184     SubExprs.push_back(TheCall->getArg(3)); // Order
1185     SubExprs.push_back(TheCall->getArg(1)); // Val1
1186     SubExprs.push_back(TheCall->getArg(2)); // Val2
1187     break;
1188   case C11CmpXchg:
1189     SubExprs.push_back(TheCall->getArg(3)); // Order
1190     SubExprs.push_back(TheCall->getArg(1)); // Val1
1191     SubExprs.push_back(TheCall->getArg(4)); // OrderFail
1192     SubExprs.push_back(TheCall->getArg(2)); // Val2
1193     break;
1194   case GNUCmpXchg:
1195     SubExprs.push_back(TheCall->getArg(4)); // Order
1196     SubExprs.push_back(TheCall->getArg(1)); // Val1
1197     SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1198     SubExprs.push_back(TheCall->getArg(2)); // Val2
1199     SubExprs.push_back(TheCall->getArg(3)); // Weak
1200     break;
1201   }
1202 
1203   AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1204                                             SubExprs, ResultType, Op,
1205                                             TheCall->getRParenLoc());
1206 
1207   if ((Op == AtomicExpr::AO__c11_atomic_load ||
1208        (Op == AtomicExpr::AO__c11_atomic_store)) &&
1209       Context.AtomicUsesUnsupportedLibcall(AE))
1210     Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1211     ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
1212 
1213   return Owned(AE);
1214 }
1215 
1216 
1217 /// checkBuiltinArgument - Given a call to a builtin function, perform
1218 /// normal type-checking on the given argument, updating the call in
1219 /// place.  This is useful when a builtin function requires custom
1220 /// type-checking for some of its arguments but not necessarily all of
1221 /// them.
1222 ///
1223 /// Returns true on error.
1224 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1225   FunctionDecl *Fn = E->getDirectCallee();
1226   assert(Fn && "builtin call without direct callee!");
1227 
1228   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1229   InitializedEntity Entity =
1230     InitializedEntity::InitializeParameter(S.Context, Param);
1231 
1232   ExprResult Arg = E->getArg(0);
1233   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1234   if (Arg.isInvalid())
1235     return true;
1236 
1237   E->setArg(ArgIndex, Arg.take());
1238   return false;
1239 }
1240 
1241 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
1242 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
1243 /// type of its first argument.  The main ActOnCallExpr routines have already
1244 /// promoted the types of arguments because all of these calls are prototyped as
1245 /// void(...).
1246 ///
1247 /// This function goes through and does final semantic checking for these
1248 /// builtins,
1249 ExprResult
1250 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
1251   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
1252   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1253   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1254 
1255   // Ensure that we have at least one argument to do type inference from.
1256   if (TheCall->getNumArgs() < 1) {
1257     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1258       << 0 << 1 << TheCall->getNumArgs()
1259       << TheCall->getCallee()->getSourceRange();
1260     return ExprError();
1261   }
1262 
1263   // Inspect the first argument of the atomic builtin.  This should always be
1264   // a pointer type, whose element is an integral scalar or pointer type.
1265   // Because it is a pointer type, we don't have to worry about any implicit
1266   // casts here.
1267   // FIXME: We don't allow floating point scalars as input.
1268   Expr *FirstArg = TheCall->getArg(0);
1269   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1270   if (FirstArgResult.isInvalid())
1271     return ExprError();
1272   FirstArg = FirstArgResult.take();
1273   TheCall->setArg(0, FirstArg);
1274 
1275   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1276   if (!pointerType) {
1277     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1278       << FirstArg->getType() << FirstArg->getSourceRange();
1279     return ExprError();
1280   }
1281 
1282   QualType ValType = pointerType->getPointeeType();
1283   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1284       !ValType->isBlockPointerType()) {
1285     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1286       << FirstArg->getType() << FirstArg->getSourceRange();
1287     return ExprError();
1288   }
1289 
1290   switch (ValType.getObjCLifetime()) {
1291   case Qualifiers::OCL_None:
1292   case Qualifiers::OCL_ExplicitNone:
1293     // okay
1294     break;
1295 
1296   case Qualifiers::OCL_Weak:
1297   case Qualifiers::OCL_Strong:
1298   case Qualifiers::OCL_Autoreleasing:
1299     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1300       << ValType << FirstArg->getSourceRange();
1301     return ExprError();
1302   }
1303 
1304   // Strip any qualifiers off ValType.
1305   ValType = ValType.getUnqualifiedType();
1306 
1307   // The majority of builtins return a value, but a few have special return
1308   // types, so allow them to override appropriately below.
1309   QualType ResultType = ValType;
1310 
1311   // We need to figure out which concrete builtin this maps onto.  For example,
1312   // __sync_fetch_and_add with a 2 byte object turns into
1313   // __sync_fetch_and_add_2.
1314 #define BUILTIN_ROW(x) \
1315   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1316     Builtin::BI##x##_8, Builtin::BI##x##_16 }
1317 
1318   static const unsigned BuiltinIndices[][5] = {
1319     BUILTIN_ROW(__sync_fetch_and_add),
1320     BUILTIN_ROW(__sync_fetch_and_sub),
1321     BUILTIN_ROW(__sync_fetch_and_or),
1322     BUILTIN_ROW(__sync_fetch_and_and),
1323     BUILTIN_ROW(__sync_fetch_and_xor),
1324 
1325     BUILTIN_ROW(__sync_add_and_fetch),
1326     BUILTIN_ROW(__sync_sub_and_fetch),
1327     BUILTIN_ROW(__sync_and_and_fetch),
1328     BUILTIN_ROW(__sync_or_and_fetch),
1329     BUILTIN_ROW(__sync_xor_and_fetch),
1330 
1331     BUILTIN_ROW(__sync_val_compare_and_swap),
1332     BUILTIN_ROW(__sync_bool_compare_and_swap),
1333     BUILTIN_ROW(__sync_lock_test_and_set),
1334     BUILTIN_ROW(__sync_lock_release),
1335     BUILTIN_ROW(__sync_swap)
1336   };
1337 #undef BUILTIN_ROW
1338 
1339   // Determine the index of the size.
1340   unsigned SizeIndex;
1341   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
1342   case 1: SizeIndex = 0; break;
1343   case 2: SizeIndex = 1; break;
1344   case 4: SizeIndex = 2; break;
1345   case 8: SizeIndex = 3; break;
1346   case 16: SizeIndex = 4; break;
1347   default:
1348     Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1349       << FirstArg->getType() << FirstArg->getSourceRange();
1350     return ExprError();
1351   }
1352 
1353   // Each of these builtins has one pointer argument, followed by some number of
1354   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1355   // that we ignore.  Find out which row of BuiltinIndices to read from as well
1356   // as the number of fixed args.
1357   unsigned BuiltinID = FDecl->getBuiltinID();
1358   unsigned BuiltinIndex, NumFixed = 1;
1359   switch (BuiltinID) {
1360   default: llvm_unreachable("Unknown overloaded atomic builtin!");
1361   case Builtin::BI__sync_fetch_and_add:
1362   case Builtin::BI__sync_fetch_and_add_1:
1363   case Builtin::BI__sync_fetch_and_add_2:
1364   case Builtin::BI__sync_fetch_and_add_4:
1365   case Builtin::BI__sync_fetch_and_add_8:
1366   case Builtin::BI__sync_fetch_and_add_16:
1367     BuiltinIndex = 0;
1368     break;
1369 
1370   case Builtin::BI__sync_fetch_and_sub:
1371   case Builtin::BI__sync_fetch_and_sub_1:
1372   case Builtin::BI__sync_fetch_and_sub_2:
1373   case Builtin::BI__sync_fetch_and_sub_4:
1374   case Builtin::BI__sync_fetch_and_sub_8:
1375   case Builtin::BI__sync_fetch_and_sub_16:
1376     BuiltinIndex = 1;
1377     break;
1378 
1379   case Builtin::BI__sync_fetch_and_or:
1380   case Builtin::BI__sync_fetch_and_or_1:
1381   case Builtin::BI__sync_fetch_and_or_2:
1382   case Builtin::BI__sync_fetch_and_or_4:
1383   case Builtin::BI__sync_fetch_and_or_8:
1384   case Builtin::BI__sync_fetch_and_or_16:
1385     BuiltinIndex = 2;
1386     break;
1387 
1388   case Builtin::BI__sync_fetch_and_and:
1389   case Builtin::BI__sync_fetch_and_and_1:
1390   case Builtin::BI__sync_fetch_and_and_2:
1391   case Builtin::BI__sync_fetch_and_and_4:
1392   case Builtin::BI__sync_fetch_and_and_8:
1393   case Builtin::BI__sync_fetch_and_and_16:
1394     BuiltinIndex = 3;
1395     break;
1396 
1397   case Builtin::BI__sync_fetch_and_xor:
1398   case Builtin::BI__sync_fetch_and_xor_1:
1399   case Builtin::BI__sync_fetch_and_xor_2:
1400   case Builtin::BI__sync_fetch_and_xor_4:
1401   case Builtin::BI__sync_fetch_and_xor_8:
1402   case Builtin::BI__sync_fetch_and_xor_16:
1403     BuiltinIndex = 4;
1404     break;
1405 
1406   case Builtin::BI__sync_add_and_fetch:
1407   case Builtin::BI__sync_add_and_fetch_1:
1408   case Builtin::BI__sync_add_and_fetch_2:
1409   case Builtin::BI__sync_add_and_fetch_4:
1410   case Builtin::BI__sync_add_and_fetch_8:
1411   case Builtin::BI__sync_add_and_fetch_16:
1412     BuiltinIndex = 5;
1413     break;
1414 
1415   case Builtin::BI__sync_sub_and_fetch:
1416   case Builtin::BI__sync_sub_and_fetch_1:
1417   case Builtin::BI__sync_sub_and_fetch_2:
1418   case Builtin::BI__sync_sub_and_fetch_4:
1419   case Builtin::BI__sync_sub_and_fetch_8:
1420   case Builtin::BI__sync_sub_and_fetch_16:
1421     BuiltinIndex = 6;
1422     break;
1423 
1424   case Builtin::BI__sync_and_and_fetch:
1425   case Builtin::BI__sync_and_and_fetch_1:
1426   case Builtin::BI__sync_and_and_fetch_2:
1427   case Builtin::BI__sync_and_and_fetch_4:
1428   case Builtin::BI__sync_and_and_fetch_8:
1429   case Builtin::BI__sync_and_and_fetch_16:
1430     BuiltinIndex = 7;
1431     break;
1432 
1433   case Builtin::BI__sync_or_and_fetch:
1434   case Builtin::BI__sync_or_and_fetch_1:
1435   case Builtin::BI__sync_or_and_fetch_2:
1436   case Builtin::BI__sync_or_and_fetch_4:
1437   case Builtin::BI__sync_or_and_fetch_8:
1438   case Builtin::BI__sync_or_and_fetch_16:
1439     BuiltinIndex = 8;
1440     break;
1441 
1442   case Builtin::BI__sync_xor_and_fetch:
1443   case Builtin::BI__sync_xor_and_fetch_1:
1444   case Builtin::BI__sync_xor_and_fetch_2:
1445   case Builtin::BI__sync_xor_and_fetch_4:
1446   case Builtin::BI__sync_xor_and_fetch_8:
1447   case Builtin::BI__sync_xor_and_fetch_16:
1448     BuiltinIndex = 9;
1449     break;
1450 
1451   case Builtin::BI__sync_val_compare_and_swap:
1452   case Builtin::BI__sync_val_compare_and_swap_1:
1453   case Builtin::BI__sync_val_compare_and_swap_2:
1454   case Builtin::BI__sync_val_compare_and_swap_4:
1455   case Builtin::BI__sync_val_compare_and_swap_8:
1456   case Builtin::BI__sync_val_compare_and_swap_16:
1457     BuiltinIndex = 10;
1458     NumFixed = 2;
1459     break;
1460 
1461   case Builtin::BI__sync_bool_compare_and_swap:
1462   case Builtin::BI__sync_bool_compare_and_swap_1:
1463   case Builtin::BI__sync_bool_compare_and_swap_2:
1464   case Builtin::BI__sync_bool_compare_and_swap_4:
1465   case Builtin::BI__sync_bool_compare_and_swap_8:
1466   case Builtin::BI__sync_bool_compare_and_swap_16:
1467     BuiltinIndex = 11;
1468     NumFixed = 2;
1469     ResultType = Context.BoolTy;
1470     break;
1471 
1472   case Builtin::BI__sync_lock_test_and_set:
1473   case Builtin::BI__sync_lock_test_and_set_1:
1474   case Builtin::BI__sync_lock_test_and_set_2:
1475   case Builtin::BI__sync_lock_test_and_set_4:
1476   case Builtin::BI__sync_lock_test_and_set_8:
1477   case Builtin::BI__sync_lock_test_and_set_16:
1478     BuiltinIndex = 12;
1479     break;
1480 
1481   case Builtin::BI__sync_lock_release:
1482   case Builtin::BI__sync_lock_release_1:
1483   case Builtin::BI__sync_lock_release_2:
1484   case Builtin::BI__sync_lock_release_4:
1485   case Builtin::BI__sync_lock_release_8:
1486   case Builtin::BI__sync_lock_release_16:
1487     BuiltinIndex = 13;
1488     NumFixed = 0;
1489     ResultType = Context.VoidTy;
1490     break;
1491 
1492   case Builtin::BI__sync_swap:
1493   case Builtin::BI__sync_swap_1:
1494   case Builtin::BI__sync_swap_2:
1495   case Builtin::BI__sync_swap_4:
1496   case Builtin::BI__sync_swap_8:
1497   case Builtin::BI__sync_swap_16:
1498     BuiltinIndex = 14;
1499     break;
1500   }
1501 
1502   // Now that we know how many fixed arguments we expect, first check that we
1503   // have at least that many.
1504   if (TheCall->getNumArgs() < 1+NumFixed) {
1505     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1506       << 0 << 1+NumFixed << TheCall->getNumArgs()
1507       << TheCall->getCallee()->getSourceRange();
1508     return ExprError();
1509   }
1510 
1511   // Get the decl for the concrete builtin from this, we can tell what the
1512   // concrete integer type we should convert to is.
1513   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1514   const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
1515   FunctionDecl *NewBuiltinDecl;
1516   if (NewBuiltinID == BuiltinID)
1517     NewBuiltinDecl = FDecl;
1518   else {
1519     // Perform builtin lookup to avoid redeclaring it.
1520     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1521     LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1522     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1523     assert(Res.getFoundDecl());
1524     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
1525     if (NewBuiltinDecl == 0)
1526       return ExprError();
1527   }
1528 
1529   // The first argument --- the pointer --- has a fixed type; we
1530   // deduce the types of the rest of the arguments accordingly.  Walk
1531   // the remaining arguments, converting them to the deduced value type.
1532   for (unsigned i = 0; i != NumFixed; ++i) {
1533     ExprResult Arg = TheCall->getArg(i+1);
1534 
1535     // GCC does an implicit conversion to the pointer or integer ValType.  This
1536     // can fail in some cases (1i -> int**), check for this error case now.
1537     // Initialize the argument.
1538     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1539                                                    ValType, /*consume*/ false);
1540     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1541     if (Arg.isInvalid())
1542       return ExprError();
1543 
1544     // Okay, we have something that *can* be converted to the right type.  Check
1545     // to see if there is a potentially weird extension going on here.  This can
1546     // happen when you do an atomic operation on something like an char* and
1547     // pass in 42.  The 42 gets converted to char.  This is even more strange
1548     // for things like 45.123 -> char, etc.
1549     // FIXME: Do this check.
1550     TheCall->setArg(i+1, Arg.take());
1551   }
1552 
1553   ASTContext& Context = this->getASTContext();
1554 
1555   // Create a new DeclRefExpr to refer to the new decl.
1556   DeclRefExpr* NewDRE = DeclRefExpr::Create(
1557       Context,
1558       DRE->getQualifierLoc(),
1559       SourceLocation(),
1560       NewBuiltinDecl,
1561       /*enclosing*/ false,
1562       DRE->getLocation(),
1563       Context.BuiltinFnTy,
1564       DRE->getValueKind());
1565 
1566   // Set the callee in the CallExpr.
1567   // FIXME: This loses syntactic information.
1568   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1569   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1570                                               CK_BuiltinFnToFnPtr);
1571   TheCall->setCallee(PromotedCall.take());
1572 
1573   // Change the result type of the call to match the original value type. This
1574   // is arbitrary, but the codegen for these builtins ins design to handle it
1575   // gracefully.
1576   TheCall->setType(ResultType);
1577 
1578   return TheCallResult;
1579 }
1580 
1581 /// CheckObjCString - Checks that the argument to the builtin
1582 /// CFString constructor is correct
1583 /// Note: It might also make sense to do the UTF-16 conversion here (would
1584 /// simplify the backend).
1585 bool Sema::CheckObjCString(Expr *Arg) {
1586   Arg = Arg->IgnoreParenCasts();
1587   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1588 
1589   if (!Literal || !Literal->isAscii()) {
1590     Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1591       << Arg->getSourceRange();
1592     return true;
1593   }
1594 
1595   if (Literal->containsNonAsciiOrNull()) {
1596     StringRef String = Literal->getString();
1597     unsigned NumBytes = String.size();
1598     SmallVector<UTF16, 128> ToBuf(NumBytes);
1599     const UTF8 *FromPtr = (const UTF8 *)String.data();
1600     UTF16 *ToPtr = &ToBuf[0];
1601 
1602     ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1603                                                  &ToPtr, ToPtr + NumBytes,
1604                                                  strictConversion);
1605     // Check for conversion failure.
1606     if (Result != conversionOK)
1607       Diag(Arg->getLocStart(),
1608            diag::warn_cfstring_truncated) << Arg->getSourceRange();
1609   }
1610   return false;
1611 }
1612 
1613 /// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1614 /// Emit an error and return true on failure, return false on success.
1615 bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1616   Expr *Fn = TheCall->getCallee();
1617   if (TheCall->getNumArgs() > 2) {
1618     Diag(TheCall->getArg(2)->getLocStart(),
1619          diag::err_typecheck_call_too_many_args)
1620       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1621       << Fn->getSourceRange()
1622       << SourceRange(TheCall->getArg(2)->getLocStart(),
1623                      (*(TheCall->arg_end()-1))->getLocEnd());
1624     return true;
1625   }
1626 
1627   if (TheCall->getNumArgs() < 2) {
1628     return Diag(TheCall->getLocEnd(),
1629       diag::err_typecheck_call_too_few_args_at_least)
1630       << 0 /*function call*/ << 2 << TheCall->getNumArgs();
1631   }
1632 
1633   // Type-check the first argument normally.
1634   if (checkBuiltinArgument(*this, TheCall, 0))
1635     return true;
1636 
1637   // Determine whether the current function is variadic or not.
1638   BlockScopeInfo *CurBlock = getCurBlock();
1639   bool isVariadic;
1640   if (CurBlock)
1641     isVariadic = CurBlock->TheDecl->isVariadic();
1642   else if (FunctionDecl *FD = getCurFunctionDecl())
1643     isVariadic = FD->isVariadic();
1644   else
1645     isVariadic = getCurMethodDecl()->isVariadic();
1646 
1647   if (!isVariadic) {
1648     Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1649     return true;
1650   }
1651 
1652   // Verify that the second argument to the builtin is the last argument of the
1653   // current function or method.
1654   bool SecondArgIsLastNamedArgument = false;
1655   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
1656 
1657   // These are valid if SecondArgIsLastNamedArgument is false after the next
1658   // block.
1659   QualType Type;
1660   SourceLocation ParamLoc;
1661 
1662   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1663     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
1664       // FIXME: This isn't correct for methods (results in bogus warning).
1665       // Get the last formal in the current function.
1666       const ParmVarDecl *LastArg;
1667       if (CurBlock)
1668         LastArg = *(CurBlock->TheDecl->param_end()-1);
1669       else if (FunctionDecl *FD = getCurFunctionDecl())
1670         LastArg = *(FD->param_end()-1);
1671       else
1672         LastArg = *(getCurMethodDecl()->param_end()-1);
1673       SecondArgIsLastNamedArgument = PV == LastArg;
1674 
1675       Type = PV->getType();
1676       ParamLoc = PV->getLocation();
1677     }
1678   }
1679 
1680   if (!SecondArgIsLastNamedArgument)
1681     Diag(TheCall->getArg(1)->getLocStart(),
1682          diag::warn_second_parameter_of_va_start_not_last_named_argument);
1683   else if (Type->isReferenceType()) {
1684     Diag(Arg->getLocStart(),
1685          diag::warn_va_start_of_reference_type_is_undefined);
1686     Diag(ParamLoc, diag::note_parameter_type) << Type;
1687   }
1688 
1689   TheCall->setType(Context.VoidTy);
1690   return false;
1691 }
1692 
1693 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1694 /// friends.  This is declared to take (...), so we have to check everything.
1695 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1696   if (TheCall->getNumArgs() < 2)
1697     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
1698       << 0 << 2 << TheCall->getNumArgs()/*function call*/;
1699   if (TheCall->getNumArgs() > 2)
1700     return Diag(TheCall->getArg(2)->getLocStart(),
1701                 diag::err_typecheck_call_too_many_args)
1702       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1703       << SourceRange(TheCall->getArg(2)->getLocStart(),
1704                      (*(TheCall->arg_end()-1))->getLocEnd());
1705 
1706   ExprResult OrigArg0 = TheCall->getArg(0);
1707   ExprResult OrigArg1 = TheCall->getArg(1);
1708 
1709   // Do standard promotions between the two arguments, returning their common
1710   // type.
1711   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
1712   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1713     return true;
1714 
1715   // Make sure any conversions are pushed back into the call; this is
1716   // type safe since unordered compare builtins are declared as "_Bool
1717   // foo(...)".
1718   TheCall->setArg(0, OrigArg0.get());
1719   TheCall->setArg(1, OrigArg1.get());
1720 
1721   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
1722     return false;
1723 
1724   // If the common type isn't a real floating type, then the arguments were
1725   // invalid for this operation.
1726   if (Res.isNull() || !Res->isRealFloatingType())
1727     return Diag(OrigArg0.get()->getLocStart(),
1728                 diag::err_typecheck_call_invalid_ordered_compare)
1729       << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1730       << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
1731 
1732   return false;
1733 }
1734 
1735 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1736 /// __builtin_isnan and friends.  This is declared to take (...), so we have
1737 /// to check everything. We expect the last argument to be a floating point
1738 /// value.
1739 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1740   if (TheCall->getNumArgs() < NumArgs)
1741     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
1742       << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
1743   if (TheCall->getNumArgs() > NumArgs)
1744     return Diag(TheCall->getArg(NumArgs)->getLocStart(),
1745                 diag::err_typecheck_call_too_many_args)
1746       << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
1747       << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
1748                      (*(TheCall->arg_end()-1))->getLocEnd());
1749 
1750   Expr *OrigArg = TheCall->getArg(NumArgs-1);
1751 
1752   if (OrigArg->isTypeDependent())
1753     return false;
1754 
1755   // This operation requires a non-_Complex floating-point number.
1756   if (!OrigArg->getType()->isRealFloatingType())
1757     return Diag(OrigArg->getLocStart(),
1758                 diag::err_typecheck_call_invalid_unary_fp)
1759       << OrigArg->getType() << OrigArg->getSourceRange();
1760 
1761   // If this is an implicit conversion from float -> double, remove it.
1762   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1763     Expr *CastArg = Cast->getSubExpr();
1764     if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1765       assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1766              "promotion from float to double is the only expected cast here");
1767       Cast->setSubExpr(0);
1768       TheCall->setArg(NumArgs-1, CastArg);
1769     }
1770   }
1771 
1772   return false;
1773 }
1774 
1775 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1776 // This is declared to take (...), so we have to check everything.
1777 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
1778   if (TheCall->getNumArgs() < 2)
1779     return ExprError(Diag(TheCall->getLocEnd(),
1780                           diag::err_typecheck_call_too_few_args_at_least)
1781                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1782                      << TheCall->getSourceRange());
1783 
1784   // Determine which of the following types of shufflevector we're checking:
1785   // 1) unary, vector mask: (lhs, mask)
1786   // 2) binary, vector mask: (lhs, rhs, mask)
1787   // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1788   QualType resType = TheCall->getArg(0)->getType();
1789   unsigned numElements = 0;
1790 
1791   if (!TheCall->getArg(0)->isTypeDependent() &&
1792       !TheCall->getArg(1)->isTypeDependent()) {
1793     QualType LHSType = TheCall->getArg(0)->getType();
1794     QualType RHSType = TheCall->getArg(1)->getType();
1795 
1796     if (!LHSType->isVectorType() || !RHSType->isVectorType())
1797       return ExprError(Diag(TheCall->getLocStart(),
1798                             diag::err_shufflevector_non_vector)
1799                        << SourceRange(TheCall->getArg(0)->getLocStart(),
1800                                       TheCall->getArg(1)->getLocEnd()));
1801 
1802     numElements = LHSType->getAs<VectorType>()->getNumElements();
1803     unsigned numResElements = TheCall->getNumArgs() - 2;
1804 
1805     // Check to see if we have a call with 2 vector arguments, the unary shuffle
1806     // with mask.  If so, verify that RHS is an integer vector type with the
1807     // same number of elts as lhs.
1808     if (TheCall->getNumArgs() == 2) {
1809       if (!RHSType->hasIntegerRepresentation() ||
1810           RHSType->getAs<VectorType>()->getNumElements() != numElements)
1811         return ExprError(Diag(TheCall->getLocStart(),
1812                               diag::err_shufflevector_incompatible_vector)
1813                          << SourceRange(TheCall->getArg(1)->getLocStart(),
1814                                         TheCall->getArg(1)->getLocEnd()));
1815     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
1816       return ExprError(Diag(TheCall->getLocStart(),
1817                             diag::err_shufflevector_incompatible_vector)
1818                        << SourceRange(TheCall->getArg(0)->getLocStart(),
1819                                       TheCall->getArg(1)->getLocEnd()));
1820     } else if (numElements != numResElements) {
1821       QualType eltType = LHSType->getAs<VectorType>()->getElementType();
1822       resType = Context.getVectorType(eltType, numResElements,
1823                                       VectorType::GenericVector);
1824     }
1825   }
1826 
1827   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
1828     if (TheCall->getArg(i)->isTypeDependent() ||
1829         TheCall->getArg(i)->isValueDependent())
1830       continue;
1831 
1832     llvm::APSInt Result(32);
1833     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1834       return ExprError(Diag(TheCall->getLocStart(),
1835                             diag::err_shufflevector_nonconstant_argument)
1836                        << TheCall->getArg(i)->getSourceRange());
1837 
1838     // Allow -1 which will be translated to undef in the IR.
1839     if (Result.isSigned() && Result.isAllOnesValue())
1840       continue;
1841 
1842     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
1843       return ExprError(Diag(TheCall->getLocStart(),
1844                             diag::err_shufflevector_argument_too_large)
1845                        << TheCall->getArg(i)->getSourceRange());
1846   }
1847 
1848   SmallVector<Expr*, 32> exprs;
1849 
1850   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
1851     exprs.push_back(TheCall->getArg(i));
1852     TheCall->setArg(i, 0);
1853   }
1854 
1855   return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
1856                                             TheCall->getCallee()->getLocStart(),
1857                                             TheCall->getRParenLoc()));
1858 }
1859 
1860 /// SemaConvertVectorExpr - Handle __builtin_convertvector
1861 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
1862                                        SourceLocation BuiltinLoc,
1863                                        SourceLocation RParenLoc) {
1864   ExprValueKind VK = VK_RValue;
1865   ExprObjectKind OK = OK_Ordinary;
1866   QualType DstTy = TInfo->getType();
1867   QualType SrcTy = E->getType();
1868 
1869   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
1870     return ExprError(Diag(BuiltinLoc,
1871                           diag::err_convertvector_non_vector)
1872                      << E->getSourceRange());
1873   if (!DstTy->isVectorType() && !DstTy->isDependentType())
1874     return ExprError(Diag(BuiltinLoc,
1875                           diag::err_convertvector_non_vector_type));
1876 
1877   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
1878     unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
1879     unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
1880     if (SrcElts != DstElts)
1881       return ExprError(Diag(BuiltinLoc,
1882                             diag::err_convertvector_incompatible_vector)
1883                        << E->getSourceRange());
1884   }
1885 
1886   return Owned(new (Context) ConvertVectorExpr(E, TInfo, DstTy, VK, OK,
1887                BuiltinLoc, RParenLoc));
1888 
1889 }
1890 
1891 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1892 // This is declared to take (const void*, ...) and can take two
1893 // optional constant int args.
1894 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
1895   unsigned NumArgs = TheCall->getNumArgs();
1896 
1897   if (NumArgs > 3)
1898     return Diag(TheCall->getLocEnd(),
1899              diag::err_typecheck_call_too_many_args_at_most)
1900              << 0 /*function call*/ << 3 << NumArgs
1901              << TheCall->getSourceRange();
1902 
1903   // Argument 0 is checked for us and the remaining arguments must be
1904   // constant integers.
1905   for (unsigned i = 1; i != NumArgs; ++i) {
1906     Expr *Arg = TheCall->getArg(i);
1907 
1908     // We can't check the value of a dependent argument.
1909     if (Arg->isTypeDependent() || Arg->isValueDependent())
1910       continue;
1911 
1912     llvm::APSInt Result;
1913     if (SemaBuiltinConstantArg(TheCall, i, Result))
1914       return true;
1915 
1916     // FIXME: gcc issues a warning and rewrites these to 0. These
1917     // seems especially odd for the third argument since the default
1918     // is 3.
1919     if (i == 1) {
1920       if (Result.getLimitedValue() > 1)
1921         return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1922              << "0" << "1" << Arg->getSourceRange();
1923     } else {
1924       if (Result.getLimitedValue() > 3)
1925         return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1926             << "0" << "3" << Arg->getSourceRange();
1927     }
1928   }
1929 
1930   return false;
1931 }
1932 
1933 /// SemaBuiltinMMPrefetch - Handle _mm_prefetch.
1934 // This is declared to take (const char*, int)
1935 bool Sema::SemaBuiltinMMPrefetch(CallExpr *TheCall) {
1936   Expr *Arg = TheCall->getArg(1);
1937 
1938   // We can't check the value of a dependent argument.
1939   if (Arg->isTypeDependent() || Arg->isValueDependent())
1940     return false;
1941 
1942   llvm::APSInt Result;
1943   if (SemaBuiltinConstantArg(TheCall, 1, Result))
1944     return true;
1945 
1946   if (Result.getLimitedValue() > 3)
1947     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1948         << "0" << "3" << Arg->getSourceRange();
1949 
1950   return false;
1951 }
1952 
1953 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1954 /// TheCall is a constant expression.
1955 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1956                                   llvm::APSInt &Result) {
1957   Expr *Arg = TheCall->getArg(ArgNum);
1958   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1959   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1960 
1961   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1962 
1963   if (!Arg->isIntegerConstantExpr(Result, Context))
1964     return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
1965                 << FDecl->getDeclName() <<  Arg->getSourceRange();
1966 
1967   return false;
1968 }
1969 
1970 /// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1971 /// int type). This simply type checks that type is one of the defined
1972 /// constants (0-3).
1973 // For compatibility check 0-3, llvm only handles 0 and 2.
1974 bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
1975   llvm::APSInt Result;
1976 
1977   // We can't check the value of a dependent argument.
1978   if (TheCall->getArg(1)->isTypeDependent() ||
1979       TheCall->getArg(1)->isValueDependent())
1980     return false;
1981 
1982   // Check constant-ness first.
1983   if (SemaBuiltinConstantArg(TheCall, 1, Result))
1984     return true;
1985 
1986   Expr *Arg = TheCall->getArg(1);
1987   if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
1988     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1989              << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1990   }
1991 
1992   return false;
1993 }
1994 
1995 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
1996 /// This checks that val is a constant 1.
1997 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1998   Expr *Arg = TheCall->getArg(1);
1999   llvm::APSInt Result;
2000 
2001   // TODO: This is less than ideal. Overload this to take a value.
2002   if (SemaBuiltinConstantArg(TheCall, 1, Result))
2003     return true;
2004 
2005   if (Result != 1)
2006     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2007              << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2008 
2009   return false;
2010 }
2011 
2012 namespace {
2013 enum StringLiteralCheckType {
2014   SLCT_NotALiteral,
2015   SLCT_UncheckedLiteral,
2016   SLCT_CheckedLiteral
2017 };
2018 }
2019 
2020 // Determine if an expression is a string literal or constant string.
2021 // If this function returns false on the arguments to a function expecting a
2022 // format string, we will usually need to emit a warning.
2023 // True string literals are then checked by CheckFormatString.
2024 static StringLiteralCheckType
2025 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2026                       bool HasVAListArg, unsigned format_idx,
2027                       unsigned firstDataArg, Sema::FormatStringType Type,
2028                       Sema::VariadicCallType CallType, bool InFunctionCall,
2029                       llvm::SmallBitVector &CheckedVarArgs) {
2030  tryAgain:
2031   if (E->isTypeDependent() || E->isValueDependent())
2032     return SLCT_NotALiteral;
2033 
2034   E = E->IgnoreParenCasts();
2035 
2036   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
2037     // Technically -Wformat-nonliteral does not warn about this case.
2038     // The behavior of printf and friends in this case is implementation
2039     // dependent.  Ideally if the format string cannot be null then
2040     // it should have a 'nonnull' attribute in the function prototype.
2041     return SLCT_UncheckedLiteral;
2042 
2043   switch (E->getStmtClass()) {
2044   case Stmt::BinaryConditionalOperatorClass:
2045   case Stmt::ConditionalOperatorClass: {
2046     // The expression is a literal if both sub-expressions were, and it was
2047     // completely checked only if both sub-expressions were checked.
2048     const AbstractConditionalOperator *C =
2049         cast<AbstractConditionalOperator>(E);
2050     StringLiteralCheckType Left =
2051         checkFormatStringExpr(S, C->getTrueExpr(), Args,
2052                               HasVAListArg, format_idx, firstDataArg,
2053                               Type, CallType, InFunctionCall, CheckedVarArgs);
2054     if (Left == SLCT_NotALiteral)
2055       return SLCT_NotALiteral;
2056     StringLiteralCheckType Right =
2057         checkFormatStringExpr(S, C->getFalseExpr(), Args,
2058                               HasVAListArg, format_idx, firstDataArg,
2059                               Type, CallType, InFunctionCall, CheckedVarArgs);
2060     return Left < Right ? Left : Right;
2061   }
2062 
2063   case Stmt::ImplicitCastExprClass: {
2064     E = cast<ImplicitCastExpr>(E)->getSubExpr();
2065     goto tryAgain;
2066   }
2067 
2068   case Stmt::OpaqueValueExprClass:
2069     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2070       E = src;
2071       goto tryAgain;
2072     }
2073     return SLCT_NotALiteral;
2074 
2075   case Stmt::PredefinedExprClass:
2076     // While __func__, etc., are technically not string literals, they
2077     // cannot contain format specifiers and thus are not a security
2078     // liability.
2079     return SLCT_UncheckedLiteral;
2080 
2081   case Stmt::DeclRefExprClass: {
2082     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
2083 
2084     // As an exception, do not flag errors for variables binding to
2085     // const string literals.
2086     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2087       bool isConstant = false;
2088       QualType T = DR->getType();
2089 
2090       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2091         isConstant = AT->getElementType().isConstant(S.Context);
2092       } else if (const PointerType *PT = T->getAs<PointerType>()) {
2093         isConstant = T.isConstant(S.Context) &&
2094                      PT->getPointeeType().isConstant(S.Context);
2095       } else if (T->isObjCObjectPointerType()) {
2096         // In ObjC, there is usually no "const ObjectPointer" type,
2097         // so don't check if the pointee type is constant.
2098         isConstant = T.isConstant(S.Context);
2099       }
2100 
2101       if (isConstant) {
2102         if (const Expr *Init = VD->getAnyInitializer()) {
2103           // Look through initializers like const char c[] = { "foo" }
2104           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2105             if (InitList->isStringLiteralInit())
2106               Init = InitList->getInit(0)->IgnoreParenImpCasts();
2107           }
2108           return checkFormatStringExpr(S, Init, Args,
2109                                        HasVAListArg, format_idx,
2110                                        firstDataArg, Type, CallType,
2111                                        /*InFunctionCall*/false, CheckedVarArgs);
2112         }
2113       }
2114 
2115       // For vprintf* functions (i.e., HasVAListArg==true), we add a
2116       // special check to see if the format string is a function parameter
2117       // of the function calling the printf function.  If the function
2118       // has an attribute indicating it is a printf-like function, then we
2119       // should suppress warnings concerning non-literals being used in a call
2120       // to a vprintf function.  For example:
2121       //
2122       // void
2123       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2124       //      va_list ap;
2125       //      va_start(ap, fmt);
2126       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
2127       //      ...
2128       // }
2129       if (HasVAListArg) {
2130         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2131           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2132             int PVIndex = PV->getFunctionScopeIndex() + 1;
2133             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
2134               // adjust for implicit parameter
2135               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2136                 if (MD->isInstance())
2137                   ++PVIndex;
2138               // We also check if the formats are compatible.
2139               // We can't pass a 'scanf' string to a 'printf' function.
2140               if (PVIndex == PVFormat->getFormatIdx() &&
2141                   Type == S.GetFormatStringType(PVFormat))
2142                 return SLCT_UncheckedLiteral;
2143             }
2144           }
2145         }
2146       }
2147     }
2148 
2149     return SLCT_NotALiteral;
2150   }
2151 
2152   case Stmt::CallExprClass:
2153   case Stmt::CXXMemberCallExprClass: {
2154     const CallExpr *CE = cast<CallExpr>(E);
2155     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2156       if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2157         unsigned ArgIndex = FA->getFormatIdx();
2158         if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2159           if (MD->isInstance())
2160             --ArgIndex;
2161         const Expr *Arg = CE->getArg(ArgIndex - 1);
2162 
2163         return checkFormatStringExpr(S, Arg, Args,
2164                                      HasVAListArg, format_idx, firstDataArg,
2165                                      Type, CallType, InFunctionCall,
2166                                      CheckedVarArgs);
2167       } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2168         unsigned BuiltinID = FD->getBuiltinID();
2169         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2170             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2171           const Expr *Arg = CE->getArg(0);
2172           return checkFormatStringExpr(S, Arg, Args,
2173                                        HasVAListArg, format_idx,
2174                                        firstDataArg, Type, CallType,
2175                                        InFunctionCall, CheckedVarArgs);
2176         }
2177       }
2178     }
2179 
2180     return SLCT_NotALiteral;
2181   }
2182   case Stmt::ObjCStringLiteralClass:
2183   case Stmt::StringLiteralClass: {
2184     const StringLiteral *StrE = NULL;
2185 
2186     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
2187       StrE = ObjCFExpr->getString();
2188     else
2189       StrE = cast<StringLiteral>(E);
2190 
2191     if (StrE) {
2192       S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2193                           Type, InFunctionCall, CallType, CheckedVarArgs);
2194       return SLCT_CheckedLiteral;
2195     }
2196 
2197     return SLCT_NotALiteral;
2198   }
2199 
2200   default:
2201     return SLCT_NotALiteral;
2202   }
2203 }
2204 
2205 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
2206   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
2207   .Case("scanf", FST_Scanf)
2208   .Cases("printf", "printf0", FST_Printf)
2209   .Cases("NSString", "CFString", FST_NSString)
2210   .Case("strftime", FST_Strftime)
2211   .Case("strfmon", FST_Strfmon)
2212   .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2213   .Default(FST_Unknown);
2214 }
2215 
2216 /// CheckFormatArguments - Check calls to printf and scanf (and similar
2217 /// functions) for correct use of format strings.
2218 /// Returns true if a format string has been fully checked.
2219 bool Sema::CheckFormatArguments(const FormatAttr *Format,
2220                                 ArrayRef<const Expr *> Args,
2221                                 bool IsCXXMember,
2222                                 VariadicCallType CallType,
2223                                 SourceLocation Loc, SourceRange Range,
2224                                 llvm::SmallBitVector &CheckedVarArgs) {
2225   FormatStringInfo FSI;
2226   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
2227     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
2228                                 FSI.FirstDataArg, GetFormatStringType(Format),
2229                                 CallType, Loc, Range, CheckedVarArgs);
2230   return false;
2231 }
2232 
2233 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
2234                                 bool HasVAListArg, unsigned format_idx,
2235                                 unsigned firstDataArg, FormatStringType Type,
2236                                 VariadicCallType CallType,
2237                                 SourceLocation Loc, SourceRange Range,
2238                                 llvm::SmallBitVector &CheckedVarArgs) {
2239   // CHECK: printf/scanf-like function is called with no format string.
2240   if (format_idx >= Args.size()) {
2241     Diag(Loc, diag::warn_missing_format_string) << Range;
2242     return false;
2243   }
2244 
2245   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
2246 
2247   // CHECK: format string is not a string literal.
2248   //
2249   // Dynamically generated format strings are difficult to
2250   // automatically vet at compile time.  Requiring that format strings
2251   // are string literals: (1) permits the checking of format strings by
2252   // the compiler and thereby (2) can practically remove the source of
2253   // many format string exploits.
2254 
2255   // Format string can be either ObjC string (e.g. @"%d") or
2256   // C string (e.g. "%d")
2257   // ObjC string uses the same format specifiers as C string, so we can use
2258   // the same format string checking logic for both ObjC and C strings.
2259   StringLiteralCheckType CT =
2260       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2261                             format_idx, firstDataArg, Type, CallType,
2262                             /*IsFunctionCall*/true, CheckedVarArgs);
2263   if (CT != SLCT_NotALiteral)
2264     // Literal format string found, check done!
2265     return CT == SLCT_CheckedLiteral;
2266 
2267   // Strftime is particular as it always uses a single 'time' argument,
2268   // so it is safe to pass a non-literal string.
2269   if (Type == FST_Strftime)
2270     return false;
2271 
2272   // Do not emit diag when the string param is a macro expansion and the
2273   // format is either NSString or CFString. This is a hack to prevent
2274   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2275   // which are usually used in place of NS and CF string literals.
2276   if (Type == FST_NSString &&
2277       SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
2278     return false;
2279 
2280   // If there are no arguments specified, warn with -Wformat-security, otherwise
2281   // warn only with -Wformat-nonliteral.
2282   if (Args.size() == firstDataArg)
2283     Diag(Args[format_idx]->getLocStart(),
2284          diag::warn_format_nonliteral_noargs)
2285       << OrigFormatExpr->getSourceRange();
2286   else
2287     Diag(Args[format_idx]->getLocStart(),
2288          diag::warn_format_nonliteral)
2289            << OrigFormatExpr->getSourceRange();
2290   return false;
2291 }
2292 
2293 namespace {
2294 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2295 protected:
2296   Sema &S;
2297   const StringLiteral *FExpr;
2298   const Expr *OrigFormatExpr;
2299   const unsigned FirstDataArg;
2300   const unsigned NumDataArgs;
2301   const char *Beg; // Start of format string.
2302   const bool HasVAListArg;
2303   ArrayRef<const Expr *> Args;
2304   unsigned FormatIdx;
2305   llvm::SmallBitVector CoveredArgs;
2306   bool usesPositionalArgs;
2307   bool atFirstArg;
2308   bool inFunctionCall;
2309   Sema::VariadicCallType CallType;
2310   llvm::SmallBitVector &CheckedVarArgs;
2311 public:
2312   CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
2313                      const Expr *origFormatExpr, unsigned firstDataArg,
2314                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
2315                      ArrayRef<const Expr *> Args,
2316                      unsigned formatIdx, bool inFunctionCall,
2317                      Sema::VariadicCallType callType,
2318                      llvm::SmallBitVector &CheckedVarArgs)
2319     : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
2320       FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2321       Beg(beg), HasVAListArg(hasVAListArg),
2322       Args(Args), FormatIdx(formatIdx),
2323       usesPositionalArgs(false), atFirstArg(true),
2324       inFunctionCall(inFunctionCall), CallType(callType),
2325       CheckedVarArgs(CheckedVarArgs) {
2326     CoveredArgs.resize(numDataArgs);
2327     CoveredArgs.reset();
2328   }
2329 
2330   void DoneProcessing();
2331 
2332   void HandleIncompleteSpecifier(const char *startSpecifier,
2333                                  unsigned specifierLen);
2334 
2335   void HandleInvalidLengthModifier(
2336       const analyze_format_string::FormatSpecifier &FS,
2337       const analyze_format_string::ConversionSpecifier &CS,
2338       const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
2339 
2340   void HandleNonStandardLengthModifier(
2341       const analyze_format_string::FormatSpecifier &FS,
2342       const char *startSpecifier, unsigned specifierLen);
2343 
2344   void HandleNonStandardConversionSpecifier(
2345       const analyze_format_string::ConversionSpecifier &CS,
2346       const char *startSpecifier, unsigned specifierLen);
2347 
2348   virtual void HandlePosition(const char *startPos, unsigned posLen);
2349 
2350   virtual void HandleInvalidPosition(const char *startSpecifier,
2351                                      unsigned specifierLen,
2352                                      analyze_format_string::PositionContext p);
2353 
2354   virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
2355 
2356   void HandleNullChar(const char *nullCharacter);
2357 
2358   template <typename Range>
2359   static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2360                                    const Expr *ArgumentExpr,
2361                                    PartialDiagnostic PDiag,
2362                                    SourceLocation StringLoc,
2363                                    bool IsStringLocation, Range StringRange,
2364                                    ArrayRef<FixItHint> Fixit = None);
2365 
2366 protected:
2367   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2368                                         const char *startSpec,
2369                                         unsigned specifierLen,
2370                                         const char *csStart, unsigned csLen);
2371 
2372   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2373                                          const char *startSpec,
2374                                          unsigned specifierLen);
2375 
2376   SourceRange getFormatStringRange();
2377   CharSourceRange getSpecifierRange(const char *startSpecifier,
2378                                     unsigned specifierLen);
2379   SourceLocation getLocationOfByte(const char *x);
2380 
2381   const Expr *getDataArg(unsigned i) const;
2382 
2383   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2384                     const analyze_format_string::ConversionSpecifier &CS,
2385                     const char *startSpecifier, unsigned specifierLen,
2386                     unsigned argIndex);
2387 
2388   template <typename Range>
2389   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2390                             bool IsStringLocation, Range StringRange,
2391                             ArrayRef<FixItHint> Fixit = None);
2392 
2393   void CheckPositionalAndNonpositionalArgs(
2394       const analyze_format_string::FormatSpecifier *FS);
2395 };
2396 }
2397 
2398 SourceRange CheckFormatHandler::getFormatStringRange() {
2399   return OrigFormatExpr->getSourceRange();
2400 }
2401 
2402 CharSourceRange CheckFormatHandler::
2403 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
2404   SourceLocation Start = getLocationOfByte(startSpecifier);
2405   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
2406 
2407   // Advance the end SourceLocation by one due to half-open ranges.
2408   End = End.getLocWithOffset(1);
2409 
2410   return CharSourceRange::getCharRange(Start, End);
2411 }
2412 
2413 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
2414   return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
2415 }
2416 
2417 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2418                                                    unsigned specifierLen){
2419   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2420                        getLocationOfByte(startSpecifier),
2421                        /*IsStringLocation*/true,
2422                        getSpecifierRange(startSpecifier, specifierLen));
2423 }
2424 
2425 void CheckFormatHandler::HandleInvalidLengthModifier(
2426     const analyze_format_string::FormatSpecifier &FS,
2427     const analyze_format_string::ConversionSpecifier &CS,
2428     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
2429   using namespace analyze_format_string;
2430 
2431   const LengthModifier &LM = FS.getLengthModifier();
2432   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2433 
2434   // See if we know how to fix this length modifier.
2435   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
2436   if (FixedLM) {
2437     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
2438                          getLocationOfByte(LM.getStart()),
2439                          /*IsStringLocation*/true,
2440                          getSpecifierRange(startSpecifier, specifierLen));
2441 
2442     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2443       << FixedLM->toString()
2444       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2445 
2446   } else {
2447     FixItHint Hint;
2448     if (DiagID == diag::warn_format_nonsensical_length)
2449       Hint = FixItHint::CreateRemoval(LMRange);
2450 
2451     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
2452                          getLocationOfByte(LM.getStart()),
2453                          /*IsStringLocation*/true,
2454                          getSpecifierRange(startSpecifier, specifierLen),
2455                          Hint);
2456   }
2457 }
2458 
2459 void CheckFormatHandler::HandleNonStandardLengthModifier(
2460     const analyze_format_string::FormatSpecifier &FS,
2461     const char *startSpecifier, unsigned specifierLen) {
2462   using namespace analyze_format_string;
2463 
2464   const LengthModifier &LM = FS.getLengthModifier();
2465   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2466 
2467   // See if we know how to fix this length modifier.
2468   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
2469   if (FixedLM) {
2470     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2471                            << LM.toString() << 0,
2472                          getLocationOfByte(LM.getStart()),
2473                          /*IsStringLocation*/true,
2474                          getSpecifierRange(startSpecifier, specifierLen));
2475 
2476     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2477       << FixedLM->toString()
2478       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2479 
2480   } else {
2481     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2482                            << LM.toString() << 0,
2483                          getLocationOfByte(LM.getStart()),
2484                          /*IsStringLocation*/true,
2485                          getSpecifierRange(startSpecifier, specifierLen));
2486   }
2487 }
2488 
2489 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2490     const analyze_format_string::ConversionSpecifier &CS,
2491     const char *startSpecifier, unsigned specifierLen) {
2492   using namespace analyze_format_string;
2493 
2494   // See if we know how to fix this conversion specifier.
2495   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
2496   if (FixedCS) {
2497     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2498                           << CS.toString() << /*conversion specifier*/1,
2499                          getLocationOfByte(CS.getStart()),
2500                          /*IsStringLocation*/true,
2501                          getSpecifierRange(startSpecifier, specifierLen));
2502 
2503     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2504     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2505       << FixedCS->toString()
2506       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2507   } else {
2508     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2509                           << CS.toString() << /*conversion specifier*/1,
2510                          getLocationOfByte(CS.getStart()),
2511                          /*IsStringLocation*/true,
2512                          getSpecifierRange(startSpecifier, specifierLen));
2513   }
2514 }
2515 
2516 void CheckFormatHandler::HandlePosition(const char *startPos,
2517                                         unsigned posLen) {
2518   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2519                                getLocationOfByte(startPos),
2520                                /*IsStringLocation*/true,
2521                                getSpecifierRange(startPos, posLen));
2522 }
2523 
2524 void
2525 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2526                                      analyze_format_string::PositionContext p) {
2527   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2528                          << (unsigned) p,
2529                        getLocationOfByte(startPos), /*IsStringLocation*/true,
2530                        getSpecifierRange(startPos, posLen));
2531 }
2532 
2533 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
2534                                             unsigned posLen) {
2535   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2536                                getLocationOfByte(startPos),
2537                                /*IsStringLocation*/true,
2538                                getSpecifierRange(startPos, posLen));
2539 }
2540 
2541 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
2542   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
2543     // The presence of a null character is likely an error.
2544     EmitFormatDiagnostic(
2545       S.PDiag(diag::warn_printf_format_string_contains_null_char),
2546       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2547       getFormatStringRange());
2548   }
2549 }
2550 
2551 // Note that this may return NULL if there was an error parsing or building
2552 // one of the argument expressions.
2553 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
2554   return Args[FirstDataArg + i];
2555 }
2556 
2557 void CheckFormatHandler::DoneProcessing() {
2558     // Does the number of data arguments exceed the number of
2559     // format conversions in the format string?
2560   if (!HasVAListArg) {
2561       // Find any arguments that weren't covered.
2562     CoveredArgs.flip();
2563     signed notCoveredArg = CoveredArgs.find_first();
2564     if (notCoveredArg >= 0) {
2565       assert((unsigned)notCoveredArg < NumDataArgs);
2566       if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2567         SourceLocation Loc = E->getLocStart();
2568         if (!S.getSourceManager().isInSystemMacro(Loc)) {
2569           EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2570                                Loc, /*IsStringLocation*/false,
2571                                getFormatStringRange());
2572         }
2573       }
2574     }
2575   }
2576 }
2577 
2578 bool
2579 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2580                                                      SourceLocation Loc,
2581                                                      const char *startSpec,
2582                                                      unsigned specifierLen,
2583                                                      const char *csStart,
2584                                                      unsigned csLen) {
2585 
2586   bool keepGoing = true;
2587   if (argIndex < NumDataArgs) {
2588     // Consider the argument coverered, even though the specifier doesn't
2589     // make sense.
2590     CoveredArgs.set(argIndex);
2591   }
2592   else {
2593     // If argIndex exceeds the number of data arguments we
2594     // don't issue a warning because that is just a cascade of warnings (and
2595     // they may have intended '%%' anyway). We don't want to continue processing
2596     // the format string after this point, however, as we will like just get
2597     // gibberish when trying to match arguments.
2598     keepGoing = false;
2599   }
2600 
2601   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2602                          << StringRef(csStart, csLen),
2603                        Loc, /*IsStringLocation*/true,
2604                        getSpecifierRange(startSpec, specifierLen));
2605 
2606   return keepGoing;
2607 }
2608 
2609 void
2610 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2611                                                       const char *startSpec,
2612                                                       unsigned specifierLen) {
2613   EmitFormatDiagnostic(
2614     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2615     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2616 }
2617 
2618 bool
2619 CheckFormatHandler::CheckNumArgs(
2620   const analyze_format_string::FormatSpecifier &FS,
2621   const analyze_format_string::ConversionSpecifier &CS,
2622   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2623 
2624   if (argIndex >= NumDataArgs) {
2625     PartialDiagnostic PDiag = FS.usesPositionalArg()
2626       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2627            << (argIndex+1) << NumDataArgs)
2628       : S.PDiag(diag::warn_printf_insufficient_data_args);
2629     EmitFormatDiagnostic(
2630       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2631       getSpecifierRange(startSpecifier, specifierLen));
2632     return false;
2633   }
2634   return true;
2635 }
2636 
2637 template<typename Range>
2638 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2639                                               SourceLocation Loc,
2640                                               bool IsStringLocation,
2641                                               Range StringRange,
2642                                               ArrayRef<FixItHint> FixIt) {
2643   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
2644                        Loc, IsStringLocation, StringRange, FixIt);
2645 }
2646 
2647 /// \brief If the format string is not within the funcion call, emit a note
2648 /// so that the function call and string are in diagnostic messages.
2649 ///
2650 /// \param InFunctionCall if true, the format string is within the function
2651 /// call and only one diagnostic message will be produced.  Otherwise, an
2652 /// extra note will be emitted pointing to location of the format string.
2653 ///
2654 /// \param ArgumentExpr the expression that is passed as the format string
2655 /// argument in the function call.  Used for getting locations when two
2656 /// diagnostics are emitted.
2657 ///
2658 /// \param PDiag the callee should already have provided any strings for the
2659 /// diagnostic message.  This function only adds locations and fixits
2660 /// to diagnostics.
2661 ///
2662 /// \param Loc primary location for diagnostic.  If two diagnostics are
2663 /// required, one will be at Loc and a new SourceLocation will be created for
2664 /// the other one.
2665 ///
2666 /// \param IsStringLocation if true, Loc points to the format string should be
2667 /// used for the note.  Otherwise, Loc points to the argument list and will
2668 /// be used with PDiag.
2669 ///
2670 /// \param StringRange some or all of the string to highlight.  This is
2671 /// templated so it can accept either a CharSourceRange or a SourceRange.
2672 ///
2673 /// \param FixIt optional fix it hint for the format string.
2674 template<typename Range>
2675 void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2676                                               const Expr *ArgumentExpr,
2677                                               PartialDiagnostic PDiag,
2678                                               SourceLocation Loc,
2679                                               bool IsStringLocation,
2680                                               Range StringRange,
2681                                               ArrayRef<FixItHint> FixIt) {
2682   if (InFunctionCall) {
2683     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2684     D << StringRange;
2685     for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2686          I != E; ++I) {
2687       D << *I;
2688     }
2689   } else {
2690     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2691       << ArgumentExpr->getSourceRange();
2692 
2693     const Sema::SemaDiagnosticBuilder &Note =
2694       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2695              diag::note_format_string_defined);
2696 
2697     Note << StringRange;
2698     for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2699          I != E; ++I) {
2700       Note << *I;
2701     }
2702   }
2703 }
2704 
2705 //===--- CHECK: Printf format string checking ------------------------------===//
2706 
2707 namespace {
2708 class CheckPrintfHandler : public CheckFormatHandler {
2709   bool ObjCContext;
2710 public:
2711   CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2712                      const Expr *origFormatExpr, unsigned firstDataArg,
2713                      unsigned numDataArgs, bool isObjC,
2714                      const char *beg, bool hasVAListArg,
2715                      ArrayRef<const Expr *> Args,
2716                      unsigned formatIdx, bool inFunctionCall,
2717                      Sema::VariadicCallType CallType,
2718                      llvm::SmallBitVector &CheckedVarArgs)
2719     : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2720                          numDataArgs, beg, hasVAListArg, Args,
2721                          formatIdx, inFunctionCall, CallType, CheckedVarArgs),
2722       ObjCContext(isObjC)
2723   {}
2724 
2725 
2726   bool HandleInvalidPrintfConversionSpecifier(
2727                                       const analyze_printf::PrintfSpecifier &FS,
2728                                       const char *startSpecifier,
2729                                       unsigned specifierLen);
2730 
2731   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2732                              const char *startSpecifier,
2733                              unsigned specifierLen);
2734   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2735                        const char *StartSpecifier,
2736                        unsigned SpecifierLen,
2737                        const Expr *E);
2738 
2739   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2740                     const char *startSpecifier, unsigned specifierLen);
2741   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2742                            const analyze_printf::OptionalAmount &Amt,
2743                            unsigned type,
2744                            const char *startSpecifier, unsigned specifierLen);
2745   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2746                   const analyze_printf::OptionalFlag &flag,
2747                   const char *startSpecifier, unsigned specifierLen);
2748   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2749                          const analyze_printf::OptionalFlag &ignoredFlag,
2750                          const analyze_printf::OptionalFlag &flag,
2751                          const char *startSpecifier, unsigned specifierLen);
2752   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
2753                            const Expr *E);
2754 
2755 };
2756 }
2757 
2758 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2759                                       const analyze_printf::PrintfSpecifier &FS,
2760                                       const char *startSpecifier,
2761                                       unsigned specifierLen) {
2762   const analyze_printf::PrintfConversionSpecifier &CS =
2763     FS.getConversionSpecifier();
2764 
2765   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2766                                           getLocationOfByte(CS.getStart()),
2767                                           startSpecifier, specifierLen,
2768                                           CS.getStart(), CS.getLength());
2769 }
2770 
2771 bool CheckPrintfHandler::HandleAmount(
2772                                const analyze_format_string::OptionalAmount &Amt,
2773                                unsigned k, const char *startSpecifier,
2774                                unsigned specifierLen) {
2775 
2776   if (Amt.hasDataArgument()) {
2777     if (!HasVAListArg) {
2778       unsigned argIndex = Amt.getArgIndex();
2779       if (argIndex >= NumDataArgs) {
2780         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2781                                << k,
2782                              getLocationOfByte(Amt.getStart()),
2783                              /*IsStringLocation*/true,
2784                              getSpecifierRange(startSpecifier, specifierLen));
2785         // Don't do any more checking.  We will just emit
2786         // spurious errors.
2787         return false;
2788       }
2789 
2790       // Type check the data argument.  It should be an 'int'.
2791       // Although not in conformance with C99, we also allow the argument to be
2792       // an 'unsigned int' as that is a reasonably safe case.  GCC also
2793       // doesn't emit a warning for that case.
2794       CoveredArgs.set(argIndex);
2795       const Expr *Arg = getDataArg(argIndex);
2796       if (!Arg)
2797         return false;
2798 
2799       QualType T = Arg->getType();
2800 
2801       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2802       assert(AT.isValid());
2803 
2804       if (!AT.matchesType(S.Context, T)) {
2805         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
2806                                << k << AT.getRepresentativeTypeName(S.Context)
2807                                << T << Arg->getSourceRange(),
2808                              getLocationOfByte(Amt.getStart()),
2809                              /*IsStringLocation*/true,
2810                              getSpecifierRange(startSpecifier, specifierLen));
2811         // Don't do any more checking.  We will just emit
2812         // spurious errors.
2813         return false;
2814       }
2815     }
2816   }
2817   return true;
2818 }
2819 
2820 void CheckPrintfHandler::HandleInvalidAmount(
2821                                       const analyze_printf::PrintfSpecifier &FS,
2822                                       const analyze_printf::OptionalAmount &Amt,
2823                                       unsigned type,
2824                                       const char *startSpecifier,
2825                                       unsigned specifierLen) {
2826   const analyze_printf::PrintfConversionSpecifier &CS =
2827     FS.getConversionSpecifier();
2828 
2829   FixItHint fixit =
2830     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2831       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2832                                  Amt.getConstantLength()))
2833       : FixItHint();
2834 
2835   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2836                          << type << CS.toString(),
2837                        getLocationOfByte(Amt.getStart()),
2838                        /*IsStringLocation*/true,
2839                        getSpecifierRange(startSpecifier, specifierLen),
2840                        fixit);
2841 }
2842 
2843 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2844                                     const analyze_printf::OptionalFlag &flag,
2845                                     const char *startSpecifier,
2846                                     unsigned specifierLen) {
2847   // Warn about pointless flag with a fixit removal.
2848   const analyze_printf::PrintfConversionSpecifier &CS =
2849     FS.getConversionSpecifier();
2850   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2851                          << flag.toString() << CS.toString(),
2852                        getLocationOfByte(flag.getPosition()),
2853                        /*IsStringLocation*/true,
2854                        getSpecifierRange(startSpecifier, specifierLen),
2855                        FixItHint::CreateRemoval(
2856                          getSpecifierRange(flag.getPosition(), 1)));
2857 }
2858 
2859 void CheckPrintfHandler::HandleIgnoredFlag(
2860                                 const analyze_printf::PrintfSpecifier &FS,
2861                                 const analyze_printf::OptionalFlag &ignoredFlag,
2862                                 const analyze_printf::OptionalFlag &flag,
2863                                 const char *startSpecifier,
2864                                 unsigned specifierLen) {
2865   // Warn about ignored flag with a fixit removal.
2866   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2867                          << ignoredFlag.toString() << flag.toString(),
2868                        getLocationOfByte(ignoredFlag.getPosition()),
2869                        /*IsStringLocation*/true,
2870                        getSpecifierRange(startSpecifier, specifierLen),
2871                        FixItHint::CreateRemoval(
2872                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
2873 }
2874 
2875 // Determines if the specified is a C++ class or struct containing
2876 // a member with the specified name and kind (e.g. a CXXMethodDecl named
2877 // "c_str()").
2878 template<typename MemberKind>
2879 static llvm::SmallPtrSet<MemberKind*, 1>
2880 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2881   const RecordType *RT = Ty->getAs<RecordType>();
2882   llvm::SmallPtrSet<MemberKind*, 1> Results;
2883 
2884   if (!RT)
2885     return Results;
2886   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
2887   if (!RD || !RD->getDefinition())
2888     return Results;
2889 
2890   LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2891                  Sema::LookupMemberName);
2892   R.suppressDiagnostics();
2893 
2894   // We just need to include all members of the right kind turned up by the
2895   // filter, at this point.
2896   if (S.LookupQualifiedName(R, RT->getDecl()))
2897     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2898       NamedDecl *decl = (*I)->getUnderlyingDecl();
2899       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2900         Results.insert(FK);
2901     }
2902   return Results;
2903 }
2904 
2905 /// Check if we could call '.c_str()' on an object.
2906 ///
2907 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
2908 /// allow the call, or if it would be ambiguous).
2909 bool Sema::hasCStrMethod(const Expr *E) {
2910   typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2911   MethodSet Results =
2912       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
2913   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2914        MI != ME; ++MI)
2915     if ((*MI)->getMinRequiredArguments() == 0)
2916       return true;
2917   return false;
2918 }
2919 
2920 // Check if a (w)string was passed when a (w)char* was needed, and offer a
2921 // better diagnostic if so. AT is assumed to be valid.
2922 // Returns true when a c_str() conversion method is found.
2923 bool CheckPrintfHandler::checkForCStrMembers(
2924     const analyze_printf::ArgType &AT, const Expr *E) {
2925   typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2926 
2927   MethodSet Results =
2928       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2929 
2930   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2931        MI != ME; ++MI) {
2932     const CXXMethodDecl *Method = *MI;
2933     if (Method->getMinRequiredArguments() == 0 &&
2934         AT.matchesType(S.Context, Method->getReturnType())) {
2935       // FIXME: Suggest parens if the expression needs them.
2936       SourceLocation EndLoc =
2937           S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
2938       S.Diag(E->getLocStart(), diag::note_printf_c_str)
2939           << "c_str()"
2940           << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2941       return true;
2942     }
2943   }
2944 
2945   return false;
2946 }
2947 
2948 bool
2949 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
2950                                             &FS,
2951                                           const char *startSpecifier,
2952                                           unsigned specifierLen) {
2953 
2954   using namespace analyze_format_string;
2955   using namespace analyze_printf;
2956   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
2957 
2958   if (FS.consumesDataArgument()) {
2959     if (atFirstArg) {
2960         atFirstArg = false;
2961         usesPositionalArgs = FS.usesPositionalArg();
2962     }
2963     else if (usesPositionalArgs != FS.usesPositionalArg()) {
2964       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2965                                         startSpecifier, specifierLen);
2966       return false;
2967     }
2968   }
2969 
2970   // First check if the field width, precision, and conversion specifier
2971   // have matching data arguments.
2972   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2973                     startSpecifier, specifierLen)) {
2974     return false;
2975   }
2976 
2977   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2978                     startSpecifier, specifierLen)) {
2979     return false;
2980   }
2981 
2982   if (!CS.consumesDataArgument()) {
2983     // FIXME: Technically specifying a precision or field width here
2984     // makes no sense.  Worth issuing a warning at some point.
2985     return true;
2986   }
2987 
2988   // Consume the argument.
2989   unsigned argIndex = FS.getArgIndex();
2990   if (argIndex < NumDataArgs) {
2991     // The check to see if the argIndex is valid will come later.
2992     // We set the bit here because we may exit early from this
2993     // function if we encounter some other error.
2994     CoveredArgs.set(argIndex);
2995   }
2996 
2997   // Check for using an Objective-C specific conversion specifier
2998   // in a non-ObjC literal.
2999   if (!ObjCContext && CS.isObjCArg()) {
3000     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3001                                                   specifierLen);
3002   }
3003 
3004   // Check for invalid use of field width
3005   if (!FS.hasValidFieldWidth()) {
3006     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
3007         startSpecifier, specifierLen);
3008   }
3009 
3010   // Check for invalid use of precision
3011   if (!FS.hasValidPrecision()) {
3012     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3013         startSpecifier, specifierLen);
3014   }
3015 
3016   // Check each flag does not conflict with any other component.
3017   if (!FS.hasValidThousandsGroupingPrefix())
3018     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
3019   if (!FS.hasValidLeadingZeros())
3020     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3021   if (!FS.hasValidPlusPrefix())
3022     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
3023   if (!FS.hasValidSpacePrefix())
3024     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
3025   if (!FS.hasValidAlternativeForm())
3026     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3027   if (!FS.hasValidLeftJustified())
3028     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3029 
3030   // Check that flags are not ignored by another flag
3031   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3032     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3033         startSpecifier, specifierLen);
3034   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3035     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3036             startSpecifier, specifierLen);
3037 
3038   // Check the length modifier is valid with the given conversion specifier.
3039   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
3040     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3041                                 diag::warn_format_nonsensical_length);
3042   else if (!FS.hasStandardLengthModifier())
3043     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
3044   else if (!FS.hasStandardLengthConversionCombination())
3045     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3046                                 diag::warn_format_non_standard_conversion_spec);
3047 
3048   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3049     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3050 
3051   // The remaining checks depend on the data arguments.
3052   if (HasVAListArg)
3053     return true;
3054 
3055   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
3056     return false;
3057 
3058   const Expr *Arg = getDataArg(argIndex);
3059   if (!Arg)
3060     return true;
3061 
3062   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
3063 }
3064 
3065 static bool requiresParensToAddCast(const Expr *E) {
3066   // FIXME: We should have a general way to reason about operator
3067   // precedence and whether parens are actually needed here.
3068   // Take care of a few common cases where they aren't.
3069   const Expr *Inside = E->IgnoreImpCasts();
3070   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3071     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3072 
3073   switch (Inside->getStmtClass()) {
3074   case Stmt::ArraySubscriptExprClass:
3075   case Stmt::CallExprClass:
3076   case Stmt::CharacterLiteralClass:
3077   case Stmt::CXXBoolLiteralExprClass:
3078   case Stmt::DeclRefExprClass:
3079   case Stmt::FloatingLiteralClass:
3080   case Stmt::IntegerLiteralClass:
3081   case Stmt::MemberExprClass:
3082   case Stmt::ObjCArrayLiteralClass:
3083   case Stmt::ObjCBoolLiteralExprClass:
3084   case Stmt::ObjCBoxedExprClass:
3085   case Stmt::ObjCDictionaryLiteralClass:
3086   case Stmt::ObjCEncodeExprClass:
3087   case Stmt::ObjCIvarRefExprClass:
3088   case Stmt::ObjCMessageExprClass:
3089   case Stmt::ObjCPropertyRefExprClass:
3090   case Stmt::ObjCStringLiteralClass:
3091   case Stmt::ObjCSubscriptRefExprClass:
3092   case Stmt::ParenExprClass:
3093   case Stmt::StringLiteralClass:
3094   case Stmt::UnaryOperatorClass:
3095     return false;
3096   default:
3097     return true;
3098   }
3099 }
3100 
3101 bool
3102 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3103                                     const char *StartSpecifier,
3104                                     unsigned SpecifierLen,
3105                                     const Expr *E) {
3106   using namespace analyze_format_string;
3107   using namespace analyze_printf;
3108   // Now type check the data expression that matches the
3109   // format specifier.
3110   const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3111                                                     ObjCContext);
3112   if (!AT.isValid())
3113     return true;
3114 
3115   QualType ExprTy = E->getType();
3116   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3117     ExprTy = TET->getUnderlyingExpr()->getType();
3118   }
3119 
3120   if (AT.matchesType(S.Context, ExprTy))
3121     return true;
3122 
3123   // Look through argument promotions for our error message's reported type.
3124   // This includes the integral and floating promotions, but excludes array
3125   // and function pointer decay; seeing that an argument intended to be a
3126   // string has type 'char [6]' is probably more confusing than 'char *'.
3127   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3128     if (ICE->getCastKind() == CK_IntegralCast ||
3129         ICE->getCastKind() == CK_FloatingCast) {
3130       E = ICE->getSubExpr();
3131       ExprTy = E->getType();
3132 
3133       // Check if we didn't match because of an implicit cast from a 'char'
3134       // or 'short' to an 'int'.  This is done because printf is a varargs
3135       // function.
3136       if (ICE->getType() == S.Context.IntTy ||
3137           ICE->getType() == S.Context.UnsignedIntTy) {
3138         // All further checking is done on the subexpression.
3139         if (AT.matchesType(S.Context, ExprTy))
3140           return true;
3141       }
3142     }
3143   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3144     // Special case for 'a', which has type 'int' in C.
3145     // Note, however, that we do /not/ want to treat multibyte constants like
3146     // 'MooV' as characters! This form is deprecated but still exists.
3147     if (ExprTy == S.Context.IntTy)
3148       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3149         ExprTy = S.Context.CharTy;
3150   }
3151 
3152   // %C in an Objective-C context prints a unichar, not a wchar_t.
3153   // If the argument is an integer of some kind, believe the %C and suggest
3154   // a cast instead of changing the conversion specifier.
3155   QualType IntendedTy = ExprTy;
3156   if (ObjCContext &&
3157       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3158     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3159         !ExprTy->isCharType()) {
3160       // 'unichar' is defined as a typedef of unsigned short, but we should
3161       // prefer using the typedef if it is visible.
3162       IntendedTy = S.Context.UnsignedShortTy;
3163 
3164       // While we are here, check if the value is an IntegerLiteral that happens
3165       // to be within the valid range.
3166       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3167         const llvm::APInt &V = IL->getValue();
3168         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3169           return true;
3170       }
3171 
3172       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3173                           Sema::LookupOrdinaryName);
3174       if (S.LookupName(Result, S.getCurScope())) {
3175         NamedDecl *ND = Result.getFoundDecl();
3176         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3177           if (TD->getUnderlyingType() == IntendedTy)
3178             IntendedTy = S.Context.getTypedefType(TD);
3179       }
3180     }
3181   }
3182 
3183   // Special-case some of Darwin's platform-independence types by suggesting
3184   // casts to primitive types that are known to be large enough.
3185   bool ShouldNotPrintDirectly = false;
3186   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
3187     // Use a 'while' to peel off layers of typedefs.
3188     QualType TyTy = IntendedTy;
3189     while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
3190       StringRef Name = UserTy->getDecl()->getName();
3191       QualType CastTy = llvm::StringSwitch<QualType>(Name)
3192         .Case("NSInteger", S.Context.LongTy)
3193         .Case("NSUInteger", S.Context.UnsignedLongTy)
3194         .Case("SInt32", S.Context.IntTy)
3195         .Case("UInt32", S.Context.UnsignedIntTy)
3196         .Default(QualType());
3197 
3198       if (!CastTy.isNull()) {
3199         ShouldNotPrintDirectly = true;
3200         IntendedTy = CastTy;
3201         break;
3202       }
3203       TyTy = UserTy->desugar();
3204     }
3205   }
3206 
3207   // We may be able to offer a FixItHint if it is a supported type.
3208   PrintfSpecifier fixedFS = FS;
3209   bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
3210                                  S.Context, ObjCContext);
3211 
3212   if (success) {
3213     // Get the fix string from the fixed format specifier
3214     SmallString<16> buf;
3215     llvm::raw_svector_ostream os(buf);
3216     fixedFS.toString(os);
3217 
3218     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3219 
3220     if (IntendedTy == ExprTy) {
3221       // In this case, the specifier is wrong and should be changed to match
3222       // the argument.
3223       EmitFormatDiagnostic(
3224         S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3225           << AT.getRepresentativeTypeName(S.Context) << IntendedTy
3226           << E->getSourceRange(),
3227         E->getLocStart(),
3228         /*IsStringLocation*/false,
3229         SpecRange,
3230         FixItHint::CreateReplacement(SpecRange, os.str()));
3231 
3232     } else {
3233       // The canonical type for formatting this value is different from the
3234       // actual type of the expression. (This occurs, for example, with Darwin's
3235       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3236       // should be printed as 'long' for 64-bit compatibility.)
3237       // Rather than emitting a normal format/argument mismatch, we want to
3238       // add a cast to the recommended type (and correct the format string
3239       // if necessary).
3240       SmallString<16> CastBuf;
3241       llvm::raw_svector_ostream CastFix(CastBuf);
3242       CastFix << "(";
3243       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3244       CastFix << ")";
3245 
3246       SmallVector<FixItHint,4> Hints;
3247       if (!AT.matchesType(S.Context, IntendedTy))
3248         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3249 
3250       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3251         // If there's already a cast present, just replace it.
3252         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3253         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3254 
3255       } else if (!requiresParensToAddCast(E)) {
3256         // If the expression has high enough precedence,
3257         // just write the C-style cast.
3258         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3259                                                    CastFix.str()));
3260       } else {
3261         // Otherwise, add parens around the expression as well as the cast.
3262         CastFix << "(";
3263         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3264                                                    CastFix.str()));
3265 
3266         SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd());
3267         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3268       }
3269 
3270       if (ShouldNotPrintDirectly) {
3271         // The expression has a type that should not be printed directly.
3272         // We extract the name from the typedef because we don't want to show
3273         // the underlying type in the diagnostic.
3274         StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
3275 
3276         EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
3277                                << Name << IntendedTy
3278                                << E->getSourceRange(),
3279                              E->getLocStart(), /*IsStringLocation=*/false,
3280                              SpecRange, Hints);
3281       } else {
3282         // In this case, the expression could be printed using a different
3283         // specifier, but we've decided that the specifier is probably correct
3284         // and we should cast instead. Just use the normal warning message.
3285         EmitFormatDiagnostic(
3286           S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3287             << AT.getRepresentativeTypeName(S.Context) << ExprTy
3288             << E->getSourceRange(),
3289           E->getLocStart(), /*IsStringLocation*/false,
3290           SpecRange, Hints);
3291       }
3292     }
3293   } else {
3294     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3295                                                    SpecifierLen);
3296     // Since the warning for passing non-POD types to variadic functions
3297     // was deferred until now, we emit a warning for non-POD
3298     // arguments here.
3299     switch (S.isValidVarArgType(ExprTy)) {
3300     case Sema::VAK_Valid:
3301     case Sema::VAK_ValidInCXX11:
3302       EmitFormatDiagnostic(
3303         S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3304           << AT.getRepresentativeTypeName(S.Context) << ExprTy
3305           << CSR
3306           << E->getSourceRange(),
3307         E->getLocStart(), /*IsStringLocation*/false, CSR);
3308       break;
3309 
3310     case Sema::VAK_Undefined:
3311       EmitFormatDiagnostic(
3312         S.PDiag(diag::warn_non_pod_vararg_with_format_string)
3313           << S.getLangOpts().CPlusPlus11
3314           << ExprTy
3315           << CallType
3316           << AT.getRepresentativeTypeName(S.Context)
3317           << CSR
3318           << E->getSourceRange(),
3319         E->getLocStart(), /*IsStringLocation*/false, CSR);
3320       checkForCStrMembers(AT, E);
3321       break;
3322 
3323     case Sema::VAK_Invalid:
3324       if (ExprTy->isObjCObjectType())
3325         EmitFormatDiagnostic(
3326           S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3327             << S.getLangOpts().CPlusPlus11
3328             << ExprTy
3329             << CallType
3330             << AT.getRepresentativeTypeName(S.Context)
3331             << CSR
3332             << E->getSourceRange(),
3333           E->getLocStart(), /*IsStringLocation*/false, CSR);
3334       else
3335         // FIXME: If this is an initializer list, suggest removing the braces
3336         // or inserting a cast to the target type.
3337         S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3338           << isa<InitListExpr>(E) << ExprTy << CallType
3339           << AT.getRepresentativeTypeName(S.Context)
3340           << E->getSourceRange();
3341       break;
3342     }
3343 
3344     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3345            "format string specifier index out of range");
3346     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
3347   }
3348 
3349   return true;
3350 }
3351 
3352 //===--- CHECK: Scanf format string checking ------------------------------===//
3353 
3354 namespace {
3355 class CheckScanfHandler : public CheckFormatHandler {
3356 public:
3357   CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3358                     const Expr *origFormatExpr, unsigned firstDataArg,
3359                     unsigned numDataArgs, const char *beg, bool hasVAListArg,
3360                     ArrayRef<const Expr *> Args,
3361                     unsigned formatIdx, bool inFunctionCall,
3362                     Sema::VariadicCallType CallType,
3363                     llvm::SmallBitVector &CheckedVarArgs)
3364     : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3365                          numDataArgs, beg, hasVAListArg,
3366                          Args, formatIdx, inFunctionCall, CallType,
3367                          CheckedVarArgs)
3368   {}
3369 
3370   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3371                             const char *startSpecifier,
3372                             unsigned specifierLen);
3373 
3374   bool HandleInvalidScanfConversionSpecifier(
3375           const analyze_scanf::ScanfSpecifier &FS,
3376           const char *startSpecifier,
3377           unsigned specifierLen);
3378 
3379   void HandleIncompleteScanList(const char *start, const char *end);
3380 };
3381 }
3382 
3383 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3384                                                  const char *end) {
3385   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3386                        getLocationOfByte(end), /*IsStringLocation*/true,
3387                        getSpecifierRange(start, end - start));
3388 }
3389 
3390 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3391                                         const analyze_scanf::ScanfSpecifier &FS,
3392                                         const char *startSpecifier,
3393                                         unsigned specifierLen) {
3394 
3395   const analyze_scanf::ScanfConversionSpecifier &CS =
3396     FS.getConversionSpecifier();
3397 
3398   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3399                                           getLocationOfByte(CS.getStart()),
3400                                           startSpecifier, specifierLen,
3401                                           CS.getStart(), CS.getLength());
3402 }
3403 
3404 bool CheckScanfHandler::HandleScanfSpecifier(
3405                                        const analyze_scanf::ScanfSpecifier &FS,
3406                                        const char *startSpecifier,
3407                                        unsigned specifierLen) {
3408 
3409   using namespace analyze_scanf;
3410   using namespace analyze_format_string;
3411 
3412   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
3413 
3414   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
3415   // be used to decide if we are using positional arguments consistently.
3416   if (FS.consumesDataArgument()) {
3417     if (atFirstArg) {
3418       atFirstArg = false;
3419       usesPositionalArgs = FS.usesPositionalArg();
3420     }
3421     else if (usesPositionalArgs != FS.usesPositionalArg()) {
3422       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3423                                         startSpecifier, specifierLen);
3424       return false;
3425     }
3426   }
3427 
3428   // Check if the field with is non-zero.
3429   const OptionalAmount &Amt = FS.getFieldWidth();
3430   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3431     if (Amt.getConstantAmount() == 0) {
3432       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3433                                                    Amt.getConstantLength());
3434       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3435                            getLocationOfByte(Amt.getStart()),
3436                            /*IsStringLocation*/true, R,
3437                            FixItHint::CreateRemoval(R));
3438     }
3439   }
3440 
3441   if (!FS.consumesDataArgument()) {
3442     // FIXME: Technically specifying a precision or field width here
3443     // makes no sense.  Worth issuing a warning at some point.
3444     return true;
3445   }
3446 
3447   // Consume the argument.
3448   unsigned argIndex = FS.getArgIndex();
3449   if (argIndex < NumDataArgs) {
3450       // The check to see if the argIndex is valid will come later.
3451       // We set the bit here because we may exit early from this
3452       // function if we encounter some other error.
3453     CoveredArgs.set(argIndex);
3454   }
3455 
3456   // Check the length modifier is valid with the given conversion specifier.
3457   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
3458     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3459                                 diag::warn_format_nonsensical_length);
3460   else if (!FS.hasStandardLengthModifier())
3461     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
3462   else if (!FS.hasStandardLengthConversionCombination())
3463     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3464                                 diag::warn_format_non_standard_conversion_spec);
3465 
3466   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3467     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3468 
3469   // The remaining checks depend on the data arguments.
3470   if (HasVAListArg)
3471     return true;
3472 
3473   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
3474     return false;
3475 
3476   // Check that the argument type matches the format specifier.
3477   const Expr *Ex = getDataArg(argIndex);
3478   if (!Ex)
3479     return true;
3480 
3481   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3482   if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
3483     ScanfSpecifier fixedFS = FS;
3484     bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
3485                                    S.Context);
3486 
3487     if (success) {
3488       // Get the fix string from the fixed format specifier.
3489       SmallString<128> buf;
3490       llvm::raw_svector_ostream os(buf);
3491       fixedFS.toString(os);
3492 
3493       EmitFormatDiagnostic(
3494         S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3495           << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
3496           << Ex->getSourceRange(),
3497         Ex->getLocStart(),
3498         /*IsStringLocation*/false,
3499         getSpecifierRange(startSpecifier, specifierLen),
3500         FixItHint::CreateReplacement(
3501           getSpecifierRange(startSpecifier, specifierLen),
3502           os.str()));
3503     } else {
3504       EmitFormatDiagnostic(
3505         S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3506           << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
3507           << Ex->getSourceRange(),
3508         Ex->getLocStart(),
3509         /*IsStringLocation*/false,
3510         getSpecifierRange(startSpecifier, specifierLen));
3511     }
3512   }
3513 
3514   return true;
3515 }
3516 
3517 void Sema::CheckFormatString(const StringLiteral *FExpr,
3518                              const Expr *OrigFormatExpr,
3519                              ArrayRef<const Expr *> Args,
3520                              bool HasVAListArg, unsigned format_idx,
3521                              unsigned firstDataArg, FormatStringType Type,
3522                              bool inFunctionCall, VariadicCallType CallType,
3523                              llvm::SmallBitVector &CheckedVarArgs) {
3524 
3525   // CHECK: is the format string a wide literal?
3526   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
3527     CheckFormatHandler::EmitFormatDiagnostic(
3528       *this, inFunctionCall, Args[format_idx],
3529       PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3530       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
3531     return;
3532   }
3533 
3534   // Str - The format string.  NOTE: this is NOT null-terminated!
3535   StringRef StrRef = FExpr->getString();
3536   const char *Str = StrRef.data();
3537   // Account for cases where the string literal is truncated in a declaration.
3538   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
3539   assert(T && "String literal not of constant array type!");
3540   size_t TypeSize = T->getSize().getZExtValue();
3541   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
3542   const unsigned numDataArgs = Args.size() - firstDataArg;
3543 
3544   // Emit a warning if the string literal is truncated and does not contain an
3545   // embedded null character.
3546   if (TypeSize <= StrRef.size() &&
3547       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
3548     CheckFormatHandler::EmitFormatDiagnostic(
3549         *this, inFunctionCall, Args[format_idx],
3550         PDiag(diag::warn_printf_format_string_not_null_terminated),
3551         FExpr->getLocStart(),
3552         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
3553     return;
3554   }
3555 
3556   // CHECK: empty format string?
3557   if (StrLen == 0 && numDataArgs > 0) {
3558     CheckFormatHandler::EmitFormatDiagnostic(
3559       *this, inFunctionCall, Args[format_idx],
3560       PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3561       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
3562     return;
3563   }
3564 
3565   if (Type == FST_Printf || Type == FST_NSString) {
3566     CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
3567                          numDataArgs, (Type == FST_NSString),
3568                          Str, HasVAListArg, Args, format_idx,
3569                          inFunctionCall, CallType, CheckedVarArgs);
3570 
3571     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
3572                                                   getLangOpts(),
3573                                                   Context.getTargetInfo()))
3574       H.DoneProcessing();
3575   } else if (Type == FST_Scanf) {
3576     CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
3577                         Str, HasVAListArg, Args, format_idx,
3578                         inFunctionCall, CallType, CheckedVarArgs);
3579 
3580     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
3581                                                  getLangOpts(),
3582                                                  Context.getTargetInfo()))
3583       H.DoneProcessing();
3584   } // TODO: handle other formats
3585 }
3586 
3587 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
3588 
3589 // Returns the related absolute value function that is larger, of 0 if one
3590 // does not exist.
3591 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
3592   switch (AbsFunction) {
3593   default:
3594     return 0;
3595 
3596   case Builtin::BI__builtin_abs:
3597     return Builtin::BI__builtin_labs;
3598   case Builtin::BI__builtin_labs:
3599     return Builtin::BI__builtin_llabs;
3600   case Builtin::BI__builtin_llabs:
3601     return 0;
3602 
3603   case Builtin::BI__builtin_fabsf:
3604     return Builtin::BI__builtin_fabs;
3605   case Builtin::BI__builtin_fabs:
3606     return Builtin::BI__builtin_fabsl;
3607   case Builtin::BI__builtin_fabsl:
3608     return 0;
3609 
3610   case Builtin::BI__builtin_cabsf:
3611     return Builtin::BI__builtin_cabs;
3612   case Builtin::BI__builtin_cabs:
3613     return Builtin::BI__builtin_cabsl;
3614   case Builtin::BI__builtin_cabsl:
3615     return 0;
3616 
3617   case Builtin::BIabs:
3618     return Builtin::BIlabs;
3619   case Builtin::BIlabs:
3620     return Builtin::BIllabs;
3621   case Builtin::BIllabs:
3622     return 0;
3623 
3624   case Builtin::BIfabsf:
3625     return Builtin::BIfabs;
3626   case Builtin::BIfabs:
3627     return Builtin::BIfabsl;
3628   case Builtin::BIfabsl:
3629     return 0;
3630 
3631   case Builtin::BIcabsf:
3632    return Builtin::BIcabs;
3633   case Builtin::BIcabs:
3634     return Builtin::BIcabsl;
3635   case Builtin::BIcabsl:
3636     return 0;
3637   }
3638 }
3639 
3640 // Returns the argument type of the absolute value function.
3641 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
3642                                              unsigned AbsType) {
3643   if (AbsType == 0)
3644     return QualType();
3645 
3646   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3647   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
3648   if (Error != ASTContext::GE_None)
3649     return QualType();
3650 
3651   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
3652   if (!FT)
3653     return QualType();
3654 
3655   if (FT->getNumParams() != 1)
3656     return QualType();
3657 
3658   return FT->getParamType(0);
3659 }
3660 
3661 // Returns the best absolute value function, or zero, based on type and
3662 // current absolute value function.
3663 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
3664                                    unsigned AbsFunctionKind) {
3665   unsigned BestKind = 0;
3666   uint64_t ArgSize = Context.getTypeSize(ArgType);
3667   for (unsigned Kind = AbsFunctionKind; Kind != 0;
3668        Kind = getLargerAbsoluteValueFunction(Kind)) {
3669     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
3670     if (Context.getTypeSize(ParamType) >= ArgSize) {
3671       if (BestKind == 0)
3672         BestKind = Kind;
3673       else if (Context.hasSameType(ParamType, ArgType)) {
3674         BestKind = Kind;
3675         break;
3676       }
3677     }
3678   }
3679   return BestKind;
3680 }
3681 
3682 enum AbsoluteValueKind {
3683   AVK_Integer,
3684   AVK_Floating,
3685   AVK_Complex
3686 };
3687 
3688 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
3689   if (T->isIntegralOrEnumerationType())
3690     return AVK_Integer;
3691   if (T->isRealFloatingType())
3692     return AVK_Floating;
3693   if (T->isAnyComplexType())
3694     return AVK_Complex;
3695 
3696   llvm_unreachable("Type not integer, floating, or complex");
3697 }
3698 
3699 // Changes the absolute value function to a different type.  Preserves whether
3700 // the function is a builtin.
3701 static unsigned changeAbsFunction(unsigned AbsKind,
3702                                   AbsoluteValueKind ValueKind) {
3703   switch (ValueKind) {
3704   case AVK_Integer:
3705     switch (AbsKind) {
3706     default:
3707       return 0;
3708     case Builtin::BI__builtin_fabsf:
3709     case Builtin::BI__builtin_fabs:
3710     case Builtin::BI__builtin_fabsl:
3711     case Builtin::BI__builtin_cabsf:
3712     case Builtin::BI__builtin_cabs:
3713     case Builtin::BI__builtin_cabsl:
3714       return Builtin::BI__builtin_abs;
3715     case Builtin::BIfabsf:
3716     case Builtin::BIfabs:
3717     case Builtin::BIfabsl:
3718     case Builtin::BIcabsf:
3719     case Builtin::BIcabs:
3720     case Builtin::BIcabsl:
3721       return Builtin::BIabs;
3722     }
3723   case AVK_Floating:
3724     switch (AbsKind) {
3725     default:
3726       return 0;
3727     case Builtin::BI__builtin_abs:
3728     case Builtin::BI__builtin_labs:
3729     case Builtin::BI__builtin_llabs:
3730     case Builtin::BI__builtin_cabsf:
3731     case Builtin::BI__builtin_cabs:
3732     case Builtin::BI__builtin_cabsl:
3733       return Builtin::BI__builtin_fabsf;
3734     case Builtin::BIabs:
3735     case Builtin::BIlabs:
3736     case Builtin::BIllabs:
3737     case Builtin::BIcabsf:
3738     case Builtin::BIcabs:
3739     case Builtin::BIcabsl:
3740       return Builtin::BIfabsf;
3741     }
3742   case AVK_Complex:
3743     switch (AbsKind) {
3744     default:
3745       return 0;
3746     case Builtin::BI__builtin_abs:
3747     case Builtin::BI__builtin_labs:
3748     case Builtin::BI__builtin_llabs:
3749     case Builtin::BI__builtin_fabsf:
3750     case Builtin::BI__builtin_fabs:
3751     case Builtin::BI__builtin_fabsl:
3752       return Builtin::BI__builtin_cabsf;
3753     case Builtin::BIabs:
3754     case Builtin::BIlabs:
3755     case Builtin::BIllabs:
3756     case Builtin::BIfabsf:
3757     case Builtin::BIfabs:
3758     case Builtin::BIfabsl:
3759       return Builtin::BIcabsf;
3760     }
3761   }
3762   llvm_unreachable("Unable to convert function");
3763 }
3764 
3765 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
3766   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
3767   if (!FnInfo)
3768     return 0;
3769 
3770   switch (FDecl->getBuiltinID()) {
3771   default:
3772     return 0;
3773   case Builtin::BI__builtin_abs:
3774   case Builtin::BI__builtin_fabs:
3775   case Builtin::BI__builtin_fabsf:
3776   case Builtin::BI__builtin_fabsl:
3777   case Builtin::BI__builtin_labs:
3778   case Builtin::BI__builtin_llabs:
3779   case Builtin::BI__builtin_cabs:
3780   case Builtin::BI__builtin_cabsf:
3781   case Builtin::BI__builtin_cabsl:
3782   case Builtin::BIabs:
3783   case Builtin::BIlabs:
3784   case Builtin::BIllabs:
3785   case Builtin::BIfabs:
3786   case Builtin::BIfabsf:
3787   case Builtin::BIfabsl:
3788   case Builtin::BIcabs:
3789   case Builtin::BIcabsf:
3790   case Builtin::BIcabsl:
3791     return FDecl->getBuiltinID();
3792   }
3793   llvm_unreachable("Unknown Builtin type");
3794 }
3795 
3796 // If the replacement is valid, emit a note with replacement function.
3797 // Additionally, suggest including the proper header if not already included.
3798 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
3799                             unsigned AbsKind) {
3800   std::string AbsName = S.Context.BuiltinInfo.GetName(AbsKind);
3801 
3802   // Look up absolute value function in TU scope.
3803   DeclarationName DN(&S.Context.Idents.get(AbsName));
3804   LookupResult R(S, DN, Loc, Sema::LookupAnyName);
3805   R.suppressDiagnostics();
3806   S.LookupName(R, S.TUScope);
3807 
3808   // Skip notes if multiple results found in lookup.
3809   if (!R.empty() && !R.isSingleResult())
3810     return;
3811 
3812   FunctionDecl *FD = 0;
3813   bool FoundFunction = R.isSingleResult();
3814   // When one result is found, see if it is the correct function.
3815   if (R.isSingleResult()) {
3816     FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3817     if (!FD || FD->getBuiltinID() != AbsKind)
3818       return;
3819   }
3820 
3821   // Look for local name conflict, prepend "::" as necessary.
3822   R.clear();
3823   S.LookupName(R, S.getCurScope());
3824 
3825   if (!FoundFunction) {
3826     if (!R.empty()) {
3827       AbsName = "::" + AbsName;
3828     }
3829   } else { // FoundFunction
3830     if (R.isSingleResult()) {
3831       if (R.getFoundDecl() != FD) {
3832         AbsName = "::" + AbsName;
3833       }
3834     } else if (!R.empty()) {
3835       AbsName = "::" + AbsName;
3836     }
3837   }
3838 
3839   S.Diag(Loc, diag::note_replace_abs_function)
3840       << AbsName << FixItHint::CreateReplacement(Range, AbsName);
3841 
3842   if (!FoundFunction) {
3843     S.Diag(Loc, diag::note_please_include_header)
3844         << S.Context.BuiltinInfo.getHeaderName(AbsKind)
3845         << S.Context.BuiltinInfo.GetName(AbsKind);
3846   }
3847 }
3848 
3849 // Warn when using the wrong abs() function.
3850 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
3851                                       const FunctionDecl *FDecl,
3852                                       IdentifierInfo *FnInfo) {
3853   if (Call->getNumArgs() != 1)
3854     return;
3855 
3856   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
3857   if (AbsKind == 0)
3858     return;
3859 
3860   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
3861   QualType ParamType = Call->getArg(0)->getType();
3862 
3863   // Unsigned types can not be negative.  Suggest to drop the absolute value
3864   // function.
3865   if (ArgType->isUnsignedIntegerType()) {
3866     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
3867     Diag(Call->getExprLoc(), diag::note_remove_abs)
3868         << FDecl
3869         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
3870     return;
3871   }
3872 
3873   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
3874   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
3875 
3876   // The argument and parameter are the same kind.  Check if they are the right
3877   // size.
3878   if (ArgValueKind == ParamValueKind) {
3879     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
3880       return;
3881 
3882     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
3883     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
3884         << FDecl << ArgType << ParamType;
3885 
3886     if (NewAbsKind == 0)
3887       return;
3888 
3889     emitReplacement(*this, Call->getExprLoc(),
3890                     Call->getCallee()->getSourceRange(), NewAbsKind);
3891     return;
3892   }
3893 
3894   // ArgValueKind != ParamValueKind
3895   // The wrong type of absolute value function was used.  Attempt to find the
3896   // proper one.
3897   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
3898   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
3899   if (NewAbsKind == 0)
3900     return;
3901 
3902   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
3903       << FDecl << ParamValueKind << ArgValueKind;
3904 
3905   emitReplacement(*this, Call->getExprLoc(),
3906                   Call->getCallee()->getSourceRange(), NewAbsKind);
3907   return;
3908 }
3909 
3910 //===--- CHECK: Standard memory functions ---------------------------------===//
3911 
3912 /// \brief Takes the expression passed to the size_t parameter of functions
3913 /// such as memcmp, strncat, etc and warns if it's a comparison.
3914 ///
3915 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
3916 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
3917                                            IdentifierInfo *FnName,
3918                                            SourceLocation FnLoc,
3919                                            SourceLocation RParenLoc) {
3920   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
3921   if (!Size)
3922     return false;
3923 
3924   // if E is binop and op is >, <, >=, <=, ==, &&, ||:
3925   if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
3926     return false;
3927 
3928   Preprocessor &PP = S.getPreprocessor();
3929   SourceRange SizeRange = Size->getSourceRange();
3930   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
3931       << SizeRange << FnName;
3932   S.Diag(FnLoc, diag::warn_memsize_comparison_paren_note)
3933       << FnName
3934       << FixItHint::CreateInsertion(
3935              PP.getLocForEndOfToken(Size->getLHS()->getLocEnd()),
3936              ")")
3937       << FixItHint::CreateRemoval(RParenLoc);
3938   S.Diag(SizeRange.getBegin(), diag::warn_memsize_comparison_cast_note)
3939       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
3940       << FixItHint::CreateInsertion(
3941              PP.getLocForEndOfToken(SizeRange.getEnd()), ")");
3942 
3943   return true;
3944 }
3945 
3946 /// \brief Determine whether the given type is a dynamic class type (e.g.,
3947 /// whether it has a vtable).
3948 static bool isDynamicClassType(QualType T) {
3949   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3950     if (CXXRecordDecl *Definition = Record->getDefinition())
3951       if (Definition->isDynamicClass())
3952         return true;
3953 
3954   return false;
3955 }
3956 
3957 /// \brief If E is a sizeof expression, returns its argument expression,
3958 /// otherwise returns NULL.
3959 static const Expr *getSizeOfExprArg(const Expr* E) {
3960   if (const UnaryExprOrTypeTraitExpr *SizeOf =
3961       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3962     if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
3963       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
3964 
3965   return 0;
3966 }
3967 
3968 /// \brief If E is a sizeof expression, returns its argument type.
3969 static QualType getSizeOfArgType(const Expr* E) {
3970   if (const UnaryExprOrTypeTraitExpr *SizeOf =
3971       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3972     if (SizeOf->getKind() == clang::UETT_SizeOf)
3973       return SizeOf->getTypeOfArgument();
3974 
3975   return QualType();
3976 }
3977 
3978 /// \brief Check for dangerous or invalid arguments to memset().
3979 ///
3980 /// This issues warnings on known problematic, dangerous or unspecified
3981 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3982 /// function calls.
3983 ///
3984 /// \param Call The call expression to diagnose.
3985 void Sema::CheckMemaccessArguments(const CallExpr *Call,
3986                                    unsigned BId,
3987                                    IdentifierInfo *FnName) {
3988   assert(BId != 0);
3989 
3990   // It is possible to have a non-standard definition of memset.  Validate
3991   // we have enough arguments, and if not, abort further checking.
3992   unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
3993   if (Call->getNumArgs() < ExpectedNumArgs)
3994     return;
3995 
3996   unsigned LastArg = (BId == Builtin::BImemset ||
3997                       BId == Builtin::BIstrndup ? 1 : 2);
3998   unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
3999   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
4000 
4001   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4002                                      Call->getLocStart(), Call->getRParenLoc()))
4003     return;
4004 
4005   // We have special checking when the length is a sizeof expression.
4006   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4007   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4008   llvm::FoldingSetNodeID SizeOfArgID;
4009 
4010   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4011     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
4012     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
4013 
4014     QualType DestTy = Dest->getType();
4015     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
4016       QualType PointeeTy = DestPtrTy->getPointeeType();
4017 
4018       // Never warn about void type pointers. This can be used to suppress
4019       // false positives.
4020       if (PointeeTy->isVoidType())
4021         continue;
4022 
4023       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4024       // actually comparing the expressions for equality. Because computing the
4025       // expression IDs can be expensive, we only do this if the diagnostic is
4026       // enabled.
4027       if (SizeOfArg &&
4028           Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
4029                                    SizeOfArg->getExprLoc())) {
4030         // We only compute IDs for expressions if the warning is enabled, and
4031         // cache the sizeof arg's ID.
4032         if (SizeOfArgID == llvm::FoldingSetNodeID())
4033           SizeOfArg->Profile(SizeOfArgID, Context, true);
4034         llvm::FoldingSetNodeID DestID;
4035         Dest->Profile(DestID, Context, true);
4036         if (DestID == SizeOfArgID) {
4037           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4038           //       over sizeof(src) as well.
4039           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
4040           StringRef ReadableName = FnName->getName();
4041 
4042           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
4043             if (UnaryOp->getOpcode() == UO_AddrOf)
4044               ActionIdx = 1; // If its an address-of operator, just remove it.
4045           if (!PointeeTy->isIncompleteType() &&
4046               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
4047             ActionIdx = 2; // If the pointee's size is sizeof(char),
4048                            // suggest an explicit length.
4049 
4050           // If the function is defined as a builtin macro, do not show macro
4051           // expansion.
4052           SourceLocation SL = SizeOfArg->getExprLoc();
4053           SourceRange DSR = Dest->getSourceRange();
4054           SourceRange SSR = SizeOfArg->getSourceRange();
4055           SourceManager &SM  = PP.getSourceManager();
4056 
4057           if (SM.isMacroArgExpansion(SL)) {
4058             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4059             SL = SM.getSpellingLoc(SL);
4060             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4061                              SM.getSpellingLoc(DSR.getEnd()));
4062             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4063                              SM.getSpellingLoc(SSR.getEnd()));
4064           }
4065 
4066           DiagRuntimeBehavior(SL, SizeOfArg,
4067                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
4068                                 << ReadableName
4069                                 << PointeeTy
4070                                 << DestTy
4071                                 << DSR
4072                                 << SSR);
4073           DiagRuntimeBehavior(SL, SizeOfArg,
4074                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4075                                 << ActionIdx
4076                                 << SSR);
4077 
4078           break;
4079         }
4080       }
4081 
4082       // Also check for cases where the sizeof argument is the exact same
4083       // type as the memory argument, and where it points to a user-defined
4084       // record type.
4085       if (SizeOfArgTy != QualType()) {
4086         if (PointeeTy->isRecordType() &&
4087             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4088           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4089                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
4090                                 << FnName << SizeOfArgTy << ArgIdx
4091                                 << PointeeTy << Dest->getSourceRange()
4092                                 << LenExpr->getSourceRange());
4093           break;
4094         }
4095       }
4096 
4097       // Always complain about dynamic classes.
4098       if (isDynamicClassType(PointeeTy)) {
4099 
4100         unsigned OperationType = 0;
4101         // "overwritten" if we're warning about the destination for any call
4102         // but memcmp; otherwise a verb appropriate to the call.
4103         if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4104           if (BId == Builtin::BImemcpy)
4105             OperationType = 1;
4106           else if(BId == Builtin::BImemmove)
4107             OperationType = 2;
4108           else if (BId == Builtin::BImemcmp)
4109             OperationType = 3;
4110         }
4111 
4112         DiagRuntimeBehavior(
4113           Dest->getExprLoc(), Dest,
4114           PDiag(diag::warn_dyn_class_memaccess)
4115             << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
4116             << FnName << PointeeTy
4117             << OperationType
4118             << Call->getCallee()->getSourceRange());
4119       } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4120                BId != Builtin::BImemset)
4121         DiagRuntimeBehavior(
4122           Dest->getExprLoc(), Dest,
4123           PDiag(diag::warn_arc_object_memaccess)
4124             << ArgIdx << FnName << PointeeTy
4125             << Call->getCallee()->getSourceRange());
4126       else
4127         continue;
4128 
4129       DiagRuntimeBehavior(
4130         Dest->getExprLoc(), Dest,
4131         PDiag(diag::note_bad_memaccess_silence)
4132           << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4133       break;
4134     }
4135   }
4136 }
4137 
4138 // A little helper routine: ignore addition and subtraction of integer literals.
4139 // This intentionally does not ignore all integer constant expressions because
4140 // we don't want to remove sizeof().
4141 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4142   Ex = Ex->IgnoreParenCasts();
4143 
4144   for (;;) {
4145     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4146     if (!BO || !BO->isAdditiveOp())
4147       break;
4148 
4149     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4150     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4151 
4152     if (isa<IntegerLiteral>(RHS))
4153       Ex = LHS;
4154     else if (isa<IntegerLiteral>(LHS))
4155       Ex = RHS;
4156     else
4157       break;
4158   }
4159 
4160   return Ex;
4161 }
4162 
4163 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4164                                                       ASTContext &Context) {
4165   // Only handle constant-sized or VLAs, but not flexible members.
4166   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4167     // Only issue the FIXIT for arrays of size > 1.
4168     if (CAT->getSize().getSExtValue() <= 1)
4169       return false;
4170   } else if (!Ty->isVariableArrayType()) {
4171     return false;
4172   }
4173   return true;
4174 }
4175 
4176 // Warn if the user has made the 'size' argument to strlcpy or strlcat
4177 // be the size of the source, instead of the destination.
4178 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4179                                     IdentifierInfo *FnName) {
4180 
4181   // Don't crash if the user has the wrong number of arguments
4182   if (Call->getNumArgs() != 3)
4183     return;
4184 
4185   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
4186   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
4187   const Expr *CompareWithSrc = NULL;
4188 
4189   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
4190                                      Call->getLocStart(), Call->getRParenLoc()))
4191     return;
4192 
4193   // Look for 'strlcpy(dst, x, sizeof(x))'
4194   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
4195     CompareWithSrc = Ex;
4196   else {
4197     // Look for 'strlcpy(dst, x, strlen(x))'
4198     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
4199       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
4200           SizeCall->getNumArgs() == 1)
4201         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
4202     }
4203   }
4204 
4205   if (!CompareWithSrc)
4206     return;
4207 
4208   // Determine if the argument to sizeof/strlen is equal to the source
4209   // argument.  In principle there's all kinds of things you could do
4210   // here, for instance creating an == expression and evaluating it with
4211   // EvaluateAsBooleanCondition, but this uses a more direct technique:
4212   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
4213   if (!SrcArgDRE)
4214     return;
4215 
4216   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
4217   if (!CompareWithSrcDRE ||
4218       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
4219     return;
4220 
4221   const Expr *OriginalSizeArg = Call->getArg(2);
4222   Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
4223     << OriginalSizeArg->getSourceRange() << FnName;
4224 
4225   // Output a FIXIT hint if the destination is an array (rather than a
4226   // pointer to an array).  This could be enhanced to handle some
4227   // pointers if we know the actual size, like if DstArg is 'array+2'
4228   // we could say 'sizeof(array)-2'.
4229   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
4230   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
4231     return;
4232 
4233   SmallString<128> sizeString;
4234   llvm::raw_svector_ostream OS(sizeString);
4235   OS << "sizeof(";
4236   DstArg->printPretty(OS, 0, getPrintingPolicy());
4237   OS << ")";
4238 
4239   Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
4240     << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
4241                                     OS.str());
4242 }
4243 
4244 /// Check if two expressions refer to the same declaration.
4245 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
4246   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
4247     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
4248       return D1->getDecl() == D2->getDecl();
4249   return false;
4250 }
4251 
4252 static const Expr *getStrlenExprArg(const Expr *E) {
4253   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
4254     const FunctionDecl *FD = CE->getDirectCallee();
4255     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
4256       return 0;
4257     return CE->getArg(0)->IgnoreParenCasts();
4258   }
4259   return 0;
4260 }
4261 
4262 // Warn on anti-patterns as the 'size' argument to strncat.
4263 // The correct size argument should look like following:
4264 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
4265 void Sema::CheckStrncatArguments(const CallExpr *CE,
4266                                  IdentifierInfo *FnName) {
4267   // Don't crash if the user has the wrong number of arguments.
4268   if (CE->getNumArgs() < 3)
4269     return;
4270   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
4271   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
4272   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
4273 
4274   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
4275                                      CE->getRParenLoc()))
4276     return;
4277 
4278   // Identify common expressions, which are wrongly used as the size argument
4279   // to strncat and may lead to buffer overflows.
4280   unsigned PatternType = 0;
4281   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
4282     // - sizeof(dst)
4283     if (referToTheSameDecl(SizeOfArg, DstArg))
4284       PatternType = 1;
4285     // - sizeof(src)
4286     else if (referToTheSameDecl(SizeOfArg, SrcArg))
4287       PatternType = 2;
4288   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
4289     if (BE->getOpcode() == BO_Sub) {
4290       const Expr *L = BE->getLHS()->IgnoreParenCasts();
4291       const Expr *R = BE->getRHS()->IgnoreParenCasts();
4292       // - sizeof(dst) - strlen(dst)
4293       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
4294           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
4295         PatternType = 1;
4296       // - sizeof(src) - (anything)
4297       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
4298         PatternType = 2;
4299     }
4300   }
4301 
4302   if (PatternType == 0)
4303     return;
4304 
4305   // Generate the diagnostic.
4306   SourceLocation SL = LenArg->getLocStart();
4307   SourceRange SR = LenArg->getSourceRange();
4308   SourceManager &SM  = PP.getSourceManager();
4309 
4310   // If the function is defined as a builtin macro, do not show macro expansion.
4311   if (SM.isMacroArgExpansion(SL)) {
4312     SL = SM.getSpellingLoc(SL);
4313     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
4314                      SM.getSpellingLoc(SR.getEnd()));
4315   }
4316 
4317   // Check if the destination is an array (rather than a pointer to an array).
4318   QualType DstTy = DstArg->getType();
4319   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
4320                                                                     Context);
4321   if (!isKnownSizeArray) {
4322     if (PatternType == 1)
4323       Diag(SL, diag::warn_strncat_wrong_size) << SR;
4324     else
4325       Diag(SL, diag::warn_strncat_src_size) << SR;
4326     return;
4327   }
4328 
4329   if (PatternType == 1)
4330     Diag(SL, diag::warn_strncat_large_size) << SR;
4331   else
4332     Diag(SL, diag::warn_strncat_src_size) << SR;
4333 
4334   SmallString<128> sizeString;
4335   llvm::raw_svector_ostream OS(sizeString);
4336   OS << "sizeof(";
4337   DstArg->printPretty(OS, 0, getPrintingPolicy());
4338   OS << ") - ";
4339   OS << "strlen(";
4340   DstArg->printPretty(OS, 0, getPrintingPolicy());
4341   OS << ") - 1";
4342 
4343   Diag(SL, diag::note_strncat_wrong_size)
4344     << FixItHint::CreateReplacement(SR, OS.str());
4345 }
4346 
4347 //===--- CHECK: Return Address of Stack Variable --------------------------===//
4348 
4349 static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4350                      Decl *ParentDecl);
4351 static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
4352                       Decl *ParentDecl);
4353 
4354 /// CheckReturnStackAddr - Check if a return statement returns the address
4355 ///   of a stack variable.
4356 static void
4357 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
4358                      SourceLocation ReturnLoc) {
4359 
4360   Expr *stackE = 0;
4361   SmallVector<DeclRefExpr *, 8> refVars;
4362 
4363   // Perform checking for returned stack addresses, local blocks,
4364   // label addresses or references to temporaries.
4365   if (lhsType->isPointerType() ||
4366       (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
4367     stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
4368   } else if (lhsType->isReferenceType()) {
4369     stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
4370   }
4371 
4372   if (stackE == 0)
4373     return; // Nothing suspicious was found.
4374 
4375   SourceLocation diagLoc;
4376   SourceRange diagRange;
4377   if (refVars.empty()) {
4378     diagLoc = stackE->getLocStart();
4379     diagRange = stackE->getSourceRange();
4380   } else {
4381     // We followed through a reference variable. 'stackE' contains the
4382     // problematic expression but we will warn at the return statement pointing
4383     // at the reference variable. We will later display the "trail" of
4384     // reference variables using notes.
4385     diagLoc = refVars[0]->getLocStart();
4386     diagRange = refVars[0]->getSourceRange();
4387   }
4388 
4389   if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
4390     S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
4391                                              : diag::warn_ret_stack_addr)
4392      << DR->getDecl()->getDeclName() << diagRange;
4393   } else if (isa<BlockExpr>(stackE)) { // local block.
4394     S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
4395   } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
4396     S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
4397   } else { // local temporary.
4398     S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
4399                                                : diag::warn_ret_local_temp_addr)
4400      << diagRange;
4401   }
4402 
4403   // Display the "trail" of reference variables that we followed until we
4404   // found the problematic expression using notes.
4405   for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
4406     VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
4407     // If this var binds to another reference var, show the range of the next
4408     // var, otherwise the var binds to the problematic expression, in which case
4409     // show the range of the expression.
4410     SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
4411                                   : stackE->getSourceRange();
4412     S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
4413         << VD->getDeclName() << range;
4414   }
4415 }
4416 
4417 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
4418 ///  check if the expression in a return statement evaluates to an address
4419 ///  to a location on the stack, a local block, an address of a label, or a
4420 ///  reference to local temporary. The recursion is used to traverse the
4421 ///  AST of the return expression, with recursion backtracking when we
4422 ///  encounter a subexpression that (1) clearly does not lead to one of the
4423 ///  above problematic expressions (2) is something we cannot determine leads to
4424 ///  a problematic expression based on such local checking.
4425 ///
4426 ///  Both EvalAddr and EvalVal follow through reference variables to evaluate
4427 ///  the expression that they point to. Such variables are added to the
4428 ///  'refVars' vector so that we know what the reference variable "trail" was.
4429 ///
4430 ///  EvalAddr processes expressions that are pointers that are used as
4431 ///  references (and not L-values).  EvalVal handles all other values.
4432 ///  At the base case of the recursion is a check for the above problematic
4433 ///  expressions.
4434 ///
4435 ///  This implementation handles:
4436 ///
4437 ///   * pointer-to-pointer casts
4438 ///   * implicit conversions from array references to pointers
4439 ///   * taking the address of fields
4440 ///   * arbitrary interplay between "&" and "*" operators
4441 ///   * pointer arithmetic from an address of a stack variable
4442 ///   * taking the address of an array element where the array is on the stack
4443 static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4444                       Decl *ParentDecl) {
4445   if (E->isTypeDependent())
4446     return NULL;
4447 
4448   // We should only be called for evaluating pointer expressions.
4449   assert((E->getType()->isAnyPointerType() ||
4450           E->getType()->isBlockPointerType() ||
4451           E->getType()->isObjCQualifiedIdType()) &&
4452          "EvalAddr only works on pointers");
4453 
4454   E = E->IgnoreParens();
4455 
4456   // Our "symbolic interpreter" is just a dispatch off the currently
4457   // viewed AST node.  We then recursively traverse the AST by calling
4458   // EvalAddr and EvalVal appropriately.
4459   switch (E->getStmtClass()) {
4460   case Stmt::DeclRefExprClass: {
4461     DeclRefExpr *DR = cast<DeclRefExpr>(E);
4462 
4463     // If we leave the immediate function, the lifetime isn't about to end.
4464     if (DR->refersToEnclosingLocal())
4465       return 0;
4466 
4467     if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
4468       // If this is a reference variable, follow through to the expression that
4469       // it points to.
4470       if (V->hasLocalStorage() &&
4471           V->getType()->isReferenceType() && V->hasInit()) {
4472         // Add the reference variable to the "trail".
4473         refVars.push_back(DR);
4474         return EvalAddr(V->getInit(), refVars, ParentDecl);
4475       }
4476 
4477     return NULL;
4478   }
4479 
4480   case Stmt::UnaryOperatorClass: {
4481     // The only unary operator that make sense to handle here
4482     // is AddrOf.  All others don't make sense as pointers.
4483     UnaryOperator *U = cast<UnaryOperator>(E);
4484 
4485     if (U->getOpcode() == UO_AddrOf)
4486       return EvalVal(U->getSubExpr(), refVars, ParentDecl);
4487     else
4488       return NULL;
4489   }
4490 
4491   case Stmt::BinaryOperatorClass: {
4492     // Handle pointer arithmetic.  All other binary operators are not valid
4493     // in this context.
4494     BinaryOperator *B = cast<BinaryOperator>(E);
4495     BinaryOperatorKind op = B->getOpcode();
4496 
4497     if (op != BO_Add && op != BO_Sub)
4498       return NULL;
4499 
4500     Expr *Base = B->getLHS();
4501 
4502     // Determine which argument is the real pointer base.  It could be
4503     // the RHS argument instead of the LHS.
4504     if (!Base->getType()->isPointerType()) Base = B->getRHS();
4505 
4506     assert (Base->getType()->isPointerType());
4507     return EvalAddr(Base, refVars, ParentDecl);
4508   }
4509 
4510   // For conditional operators we need to see if either the LHS or RHS are
4511   // valid DeclRefExpr*s.  If one of them is valid, we return it.
4512   case Stmt::ConditionalOperatorClass: {
4513     ConditionalOperator *C = cast<ConditionalOperator>(E);
4514 
4515     // Handle the GNU extension for missing LHS.
4516     // FIXME: That isn't a ConditionalOperator, so doesn't get here.
4517     if (Expr *LHSExpr = C->getLHS()) {
4518       // In C++, we can have a throw-expression, which has 'void' type.
4519       if (!LHSExpr->getType()->isVoidType())
4520         if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
4521           return LHS;
4522     }
4523 
4524     // In C++, we can have a throw-expression, which has 'void' type.
4525     if (C->getRHS()->getType()->isVoidType())
4526       return 0;
4527 
4528     return EvalAddr(C->getRHS(), refVars, ParentDecl);
4529   }
4530 
4531   case Stmt::BlockExprClass:
4532     if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
4533       return E; // local block.
4534     return NULL;
4535 
4536   case Stmt::AddrLabelExprClass:
4537     return E; // address of label.
4538 
4539   case Stmt::ExprWithCleanupsClass:
4540     return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
4541                     ParentDecl);
4542 
4543   // For casts, we need to handle conversions from arrays to
4544   // pointer values, and pointer-to-pointer conversions.
4545   case Stmt::ImplicitCastExprClass:
4546   case Stmt::CStyleCastExprClass:
4547   case Stmt::CXXFunctionalCastExprClass:
4548   case Stmt::ObjCBridgedCastExprClass:
4549   case Stmt::CXXStaticCastExprClass:
4550   case Stmt::CXXDynamicCastExprClass:
4551   case Stmt::CXXConstCastExprClass:
4552   case Stmt::CXXReinterpretCastExprClass: {
4553     Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
4554     switch (cast<CastExpr>(E)->getCastKind()) {
4555     case CK_BitCast:
4556     case CK_LValueToRValue:
4557     case CK_NoOp:
4558     case CK_BaseToDerived:
4559     case CK_DerivedToBase:
4560     case CK_UncheckedDerivedToBase:
4561     case CK_Dynamic:
4562     case CK_CPointerToObjCPointerCast:
4563     case CK_BlockPointerToObjCPointerCast:
4564     case CK_AnyPointerToBlockPointerCast:
4565       return EvalAddr(SubExpr, refVars, ParentDecl);
4566 
4567     case CK_ArrayToPointerDecay:
4568       return EvalVal(SubExpr, refVars, ParentDecl);
4569 
4570     default:
4571       return 0;
4572     }
4573   }
4574 
4575   case Stmt::MaterializeTemporaryExprClass:
4576     if (Expr *Result = EvalAddr(
4577                          cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
4578                                 refVars, ParentDecl))
4579       return Result;
4580 
4581     return E;
4582 
4583   // Everything else: we simply don't reason about them.
4584   default:
4585     return NULL;
4586   }
4587 }
4588 
4589 
4590 ///  EvalVal - This function is complements EvalAddr in the mutual recursion.
4591 ///   See the comments for EvalAddr for more details.
4592 static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4593                      Decl *ParentDecl) {
4594 do {
4595   // We should only be called for evaluating non-pointer expressions, or
4596   // expressions with a pointer type that are not used as references but instead
4597   // are l-values (e.g., DeclRefExpr with a pointer type).
4598 
4599   // Our "symbolic interpreter" is just a dispatch off the currently
4600   // viewed AST node.  We then recursively traverse the AST by calling
4601   // EvalAddr and EvalVal appropriately.
4602 
4603   E = E->IgnoreParens();
4604   switch (E->getStmtClass()) {
4605   case Stmt::ImplicitCastExprClass: {
4606     ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
4607     if (IE->getValueKind() == VK_LValue) {
4608       E = IE->getSubExpr();
4609       continue;
4610     }
4611     return NULL;
4612   }
4613 
4614   case Stmt::ExprWithCleanupsClass:
4615     return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
4616 
4617   case Stmt::DeclRefExprClass: {
4618     // When we hit a DeclRefExpr we are looking at code that refers to a
4619     // variable's name. If it's not a reference variable we check if it has
4620     // local storage within the function, and if so, return the expression.
4621     DeclRefExpr *DR = cast<DeclRefExpr>(E);
4622 
4623     // If we leave the immediate function, the lifetime isn't about to end.
4624     if (DR->refersToEnclosingLocal())
4625       return 0;
4626 
4627     if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
4628       // Check if it refers to itself, e.g. "int& i = i;".
4629       if (V == ParentDecl)
4630         return DR;
4631 
4632       if (V->hasLocalStorage()) {
4633         if (!V->getType()->isReferenceType())
4634           return DR;
4635 
4636         // Reference variable, follow through to the expression that
4637         // it points to.
4638         if (V->hasInit()) {
4639           // Add the reference variable to the "trail".
4640           refVars.push_back(DR);
4641           return EvalVal(V->getInit(), refVars, V);
4642         }
4643       }
4644     }
4645 
4646     return NULL;
4647   }
4648 
4649   case Stmt::UnaryOperatorClass: {
4650     // The only unary operator that make sense to handle here
4651     // is Deref.  All others don't resolve to a "name."  This includes
4652     // handling all sorts of rvalues passed to a unary operator.
4653     UnaryOperator *U = cast<UnaryOperator>(E);
4654 
4655     if (U->getOpcode() == UO_Deref)
4656       return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
4657 
4658     return NULL;
4659   }
4660 
4661   case Stmt::ArraySubscriptExprClass: {
4662     // Array subscripts are potential references to data on the stack.  We
4663     // retrieve the DeclRefExpr* for the array variable if it indeed
4664     // has local storage.
4665     return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
4666   }
4667 
4668   case Stmt::ConditionalOperatorClass: {
4669     // For conditional operators we need to see if either the LHS or RHS are
4670     // non-NULL Expr's.  If one is non-NULL, we return it.
4671     ConditionalOperator *C = cast<ConditionalOperator>(E);
4672 
4673     // Handle the GNU extension for missing LHS.
4674     if (Expr *LHSExpr = C->getLHS()) {
4675       // In C++, we can have a throw-expression, which has 'void' type.
4676       if (!LHSExpr->getType()->isVoidType())
4677         if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
4678           return LHS;
4679     }
4680 
4681     // In C++, we can have a throw-expression, which has 'void' type.
4682     if (C->getRHS()->getType()->isVoidType())
4683       return 0;
4684 
4685     return EvalVal(C->getRHS(), refVars, ParentDecl);
4686   }
4687 
4688   // Accesses to members are potential references to data on the stack.
4689   case Stmt::MemberExprClass: {
4690     MemberExpr *M = cast<MemberExpr>(E);
4691 
4692     // Check for indirect access.  We only want direct field accesses.
4693     if (M->isArrow())
4694       return NULL;
4695 
4696     // Check whether the member type is itself a reference, in which case
4697     // we're not going to refer to the member, but to what the member refers to.
4698     if (M->getMemberDecl()->getType()->isReferenceType())
4699       return NULL;
4700 
4701     return EvalVal(M->getBase(), refVars, ParentDecl);
4702   }
4703 
4704   case Stmt::MaterializeTemporaryExprClass:
4705     if (Expr *Result = EvalVal(
4706                           cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
4707                                refVars, ParentDecl))
4708       return Result;
4709 
4710     return E;
4711 
4712   default:
4713     // Check that we don't return or take the address of a reference to a
4714     // temporary. This is only useful in C++.
4715     if (!E->isTypeDependent() && E->isRValue())
4716       return E;
4717 
4718     // Everything else: we simply don't reason about them.
4719     return NULL;
4720   }
4721 } while (true);
4722 }
4723 
4724 void
4725 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
4726                          SourceLocation ReturnLoc,
4727                          bool isObjCMethod,
4728                          const AttrVec *Attrs,
4729                          const FunctionDecl *FD) {
4730   CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
4731 
4732   // Check if the return value is null but should not be.
4733   if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
4734       CheckNonNullExpr(*this, RetValExp))
4735     Diag(ReturnLoc, diag::warn_null_ret)
4736       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
4737 
4738   // C++11 [basic.stc.dynamic.allocation]p4:
4739   //   If an allocation function declared with a non-throwing
4740   //   exception-specification fails to allocate storage, it shall return
4741   //   a null pointer. Any other allocation function that fails to allocate
4742   //   storage shall indicate failure only by throwing an exception [...]
4743   if (FD) {
4744     OverloadedOperatorKind Op = FD->getOverloadedOperator();
4745     if (Op == OO_New || Op == OO_Array_New) {
4746       const FunctionProtoType *Proto
4747         = FD->getType()->castAs<FunctionProtoType>();
4748       if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
4749           CheckNonNullExpr(*this, RetValExp))
4750         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
4751           << FD << getLangOpts().CPlusPlus11;
4752     }
4753   }
4754 }
4755 
4756 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
4757 
4758 /// Check for comparisons of floating point operands using != and ==.
4759 /// Issue a warning if these are no self-comparisons, as they are not likely
4760 /// to do what the programmer intended.
4761 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
4762   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
4763   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
4764 
4765   // Special case: check for x == x (which is OK).
4766   // Do not emit warnings for such cases.
4767   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
4768     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
4769       if (DRL->getDecl() == DRR->getDecl())
4770         return;
4771 
4772 
4773   // Special case: check for comparisons against literals that can be exactly
4774   //  represented by APFloat.  In such cases, do not emit a warning.  This
4775   //  is a heuristic: often comparison against such literals are used to
4776   //  detect if a value in a variable has not changed.  This clearly can
4777   //  lead to false negatives.
4778   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
4779     if (FLL->isExact())
4780       return;
4781   } else
4782     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
4783       if (FLR->isExact())
4784         return;
4785 
4786   // Check for comparisons with builtin types.
4787   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
4788     if (CL->getBuiltinCallee())
4789       return;
4790 
4791   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
4792     if (CR->getBuiltinCallee())
4793       return;
4794 
4795   // Emit the diagnostic.
4796   Diag(Loc, diag::warn_floatingpoint_eq)
4797     << LHS->getSourceRange() << RHS->getSourceRange();
4798 }
4799 
4800 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
4801 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
4802 
4803 namespace {
4804 
4805 /// Structure recording the 'active' range of an integer-valued
4806 /// expression.
4807 struct IntRange {
4808   /// The number of bits active in the int.
4809   unsigned Width;
4810 
4811   /// True if the int is known not to have negative values.
4812   bool NonNegative;
4813 
4814   IntRange(unsigned Width, bool NonNegative)
4815     : Width(Width), NonNegative(NonNegative)
4816   {}
4817 
4818   /// Returns the range of the bool type.
4819   static IntRange forBoolType() {
4820     return IntRange(1, true);
4821   }
4822 
4823   /// Returns the range of an opaque value of the given integral type.
4824   static IntRange forValueOfType(ASTContext &C, QualType T) {
4825     return forValueOfCanonicalType(C,
4826                           T->getCanonicalTypeInternal().getTypePtr());
4827   }
4828 
4829   /// Returns the range of an opaque value of a canonical integral type.
4830   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
4831     assert(T->isCanonicalUnqualified());
4832 
4833     if (const VectorType *VT = dyn_cast<VectorType>(T))
4834       T = VT->getElementType().getTypePtr();
4835     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4836       T = CT->getElementType().getTypePtr();
4837 
4838     // For enum types, use the known bit width of the enumerators.
4839     if (const EnumType *ET = dyn_cast<EnumType>(T)) {
4840       EnumDecl *Enum = ET->getDecl();
4841       if (!Enum->isCompleteDefinition())
4842         return IntRange(C.getIntWidth(QualType(T, 0)), false);
4843 
4844       unsigned NumPositive = Enum->getNumPositiveBits();
4845       unsigned NumNegative = Enum->getNumNegativeBits();
4846 
4847       if (NumNegative == 0)
4848         return IntRange(NumPositive, true/*NonNegative*/);
4849       else
4850         return IntRange(std::max(NumPositive + 1, NumNegative),
4851                         false/*NonNegative*/);
4852     }
4853 
4854     const BuiltinType *BT = cast<BuiltinType>(T);
4855     assert(BT->isInteger());
4856 
4857     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4858   }
4859 
4860   /// Returns the "target" range of a canonical integral type, i.e.
4861   /// the range of values expressible in the type.
4862   ///
4863   /// This matches forValueOfCanonicalType except that enums have the
4864   /// full range of their type, not the range of their enumerators.
4865   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
4866     assert(T->isCanonicalUnqualified());
4867 
4868     if (const VectorType *VT = dyn_cast<VectorType>(T))
4869       T = VT->getElementType().getTypePtr();
4870     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4871       T = CT->getElementType().getTypePtr();
4872     if (const EnumType *ET = dyn_cast<EnumType>(T))
4873       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
4874 
4875     const BuiltinType *BT = cast<BuiltinType>(T);
4876     assert(BT->isInteger());
4877 
4878     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4879   }
4880 
4881   /// Returns the supremum of two ranges: i.e. their conservative merge.
4882   static IntRange join(IntRange L, IntRange R) {
4883     return IntRange(std::max(L.Width, R.Width),
4884                     L.NonNegative && R.NonNegative);
4885   }
4886 
4887   /// Returns the infinum of two ranges: i.e. their aggressive merge.
4888   static IntRange meet(IntRange L, IntRange R) {
4889     return IntRange(std::min(L.Width, R.Width),
4890                     L.NonNegative || R.NonNegative);
4891   }
4892 };
4893 
4894 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
4895                               unsigned MaxWidth) {
4896   if (value.isSigned() && value.isNegative())
4897     return IntRange(value.getMinSignedBits(), false);
4898 
4899   if (value.getBitWidth() > MaxWidth)
4900     value = value.trunc(MaxWidth);
4901 
4902   // isNonNegative() just checks the sign bit without considering
4903   // signedness.
4904   return IntRange(value.getActiveBits(), true);
4905 }
4906 
4907 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
4908                               unsigned MaxWidth) {
4909   if (result.isInt())
4910     return GetValueRange(C, result.getInt(), MaxWidth);
4911 
4912   if (result.isVector()) {
4913     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
4914     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
4915       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
4916       R = IntRange::join(R, El);
4917     }
4918     return R;
4919   }
4920 
4921   if (result.isComplexInt()) {
4922     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
4923     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
4924     return IntRange::join(R, I);
4925   }
4926 
4927   // This can happen with lossless casts to intptr_t of "based" lvalues.
4928   // Assume it might use arbitrary bits.
4929   // FIXME: The only reason we need to pass the type in here is to get
4930   // the sign right on this one case.  It would be nice if APValue
4931   // preserved this.
4932   assert(result.isLValue() || result.isAddrLabelDiff());
4933   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
4934 }
4935 
4936 static QualType GetExprType(Expr *E) {
4937   QualType Ty = E->getType();
4938   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
4939     Ty = AtomicRHS->getValueType();
4940   return Ty;
4941 }
4942 
4943 /// Pseudo-evaluate the given integer expression, estimating the
4944 /// range of values it might take.
4945 ///
4946 /// \param MaxWidth - the width to which the value will be truncated
4947 static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
4948   E = E->IgnoreParens();
4949 
4950   // Try a full evaluation first.
4951   Expr::EvalResult result;
4952   if (E->EvaluateAsRValue(result, C))
4953     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
4954 
4955   // I think we only want to look through implicit casts here; if the
4956   // user has an explicit widening cast, we should treat the value as
4957   // being of the new, wider type.
4958   if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
4959     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
4960       return GetExprRange(C, CE->getSubExpr(), MaxWidth);
4961 
4962     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
4963 
4964     bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
4965 
4966     // Assume that non-integer casts can span the full range of the type.
4967     if (!isIntegerCast)
4968       return OutputTypeRange;
4969 
4970     IntRange SubRange
4971       = GetExprRange(C, CE->getSubExpr(),
4972                      std::min(MaxWidth, OutputTypeRange.Width));
4973 
4974     // Bail out if the subexpr's range is as wide as the cast type.
4975     if (SubRange.Width >= OutputTypeRange.Width)
4976       return OutputTypeRange;
4977 
4978     // Otherwise, we take the smaller width, and we're non-negative if
4979     // either the output type or the subexpr is.
4980     return IntRange(SubRange.Width,
4981                     SubRange.NonNegative || OutputTypeRange.NonNegative);
4982   }
4983 
4984   if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4985     // If we can fold the condition, just take that operand.
4986     bool CondResult;
4987     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
4988       return GetExprRange(C, CondResult ? CO->getTrueExpr()
4989                                         : CO->getFalseExpr(),
4990                           MaxWidth);
4991 
4992     // Otherwise, conservatively merge.
4993     IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
4994     IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
4995     return IntRange::join(L, R);
4996   }
4997 
4998   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4999     switch (BO->getOpcode()) {
5000 
5001     // Boolean-valued operations are single-bit and positive.
5002     case BO_LAnd:
5003     case BO_LOr:
5004     case BO_LT:
5005     case BO_GT:
5006     case BO_LE:
5007     case BO_GE:
5008     case BO_EQ:
5009     case BO_NE:
5010       return IntRange::forBoolType();
5011 
5012     // The type of the assignments is the type of the LHS, so the RHS
5013     // is not necessarily the same type.
5014     case BO_MulAssign:
5015     case BO_DivAssign:
5016     case BO_RemAssign:
5017     case BO_AddAssign:
5018     case BO_SubAssign:
5019     case BO_XorAssign:
5020     case BO_OrAssign:
5021       // TODO: bitfields?
5022       return IntRange::forValueOfType(C, GetExprType(E));
5023 
5024     // Simple assignments just pass through the RHS, which will have
5025     // been coerced to the LHS type.
5026     case BO_Assign:
5027       // TODO: bitfields?
5028       return GetExprRange(C, BO->getRHS(), MaxWidth);
5029 
5030     // Operations with opaque sources are black-listed.
5031     case BO_PtrMemD:
5032     case BO_PtrMemI:
5033       return IntRange::forValueOfType(C, GetExprType(E));
5034 
5035     // Bitwise-and uses the *infinum* of the two source ranges.
5036     case BO_And:
5037     case BO_AndAssign:
5038       return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5039                             GetExprRange(C, BO->getRHS(), MaxWidth));
5040 
5041     // Left shift gets black-listed based on a judgement call.
5042     case BO_Shl:
5043       // ...except that we want to treat '1 << (blah)' as logically
5044       // positive.  It's an important idiom.
5045       if (IntegerLiteral *I
5046             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5047         if (I->getValue() == 1) {
5048           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
5049           return IntRange(R.Width, /*NonNegative*/ true);
5050         }
5051       }
5052       // fallthrough
5053 
5054     case BO_ShlAssign:
5055       return IntRange::forValueOfType(C, GetExprType(E));
5056 
5057     // Right shift by a constant can narrow its left argument.
5058     case BO_Shr:
5059     case BO_ShrAssign: {
5060       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5061 
5062       // If the shift amount is a positive constant, drop the width by
5063       // that much.
5064       llvm::APSInt shift;
5065       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5066           shift.isNonNegative()) {
5067         unsigned zext = shift.getZExtValue();
5068         if (zext >= L.Width)
5069           L.Width = (L.NonNegative ? 0 : 1);
5070         else
5071           L.Width -= zext;
5072       }
5073 
5074       return L;
5075     }
5076 
5077     // Comma acts as its right operand.
5078     case BO_Comma:
5079       return GetExprRange(C, BO->getRHS(), MaxWidth);
5080 
5081     // Black-list pointer subtractions.
5082     case BO_Sub:
5083       if (BO->getLHS()->getType()->isPointerType())
5084         return IntRange::forValueOfType(C, GetExprType(E));
5085       break;
5086 
5087     // The width of a division result is mostly determined by the size
5088     // of the LHS.
5089     case BO_Div: {
5090       // Don't 'pre-truncate' the operands.
5091       unsigned opWidth = C.getIntWidth(GetExprType(E));
5092       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5093 
5094       // If the divisor is constant, use that.
5095       llvm::APSInt divisor;
5096       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5097         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5098         if (log2 >= L.Width)
5099           L.Width = (L.NonNegative ? 0 : 1);
5100         else
5101           L.Width = std::min(L.Width - log2, MaxWidth);
5102         return L;
5103       }
5104 
5105       // Otherwise, just use the LHS's width.
5106       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5107       return IntRange(L.Width, L.NonNegative && R.NonNegative);
5108     }
5109 
5110     // The result of a remainder can't be larger than the result of
5111     // either side.
5112     case BO_Rem: {
5113       // Don't 'pre-truncate' the operands.
5114       unsigned opWidth = C.getIntWidth(GetExprType(E));
5115       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5116       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5117 
5118       IntRange meet = IntRange::meet(L, R);
5119       meet.Width = std::min(meet.Width, MaxWidth);
5120       return meet;
5121     }
5122 
5123     // The default behavior is okay for these.
5124     case BO_Mul:
5125     case BO_Add:
5126     case BO_Xor:
5127     case BO_Or:
5128       break;
5129     }
5130 
5131     // The default case is to treat the operation as if it were closed
5132     // on the narrowest type that encompasses both operands.
5133     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5134     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5135     return IntRange::join(L, R);
5136   }
5137 
5138   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5139     switch (UO->getOpcode()) {
5140     // Boolean-valued operations are white-listed.
5141     case UO_LNot:
5142       return IntRange::forBoolType();
5143 
5144     // Operations with opaque sources are black-listed.
5145     case UO_Deref:
5146     case UO_AddrOf: // should be impossible
5147       return IntRange::forValueOfType(C, GetExprType(E));
5148 
5149     default:
5150       return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5151     }
5152   }
5153 
5154   if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5155     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5156 
5157   if (FieldDecl *BitField = E->getSourceBitField())
5158     return IntRange(BitField->getBitWidthValue(C),
5159                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
5160 
5161   return IntRange::forValueOfType(C, GetExprType(E));
5162 }
5163 
5164 static IntRange GetExprRange(ASTContext &C, Expr *E) {
5165   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
5166 }
5167 
5168 /// Checks whether the given value, which currently has the given
5169 /// source semantics, has the same value when coerced through the
5170 /// target semantics.
5171 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
5172                                  const llvm::fltSemantics &Src,
5173                                  const llvm::fltSemantics &Tgt) {
5174   llvm::APFloat truncated = value;
5175 
5176   bool ignored;
5177   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
5178   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
5179 
5180   return truncated.bitwiseIsEqual(value);
5181 }
5182 
5183 /// Checks whether the given value, which currently has the given
5184 /// source semantics, has the same value when coerced through the
5185 /// target semantics.
5186 ///
5187 /// The value might be a vector of floats (or a complex number).
5188 static bool IsSameFloatAfterCast(const APValue &value,
5189                                  const llvm::fltSemantics &Src,
5190                                  const llvm::fltSemantics &Tgt) {
5191   if (value.isFloat())
5192     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
5193 
5194   if (value.isVector()) {
5195     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
5196       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
5197         return false;
5198     return true;
5199   }
5200 
5201   assert(value.isComplexFloat());
5202   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
5203           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
5204 }
5205 
5206 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
5207 
5208 static bool IsZero(Sema &S, Expr *E) {
5209   // Suppress cases where we are comparing against an enum constant.
5210   if (const DeclRefExpr *DR =
5211       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
5212     if (isa<EnumConstantDecl>(DR->getDecl()))
5213       return false;
5214 
5215   // Suppress cases where the '0' value is expanded from a macro.
5216   if (E->getLocStart().isMacroID())
5217     return false;
5218 
5219   llvm::APSInt Value;
5220   return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
5221 }
5222 
5223 static bool HasEnumType(Expr *E) {
5224   // Strip off implicit integral promotions.
5225   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5226     if (ICE->getCastKind() != CK_IntegralCast &&
5227         ICE->getCastKind() != CK_NoOp)
5228       break;
5229     E = ICE->getSubExpr();
5230   }
5231 
5232   return E->getType()->isEnumeralType();
5233 }
5234 
5235 static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
5236   // Disable warning in template instantiations.
5237   if (!S.ActiveTemplateInstantiations.empty())
5238     return;
5239 
5240   BinaryOperatorKind op = E->getOpcode();
5241   if (E->isValueDependent())
5242     return;
5243 
5244   if (op == BO_LT && IsZero(S, E->getRHS())) {
5245     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
5246       << "< 0" << "false" << HasEnumType(E->getLHS())
5247       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5248   } else if (op == BO_GE && IsZero(S, E->getRHS())) {
5249     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
5250       << ">= 0" << "true" << HasEnumType(E->getLHS())
5251       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5252   } else if (op == BO_GT && IsZero(S, E->getLHS())) {
5253     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
5254       << "0 >" << "false" << HasEnumType(E->getRHS())
5255       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5256   } else if (op == BO_LE && IsZero(S, E->getLHS())) {
5257     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
5258       << "0 <=" << "true" << HasEnumType(E->getRHS())
5259       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5260   }
5261 }
5262 
5263 static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
5264                                          Expr *Constant, Expr *Other,
5265                                          llvm::APSInt Value,
5266                                          bool RhsConstant) {
5267   // Disable warning in template instantiations.
5268   if (!S.ActiveTemplateInstantiations.empty())
5269     return;
5270 
5271   // 0 values are handled later by CheckTrivialUnsignedComparison().
5272   if (Value == 0)
5273     return;
5274 
5275   BinaryOperatorKind op = E->getOpcode();
5276   QualType OtherT = Other->getType();
5277   QualType ConstantT = Constant->getType();
5278   QualType CommonT = E->getLHS()->getType();
5279   if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
5280     return;
5281   assert((OtherT->isIntegerType() && ConstantT->isIntegerType())
5282          && "comparison with non-integer type");
5283 
5284   bool ConstantSigned = ConstantT->isSignedIntegerType();
5285   bool CommonSigned = CommonT->isSignedIntegerType();
5286 
5287   bool EqualityOnly = false;
5288 
5289   // TODO: Investigate using GetExprRange() to get tighter bounds on
5290   // on the bit ranges.
5291   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
5292   unsigned OtherWidth = OtherRange.Width;
5293 
5294   if (CommonSigned) {
5295     // The common type is signed, therefore no signed to unsigned conversion.
5296     if (!OtherRange.NonNegative) {
5297       // Check that the constant is representable in type OtherT.
5298       if (ConstantSigned) {
5299         if (OtherWidth >= Value.getMinSignedBits())
5300           return;
5301       } else { // !ConstantSigned
5302         if (OtherWidth >= Value.getActiveBits() + 1)
5303           return;
5304       }
5305     } else { // !OtherSigned
5306       // Check that the constant is representable in type OtherT.
5307       // Negative values are out of range.
5308       if (ConstantSigned) {
5309         if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
5310           return;
5311       } else { // !ConstantSigned
5312         if (OtherWidth >= Value.getActiveBits())
5313           return;
5314       }
5315     }
5316   } else {  // !CommonSigned
5317     if (OtherRange.NonNegative) {
5318       if (OtherWidth >= Value.getActiveBits())
5319         return;
5320     } else if (!OtherRange.NonNegative && !ConstantSigned) {
5321       // Check to see if the constant is representable in OtherT.
5322       if (OtherWidth > Value.getActiveBits())
5323         return;
5324       // Check to see if the constant is equivalent to a negative value
5325       // cast to CommonT.
5326       if (S.Context.getIntWidth(ConstantT) == S.Context.getIntWidth(CommonT) &&
5327           Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
5328         return;
5329       // The constant value rests between values that OtherT can represent after
5330       // conversion.  Relational comparison still works, but equality
5331       // comparisons will be tautological.
5332       EqualityOnly = true;
5333     } else { // OtherSigned && ConstantSigned
5334       assert(0 && "Two signed types converted to unsigned types.");
5335     }
5336   }
5337 
5338   bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
5339 
5340   bool IsTrue = true;
5341   if (op == BO_EQ || op == BO_NE) {
5342     IsTrue = op == BO_NE;
5343   } else if (EqualityOnly) {
5344     return;
5345   } else if (RhsConstant) {
5346     if (op == BO_GT || op == BO_GE)
5347       IsTrue = !PositiveConstant;
5348     else // op == BO_LT || op == BO_LE
5349       IsTrue = PositiveConstant;
5350   } else {
5351     if (op == BO_LT || op == BO_LE)
5352       IsTrue = !PositiveConstant;
5353     else // op == BO_GT || op == BO_GE
5354       IsTrue = PositiveConstant;
5355   }
5356 
5357   // If this is a comparison to an enum constant, include that
5358   // constant in the diagnostic.
5359   const EnumConstantDecl *ED = 0;
5360   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
5361     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
5362 
5363   SmallString<64> PrettySourceValue;
5364   llvm::raw_svector_ostream OS(PrettySourceValue);
5365   if (ED)
5366     OS << '\'' << *ED << "' (" << Value << ")";
5367   else
5368     OS << Value;
5369 
5370   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5371                         S.PDiag(diag::warn_out_of_range_compare)
5372                           << OS.str() << OtherT << IsTrue
5373                           << E->getLHS()->getSourceRange()
5374                           << E->getRHS()->getSourceRange());
5375 }
5376 
5377 /// Analyze the operands of the given comparison.  Implements the
5378 /// fallback case from AnalyzeComparison.
5379 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
5380   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5381   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
5382 }
5383 
5384 /// \brief Implements -Wsign-compare.
5385 ///
5386 /// \param E the binary operator to check for warnings
5387 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
5388   // The type the comparison is being performed in.
5389   QualType T = E->getLHS()->getType();
5390   assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
5391          && "comparison with mismatched types");
5392   if (E->isValueDependent())
5393     return AnalyzeImpConvsInComparison(S, E);
5394 
5395   Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
5396   Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
5397 
5398   bool IsComparisonConstant = false;
5399 
5400   // Check whether an integer constant comparison results in a value
5401   // of 'true' or 'false'.
5402   if (T->isIntegralType(S.Context)) {
5403     llvm::APSInt RHSValue;
5404     bool IsRHSIntegralLiteral =
5405       RHS->isIntegerConstantExpr(RHSValue, S.Context);
5406     llvm::APSInt LHSValue;
5407     bool IsLHSIntegralLiteral =
5408       LHS->isIntegerConstantExpr(LHSValue, S.Context);
5409     if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
5410         DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
5411     else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
5412       DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
5413     else
5414       IsComparisonConstant =
5415         (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
5416   } else if (!T->hasUnsignedIntegerRepresentation())
5417       IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
5418 
5419   // We don't do anything special if this isn't an unsigned integral
5420   // comparison:  we're only interested in integral comparisons, and
5421   // signed comparisons only happen in cases we don't care to warn about.
5422   //
5423   // We also don't care about value-dependent expressions or expressions
5424   // whose result is a constant.
5425   if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
5426     return AnalyzeImpConvsInComparison(S, E);
5427 
5428   // Check to see if one of the (unmodified) operands is of different
5429   // signedness.
5430   Expr *signedOperand, *unsignedOperand;
5431   if (LHS->getType()->hasSignedIntegerRepresentation()) {
5432     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
5433            "unsigned comparison between two signed integer expressions?");
5434     signedOperand = LHS;
5435     unsignedOperand = RHS;
5436   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
5437     signedOperand = RHS;
5438     unsignedOperand = LHS;
5439   } else {
5440     CheckTrivialUnsignedComparison(S, E);
5441     return AnalyzeImpConvsInComparison(S, E);
5442   }
5443 
5444   // Otherwise, calculate the effective range of the signed operand.
5445   IntRange signedRange = GetExprRange(S.Context, signedOperand);
5446 
5447   // Go ahead and analyze implicit conversions in the operands.  Note
5448   // that we skip the implicit conversions on both sides.
5449   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
5450   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
5451 
5452   // If the signed range is non-negative, -Wsign-compare won't fire,
5453   // but we should still check for comparisons which are always true
5454   // or false.
5455   if (signedRange.NonNegative)
5456     return CheckTrivialUnsignedComparison(S, E);
5457 
5458   // For (in)equality comparisons, if the unsigned operand is a
5459   // constant which cannot collide with a overflowed signed operand,
5460   // then reinterpreting the signed operand as unsigned will not
5461   // change the result of the comparison.
5462   if (E->isEqualityOp()) {
5463     unsigned comparisonWidth = S.Context.getIntWidth(T);
5464     IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
5465 
5466     // We should never be unable to prove that the unsigned operand is
5467     // non-negative.
5468     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
5469 
5470     if (unsignedRange.Width < comparisonWidth)
5471       return;
5472   }
5473 
5474   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5475     S.PDiag(diag::warn_mixed_sign_comparison)
5476       << LHS->getType() << RHS->getType()
5477       << LHS->getSourceRange() << RHS->getSourceRange());
5478 }
5479 
5480 /// Analyzes an attempt to assign the given value to a bitfield.
5481 ///
5482 /// Returns true if there was something fishy about the attempt.
5483 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
5484                                       SourceLocation InitLoc) {
5485   assert(Bitfield->isBitField());
5486   if (Bitfield->isInvalidDecl())
5487     return false;
5488 
5489   // White-list bool bitfields.
5490   if (Bitfield->getType()->isBooleanType())
5491     return false;
5492 
5493   // Ignore value- or type-dependent expressions.
5494   if (Bitfield->getBitWidth()->isValueDependent() ||
5495       Bitfield->getBitWidth()->isTypeDependent() ||
5496       Init->isValueDependent() ||
5497       Init->isTypeDependent())
5498     return false;
5499 
5500   Expr *OriginalInit = Init->IgnoreParenImpCasts();
5501 
5502   llvm::APSInt Value;
5503   if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
5504     return false;
5505 
5506   unsigned OriginalWidth = Value.getBitWidth();
5507   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
5508 
5509   if (OriginalWidth <= FieldWidth)
5510     return false;
5511 
5512   // Compute the value which the bitfield will contain.
5513   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
5514   TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
5515 
5516   // Check whether the stored value is equal to the original value.
5517   TruncatedValue = TruncatedValue.extend(OriginalWidth);
5518   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
5519     return false;
5520 
5521   // Special-case bitfields of width 1: booleans are naturally 0/1, and
5522   // therefore don't strictly fit into a signed bitfield of width 1.
5523   if (FieldWidth == 1 && Value == 1)
5524     return false;
5525 
5526   std::string PrettyValue = Value.toString(10);
5527   std::string PrettyTrunc = TruncatedValue.toString(10);
5528 
5529   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
5530     << PrettyValue << PrettyTrunc << OriginalInit->getType()
5531     << Init->getSourceRange();
5532 
5533   return true;
5534 }
5535 
5536 /// Analyze the given simple or compound assignment for warning-worthy
5537 /// operations.
5538 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
5539   // Just recurse on the LHS.
5540   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5541 
5542   // We want to recurse on the RHS as normal unless we're assigning to
5543   // a bitfield.
5544   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
5545     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
5546                                   E->getOperatorLoc())) {
5547       // Recurse, ignoring any implicit conversions on the RHS.
5548       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
5549                                         E->getOperatorLoc());
5550     }
5551   }
5552 
5553   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
5554 }
5555 
5556 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
5557 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
5558                             SourceLocation CContext, unsigned diag,
5559                             bool pruneControlFlow = false) {
5560   if (pruneControlFlow) {
5561     S.DiagRuntimeBehavior(E->getExprLoc(), E,
5562                           S.PDiag(diag)
5563                             << SourceType << T << E->getSourceRange()
5564                             << SourceRange(CContext));
5565     return;
5566   }
5567   S.Diag(E->getExprLoc(), diag)
5568     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
5569 }
5570 
5571 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
5572 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
5573                             SourceLocation CContext, unsigned diag,
5574                             bool pruneControlFlow = false) {
5575   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
5576 }
5577 
5578 /// Diagnose an implicit cast from a literal expression. Does not warn when the
5579 /// cast wouldn't lose information.
5580 void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
5581                                     SourceLocation CContext) {
5582   // Try to convert the literal exactly to an integer. If we can, don't warn.
5583   bool isExact = false;
5584   const llvm::APFloat &Value = FL->getValue();
5585   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
5586                             T->hasUnsignedIntegerRepresentation());
5587   if (Value.convertToInteger(IntegerValue,
5588                              llvm::APFloat::rmTowardZero, &isExact)
5589       == llvm::APFloat::opOK && isExact)
5590     return;
5591 
5592   // FIXME: Force the precision of the source value down so we don't print
5593   // digits which are usually useless (we don't really care here if we
5594   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
5595   // would automatically print the shortest representation, but it's a bit
5596   // tricky to implement.
5597   SmallString<16> PrettySourceValue;
5598   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
5599   precision = (precision * 59 + 195) / 196;
5600   Value.toString(PrettySourceValue, precision);
5601 
5602   SmallString<16> PrettyTargetValue;
5603   if (T->isSpecificBuiltinType(BuiltinType::Bool))
5604     PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
5605   else
5606     IntegerValue.toString(PrettyTargetValue);
5607 
5608   S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
5609     << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
5610     << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
5611 }
5612 
5613 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
5614   if (!Range.Width) return "0";
5615 
5616   llvm::APSInt ValueInRange = Value;
5617   ValueInRange.setIsSigned(!Range.NonNegative);
5618   ValueInRange = ValueInRange.trunc(Range.Width);
5619   return ValueInRange.toString(10);
5620 }
5621 
5622 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
5623   if (!isa<ImplicitCastExpr>(Ex))
5624     return false;
5625 
5626   Expr *InnerE = Ex->IgnoreParenImpCasts();
5627   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
5628   const Type *Source =
5629     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5630   if (Target->isDependentType())
5631     return false;
5632 
5633   const BuiltinType *FloatCandidateBT =
5634     dyn_cast<BuiltinType>(ToBool ? Source : Target);
5635   const Type *BoolCandidateType = ToBool ? Target : Source;
5636 
5637   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
5638           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
5639 }
5640 
5641 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
5642                                       SourceLocation CC) {
5643   unsigned NumArgs = TheCall->getNumArgs();
5644   for (unsigned i = 0; i < NumArgs; ++i) {
5645     Expr *CurrA = TheCall->getArg(i);
5646     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
5647       continue;
5648 
5649     bool IsSwapped = ((i > 0) &&
5650         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
5651     IsSwapped |= ((i < (NumArgs - 1)) &&
5652         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
5653     if (IsSwapped) {
5654       // Warn on this floating-point to bool conversion.
5655       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
5656                       CurrA->getType(), CC,
5657                       diag::warn_impcast_floating_point_to_bool);
5658     }
5659   }
5660 }
5661 
5662 void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
5663                              SourceLocation CC, bool *ICContext = 0) {
5664   if (E->isTypeDependent() || E->isValueDependent()) return;
5665 
5666   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
5667   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
5668   if (Source == Target) return;
5669   if (Target->isDependentType()) return;
5670 
5671   // If the conversion context location is invalid don't complain. We also
5672   // don't want to emit a warning if the issue occurs from the expansion of
5673   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
5674   // delay this check as long as possible. Once we detect we are in that
5675   // scenario, we just return.
5676   if (CC.isInvalid())
5677     return;
5678 
5679   // Diagnose implicit casts to bool.
5680   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
5681     if (isa<StringLiteral>(E))
5682       // Warn on string literal to bool.  Checks for string literals in logical
5683       // and expressions, for instance, assert(0 && "error here"), are
5684       // prevented by a check in AnalyzeImplicitConversions().
5685       return DiagnoseImpCast(S, E, T, CC,
5686                              diag::warn_impcast_string_literal_to_bool);
5687     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
5688         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
5689       // This covers the literal expressions that evaluate to Objective-C
5690       // objects.
5691       return DiagnoseImpCast(S, E, T, CC,
5692                              diag::warn_impcast_objective_c_literal_to_bool);
5693     }
5694     if (Source->isPointerType() || Source->canDecayToPointerType()) {
5695       // Warn on pointer to bool conversion that is always true.
5696       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
5697                                      SourceRange(CC));
5698     }
5699   }
5700 
5701   // Strip vector types.
5702   if (isa<VectorType>(Source)) {
5703     if (!isa<VectorType>(Target)) {
5704       if (S.SourceMgr.isInSystemMacro(CC))
5705         return;
5706       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
5707     }
5708 
5709     // If the vector cast is cast between two vectors of the same size, it is
5710     // a bitcast, not a conversion.
5711     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
5712       return;
5713 
5714     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
5715     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
5716   }
5717 
5718   // Strip complex types.
5719   if (isa<ComplexType>(Source)) {
5720     if (!isa<ComplexType>(Target)) {
5721       if (S.SourceMgr.isInSystemMacro(CC))
5722         return;
5723 
5724       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
5725     }
5726 
5727     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
5728     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
5729   }
5730 
5731   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
5732   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
5733 
5734   // If the source is floating point...
5735   if (SourceBT && SourceBT->isFloatingPoint()) {
5736     // ...and the target is floating point...
5737     if (TargetBT && TargetBT->isFloatingPoint()) {
5738       // ...then warn if we're dropping FP rank.
5739 
5740       // Builtin FP kinds are ordered by increasing FP rank.
5741       if (SourceBT->getKind() > TargetBT->getKind()) {
5742         // Don't warn about float constants that are precisely
5743         // representable in the target type.
5744         Expr::EvalResult result;
5745         if (E->EvaluateAsRValue(result, S.Context)) {
5746           // Value might be a float, a float vector, or a float complex.
5747           if (IsSameFloatAfterCast(result.Val,
5748                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
5749                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
5750             return;
5751         }
5752 
5753         if (S.SourceMgr.isInSystemMacro(CC))
5754           return;
5755 
5756         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
5757       }
5758       return;
5759     }
5760 
5761     // If the target is integral, always warn.
5762     if (TargetBT && TargetBT->isInteger()) {
5763       if (S.SourceMgr.isInSystemMacro(CC))
5764         return;
5765 
5766       Expr *InnerE = E->IgnoreParenImpCasts();
5767       // We also want to warn on, e.g., "int i = -1.234"
5768       if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
5769         if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
5770           InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
5771 
5772       if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
5773         DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
5774       } else {
5775         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
5776       }
5777     }
5778 
5779     // If the target is bool, warn if expr is a function or method call.
5780     if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
5781         isa<CallExpr>(E)) {
5782       // Check last argument of function call to see if it is an
5783       // implicit cast from a type matching the type the result
5784       // is being cast to.
5785       CallExpr *CEx = cast<CallExpr>(E);
5786       unsigned NumArgs = CEx->getNumArgs();
5787       if (NumArgs > 0) {
5788         Expr *LastA = CEx->getArg(NumArgs - 1);
5789         Expr *InnerE = LastA->IgnoreParenImpCasts();
5790         const Type *InnerType =
5791           S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5792         if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
5793           // Warn on this floating-point to bool conversion
5794           DiagnoseImpCast(S, E, T, CC,
5795                           diag::warn_impcast_floating_point_to_bool);
5796         }
5797       }
5798     }
5799     return;
5800   }
5801 
5802   if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
5803            == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
5804       && !Target->isBlockPointerType() && !Target->isMemberPointerType()
5805       && Target->isScalarType() && !Target->isNullPtrType()) {
5806     SourceLocation Loc = E->getSourceRange().getBegin();
5807     if (Loc.isMacroID())
5808       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
5809     if (!Loc.isMacroID() || CC.isMacroID())
5810       S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
5811           << T << clang::SourceRange(CC)
5812           << FixItHint::CreateReplacement(Loc,
5813                                           S.getFixItZeroLiteralForType(T, Loc));
5814   }
5815 
5816   if (!Source->isIntegerType() || !Target->isIntegerType())
5817     return;
5818 
5819   // TODO: remove this early return once the false positives for constant->bool
5820   // in templates, macros, etc, are reduced or removed.
5821   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
5822     return;
5823 
5824   IntRange SourceRange = GetExprRange(S.Context, E);
5825   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
5826 
5827   if (SourceRange.Width > TargetRange.Width) {
5828     // If the source is a constant, use a default-on diagnostic.
5829     // TODO: this should happen for bitfield stores, too.
5830     llvm::APSInt Value(32);
5831     if (E->isIntegerConstantExpr(Value, S.Context)) {
5832       if (S.SourceMgr.isInSystemMacro(CC))
5833         return;
5834 
5835       std::string PrettySourceValue = Value.toString(10);
5836       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
5837 
5838       S.DiagRuntimeBehavior(E->getExprLoc(), E,
5839         S.PDiag(diag::warn_impcast_integer_precision_constant)
5840             << PrettySourceValue << PrettyTargetValue
5841             << E->getType() << T << E->getSourceRange()
5842             << clang::SourceRange(CC));
5843       return;
5844     }
5845 
5846     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
5847     if (S.SourceMgr.isInSystemMacro(CC))
5848       return;
5849 
5850     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
5851       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
5852                              /* pruneControlFlow */ true);
5853     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
5854   }
5855 
5856   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
5857       (!TargetRange.NonNegative && SourceRange.NonNegative &&
5858        SourceRange.Width == TargetRange.Width)) {
5859 
5860     if (S.SourceMgr.isInSystemMacro(CC))
5861       return;
5862 
5863     unsigned DiagID = diag::warn_impcast_integer_sign;
5864 
5865     // Traditionally, gcc has warned about this under -Wsign-compare.
5866     // We also want to warn about it in -Wconversion.
5867     // So if -Wconversion is off, use a completely identical diagnostic
5868     // in the sign-compare group.
5869     // The conditional-checking code will
5870     if (ICContext) {
5871       DiagID = diag::warn_impcast_integer_sign_conditional;
5872       *ICContext = true;
5873     }
5874 
5875     return DiagnoseImpCast(S, E, T, CC, DiagID);
5876   }
5877 
5878   // Diagnose conversions between different enumeration types.
5879   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
5880   // type, to give us better diagnostics.
5881   QualType SourceType = E->getType();
5882   if (!S.getLangOpts().CPlusPlus) {
5883     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5884       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
5885         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
5886         SourceType = S.Context.getTypeDeclType(Enum);
5887         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
5888       }
5889   }
5890 
5891   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
5892     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
5893       if (SourceEnum->getDecl()->hasNameForLinkage() &&
5894           TargetEnum->getDecl()->hasNameForLinkage() &&
5895           SourceEnum != TargetEnum) {
5896         if (S.SourceMgr.isInSystemMacro(CC))
5897           return;
5898 
5899         return DiagnoseImpCast(S, E, SourceType, T, CC,
5900                                diag::warn_impcast_different_enum_types);
5901       }
5902 
5903   return;
5904 }
5905 
5906 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5907                               SourceLocation CC, QualType T);
5908 
5909 void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
5910                              SourceLocation CC, bool &ICContext) {
5911   E = E->IgnoreParenImpCasts();
5912 
5913   if (isa<ConditionalOperator>(E))
5914     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
5915 
5916   AnalyzeImplicitConversions(S, E, CC);
5917   if (E->getType() != T)
5918     return CheckImplicitConversion(S, E, T, CC, &ICContext);
5919   return;
5920 }
5921 
5922 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5923                               SourceLocation CC, QualType T) {
5924   AnalyzeImplicitConversions(S, E->getCond(), CC);
5925 
5926   bool Suspicious = false;
5927   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
5928   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
5929 
5930   // If -Wconversion would have warned about either of the candidates
5931   // for a signedness conversion to the context type...
5932   if (!Suspicious) return;
5933 
5934   // ...but it's currently ignored...
5935   if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
5936                                  CC))
5937     return;
5938 
5939   // ...then check whether it would have warned about either of the
5940   // candidates for a signedness conversion to the condition type.
5941   if (E->getType() == T) return;
5942 
5943   Suspicious = false;
5944   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
5945                           E->getType(), CC, &Suspicious);
5946   if (!Suspicious)
5947     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
5948                             E->getType(), CC, &Suspicious);
5949 }
5950 
5951 /// AnalyzeImplicitConversions - Find and report any interesting
5952 /// implicit conversions in the given expression.  There are a couple
5953 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
5954 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
5955   QualType T = OrigE->getType();
5956   Expr *E = OrigE->IgnoreParenImpCasts();
5957 
5958   if (E->isTypeDependent() || E->isValueDependent())
5959     return;
5960 
5961   // For conditional operators, we analyze the arguments as if they
5962   // were being fed directly into the output.
5963   if (isa<ConditionalOperator>(E)) {
5964     ConditionalOperator *CO = cast<ConditionalOperator>(E);
5965     CheckConditionalOperator(S, CO, CC, T);
5966     return;
5967   }
5968 
5969   // Check implicit argument conversions for function calls.
5970   if (CallExpr *Call = dyn_cast<CallExpr>(E))
5971     CheckImplicitArgumentConversions(S, Call, CC);
5972 
5973   // Go ahead and check any implicit conversions we might have skipped.
5974   // The non-canonical typecheck is just an optimization;
5975   // CheckImplicitConversion will filter out dead implicit conversions.
5976   if (E->getType() != T)
5977     CheckImplicitConversion(S, E, T, CC);
5978 
5979   // Now continue drilling into this expression.
5980 
5981   if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
5982     if (POE->getResultExpr())
5983       E = POE->getResultExpr();
5984   }
5985 
5986   if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5987     return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
5988 
5989   // Skip past explicit casts.
5990   if (isa<ExplicitCastExpr>(E)) {
5991     E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
5992     return AnalyzeImplicitConversions(S, E, CC);
5993   }
5994 
5995   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5996     // Do a somewhat different check with comparison operators.
5997     if (BO->isComparisonOp())
5998       return AnalyzeComparison(S, BO);
5999 
6000     // And with simple assignments.
6001     if (BO->getOpcode() == BO_Assign)
6002       return AnalyzeAssignment(S, BO);
6003   }
6004 
6005   // These break the otherwise-useful invariant below.  Fortunately,
6006   // we don't really need to recurse into them, because any internal
6007   // expressions should have been analyzed already when they were
6008   // built into statements.
6009   if (isa<StmtExpr>(E)) return;
6010 
6011   // Don't descend into unevaluated contexts.
6012   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
6013 
6014   // Now just recurse over the expression's children.
6015   CC = E->getExprLoc();
6016   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
6017   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
6018   for (Stmt::child_range I = E->children(); I; ++I) {
6019     Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
6020     if (!ChildExpr)
6021       continue;
6022 
6023     if (IsLogicalAndOperator &&
6024         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
6025       // Ignore checking string literals that are in logical and operators.
6026       // This is a common pattern for asserts.
6027       continue;
6028     AnalyzeImplicitConversions(S, ChildExpr, CC);
6029   }
6030 }
6031 
6032 } // end anonymous namespace
6033 
6034 enum {
6035   AddressOf,
6036   FunctionPointer,
6037   ArrayPointer
6038 };
6039 
6040 /// \brief Diagnose pointers that are always non-null.
6041 /// \param E the expression containing the pointer
6042 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
6043 /// compared to a null pointer
6044 /// \param IsEqual True when the comparison is equal to a null pointer
6045 /// \param Range Extra SourceRange to highlight in the diagnostic
6046 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
6047                                         Expr::NullPointerConstantKind NullKind,
6048                                         bool IsEqual, SourceRange Range) {
6049 
6050   // Don't warn inside macros.
6051   if (E->getExprLoc().isMacroID())
6052       return;
6053   E = E->IgnoreImpCasts();
6054 
6055   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
6056 
6057   bool IsAddressOf = false;
6058 
6059   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6060     if (UO->getOpcode() != UO_AddrOf)
6061       return;
6062     IsAddressOf = true;
6063     E = UO->getSubExpr();
6064   }
6065 
6066   // Expect to find a single Decl.  Skip anything more complicated.
6067   ValueDecl *D = 0;
6068   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
6069     D = R->getDecl();
6070   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6071     D = M->getMemberDecl();
6072   }
6073 
6074   // Weak Decls can be null.
6075   if (!D || D->isWeak())
6076     return;
6077 
6078   QualType T = D->getType();
6079   const bool IsArray = T->isArrayType();
6080   const bool IsFunction = T->isFunctionType();
6081 
6082   if (IsAddressOf) {
6083     // Address of function is used to silence the function warning.
6084     if (IsFunction)
6085       return;
6086     // Address of reference can be null.
6087     if (T->isReferenceType())
6088       return;
6089   }
6090 
6091   // Found nothing.
6092   if (!IsAddressOf && !IsFunction && !IsArray)
6093     return;
6094 
6095   // Pretty print the expression for the diagnostic.
6096   std::string Str;
6097   llvm::raw_string_ostream S(Str);
6098   E->printPretty(S, 0, getPrintingPolicy());
6099 
6100   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
6101                               : diag::warn_impcast_pointer_to_bool;
6102   unsigned DiagType;
6103   if (IsAddressOf)
6104     DiagType = AddressOf;
6105   else if (IsFunction)
6106     DiagType = FunctionPointer;
6107   else if (IsArray)
6108     DiagType = ArrayPointer;
6109   else
6110     llvm_unreachable("Could not determine diagnostic.");
6111   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
6112                                 << Range << IsEqual;
6113 
6114   if (!IsFunction)
6115     return;
6116 
6117   // Suggest '&' to silence the function warning.
6118   Diag(E->getExprLoc(), diag::note_function_warning_silence)
6119       << FixItHint::CreateInsertion(E->getLocStart(), "&");
6120 
6121   // Check to see if '()' fixit should be emitted.
6122   QualType ReturnType;
6123   UnresolvedSet<4> NonTemplateOverloads;
6124   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
6125   if (ReturnType.isNull())
6126     return;
6127 
6128   if (IsCompare) {
6129     // There are two cases here.  If there is null constant, the only suggest
6130     // for a pointer return type.  If the null is 0, then suggest if the return
6131     // type is a pointer or an integer type.
6132     if (!ReturnType->isPointerType()) {
6133       if (NullKind == Expr::NPCK_ZeroExpression ||
6134           NullKind == Expr::NPCK_ZeroLiteral) {
6135         if (!ReturnType->isIntegerType())
6136           return;
6137       } else {
6138         return;
6139       }
6140     }
6141   } else { // !IsCompare
6142     // For function to bool, only suggest if the function pointer has bool
6143     // return type.
6144     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
6145       return;
6146   }
6147   Diag(E->getExprLoc(), diag::note_function_to_function_call)
6148       << FixItHint::CreateInsertion(
6149              getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
6150 }
6151 
6152 
6153 /// Diagnoses "dangerous" implicit conversions within the given
6154 /// expression (which is a full expression).  Implements -Wconversion
6155 /// and -Wsign-compare.
6156 ///
6157 /// \param CC the "context" location of the implicit conversion, i.e.
6158 ///   the most location of the syntactic entity requiring the implicit
6159 ///   conversion
6160 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
6161   // Don't diagnose in unevaluated contexts.
6162   if (isUnevaluatedContext())
6163     return;
6164 
6165   // Don't diagnose for value- or type-dependent expressions.
6166   if (E->isTypeDependent() || E->isValueDependent())
6167     return;
6168 
6169   // Check for array bounds violations in cases where the check isn't triggered
6170   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
6171   // ArraySubscriptExpr is on the RHS of a variable initialization.
6172   CheckArrayAccess(E);
6173 
6174   // This is not the right CC for (e.g.) a variable initialization.
6175   AnalyzeImplicitConversions(*this, E, CC);
6176 }
6177 
6178 /// Diagnose when expression is an integer constant expression and its evaluation
6179 /// results in integer overflow
6180 void Sema::CheckForIntOverflow (Expr *E) {
6181   if (isa<BinaryOperator>(E->IgnoreParens()))
6182     E->EvaluateForOverflow(Context);
6183 }
6184 
6185 namespace {
6186 /// \brief Visitor for expressions which looks for unsequenced operations on the
6187 /// same object.
6188 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
6189   typedef EvaluatedExprVisitor<SequenceChecker> Base;
6190 
6191   /// \brief A tree of sequenced regions within an expression. Two regions are
6192   /// unsequenced if one is an ancestor or a descendent of the other. When we
6193   /// finish processing an expression with sequencing, such as a comma
6194   /// expression, we fold its tree nodes into its parent, since they are
6195   /// unsequenced with respect to nodes we will visit later.
6196   class SequenceTree {
6197     struct Value {
6198       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
6199       unsigned Parent : 31;
6200       bool Merged : 1;
6201     };
6202     SmallVector<Value, 8> Values;
6203 
6204   public:
6205     /// \brief A region within an expression which may be sequenced with respect
6206     /// to some other region.
6207     class Seq {
6208       explicit Seq(unsigned N) : Index(N) {}
6209       unsigned Index;
6210       friend class SequenceTree;
6211     public:
6212       Seq() : Index(0) {}
6213     };
6214 
6215     SequenceTree() { Values.push_back(Value(0)); }
6216     Seq root() const { return Seq(0); }
6217 
6218     /// \brief Create a new sequence of operations, which is an unsequenced
6219     /// subset of \p Parent. This sequence of operations is sequenced with
6220     /// respect to other children of \p Parent.
6221     Seq allocate(Seq Parent) {
6222       Values.push_back(Value(Parent.Index));
6223       return Seq(Values.size() - 1);
6224     }
6225 
6226     /// \brief Merge a sequence of operations into its parent.
6227     void merge(Seq S) {
6228       Values[S.Index].Merged = true;
6229     }
6230 
6231     /// \brief Determine whether two operations are unsequenced. This operation
6232     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
6233     /// should have been merged into its parent as appropriate.
6234     bool isUnsequenced(Seq Cur, Seq Old) {
6235       unsigned C = representative(Cur.Index);
6236       unsigned Target = representative(Old.Index);
6237       while (C >= Target) {
6238         if (C == Target)
6239           return true;
6240         C = Values[C].Parent;
6241       }
6242       return false;
6243     }
6244 
6245   private:
6246     /// \brief Pick a representative for a sequence.
6247     unsigned representative(unsigned K) {
6248       if (Values[K].Merged)
6249         // Perform path compression as we go.
6250         return Values[K].Parent = representative(Values[K].Parent);
6251       return K;
6252     }
6253   };
6254 
6255   /// An object for which we can track unsequenced uses.
6256   typedef NamedDecl *Object;
6257 
6258   /// Different flavors of object usage which we track. We only track the
6259   /// least-sequenced usage of each kind.
6260   enum UsageKind {
6261     /// A read of an object. Multiple unsequenced reads are OK.
6262     UK_Use,
6263     /// A modification of an object which is sequenced before the value
6264     /// computation of the expression, such as ++n in C++.
6265     UK_ModAsValue,
6266     /// A modification of an object which is not sequenced before the value
6267     /// computation of the expression, such as n++.
6268     UK_ModAsSideEffect,
6269 
6270     UK_Count = UK_ModAsSideEffect + 1
6271   };
6272 
6273   struct Usage {
6274     Usage() : Use(0), Seq() {}
6275     Expr *Use;
6276     SequenceTree::Seq Seq;
6277   };
6278 
6279   struct UsageInfo {
6280     UsageInfo() : Diagnosed(false) {}
6281     Usage Uses[UK_Count];
6282     /// Have we issued a diagnostic for this variable already?
6283     bool Diagnosed;
6284   };
6285   typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
6286 
6287   Sema &SemaRef;
6288   /// Sequenced regions within the expression.
6289   SequenceTree Tree;
6290   /// Declaration modifications and references which we have seen.
6291   UsageInfoMap UsageMap;
6292   /// The region we are currently within.
6293   SequenceTree::Seq Region;
6294   /// Filled in with declarations which were modified as a side-effect
6295   /// (that is, post-increment operations).
6296   SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
6297   /// Expressions to check later. We defer checking these to reduce
6298   /// stack usage.
6299   SmallVectorImpl<Expr *> &WorkList;
6300 
6301   /// RAII object wrapping the visitation of a sequenced subexpression of an
6302   /// expression. At the end of this process, the side-effects of the evaluation
6303   /// become sequenced with respect to the value computation of the result, so
6304   /// we downgrade any UK_ModAsSideEffect within the evaluation to
6305   /// UK_ModAsValue.
6306   struct SequencedSubexpression {
6307     SequencedSubexpression(SequenceChecker &Self)
6308       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
6309       Self.ModAsSideEffect = &ModAsSideEffect;
6310     }
6311     ~SequencedSubexpression() {
6312       for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
6313         UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
6314         U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
6315         Self.addUsage(U, ModAsSideEffect[I].first,
6316                       ModAsSideEffect[I].second.Use, UK_ModAsValue);
6317       }
6318       Self.ModAsSideEffect = OldModAsSideEffect;
6319     }
6320 
6321     SequenceChecker &Self;
6322     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
6323     SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
6324   };
6325 
6326   /// RAII object wrapping the visitation of a subexpression which we might
6327   /// choose to evaluate as a constant. If any subexpression is evaluated and
6328   /// found to be non-constant, this allows us to suppress the evaluation of
6329   /// the outer expression.
6330   class EvaluationTracker {
6331   public:
6332     EvaluationTracker(SequenceChecker &Self)
6333         : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
6334       Self.EvalTracker = this;
6335     }
6336     ~EvaluationTracker() {
6337       Self.EvalTracker = Prev;
6338       if (Prev)
6339         Prev->EvalOK &= EvalOK;
6340     }
6341 
6342     bool evaluate(const Expr *E, bool &Result) {
6343       if (!EvalOK || E->isValueDependent())
6344         return false;
6345       EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
6346       return EvalOK;
6347     }
6348 
6349   private:
6350     SequenceChecker &Self;
6351     EvaluationTracker *Prev;
6352     bool EvalOK;
6353   } *EvalTracker;
6354 
6355   /// \brief Find the object which is produced by the specified expression,
6356   /// if any.
6357   Object getObject(Expr *E, bool Mod) const {
6358     E = E->IgnoreParenCasts();
6359     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6360       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
6361         return getObject(UO->getSubExpr(), Mod);
6362     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6363       if (BO->getOpcode() == BO_Comma)
6364         return getObject(BO->getRHS(), Mod);
6365       if (Mod && BO->isAssignmentOp())
6366         return getObject(BO->getLHS(), Mod);
6367     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
6368       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
6369       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
6370         return ME->getMemberDecl();
6371     } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6372       // FIXME: If this is a reference, map through to its value.
6373       return DRE->getDecl();
6374     return 0;
6375   }
6376 
6377   /// \brief Note that an object was modified or used by an expression.
6378   void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
6379     Usage &U = UI.Uses[UK];
6380     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
6381       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
6382         ModAsSideEffect->push_back(std::make_pair(O, U));
6383       U.Use = Ref;
6384       U.Seq = Region;
6385     }
6386   }
6387   /// \brief Check whether a modification or use conflicts with a prior usage.
6388   void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
6389                   bool IsModMod) {
6390     if (UI.Diagnosed)
6391       return;
6392 
6393     const Usage &U = UI.Uses[OtherKind];
6394     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
6395       return;
6396 
6397     Expr *Mod = U.Use;
6398     Expr *ModOrUse = Ref;
6399     if (OtherKind == UK_Use)
6400       std::swap(Mod, ModOrUse);
6401 
6402     SemaRef.Diag(Mod->getExprLoc(),
6403                  IsModMod ? diag::warn_unsequenced_mod_mod
6404                           : diag::warn_unsequenced_mod_use)
6405       << O << SourceRange(ModOrUse->getExprLoc());
6406     UI.Diagnosed = true;
6407   }
6408 
6409   void notePreUse(Object O, Expr *Use) {
6410     UsageInfo &U = UsageMap[O];
6411     // Uses conflict with other modifications.
6412     checkUsage(O, U, Use, UK_ModAsValue, false);
6413   }
6414   void notePostUse(Object O, Expr *Use) {
6415     UsageInfo &U = UsageMap[O];
6416     checkUsage(O, U, Use, UK_ModAsSideEffect, false);
6417     addUsage(U, O, Use, UK_Use);
6418   }
6419 
6420   void notePreMod(Object O, Expr *Mod) {
6421     UsageInfo &U = UsageMap[O];
6422     // Modifications conflict with other modifications and with uses.
6423     checkUsage(O, U, Mod, UK_ModAsValue, true);
6424     checkUsage(O, U, Mod, UK_Use, false);
6425   }
6426   void notePostMod(Object O, Expr *Use, UsageKind UK) {
6427     UsageInfo &U = UsageMap[O];
6428     checkUsage(O, U, Use, UK_ModAsSideEffect, true);
6429     addUsage(U, O, Use, UK);
6430   }
6431 
6432 public:
6433   SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
6434       : Base(S.Context), SemaRef(S), Region(Tree.root()), ModAsSideEffect(0),
6435         WorkList(WorkList), EvalTracker(0) {
6436     Visit(E);
6437   }
6438 
6439   void VisitStmt(Stmt *S) {
6440     // Skip all statements which aren't expressions for now.
6441   }
6442 
6443   void VisitExpr(Expr *E) {
6444     // By default, just recurse to evaluated subexpressions.
6445     Base::VisitStmt(E);
6446   }
6447 
6448   void VisitCastExpr(CastExpr *E) {
6449     Object O = Object();
6450     if (E->getCastKind() == CK_LValueToRValue)
6451       O = getObject(E->getSubExpr(), false);
6452 
6453     if (O)
6454       notePreUse(O, E);
6455     VisitExpr(E);
6456     if (O)
6457       notePostUse(O, E);
6458   }
6459 
6460   void VisitBinComma(BinaryOperator *BO) {
6461     // C++11 [expr.comma]p1:
6462     //   Every value computation and side effect associated with the left
6463     //   expression is sequenced before every value computation and side
6464     //   effect associated with the right expression.
6465     SequenceTree::Seq LHS = Tree.allocate(Region);
6466     SequenceTree::Seq RHS = Tree.allocate(Region);
6467     SequenceTree::Seq OldRegion = Region;
6468 
6469     {
6470       SequencedSubexpression SeqLHS(*this);
6471       Region = LHS;
6472       Visit(BO->getLHS());
6473     }
6474 
6475     Region = RHS;
6476     Visit(BO->getRHS());
6477 
6478     Region = OldRegion;
6479 
6480     // Forget that LHS and RHS are sequenced. They are both unsequenced
6481     // with respect to other stuff.
6482     Tree.merge(LHS);
6483     Tree.merge(RHS);
6484   }
6485 
6486   void VisitBinAssign(BinaryOperator *BO) {
6487     // The modification is sequenced after the value computation of the LHS
6488     // and RHS, so check it before inspecting the operands and update the
6489     // map afterwards.
6490     Object O = getObject(BO->getLHS(), true);
6491     if (!O)
6492       return VisitExpr(BO);
6493 
6494     notePreMod(O, BO);
6495 
6496     // C++11 [expr.ass]p7:
6497     //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
6498     //   only once.
6499     //
6500     // Therefore, for a compound assignment operator, O is considered used
6501     // everywhere except within the evaluation of E1 itself.
6502     if (isa<CompoundAssignOperator>(BO))
6503       notePreUse(O, BO);
6504 
6505     Visit(BO->getLHS());
6506 
6507     if (isa<CompoundAssignOperator>(BO))
6508       notePostUse(O, BO);
6509 
6510     Visit(BO->getRHS());
6511 
6512     // C++11 [expr.ass]p1:
6513     //   the assignment is sequenced [...] before the value computation of the
6514     //   assignment expression.
6515     // C11 6.5.16/3 has no such rule.
6516     notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6517                                                        : UK_ModAsSideEffect);
6518   }
6519   void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
6520     VisitBinAssign(CAO);
6521   }
6522 
6523   void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6524   void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6525   void VisitUnaryPreIncDec(UnaryOperator *UO) {
6526     Object O = getObject(UO->getSubExpr(), true);
6527     if (!O)
6528       return VisitExpr(UO);
6529 
6530     notePreMod(O, UO);
6531     Visit(UO->getSubExpr());
6532     // C++11 [expr.pre.incr]p1:
6533     //   the expression ++x is equivalent to x+=1
6534     notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6535                                                        : UK_ModAsSideEffect);
6536   }
6537 
6538   void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6539   void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6540   void VisitUnaryPostIncDec(UnaryOperator *UO) {
6541     Object O = getObject(UO->getSubExpr(), true);
6542     if (!O)
6543       return VisitExpr(UO);
6544 
6545     notePreMod(O, UO);
6546     Visit(UO->getSubExpr());
6547     notePostMod(O, UO, UK_ModAsSideEffect);
6548   }
6549 
6550   /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
6551   void VisitBinLOr(BinaryOperator *BO) {
6552     // The side-effects of the LHS of an '&&' are sequenced before the
6553     // value computation of the RHS, and hence before the value computation
6554     // of the '&&' itself, unless the LHS evaluates to zero. We treat them
6555     // as if they were unconditionally sequenced.
6556     EvaluationTracker Eval(*this);
6557     {
6558       SequencedSubexpression Sequenced(*this);
6559       Visit(BO->getLHS());
6560     }
6561 
6562     bool Result;
6563     if (Eval.evaluate(BO->getLHS(), Result)) {
6564       if (!Result)
6565         Visit(BO->getRHS());
6566     } else {
6567       // Check for unsequenced operations in the RHS, treating it as an
6568       // entirely separate evaluation.
6569       //
6570       // FIXME: If there are operations in the RHS which are unsequenced
6571       // with respect to operations outside the RHS, and those operations
6572       // are unconditionally evaluated, diagnose them.
6573       WorkList.push_back(BO->getRHS());
6574     }
6575   }
6576   void VisitBinLAnd(BinaryOperator *BO) {
6577     EvaluationTracker Eval(*this);
6578     {
6579       SequencedSubexpression Sequenced(*this);
6580       Visit(BO->getLHS());
6581     }
6582 
6583     bool Result;
6584     if (Eval.evaluate(BO->getLHS(), Result)) {
6585       if (Result)
6586         Visit(BO->getRHS());
6587     } else {
6588       WorkList.push_back(BO->getRHS());
6589     }
6590   }
6591 
6592   // Only visit the condition, unless we can be sure which subexpression will
6593   // be chosen.
6594   void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
6595     EvaluationTracker Eval(*this);
6596     {
6597       SequencedSubexpression Sequenced(*this);
6598       Visit(CO->getCond());
6599     }
6600 
6601     bool Result;
6602     if (Eval.evaluate(CO->getCond(), Result))
6603       Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
6604     else {
6605       WorkList.push_back(CO->getTrueExpr());
6606       WorkList.push_back(CO->getFalseExpr());
6607     }
6608   }
6609 
6610   void VisitCallExpr(CallExpr *CE) {
6611     // C++11 [intro.execution]p15:
6612     //   When calling a function [...], every value computation and side effect
6613     //   associated with any argument expression, or with the postfix expression
6614     //   designating the called function, is sequenced before execution of every
6615     //   expression or statement in the body of the function [and thus before
6616     //   the value computation of its result].
6617     SequencedSubexpression Sequenced(*this);
6618     Base::VisitCallExpr(CE);
6619 
6620     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
6621   }
6622 
6623   void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
6624     // This is a call, so all subexpressions are sequenced before the result.
6625     SequencedSubexpression Sequenced(*this);
6626 
6627     if (!CCE->isListInitialization())
6628       return VisitExpr(CCE);
6629 
6630     // In C++11, list initializations are sequenced.
6631     SmallVector<SequenceTree::Seq, 32> Elts;
6632     SequenceTree::Seq Parent = Region;
6633     for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
6634                                         E = CCE->arg_end();
6635          I != E; ++I) {
6636       Region = Tree.allocate(Parent);
6637       Elts.push_back(Region);
6638       Visit(*I);
6639     }
6640 
6641     // Forget that the initializers are sequenced.
6642     Region = Parent;
6643     for (unsigned I = 0; I < Elts.size(); ++I)
6644       Tree.merge(Elts[I]);
6645   }
6646 
6647   void VisitInitListExpr(InitListExpr *ILE) {
6648     if (!SemaRef.getLangOpts().CPlusPlus11)
6649       return VisitExpr(ILE);
6650 
6651     // In C++11, list initializations are sequenced.
6652     SmallVector<SequenceTree::Seq, 32> Elts;
6653     SequenceTree::Seq Parent = Region;
6654     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
6655       Expr *E = ILE->getInit(I);
6656       if (!E) continue;
6657       Region = Tree.allocate(Parent);
6658       Elts.push_back(Region);
6659       Visit(E);
6660     }
6661 
6662     // Forget that the initializers are sequenced.
6663     Region = Parent;
6664     for (unsigned I = 0; I < Elts.size(); ++I)
6665       Tree.merge(Elts[I]);
6666   }
6667 };
6668 }
6669 
6670 void Sema::CheckUnsequencedOperations(Expr *E) {
6671   SmallVector<Expr *, 8> WorkList;
6672   WorkList.push_back(E);
6673   while (!WorkList.empty()) {
6674     Expr *Item = WorkList.pop_back_val();
6675     SequenceChecker(*this, Item, WorkList);
6676   }
6677 }
6678 
6679 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
6680                               bool IsConstexpr) {
6681   CheckImplicitConversions(E, CheckLoc);
6682   CheckUnsequencedOperations(E);
6683   if (!IsConstexpr && !E->isValueDependent())
6684     CheckForIntOverflow(E);
6685 }
6686 
6687 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
6688                                        FieldDecl *BitField,
6689                                        Expr *Init) {
6690   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
6691 }
6692 
6693 /// CheckParmsForFunctionDef - Check that the parameters of the given
6694 /// function are appropriate for the definition of a function. This
6695 /// takes care of any checks that cannot be performed on the
6696 /// declaration itself, e.g., that the types of each of the function
6697 /// parameters are complete.
6698 bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
6699                                     ParmVarDecl *const *PEnd,
6700                                     bool CheckParameterNames) {
6701   bool HasInvalidParm = false;
6702   for (; P != PEnd; ++P) {
6703     ParmVarDecl *Param = *P;
6704 
6705     // C99 6.7.5.3p4: the parameters in a parameter type list in a
6706     // function declarator that is part of a function definition of
6707     // that function shall not have incomplete type.
6708     //
6709     // This is also C++ [dcl.fct]p6.
6710     if (!Param->isInvalidDecl() &&
6711         RequireCompleteType(Param->getLocation(), Param->getType(),
6712                             diag::err_typecheck_decl_incomplete_type)) {
6713       Param->setInvalidDecl();
6714       HasInvalidParm = true;
6715     }
6716 
6717     // C99 6.9.1p5: If the declarator includes a parameter type list, the
6718     // declaration of each parameter shall include an identifier.
6719     if (CheckParameterNames &&
6720         Param->getIdentifier() == 0 &&
6721         !Param->isImplicit() &&
6722         !getLangOpts().CPlusPlus)
6723       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
6724 
6725     // C99 6.7.5.3p12:
6726     //   If the function declarator is not part of a definition of that
6727     //   function, parameters may have incomplete type and may use the [*]
6728     //   notation in their sequences of declarator specifiers to specify
6729     //   variable length array types.
6730     QualType PType = Param->getOriginalType();
6731     while (const ArrayType *AT = Context.getAsArrayType(PType)) {
6732       if (AT->getSizeModifier() == ArrayType::Star) {
6733         // FIXME: This diagnostic should point the '[*]' if source-location
6734         // information is added for it.
6735         Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
6736         break;
6737       }
6738       PType= AT->getElementType();
6739     }
6740 
6741     // MSVC destroys objects passed by value in the callee.  Therefore a
6742     // function definition which takes such a parameter must be able to call the
6743     // object's destructor.  However, we don't perform any direct access check
6744     // on the dtor.
6745     if (getLangOpts().CPlusPlus && Context.getTargetInfo()
6746                                        .getCXXABI()
6747                                        .areArgsDestroyedLeftToRightInCallee()) {
6748       if (!Param->isInvalidDecl()) {
6749         if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
6750           CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
6751           if (!ClassDecl->isInvalidDecl() &&
6752               !ClassDecl->hasIrrelevantDestructor() &&
6753               !ClassDecl->isDependentContext()) {
6754             CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
6755             MarkFunctionReferenced(Param->getLocation(), Destructor);
6756             DiagnoseUseOfDecl(Destructor, Param->getLocation());
6757           }
6758         }
6759       }
6760     }
6761   }
6762 
6763   return HasInvalidParm;
6764 }
6765 
6766 /// CheckCastAlign - Implements -Wcast-align, which warns when a
6767 /// pointer cast increases the alignment requirements.
6768 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
6769   // This is actually a lot of work to potentially be doing on every
6770   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
6771   if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
6772                                           TRange.getBegin())
6773         == DiagnosticsEngine::Ignored)
6774     return;
6775 
6776   // Ignore dependent types.
6777   if (T->isDependentType() || Op->getType()->isDependentType())
6778     return;
6779 
6780   // Require that the destination be a pointer type.
6781   const PointerType *DestPtr = T->getAs<PointerType>();
6782   if (!DestPtr) return;
6783 
6784   // If the destination has alignment 1, we're done.
6785   QualType DestPointee = DestPtr->getPointeeType();
6786   if (DestPointee->isIncompleteType()) return;
6787   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
6788   if (DestAlign.isOne()) return;
6789 
6790   // Require that the source be a pointer type.
6791   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
6792   if (!SrcPtr) return;
6793   QualType SrcPointee = SrcPtr->getPointeeType();
6794 
6795   // Whitelist casts from cv void*.  We already implicitly
6796   // whitelisted casts to cv void*, since they have alignment 1.
6797   // Also whitelist casts involving incomplete types, which implicitly
6798   // includes 'void'.
6799   if (SrcPointee->isIncompleteType()) return;
6800 
6801   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
6802   if (SrcAlign >= DestAlign) return;
6803 
6804   Diag(TRange.getBegin(), diag::warn_cast_align)
6805     << Op->getType() << T
6806     << static_cast<unsigned>(SrcAlign.getQuantity())
6807     << static_cast<unsigned>(DestAlign.getQuantity())
6808     << TRange << Op->getSourceRange();
6809 }
6810 
6811 static const Type* getElementType(const Expr *BaseExpr) {
6812   const Type* EltType = BaseExpr->getType().getTypePtr();
6813   if (EltType->isAnyPointerType())
6814     return EltType->getPointeeType().getTypePtr();
6815   else if (EltType->isArrayType())
6816     return EltType->getBaseElementTypeUnsafe();
6817   return EltType;
6818 }
6819 
6820 /// \brief Check whether this array fits the idiom of a size-one tail padded
6821 /// array member of a struct.
6822 ///
6823 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
6824 /// commonly used to emulate flexible arrays in C89 code.
6825 static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
6826                                     const NamedDecl *ND) {
6827   if (Size != 1 || !ND) return false;
6828 
6829   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
6830   if (!FD) return false;
6831 
6832   // Don't consider sizes resulting from macro expansions or template argument
6833   // substitution to form C89 tail-padded arrays.
6834 
6835   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
6836   while (TInfo) {
6837     TypeLoc TL = TInfo->getTypeLoc();
6838     // Look through typedefs.
6839     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
6840       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
6841       TInfo = TDL->getTypeSourceInfo();
6842       continue;
6843     }
6844     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
6845       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
6846       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
6847         return false;
6848     }
6849     break;
6850   }
6851 
6852   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
6853   if (!RD) return false;
6854   if (RD->isUnion()) return false;
6855   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
6856     if (!CRD->isStandardLayout()) return false;
6857   }
6858 
6859   // See if this is the last field decl in the record.
6860   const Decl *D = FD;
6861   while ((D = D->getNextDeclInContext()))
6862     if (isa<FieldDecl>(D))
6863       return false;
6864   return true;
6865 }
6866 
6867 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
6868                             const ArraySubscriptExpr *ASE,
6869                             bool AllowOnePastEnd, bool IndexNegated) {
6870   IndexExpr = IndexExpr->IgnoreParenImpCasts();
6871   if (IndexExpr->isValueDependent())
6872     return;
6873 
6874   const Type *EffectiveType = getElementType(BaseExpr);
6875   BaseExpr = BaseExpr->IgnoreParenCasts();
6876   const ConstantArrayType *ArrayTy =
6877     Context.getAsConstantArrayType(BaseExpr->getType());
6878   if (!ArrayTy)
6879     return;
6880 
6881   llvm::APSInt index;
6882   if (!IndexExpr->EvaluateAsInt(index, Context))
6883     return;
6884   if (IndexNegated)
6885     index = -index;
6886 
6887   const NamedDecl *ND = NULL;
6888   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6889     ND = dyn_cast<NamedDecl>(DRE->getDecl());
6890   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
6891     ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
6892 
6893   if (index.isUnsigned() || !index.isNegative()) {
6894     llvm::APInt size = ArrayTy->getSize();
6895     if (!size.isStrictlyPositive())
6896       return;
6897 
6898     const Type* BaseType = getElementType(BaseExpr);
6899     if (BaseType != EffectiveType) {
6900       // Make sure we're comparing apples to apples when comparing index to size
6901       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
6902       uint64_t array_typesize = Context.getTypeSize(BaseType);
6903       // Handle ptrarith_typesize being zero, such as when casting to void*
6904       if (!ptrarith_typesize) ptrarith_typesize = 1;
6905       if (ptrarith_typesize != array_typesize) {
6906         // There's a cast to a different size type involved
6907         uint64_t ratio = array_typesize / ptrarith_typesize;
6908         // TODO: Be smarter about handling cases where array_typesize is not a
6909         // multiple of ptrarith_typesize
6910         if (ptrarith_typesize * ratio == array_typesize)
6911           size *= llvm::APInt(size.getBitWidth(), ratio);
6912       }
6913     }
6914 
6915     if (size.getBitWidth() > index.getBitWidth())
6916       index = index.zext(size.getBitWidth());
6917     else if (size.getBitWidth() < index.getBitWidth())
6918       size = size.zext(index.getBitWidth());
6919 
6920     // For array subscripting the index must be less than size, but for pointer
6921     // arithmetic also allow the index (offset) to be equal to size since
6922     // computing the next address after the end of the array is legal and
6923     // commonly done e.g. in C++ iterators and range-based for loops.
6924     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
6925       return;
6926 
6927     // Also don't warn for arrays of size 1 which are members of some
6928     // structure. These are often used to approximate flexible arrays in C89
6929     // code.
6930     if (IsTailPaddedMemberArray(*this, size, ND))
6931       return;
6932 
6933     // Suppress the warning if the subscript expression (as identified by the
6934     // ']' location) and the index expression are both from macro expansions
6935     // within a system header.
6936     if (ASE) {
6937       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
6938           ASE->getRBracketLoc());
6939       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
6940         SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
6941             IndexExpr->getLocStart());
6942         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
6943           return;
6944       }
6945     }
6946 
6947     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
6948     if (ASE)
6949       DiagID = diag::warn_array_index_exceeds_bounds;
6950 
6951     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6952                         PDiag(DiagID) << index.toString(10, true)
6953                           << size.toString(10, true)
6954                           << (unsigned)size.getLimitedValue(~0U)
6955                           << IndexExpr->getSourceRange());
6956   } else {
6957     unsigned DiagID = diag::warn_array_index_precedes_bounds;
6958     if (!ASE) {
6959       DiagID = diag::warn_ptr_arith_precedes_bounds;
6960       if (index.isNegative()) index = -index;
6961     }
6962 
6963     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6964                         PDiag(DiagID) << index.toString(10, true)
6965                           << IndexExpr->getSourceRange());
6966   }
6967 
6968   if (!ND) {
6969     // Try harder to find a NamedDecl to point at in the note.
6970     while (const ArraySubscriptExpr *ASE =
6971            dyn_cast<ArraySubscriptExpr>(BaseExpr))
6972       BaseExpr = ASE->getBase()->IgnoreParenCasts();
6973     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6974       ND = dyn_cast<NamedDecl>(DRE->getDecl());
6975     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
6976       ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
6977   }
6978 
6979   if (ND)
6980     DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
6981                         PDiag(diag::note_array_index_out_of_bounds)
6982                           << ND->getDeclName());
6983 }
6984 
6985 void Sema::CheckArrayAccess(const Expr *expr) {
6986   int AllowOnePastEnd = 0;
6987   while (expr) {
6988     expr = expr->IgnoreParenImpCasts();
6989     switch (expr->getStmtClass()) {
6990       case Stmt::ArraySubscriptExprClass: {
6991         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
6992         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
6993                          AllowOnePastEnd > 0);
6994         return;
6995       }
6996       case Stmt::UnaryOperatorClass: {
6997         // Only unwrap the * and & unary operators
6998         const UnaryOperator *UO = cast<UnaryOperator>(expr);
6999         expr = UO->getSubExpr();
7000         switch (UO->getOpcode()) {
7001           case UO_AddrOf:
7002             AllowOnePastEnd++;
7003             break;
7004           case UO_Deref:
7005             AllowOnePastEnd--;
7006             break;
7007           default:
7008             return;
7009         }
7010         break;
7011       }
7012       case Stmt::ConditionalOperatorClass: {
7013         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
7014         if (const Expr *lhs = cond->getLHS())
7015           CheckArrayAccess(lhs);
7016         if (const Expr *rhs = cond->getRHS())
7017           CheckArrayAccess(rhs);
7018         return;
7019       }
7020       default:
7021         return;
7022     }
7023   }
7024 }
7025 
7026 //===--- CHECK: Objective-C retain cycles ----------------------------------//
7027 
7028 namespace {
7029   struct RetainCycleOwner {
7030     RetainCycleOwner() : Variable(0), Indirect(false) {}
7031     VarDecl *Variable;
7032     SourceRange Range;
7033     SourceLocation Loc;
7034     bool Indirect;
7035 
7036     void setLocsFrom(Expr *e) {
7037       Loc = e->getExprLoc();
7038       Range = e->getSourceRange();
7039     }
7040   };
7041 }
7042 
7043 /// Consider whether capturing the given variable can possibly lead to
7044 /// a retain cycle.
7045 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
7046   // In ARC, it's captured strongly iff the variable has __strong
7047   // lifetime.  In MRR, it's captured strongly if the variable is
7048   // __block and has an appropriate type.
7049   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7050     return false;
7051 
7052   owner.Variable = var;
7053   if (ref)
7054     owner.setLocsFrom(ref);
7055   return true;
7056 }
7057 
7058 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
7059   while (true) {
7060     e = e->IgnoreParens();
7061     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
7062       switch (cast->getCastKind()) {
7063       case CK_BitCast:
7064       case CK_LValueBitCast:
7065       case CK_LValueToRValue:
7066       case CK_ARCReclaimReturnedObject:
7067         e = cast->getSubExpr();
7068         continue;
7069 
7070       default:
7071         return false;
7072       }
7073     }
7074 
7075     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
7076       ObjCIvarDecl *ivar = ref->getDecl();
7077       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7078         return false;
7079 
7080       // Try to find a retain cycle in the base.
7081       if (!findRetainCycleOwner(S, ref->getBase(), owner))
7082         return false;
7083 
7084       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
7085       owner.Indirect = true;
7086       return true;
7087     }
7088 
7089     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
7090       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
7091       if (!var) return false;
7092       return considerVariable(var, ref, owner);
7093     }
7094 
7095     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
7096       if (member->isArrow()) return false;
7097 
7098       // Don't count this as an indirect ownership.
7099       e = member->getBase();
7100       continue;
7101     }
7102 
7103     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
7104       // Only pay attention to pseudo-objects on property references.
7105       ObjCPropertyRefExpr *pre
7106         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
7107                                               ->IgnoreParens());
7108       if (!pre) return false;
7109       if (pre->isImplicitProperty()) return false;
7110       ObjCPropertyDecl *property = pre->getExplicitProperty();
7111       if (!property->isRetaining() &&
7112           !(property->getPropertyIvarDecl() &&
7113             property->getPropertyIvarDecl()->getType()
7114               .getObjCLifetime() == Qualifiers::OCL_Strong))
7115           return false;
7116 
7117       owner.Indirect = true;
7118       if (pre->isSuperReceiver()) {
7119         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
7120         if (!owner.Variable)
7121           return false;
7122         owner.Loc = pre->getLocation();
7123         owner.Range = pre->getSourceRange();
7124         return true;
7125       }
7126       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
7127                               ->getSourceExpr());
7128       continue;
7129     }
7130 
7131     // Array ivars?
7132 
7133     return false;
7134   }
7135 }
7136 
7137 namespace {
7138   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
7139     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
7140       : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
7141         Variable(variable), Capturer(0) {}
7142 
7143     VarDecl *Variable;
7144     Expr *Capturer;
7145 
7146     void VisitDeclRefExpr(DeclRefExpr *ref) {
7147       if (ref->getDecl() == Variable && !Capturer)
7148         Capturer = ref;
7149     }
7150 
7151     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
7152       if (Capturer) return;
7153       Visit(ref->getBase());
7154       if (Capturer && ref->isFreeIvar())
7155         Capturer = ref;
7156     }
7157 
7158     void VisitBlockExpr(BlockExpr *block) {
7159       // Look inside nested blocks
7160       if (block->getBlockDecl()->capturesVariable(Variable))
7161         Visit(block->getBlockDecl()->getBody());
7162     }
7163 
7164     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
7165       if (Capturer) return;
7166       if (OVE->getSourceExpr())
7167         Visit(OVE->getSourceExpr());
7168     }
7169   };
7170 }
7171 
7172 /// Check whether the given argument is a block which captures a
7173 /// variable.
7174 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
7175   assert(owner.Variable && owner.Loc.isValid());
7176 
7177   e = e->IgnoreParenCasts();
7178 
7179   // Look through [^{...} copy] and Block_copy(^{...}).
7180   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
7181     Selector Cmd = ME->getSelector();
7182     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
7183       e = ME->getInstanceReceiver();
7184       if (!e)
7185         return 0;
7186       e = e->IgnoreParenCasts();
7187     }
7188   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
7189     if (CE->getNumArgs() == 1) {
7190       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
7191       if (Fn) {
7192         const IdentifierInfo *FnI = Fn->getIdentifier();
7193         if (FnI && FnI->isStr("_Block_copy")) {
7194           e = CE->getArg(0)->IgnoreParenCasts();
7195         }
7196       }
7197     }
7198   }
7199 
7200   BlockExpr *block = dyn_cast<BlockExpr>(e);
7201   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
7202     return 0;
7203 
7204   FindCaptureVisitor visitor(S.Context, owner.Variable);
7205   visitor.Visit(block->getBlockDecl()->getBody());
7206   return visitor.Capturer;
7207 }
7208 
7209 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
7210                                 RetainCycleOwner &owner) {
7211   assert(capturer);
7212   assert(owner.Variable && owner.Loc.isValid());
7213 
7214   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
7215     << owner.Variable << capturer->getSourceRange();
7216   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
7217     << owner.Indirect << owner.Range;
7218 }
7219 
7220 /// Check for a keyword selector that starts with the word 'add' or
7221 /// 'set'.
7222 static bool isSetterLikeSelector(Selector sel) {
7223   if (sel.isUnarySelector()) return false;
7224 
7225   StringRef str = sel.getNameForSlot(0);
7226   while (!str.empty() && str.front() == '_') str = str.substr(1);
7227   if (str.startswith("set"))
7228     str = str.substr(3);
7229   else if (str.startswith("add")) {
7230     // Specially whitelist 'addOperationWithBlock:'.
7231     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
7232       return false;
7233     str = str.substr(3);
7234   }
7235   else
7236     return false;
7237 
7238   if (str.empty()) return true;
7239   return !isLowercase(str.front());
7240 }
7241 
7242 /// Check a message send to see if it's likely to cause a retain cycle.
7243 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
7244   // Only check instance methods whose selector looks like a setter.
7245   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
7246     return;
7247 
7248   // Try to find a variable that the receiver is strongly owned by.
7249   RetainCycleOwner owner;
7250   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
7251     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
7252       return;
7253   } else {
7254     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
7255     owner.Variable = getCurMethodDecl()->getSelfDecl();
7256     owner.Loc = msg->getSuperLoc();
7257     owner.Range = msg->getSuperLoc();
7258   }
7259 
7260   // Check whether the receiver is captured by any of the arguments.
7261   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
7262     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
7263       return diagnoseRetainCycle(*this, capturer, owner);
7264 }
7265 
7266 /// Check a property assign to see if it's likely to cause a retain cycle.
7267 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
7268   RetainCycleOwner owner;
7269   if (!findRetainCycleOwner(*this, receiver, owner))
7270     return;
7271 
7272   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
7273     diagnoseRetainCycle(*this, capturer, owner);
7274 }
7275 
7276 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
7277   RetainCycleOwner Owner;
7278   if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner))
7279     return;
7280 
7281   // Because we don't have an expression for the variable, we have to set the
7282   // location explicitly here.
7283   Owner.Loc = Var->getLocation();
7284   Owner.Range = Var->getSourceRange();
7285 
7286   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
7287     diagnoseRetainCycle(*this, Capturer, Owner);
7288 }
7289 
7290 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
7291                                      Expr *RHS, bool isProperty) {
7292   // Check if RHS is an Objective-C object literal, which also can get
7293   // immediately zapped in a weak reference.  Note that we explicitly
7294   // allow ObjCStringLiterals, since those are designed to never really die.
7295   RHS = RHS->IgnoreParenImpCasts();
7296 
7297   // This enum needs to match with the 'select' in
7298   // warn_objc_arc_literal_assign (off-by-1).
7299   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
7300   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
7301     return false;
7302 
7303   S.Diag(Loc, diag::warn_arc_literal_assign)
7304     << (unsigned) Kind
7305     << (isProperty ? 0 : 1)
7306     << RHS->getSourceRange();
7307 
7308   return true;
7309 }
7310 
7311 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
7312                                     Qualifiers::ObjCLifetime LT,
7313                                     Expr *RHS, bool isProperty) {
7314   // Strip off any implicit cast added to get to the one ARC-specific.
7315   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
7316     if (cast->getCastKind() == CK_ARCConsumeObject) {
7317       S.Diag(Loc, diag::warn_arc_retained_assign)
7318         << (LT == Qualifiers::OCL_ExplicitNone)
7319         << (isProperty ? 0 : 1)
7320         << RHS->getSourceRange();
7321       return true;
7322     }
7323     RHS = cast->getSubExpr();
7324   }
7325 
7326   if (LT == Qualifiers::OCL_Weak &&
7327       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
7328     return true;
7329 
7330   return false;
7331 }
7332 
7333 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
7334                               QualType LHS, Expr *RHS) {
7335   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
7336 
7337   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
7338     return false;
7339 
7340   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
7341     return true;
7342 
7343   return false;
7344 }
7345 
7346 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
7347                               Expr *LHS, Expr *RHS) {
7348   QualType LHSType;
7349   // PropertyRef on LHS type need be directly obtained from
7350   // its declaration as it has a PseudoType.
7351   ObjCPropertyRefExpr *PRE
7352     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
7353   if (PRE && !PRE->isImplicitProperty()) {
7354     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7355     if (PD)
7356       LHSType = PD->getType();
7357   }
7358 
7359   if (LHSType.isNull())
7360     LHSType = LHS->getType();
7361 
7362   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
7363 
7364   if (LT == Qualifiers::OCL_Weak) {
7365     DiagnosticsEngine::Level Level =
7366       Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
7367     if (Level != DiagnosticsEngine::Ignored)
7368       getCurFunction()->markSafeWeakUse(LHS);
7369   }
7370 
7371   if (checkUnsafeAssigns(Loc, LHSType, RHS))
7372     return;
7373 
7374   // FIXME. Check for other life times.
7375   if (LT != Qualifiers::OCL_None)
7376     return;
7377 
7378   if (PRE) {
7379     if (PRE->isImplicitProperty())
7380       return;
7381     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7382     if (!PD)
7383       return;
7384 
7385     unsigned Attributes = PD->getPropertyAttributes();
7386     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
7387       // when 'assign' attribute was not explicitly specified
7388       // by user, ignore it and rely on property type itself
7389       // for lifetime info.
7390       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
7391       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
7392           LHSType->isObjCRetainableType())
7393         return;
7394 
7395       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
7396         if (cast->getCastKind() == CK_ARCConsumeObject) {
7397           Diag(Loc, diag::warn_arc_retained_property_assign)
7398           << RHS->getSourceRange();
7399           return;
7400         }
7401         RHS = cast->getSubExpr();
7402       }
7403     }
7404     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
7405       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
7406         return;
7407     }
7408   }
7409 }
7410 
7411 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
7412 
7413 namespace {
7414 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
7415                                  SourceLocation StmtLoc,
7416                                  const NullStmt *Body) {
7417   // Do not warn if the body is a macro that expands to nothing, e.g:
7418   //
7419   // #define CALL(x)
7420   // if (condition)
7421   //   CALL(0);
7422   //
7423   if (Body->hasLeadingEmptyMacro())
7424     return false;
7425 
7426   // Get line numbers of statement and body.
7427   bool StmtLineInvalid;
7428   unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
7429                                                       &StmtLineInvalid);
7430   if (StmtLineInvalid)
7431     return false;
7432 
7433   bool BodyLineInvalid;
7434   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
7435                                                       &BodyLineInvalid);
7436   if (BodyLineInvalid)
7437     return false;
7438 
7439   // Warn if null statement and body are on the same line.
7440   if (StmtLine != BodyLine)
7441     return false;
7442 
7443   return true;
7444 }
7445 } // Unnamed namespace
7446 
7447 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
7448                                  const Stmt *Body,
7449                                  unsigned DiagID) {
7450   // Since this is a syntactic check, don't emit diagnostic for template
7451   // instantiations, this just adds noise.
7452   if (CurrentInstantiationScope)
7453     return;
7454 
7455   // The body should be a null statement.
7456   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7457   if (!NBody)
7458     return;
7459 
7460   // Do the usual checks.
7461   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7462     return;
7463 
7464   Diag(NBody->getSemiLoc(), DiagID);
7465   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7466 }
7467 
7468 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
7469                                  const Stmt *PossibleBody) {
7470   assert(!CurrentInstantiationScope); // Ensured by caller
7471 
7472   SourceLocation StmtLoc;
7473   const Stmt *Body;
7474   unsigned DiagID;
7475   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
7476     StmtLoc = FS->getRParenLoc();
7477     Body = FS->getBody();
7478     DiagID = diag::warn_empty_for_body;
7479   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
7480     StmtLoc = WS->getCond()->getSourceRange().getEnd();
7481     Body = WS->getBody();
7482     DiagID = diag::warn_empty_while_body;
7483   } else
7484     return; // Neither `for' nor `while'.
7485 
7486   // The body should be a null statement.
7487   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7488   if (!NBody)
7489     return;
7490 
7491   // Skip expensive checks if diagnostic is disabled.
7492   if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
7493           DiagnosticsEngine::Ignored)
7494     return;
7495 
7496   // Do the usual checks.
7497   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7498     return;
7499 
7500   // `for(...);' and `while(...);' are popular idioms, so in order to keep
7501   // noise level low, emit diagnostics only if for/while is followed by a
7502   // CompoundStmt, e.g.:
7503   //    for (int i = 0; i < n; i++);
7504   //    {
7505   //      a(i);
7506   //    }
7507   // or if for/while is followed by a statement with more indentation
7508   // than for/while itself:
7509   //    for (int i = 0; i < n; i++);
7510   //      a(i);
7511   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
7512   if (!ProbableTypo) {
7513     bool BodyColInvalid;
7514     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
7515                              PossibleBody->getLocStart(),
7516                              &BodyColInvalid);
7517     if (BodyColInvalid)
7518       return;
7519 
7520     bool StmtColInvalid;
7521     unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
7522                              S->getLocStart(),
7523                              &StmtColInvalid);
7524     if (StmtColInvalid)
7525       return;
7526 
7527     if (BodyCol > StmtCol)
7528       ProbableTypo = true;
7529   }
7530 
7531   if (ProbableTypo) {
7532     Diag(NBody->getSemiLoc(), DiagID);
7533     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7534   }
7535 }
7536 
7537 //===--- Layout compatibility ----------------------------------------------//
7538 
7539 namespace {
7540 
7541 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
7542 
7543 /// \brief Check if two enumeration types are layout-compatible.
7544 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
7545   // C++11 [dcl.enum] p8:
7546   // Two enumeration types are layout-compatible if they have the same
7547   // underlying type.
7548   return ED1->isComplete() && ED2->isComplete() &&
7549          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
7550 }
7551 
7552 /// \brief Check if two fields are layout-compatible.
7553 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
7554   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
7555     return false;
7556 
7557   if (Field1->isBitField() != Field2->isBitField())
7558     return false;
7559 
7560   if (Field1->isBitField()) {
7561     // Make sure that the bit-fields are the same length.
7562     unsigned Bits1 = Field1->getBitWidthValue(C);
7563     unsigned Bits2 = Field2->getBitWidthValue(C);
7564 
7565     if (Bits1 != Bits2)
7566       return false;
7567   }
7568 
7569   return true;
7570 }
7571 
7572 /// \brief Check if two standard-layout structs are layout-compatible.
7573 /// (C++11 [class.mem] p17)
7574 bool isLayoutCompatibleStruct(ASTContext &C,
7575                               RecordDecl *RD1,
7576                               RecordDecl *RD2) {
7577   // If both records are C++ classes, check that base classes match.
7578   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
7579     // If one of records is a CXXRecordDecl we are in C++ mode,
7580     // thus the other one is a CXXRecordDecl, too.
7581     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
7582     // Check number of base classes.
7583     if (D1CXX->getNumBases() != D2CXX->getNumBases())
7584       return false;
7585 
7586     // Check the base classes.
7587     for (CXXRecordDecl::base_class_const_iterator
7588                Base1 = D1CXX->bases_begin(),
7589            BaseEnd1 = D1CXX->bases_end(),
7590               Base2 = D2CXX->bases_begin();
7591          Base1 != BaseEnd1;
7592          ++Base1, ++Base2) {
7593       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
7594         return false;
7595     }
7596   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
7597     // If only RD2 is a C++ class, it should have zero base classes.
7598     if (D2CXX->getNumBases() > 0)
7599       return false;
7600   }
7601 
7602   // Check the fields.
7603   RecordDecl::field_iterator Field2 = RD2->field_begin(),
7604                              Field2End = RD2->field_end(),
7605                              Field1 = RD1->field_begin(),
7606                              Field1End = RD1->field_end();
7607   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
7608     if (!isLayoutCompatible(C, *Field1, *Field2))
7609       return false;
7610   }
7611   if (Field1 != Field1End || Field2 != Field2End)
7612     return false;
7613 
7614   return true;
7615 }
7616 
7617 /// \brief Check if two standard-layout unions are layout-compatible.
7618 /// (C++11 [class.mem] p18)
7619 bool isLayoutCompatibleUnion(ASTContext &C,
7620                              RecordDecl *RD1,
7621                              RecordDecl *RD2) {
7622   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
7623   for (auto *Field2 : RD2->fields())
7624     UnmatchedFields.insert(Field2);
7625 
7626   for (auto *Field1 : RD1->fields()) {
7627     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
7628         I = UnmatchedFields.begin(),
7629         E = UnmatchedFields.end();
7630 
7631     for ( ; I != E; ++I) {
7632       if (isLayoutCompatible(C, Field1, *I)) {
7633         bool Result = UnmatchedFields.erase(*I);
7634         (void) Result;
7635         assert(Result);
7636         break;
7637       }
7638     }
7639     if (I == E)
7640       return false;
7641   }
7642 
7643   return UnmatchedFields.empty();
7644 }
7645 
7646 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
7647   if (RD1->isUnion() != RD2->isUnion())
7648     return false;
7649 
7650   if (RD1->isUnion())
7651     return isLayoutCompatibleUnion(C, RD1, RD2);
7652   else
7653     return isLayoutCompatibleStruct(C, RD1, RD2);
7654 }
7655 
7656 /// \brief Check if two types are layout-compatible in C++11 sense.
7657 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
7658   if (T1.isNull() || T2.isNull())
7659     return false;
7660 
7661   // C++11 [basic.types] p11:
7662   // If two types T1 and T2 are the same type, then T1 and T2 are
7663   // layout-compatible types.
7664   if (C.hasSameType(T1, T2))
7665     return true;
7666 
7667   T1 = T1.getCanonicalType().getUnqualifiedType();
7668   T2 = T2.getCanonicalType().getUnqualifiedType();
7669 
7670   const Type::TypeClass TC1 = T1->getTypeClass();
7671   const Type::TypeClass TC2 = T2->getTypeClass();
7672 
7673   if (TC1 != TC2)
7674     return false;
7675 
7676   if (TC1 == Type::Enum) {
7677     return isLayoutCompatible(C,
7678                               cast<EnumType>(T1)->getDecl(),
7679                               cast<EnumType>(T2)->getDecl());
7680   } else if (TC1 == Type::Record) {
7681     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
7682       return false;
7683 
7684     return isLayoutCompatible(C,
7685                               cast<RecordType>(T1)->getDecl(),
7686                               cast<RecordType>(T2)->getDecl());
7687   }
7688 
7689   return false;
7690 }
7691 }
7692 
7693 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
7694 
7695 namespace {
7696 /// \brief Given a type tag expression find the type tag itself.
7697 ///
7698 /// \param TypeExpr Type tag expression, as it appears in user's code.
7699 ///
7700 /// \param VD Declaration of an identifier that appears in a type tag.
7701 ///
7702 /// \param MagicValue Type tag magic value.
7703 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
7704                      const ValueDecl **VD, uint64_t *MagicValue) {
7705   while(true) {
7706     if (!TypeExpr)
7707       return false;
7708 
7709     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
7710 
7711     switch (TypeExpr->getStmtClass()) {
7712     case Stmt::UnaryOperatorClass: {
7713       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
7714       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
7715         TypeExpr = UO->getSubExpr();
7716         continue;
7717       }
7718       return false;
7719     }
7720 
7721     case Stmt::DeclRefExprClass: {
7722       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
7723       *VD = DRE->getDecl();
7724       return true;
7725     }
7726 
7727     case Stmt::IntegerLiteralClass: {
7728       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
7729       llvm::APInt MagicValueAPInt = IL->getValue();
7730       if (MagicValueAPInt.getActiveBits() <= 64) {
7731         *MagicValue = MagicValueAPInt.getZExtValue();
7732         return true;
7733       } else
7734         return false;
7735     }
7736 
7737     case Stmt::BinaryConditionalOperatorClass:
7738     case Stmt::ConditionalOperatorClass: {
7739       const AbstractConditionalOperator *ACO =
7740           cast<AbstractConditionalOperator>(TypeExpr);
7741       bool Result;
7742       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
7743         if (Result)
7744           TypeExpr = ACO->getTrueExpr();
7745         else
7746           TypeExpr = ACO->getFalseExpr();
7747         continue;
7748       }
7749       return false;
7750     }
7751 
7752     case Stmt::BinaryOperatorClass: {
7753       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
7754       if (BO->getOpcode() == BO_Comma) {
7755         TypeExpr = BO->getRHS();
7756         continue;
7757       }
7758       return false;
7759     }
7760 
7761     default:
7762       return false;
7763     }
7764   }
7765 }
7766 
7767 /// \brief Retrieve the C type corresponding to type tag TypeExpr.
7768 ///
7769 /// \param TypeExpr Expression that specifies a type tag.
7770 ///
7771 /// \param MagicValues Registered magic values.
7772 ///
7773 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
7774 ///        kind.
7775 ///
7776 /// \param TypeInfo Information about the corresponding C type.
7777 ///
7778 /// \returns true if the corresponding C type was found.
7779 bool GetMatchingCType(
7780         const IdentifierInfo *ArgumentKind,
7781         const Expr *TypeExpr, const ASTContext &Ctx,
7782         const llvm::DenseMap<Sema::TypeTagMagicValue,
7783                              Sema::TypeTagData> *MagicValues,
7784         bool &FoundWrongKind,
7785         Sema::TypeTagData &TypeInfo) {
7786   FoundWrongKind = false;
7787 
7788   // Variable declaration that has type_tag_for_datatype attribute.
7789   const ValueDecl *VD = NULL;
7790 
7791   uint64_t MagicValue;
7792 
7793   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
7794     return false;
7795 
7796   if (VD) {
7797     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
7798       if (I->getArgumentKind() != ArgumentKind) {
7799         FoundWrongKind = true;
7800         return false;
7801       }
7802       TypeInfo.Type = I->getMatchingCType();
7803       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
7804       TypeInfo.MustBeNull = I->getMustBeNull();
7805       return true;
7806     }
7807     return false;
7808   }
7809 
7810   if (!MagicValues)
7811     return false;
7812 
7813   llvm::DenseMap<Sema::TypeTagMagicValue,
7814                  Sema::TypeTagData>::const_iterator I =
7815       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
7816   if (I == MagicValues->end())
7817     return false;
7818 
7819   TypeInfo = I->second;
7820   return true;
7821 }
7822 } // unnamed namespace
7823 
7824 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
7825                                       uint64_t MagicValue, QualType Type,
7826                                       bool LayoutCompatible,
7827                                       bool MustBeNull) {
7828   if (!TypeTagForDatatypeMagicValues)
7829     TypeTagForDatatypeMagicValues.reset(
7830         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
7831 
7832   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
7833   (*TypeTagForDatatypeMagicValues)[Magic] =
7834       TypeTagData(Type, LayoutCompatible, MustBeNull);
7835 }
7836 
7837 namespace {
7838 bool IsSameCharType(QualType T1, QualType T2) {
7839   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
7840   if (!BT1)
7841     return false;
7842 
7843   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
7844   if (!BT2)
7845     return false;
7846 
7847   BuiltinType::Kind T1Kind = BT1->getKind();
7848   BuiltinType::Kind T2Kind = BT2->getKind();
7849 
7850   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
7851          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
7852          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
7853          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
7854 }
7855 } // unnamed namespace
7856 
7857 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
7858                                     const Expr * const *ExprArgs) {
7859   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
7860   bool IsPointerAttr = Attr->getIsPointer();
7861 
7862   const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
7863   bool FoundWrongKind;
7864   TypeTagData TypeInfo;
7865   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
7866                         TypeTagForDatatypeMagicValues.get(),
7867                         FoundWrongKind, TypeInfo)) {
7868     if (FoundWrongKind)
7869       Diag(TypeTagExpr->getExprLoc(),
7870            diag::warn_type_tag_for_datatype_wrong_kind)
7871         << TypeTagExpr->getSourceRange();
7872     return;
7873   }
7874 
7875   const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
7876   if (IsPointerAttr) {
7877     // Skip implicit cast of pointer to `void *' (as a function argument).
7878     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
7879       if (ICE->getType()->isVoidPointerType() &&
7880           ICE->getCastKind() == CK_BitCast)
7881         ArgumentExpr = ICE->getSubExpr();
7882   }
7883   QualType ArgumentType = ArgumentExpr->getType();
7884 
7885   // Passing a `void*' pointer shouldn't trigger a warning.
7886   if (IsPointerAttr && ArgumentType->isVoidPointerType())
7887     return;
7888 
7889   if (TypeInfo.MustBeNull) {
7890     // Type tag with matching void type requires a null pointer.
7891     if (!ArgumentExpr->isNullPointerConstant(Context,
7892                                              Expr::NPC_ValueDependentIsNotNull)) {
7893       Diag(ArgumentExpr->getExprLoc(),
7894            diag::warn_type_safety_null_pointer_required)
7895           << ArgumentKind->getName()
7896           << ArgumentExpr->getSourceRange()
7897           << TypeTagExpr->getSourceRange();
7898     }
7899     return;
7900   }
7901 
7902   QualType RequiredType = TypeInfo.Type;
7903   if (IsPointerAttr)
7904     RequiredType = Context.getPointerType(RequiredType);
7905 
7906   bool mismatch = false;
7907   if (!TypeInfo.LayoutCompatible) {
7908     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
7909 
7910     // C++11 [basic.fundamental] p1:
7911     // Plain char, signed char, and unsigned char are three distinct types.
7912     //
7913     // But we treat plain `char' as equivalent to `signed char' or `unsigned
7914     // char' depending on the current char signedness mode.
7915     if (mismatch)
7916       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
7917                                            RequiredType->getPointeeType())) ||
7918           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
7919         mismatch = false;
7920   } else
7921     if (IsPointerAttr)
7922       mismatch = !isLayoutCompatible(Context,
7923                                      ArgumentType->getPointeeType(),
7924                                      RequiredType->getPointeeType());
7925     else
7926       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
7927 
7928   if (mismatch)
7929     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
7930         << ArgumentType << ArgumentKind
7931         << TypeInfo.LayoutCompatible << RequiredType
7932         << ArgumentExpr->getSourceRange()
7933         << TypeTagExpr->getSourceRange();
7934 }
7935 
7936