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/Initialization.h"
16 #include "clang/Sema/Sema.h"
17 #include "clang/Sema/SemaInternal.h"
18 #include "clang/Sema/Initialization.h"
19 #include "clang/Sema/ScopeInfo.h"
20 #include "clang/Analysis/Analyses/FormatString.h"
21 #include "clang/AST/ASTContext.h"
22 #include "clang/AST/CharUnits.h"
23 #include "clang/AST/DeclCXX.h"
24 #include "clang/AST/DeclObjC.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExprObjC.h"
27 #include "clang/AST/EvaluatedExprVisitor.h"
28 #include "clang/AST/DeclObjC.h"
29 #include "clang/AST/StmtCXX.h"
30 #include "clang/AST/StmtObjC.h"
31 #include "clang/Lex/Preprocessor.h"
32 #include "llvm/ADT/BitVector.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "clang/Basic/TargetBuiltins.h"
36 #include "clang/Basic/TargetInfo.h"
37 #include "clang/Basic/ConvertUTF.h"
38 #include <limits>
39 using namespace clang;
40 using namespace sema;
41 
42 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
43                                                     unsigned ByteNo) const {
44   return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
45                                PP.getLangOptions(), PP.getTargetInfo());
46 }
47 
48 
49 /// CheckablePrintfAttr - does a function call have a "printf" attribute
50 /// and arguments that merit checking?
51 bool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) {
52   if (Format->getType() == "printf") return true;
53   if (Format->getType() == "printf0") {
54     // printf0 allows null "format" string; if so don't check format/args
55     unsigned format_idx = Format->getFormatIdx() - 1;
56     // Does the index refer to the implicit object argument?
57     if (isa<CXXMemberCallExpr>(TheCall)) {
58       if (format_idx == 0)
59         return false;
60       --format_idx;
61     }
62     if (format_idx < TheCall->getNumArgs()) {
63       Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts();
64       if (!Format->isNullPointerConstant(Context,
65                                          Expr::NPC_ValueDependentIsNull))
66         return true;
67     }
68   }
69   return false;
70 }
71 
72 /// Checks that a call expression's argument count is the desired number.
73 /// This is useful when doing custom type-checking.  Returns true on error.
74 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
75   unsigned argCount = call->getNumArgs();
76   if (argCount == desiredArgCount) return false;
77 
78   if (argCount < desiredArgCount)
79     return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
80         << 0 /*function call*/ << desiredArgCount << argCount
81         << call->getSourceRange();
82 
83   // Highlight all the excess arguments.
84   SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
85                     call->getArg(argCount - 1)->getLocEnd());
86 
87   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
88     << 0 /*function call*/ << desiredArgCount << argCount
89     << call->getArg(1)->getSourceRange();
90 }
91 
92 /// CheckBuiltinAnnotationString - Checks that string argument to the builtin
93 /// annotation is a non wide string literal.
94 static bool CheckBuiltinAnnotationString(Sema &S, Expr *Arg) {
95   Arg = Arg->IgnoreParenCasts();
96   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
97   if (!Literal || !Literal->isAscii()) {
98     S.Diag(Arg->getLocStart(), diag::err_builtin_annotation_not_string_constant)
99       << Arg->getSourceRange();
100     return true;
101   }
102   return false;
103 }
104 
105 ExprResult
106 Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
107   ExprResult TheCallResult(Owned(TheCall));
108 
109   // Find out if any arguments are required to be integer constant expressions.
110   unsigned ICEArguments = 0;
111   ASTContext::GetBuiltinTypeError Error;
112   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
113   if (Error != ASTContext::GE_None)
114     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
115 
116   // If any arguments are required to be ICE's, check and diagnose.
117   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
118     // Skip arguments not required to be ICE's.
119     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
120 
121     llvm::APSInt Result;
122     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
123       return true;
124     ICEArguments &= ~(1 << ArgNo);
125   }
126 
127   switch (BuiltinID) {
128   case Builtin::BI__builtin___CFStringMakeConstantString:
129     assert(TheCall->getNumArgs() == 1 &&
130            "Wrong # arguments to builtin CFStringMakeConstantString");
131     if (CheckObjCString(TheCall->getArg(0)))
132       return ExprError();
133     break;
134   case Builtin::BI__builtin_stdarg_start:
135   case Builtin::BI__builtin_va_start:
136     if (SemaBuiltinVAStart(TheCall))
137       return ExprError();
138     break;
139   case Builtin::BI__builtin_isgreater:
140   case Builtin::BI__builtin_isgreaterequal:
141   case Builtin::BI__builtin_isless:
142   case Builtin::BI__builtin_islessequal:
143   case Builtin::BI__builtin_islessgreater:
144   case Builtin::BI__builtin_isunordered:
145     if (SemaBuiltinUnorderedCompare(TheCall))
146       return ExprError();
147     break;
148   case Builtin::BI__builtin_fpclassify:
149     if (SemaBuiltinFPClassification(TheCall, 6))
150       return ExprError();
151     break;
152   case Builtin::BI__builtin_isfinite:
153   case Builtin::BI__builtin_isinf:
154   case Builtin::BI__builtin_isinf_sign:
155   case Builtin::BI__builtin_isnan:
156   case Builtin::BI__builtin_isnormal:
157     if (SemaBuiltinFPClassification(TheCall, 1))
158       return ExprError();
159     break;
160   case Builtin::BI__builtin_shufflevector:
161     return SemaBuiltinShuffleVector(TheCall);
162     // TheCall will be freed by the smart pointer here, but that's fine, since
163     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
164   case Builtin::BI__builtin_prefetch:
165     if (SemaBuiltinPrefetch(TheCall))
166       return ExprError();
167     break;
168   case Builtin::BI__builtin_object_size:
169     if (SemaBuiltinObjectSize(TheCall))
170       return ExprError();
171     break;
172   case Builtin::BI__builtin_longjmp:
173     if (SemaBuiltinLongjmp(TheCall))
174       return ExprError();
175     break;
176 
177   case Builtin::BI__builtin_classify_type:
178     if (checkArgCount(*this, TheCall, 1)) return true;
179     TheCall->setType(Context.IntTy);
180     break;
181   case Builtin::BI__builtin_constant_p:
182     if (checkArgCount(*this, TheCall, 1)) return true;
183     TheCall->setType(Context.IntTy);
184     break;
185   case Builtin::BI__sync_fetch_and_add:
186   case Builtin::BI__sync_fetch_and_sub:
187   case Builtin::BI__sync_fetch_and_or:
188   case Builtin::BI__sync_fetch_and_and:
189   case Builtin::BI__sync_fetch_and_xor:
190   case Builtin::BI__sync_add_and_fetch:
191   case Builtin::BI__sync_sub_and_fetch:
192   case Builtin::BI__sync_and_and_fetch:
193   case Builtin::BI__sync_or_and_fetch:
194   case Builtin::BI__sync_xor_and_fetch:
195   case Builtin::BI__sync_val_compare_and_swap:
196   case Builtin::BI__sync_bool_compare_and_swap:
197   case Builtin::BI__sync_lock_test_and_set:
198   case Builtin::BI__sync_lock_release:
199   case Builtin::BI__sync_swap:
200     return SemaBuiltinAtomicOverloaded(move(TheCallResult));
201   case Builtin::BI__atomic_load:
202     return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Load);
203   case Builtin::BI__atomic_store:
204     return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Store);
205   case Builtin::BI__atomic_exchange:
206     return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xchg);
207   case Builtin::BI__atomic_compare_exchange_strong:
208     return SemaAtomicOpsOverloaded(move(TheCallResult),
209                                    AtomicExpr::CmpXchgStrong);
210   case Builtin::BI__atomic_compare_exchange_weak:
211     return SemaAtomicOpsOverloaded(move(TheCallResult),
212                                    AtomicExpr::CmpXchgWeak);
213   case Builtin::BI__atomic_fetch_add:
214     return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Add);
215   case Builtin::BI__atomic_fetch_sub:
216     return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Sub);
217   case Builtin::BI__atomic_fetch_and:
218     return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::And);
219   case Builtin::BI__atomic_fetch_or:
220     return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Or);
221   case Builtin::BI__atomic_fetch_xor:
222     return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xor);
223   case Builtin::BI__builtin_annotation:
224     if (CheckBuiltinAnnotationString(*this, TheCall->getArg(1)))
225       return ExprError();
226     break;
227   }
228 
229   // Since the target specific builtins for each arch overlap, only check those
230   // of the arch we are compiling for.
231   if (BuiltinID >= Builtin::FirstTSBuiltin) {
232     switch (Context.getTargetInfo().getTriple().getArch()) {
233       case llvm::Triple::arm:
234       case llvm::Triple::thumb:
235         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
236           return ExprError();
237         break;
238       default:
239         break;
240     }
241   }
242 
243   return move(TheCallResult);
244 }
245 
246 // Get the valid immediate range for the specified NEON type code.
247 static unsigned RFT(unsigned t, bool shift = false) {
248   NeonTypeFlags Type(t);
249   int IsQuad = Type.isQuad();
250   switch (Type.getEltType()) {
251   case NeonTypeFlags::Int8:
252   case NeonTypeFlags::Poly8:
253     return shift ? 7 : (8 << IsQuad) - 1;
254   case NeonTypeFlags::Int16:
255   case NeonTypeFlags::Poly16:
256     return shift ? 15 : (4 << IsQuad) - 1;
257   case NeonTypeFlags::Int32:
258     return shift ? 31 : (2 << IsQuad) - 1;
259   case NeonTypeFlags::Int64:
260     return shift ? 63 : (1 << IsQuad) - 1;
261   case NeonTypeFlags::Float16:
262     assert(!shift && "cannot shift float types!");
263     return (4 << IsQuad) - 1;
264   case NeonTypeFlags::Float32:
265     assert(!shift && "cannot shift float types!");
266     return (2 << IsQuad) - 1;
267   }
268   return 0;
269 }
270 
271 /// getNeonEltType - Return the QualType corresponding to the elements of
272 /// the vector type specified by the NeonTypeFlags.  This is used to check
273 /// the pointer arguments for Neon load/store intrinsics.
274 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) {
275   switch (Flags.getEltType()) {
276   case NeonTypeFlags::Int8:
277     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
278   case NeonTypeFlags::Int16:
279     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
280   case NeonTypeFlags::Int32:
281     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
282   case NeonTypeFlags::Int64:
283     return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
284   case NeonTypeFlags::Poly8:
285     return Context.SignedCharTy;
286   case NeonTypeFlags::Poly16:
287     return Context.ShortTy;
288   case NeonTypeFlags::Float16:
289     return Context.UnsignedShortTy;
290   case NeonTypeFlags::Float32:
291     return Context.FloatTy;
292   }
293   return QualType();
294 }
295 
296 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
297   llvm::APSInt Result;
298 
299   unsigned mask = 0;
300   unsigned TV = 0;
301   bool HasPtr = false;
302   bool HasConstPtr = false;
303   switch (BuiltinID) {
304 #define GET_NEON_OVERLOAD_CHECK
305 #include "clang/Basic/arm_neon.inc"
306 #undef GET_NEON_OVERLOAD_CHECK
307   }
308 
309   // For NEON intrinsics which are overloaded on vector element type, validate
310   // the immediate which specifies which variant to emit.
311   unsigned ImmArg = TheCall->getNumArgs()-1;
312   if (mask) {
313     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
314       return true;
315 
316     TV = Result.getLimitedValue(64);
317     if ((TV > 63) || (mask & (1 << TV)) == 0)
318       return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
319         << TheCall->getArg(ImmArg)->getSourceRange();
320   }
321 
322   if (HasPtr || HasConstPtr) {
323     // Check that pointer arguments have the specified type.
324     for (unsigned ArgNo = 0; ArgNo < ImmArg; ++ArgNo) {
325       Expr *Arg = TheCall->getArg(ArgNo);
326       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
327         Arg = ICE->getSubExpr();
328       ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
329       QualType RHSTy = RHS.get()->getType();
330       if (!RHSTy->isPointerType())
331         continue;
332       QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
333       if (HasConstPtr)
334         EltTy = EltTy.withConst();
335       QualType LHSTy = Context.getPointerType(EltTy);
336       AssignConvertType ConvTy;
337       ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
338       if (RHS.isInvalid())
339         return true;
340       if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
341                                    RHS.get(), AA_Assigning))
342         return true;
343     }
344   }
345 
346   // For NEON intrinsics which take an immediate value as part of the
347   // instruction, range check them here.
348   unsigned i = 0, l = 0, u = 0;
349   switch (BuiltinID) {
350   default: return false;
351   case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
352   case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
353   case ARM::BI__builtin_arm_vcvtr_f:
354   case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
355 #define GET_NEON_IMMEDIATE_CHECK
356 #include "clang/Basic/arm_neon.inc"
357 #undef GET_NEON_IMMEDIATE_CHECK
358   };
359 
360   // Check that the immediate argument is actually a constant.
361   if (SemaBuiltinConstantArg(TheCall, i, Result))
362     return true;
363 
364   // Range check against the upper/lower values for this isntruction.
365   unsigned Val = Result.getZExtValue();
366   if (Val < l || Val > (u + l))
367     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
368       << l << u+l << TheCall->getArg(i)->getSourceRange();
369 
370   // FIXME: VFP Intrinsics should error if VFP not present.
371   return false;
372 }
373 
374 /// CheckFunctionCall - Check a direct function call for various correctness
375 /// and safety properties not strictly enforced by the C type system.
376 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
377   // Get the IdentifierInfo* for the called function.
378   IdentifierInfo *FnInfo = FDecl->getIdentifier();
379 
380   // None of the checks below are needed for functions that don't have
381   // simple names (e.g., C++ conversion functions).
382   if (!FnInfo)
383     return false;
384 
385   // FIXME: This mechanism should be abstracted to be less fragile and
386   // more efficient. For example, just map function ids to custom
387   // handlers.
388 
389   // Printf and scanf checking.
390   for (specific_attr_iterator<FormatAttr>
391          i = FDecl->specific_attr_begin<FormatAttr>(),
392          e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
393 
394     const FormatAttr *Format = *i;
395     const bool b = Format->getType() == "scanf";
396     if (b || CheckablePrintfAttr(Format, TheCall)) {
397       bool HasVAListArg = Format->getFirstArg() == 0;
398       CheckPrintfScanfArguments(TheCall, HasVAListArg,
399                                 Format->getFormatIdx() - 1,
400                                 HasVAListArg ? 0 : Format->getFirstArg() - 1,
401                                 !b);
402     }
403   }
404 
405   for (specific_attr_iterator<NonNullAttr>
406          i = FDecl->specific_attr_begin<NonNullAttr>(),
407          e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) {
408     CheckNonNullArguments(*i, TheCall->getArgs(),
409                           TheCall->getCallee()->getLocStart());
410   }
411 
412   // Builtin handling
413   int CMF = -1;
414   switch (FDecl->getBuiltinID()) {
415   case Builtin::BI__builtin_memset:
416   case Builtin::BI__builtin___memset_chk:
417   case Builtin::BImemset:
418     CMF = CMF_Memset;
419     break;
420 
421   case Builtin::BI__builtin_memcpy:
422   case Builtin::BI__builtin___memcpy_chk:
423   case Builtin::BImemcpy:
424     CMF = CMF_Memcpy;
425     break;
426 
427   case Builtin::BI__builtin_memmove:
428   case Builtin::BI__builtin___memmove_chk:
429   case Builtin::BImemmove:
430     CMF = CMF_Memmove;
431     break;
432 
433   case Builtin::BIstrlcpy:
434   case Builtin::BIstrlcat:
435     CheckStrlcpycatArguments(TheCall, FnInfo);
436     break;
437 
438   case Builtin::BI__builtin_memcmp:
439     CMF = CMF_Memcmp;
440     break;
441 
442   case Builtin::BI__builtin_strncpy:
443   case Builtin::BI__builtin___strncpy_chk:
444   case Builtin::BIstrncpy:
445     CMF = CMF_Strncpy;
446     break;
447 
448   case Builtin::BI__builtin_strncmp:
449     CMF = CMF_Strncmp;
450     break;
451 
452   case Builtin::BI__builtin_strncasecmp:
453     CMF = CMF_Strncasecmp;
454     break;
455 
456   case Builtin::BI__builtin_strncat:
457   case Builtin::BIstrncat:
458     CMF = CMF_Strncat;
459     break;
460 
461   case Builtin::BI__builtin_strndup:
462   case Builtin::BIstrndup:
463     CMF = CMF_Strndup;
464     break;
465 
466   default:
467     if (FDecl->getLinkage() == ExternalLinkage &&
468         (!getLangOptions().CPlusPlus || FDecl->isExternC())) {
469       if (FnInfo->isStr("memset"))
470         CMF = CMF_Memset;
471       else if (FnInfo->isStr("memcpy"))
472         CMF = CMF_Memcpy;
473       else if (FnInfo->isStr("memmove"))
474         CMF = CMF_Memmove;
475       else if (FnInfo->isStr("memcmp"))
476         CMF = CMF_Memcmp;
477       else if (FnInfo->isStr("strncpy"))
478         CMF = CMF_Strncpy;
479       else if (FnInfo->isStr("strncmp"))
480         CMF = CMF_Strncmp;
481       else if (FnInfo->isStr("strncasecmp"))
482         CMF = CMF_Strncasecmp;
483       else if (FnInfo->isStr("strncat"))
484         CMF = CMF_Strncat;
485       else if (FnInfo->isStr("strndup"))
486         CMF = CMF_Strndup;
487     }
488     break;
489   }
490 
491   // Memset/memcpy/memmove handling
492   if (CMF != -1)
493     CheckMemaccessArguments(TheCall, CheckedMemoryFunction(CMF), FnInfo);
494 
495   return false;
496 }
497 
498 bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
499   // Printf checking.
500   const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
501   if (!Format)
502     return false;
503 
504   const VarDecl *V = dyn_cast<VarDecl>(NDecl);
505   if (!V)
506     return false;
507 
508   QualType Ty = V->getType();
509   if (!Ty->isBlockPointerType())
510     return false;
511 
512   const bool b = Format->getType() == "scanf";
513   if (!b && !CheckablePrintfAttr(Format, TheCall))
514     return false;
515 
516   bool HasVAListArg = Format->getFirstArg() == 0;
517   CheckPrintfScanfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
518                             HasVAListArg ? 0 : Format->getFirstArg() - 1, !b);
519 
520   return false;
521 }
522 
523 ExprResult
524 Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, AtomicExpr::AtomicOp Op) {
525   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
526   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
527 
528   // All these operations take one of the following four forms:
529   // T   __atomic_load(_Atomic(T)*, int)                              (loads)
530   // T*  __atomic_add(_Atomic(T*)*, ptrdiff_t, int)         (pointer add/sub)
531   // int __atomic_compare_exchange_strong(_Atomic(T)*, T*, T, int, int)
532   //                                                                (cmpxchg)
533   // T   __atomic_exchange(_Atomic(T)*, T, int)             (everything else)
534   // where T is an appropriate type, and the int paremeterss are for orderings.
535   unsigned NumVals = 1;
536   unsigned NumOrders = 1;
537   if (Op == AtomicExpr::Load) {
538     NumVals = 0;
539   } else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong) {
540     NumVals = 2;
541     NumOrders = 2;
542   }
543 
544   if (TheCall->getNumArgs() < NumVals+NumOrders+1) {
545     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
546       << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
547       << TheCall->getCallee()->getSourceRange();
548     return ExprError();
549   } else if (TheCall->getNumArgs() > NumVals+NumOrders+1) {
550     Diag(TheCall->getArg(NumVals+NumOrders+1)->getLocStart(),
551          diag::err_typecheck_call_too_many_args)
552       << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
553       << TheCall->getCallee()->getSourceRange();
554     return ExprError();
555   }
556 
557   // Inspect the first argument of the atomic operation.  This should always be
558   // a pointer to an _Atomic type.
559   Expr *Ptr = TheCall->getArg(0);
560   Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
561   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
562   if (!pointerType) {
563     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
564       << Ptr->getType() << Ptr->getSourceRange();
565     return ExprError();
566   }
567 
568   QualType AtomTy = pointerType->getPointeeType();
569   if (!AtomTy->isAtomicType()) {
570     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
571       << Ptr->getType() << Ptr->getSourceRange();
572     return ExprError();
573   }
574   QualType ValType = AtomTy->getAs<AtomicType>()->getValueType();
575 
576   if ((Op == AtomicExpr::Add || Op == AtomicExpr::Sub) &&
577       !ValType->isIntegerType() && !ValType->isPointerType()) {
578     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
579       << Ptr->getType() << Ptr->getSourceRange();
580     return ExprError();
581   }
582 
583   if (!ValType->isIntegerType() &&
584       (Op == AtomicExpr::And || Op == AtomicExpr::Or || Op == AtomicExpr::Xor)){
585     Diag(DRE->getLocStart(), diag::err_atomic_op_logical_needs_atomic_int)
586       << Ptr->getType() << Ptr->getSourceRange();
587     return ExprError();
588   }
589 
590   switch (ValType.getObjCLifetime()) {
591   case Qualifiers::OCL_None:
592   case Qualifiers::OCL_ExplicitNone:
593     // okay
594     break;
595 
596   case Qualifiers::OCL_Weak:
597   case Qualifiers::OCL_Strong:
598   case Qualifiers::OCL_Autoreleasing:
599     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
600       << ValType << Ptr->getSourceRange();
601     return ExprError();
602   }
603 
604   QualType ResultType = ValType;
605   if (Op == AtomicExpr::Store)
606     ResultType = Context.VoidTy;
607   else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong)
608     ResultType = Context.BoolTy;
609 
610   // The first argument --- the pointer --- has a fixed type; we
611   // deduce the types of the rest of the arguments accordingly.  Walk
612   // the remaining arguments, converting them to the deduced value type.
613   for (unsigned i = 1; i != NumVals+NumOrders+1; ++i) {
614     ExprResult Arg = TheCall->getArg(i);
615     QualType Ty;
616     if (i < NumVals+1) {
617       // The second argument to a cmpxchg is a pointer to the data which will
618       // be exchanged. The second argument to a pointer add/subtract is the
619       // amount to add/subtract, which must be a ptrdiff_t.  The third
620       // argument to a cmpxchg and the second argument in all other cases
621       // is the type of the value.
622       if (i == 1 && (Op == AtomicExpr::CmpXchgWeak ||
623                      Op == AtomicExpr::CmpXchgStrong))
624          Ty = Context.getPointerType(ValType.getUnqualifiedType());
625       else if (!ValType->isIntegerType() &&
626                (Op == AtomicExpr::Add || Op == AtomicExpr::Sub))
627         Ty = Context.getPointerDiffType();
628       else
629         Ty = ValType;
630     } else {
631       // The order(s) are always converted to int.
632       Ty = Context.IntTy;
633     }
634     InitializedEntity Entity =
635         InitializedEntity::InitializeParameter(Context, Ty, false);
636     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
637     if (Arg.isInvalid())
638       return true;
639     TheCall->setArg(i, Arg.get());
640   }
641 
642   SmallVector<Expr*, 5> SubExprs;
643   SubExprs.push_back(Ptr);
644   if (Op == AtomicExpr::Load) {
645     SubExprs.push_back(TheCall->getArg(1)); // Order
646   } else if (Op != AtomicExpr::CmpXchgWeak && Op != AtomicExpr::CmpXchgStrong) {
647     SubExprs.push_back(TheCall->getArg(2)); // Order
648     SubExprs.push_back(TheCall->getArg(1)); // Val1
649   } else {
650     SubExprs.push_back(TheCall->getArg(3)); // Order
651     SubExprs.push_back(TheCall->getArg(1)); // Val1
652     SubExprs.push_back(TheCall->getArg(2)); // Val2
653     SubExprs.push_back(TheCall->getArg(4)); // OrderFail
654   }
655 
656   return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
657                                         SubExprs.data(), SubExprs.size(),
658                                         ResultType, Op,
659                                         TheCall->getRParenLoc()));
660 }
661 
662 
663 /// checkBuiltinArgument - Given a call to a builtin function, perform
664 /// normal type-checking on the given argument, updating the call in
665 /// place.  This is useful when a builtin function requires custom
666 /// type-checking for some of its arguments but not necessarily all of
667 /// them.
668 ///
669 /// Returns true on error.
670 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
671   FunctionDecl *Fn = E->getDirectCallee();
672   assert(Fn && "builtin call without direct callee!");
673 
674   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
675   InitializedEntity Entity =
676     InitializedEntity::InitializeParameter(S.Context, Param);
677 
678   ExprResult Arg = E->getArg(0);
679   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
680   if (Arg.isInvalid())
681     return true;
682 
683   E->setArg(ArgIndex, Arg.take());
684   return false;
685 }
686 
687 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
688 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
689 /// type of its first argument.  The main ActOnCallExpr routines have already
690 /// promoted the types of arguments because all of these calls are prototyped as
691 /// void(...).
692 ///
693 /// This function goes through and does final semantic checking for these
694 /// builtins,
695 ExprResult
696 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
697   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
698   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
699   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
700 
701   // Ensure that we have at least one argument to do type inference from.
702   if (TheCall->getNumArgs() < 1) {
703     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
704       << 0 << 1 << TheCall->getNumArgs()
705       << TheCall->getCallee()->getSourceRange();
706     return ExprError();
707   }
708 
709   // Inspect the first argument of the atomic builtin.  This should always be
710   // a pointer type, whose element is an integral scalar or pointer type.
711   // Because it is a pointer type, we don't have to worry about any implicit
712   // casts here.
713   // FIXME: We don't allow floating point scalars as input.
714   Expr *FirstArg = TheCall->getArg(0);
715   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
716   if (!pointerType) {
717     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
718       << FirstArg->getType() << FirstArg->getSourceRange();
719     return ExprError();
720   }
721 
722   QualType ValType = pointerType->getPointeeType();
723   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
724       !ValType->isBlockPointerType()) {
725     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
726       << FirstArg->getType() << FirstArg->getSourceRange();
727     return ExprError();
728   }
729 
730   switch (ValType.getObjCLifetime()) {
731   case Qualifiers::OCL_None:
732   case Qualifiers::OCL_ExplicitNone:
733     // okay
734     break;
735 
736   case Qualifiers::OCL_Weak:
737   case Qualifiers::OCL_Strong:
738   case Qualifiers::OCL_Autoreleasing:
739     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
740       << ValType << FirstArg->getSourceRange();
741     return ExprError();
742   }
743 
744   // Strip any qualifiers off ValType.
745   ValType = ValType.getUnqualifiedType();
746 
747   // The majority of builtins return a value, but a few have special return
748   // types, so allow them to override appropriately below.
749   QualType ResultType = ValType;
750 
751   // We need to figure out which concrete builtin this maps onto.  For example,
752   // __sync_fetch_and_add with a 2 byte object turns into
753   // __sync_fetch_and_add_2.
754 #define BUILTIN_ROW(x) \
755   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
756     Builtin::BI##x##_8, Builtin::BI##x##_16 }
757 
758   static const unsigned BuiltinIndices[][5] = {
759     BUILTIN_ROW(__sync_fetch_and_add),
760     BUILTIN_ROW(__sync_fetch_and_sub),
761     BUILTIN_ROW(__sync_fetch_and_or),
762     BUILTIN_ROW(__sync_fetch_and_and),
763     BUILTIN_ROW(__sync_fetch_and_xor),
764 
765     BUILTIN_ROW(__sync_add_and_fetch),
766     BUILTIN_ROW(__sync_sub_and_fetch),
767     BUILTIN_ROW(__sync_and_and_fetch),
768     BUILTIN_ROW(__sync_or_and_fetch),
769     BUILTIN_ROW(__sync_xor_and_fetch),
770 
771     BUILTIN_ROW(__sync_val_compare_and_swap),
772     BUILTIN_ROW(__sync_bool_compare_and_swap),
773     BUILTIN_ROW(__sync_lock_test_and_set),
774     BUILTIN_ROW(__sync_lock_release),
775     BUILTIN_ROW(__sync_swap)
776   };
777 #undef BUILTIN_ROW
778 
779   // Determine the index of the size.
780   unsigned SizeIndex;
781   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
782   case 1: SizeIndex = 0; break;
783   case 2: SizeIndex = 1; break;
784   case 4: SizeIndex = 2; break;
785   case 8: SizeIndex = 3; break;
786   case 16: SizeIndex = 4; break;
787   default:
788     Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
789       << FirstArg->getType() << FirstArg->getSourceRange();
790     return ExprError();
791   }
792 
793   // Each of these builtins has one pointer argument, followed by some number of
794   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
795   // that we ignore.  Find out which row of BuiltinIndices to read from as well
796   // as the number of fixed args.
797   unsigned BuiltinID = FDecl->getBuiltinID();
798   unsigned BuiltinIndex, NumFixed = 1;
799   switch (BuiltinID) {
800   default: llvm_unreachable("Unknown overloaded atomic builtin!");
801   case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
802   case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
803   case Builtin::BI__sync_fetch_and_or:  BuiltinIndex = 2; break;
804   case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
805   case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
806 
807   case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break;
808   case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break;
809   case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break;
810   case Builtin::BI__sync_or_and_fetch:  BuiltinIndex = 8; break;
811   case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break;
812 
813   case Builtin::BI__sync_val_compare_and_swap:
814     BuiltinIndex = 10;
815     NumFixed = 2;
816     break;
817   case Builtin::BI__sync_bool_compare_and_swap:
818     BuiltinIndex = 11;
819     NumFixed = 2;
820     ResultType = Context.BoolTy;
821     break;
822   case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break;
823   case Builtin::BI__sync_lock_release:
824     BuiltinIndex = 13;
825     NumFixed = 0;
826     ResultType = Context.VoidTy;
827     break;
828   case Builtin::BI__sync_swap: BuiltinIndex = 14; break;
829   }
830 
831   // Now that we know how many fixed arguments we expect, first check that we
832   // have at least that many.
833   if (TheCall->getNumArgs() < 1+NumFixed) {
834     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
835       << 0 << 1+NumFixed << TheCall->getNumArgs()
836       << TheCall->getCallee()->getSourceRange();
837     return ExprError();
838   }
839 
840   // Get the decl for the concrete builtin from this, we can tell what the
841   // concrete integer type we should convert to is.
842   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
843   const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
844   IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
845   FunctionDecl *NewBuiltinDecl =
846     cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
847                                            TUScope, false, DRE->getLocStart()));
848 
849   // The first argument --- the pointer --- has a fixed type; we
850   // deduce the types of the rest of the arguments accordingly.  Walk
851   // the remaining arguments, converting them to the deduced value type.
852   for (unsigned i = 0; i != NumFixed; ++i) {
853     ExprResult Arg = TheCall->getArg(i+1);
854 
855     // GCC does an implicit conversion to the pointer or integer ValType.  This
856     // can fail in some cases (1i -> int**), check for this error case now.
857     // Initialize the argument.
858     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
859                                                    ValType, /*consume*/ false);
860     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
861     if (Arg.isInvalid())
862       return ExprError();
863 
864     // Okay, we have something that *can* be converted to the right type.  Check
865     // to see if there is a potentially weird extension going on here.  This can
866     // happen when you do an atomic operation on something like an char* and
867     // pass in 42.  The 42 gets converted to char.  This is even more strange
868     // for things like 45.123 -> char, etc.
869     // FIXME: Do this check.
870     TheCall->setArg(i+1, Arg.take());
871   }
872 
873   ASTContext& Context = this->getASTContext();
874 
875   // Create a new DeclRefExpr to refer to the new decl.
876   DeclRefExpr* NewDRE = DeclRefExpr::Create(
877       Context,
878       DRE->getQualifierLoc(),
879       NewBuiltinDecl,
880       DRE->getLocation(),
881       NewBuiltinDecl->getType(),
882       DRE->getValueKind());
883 
884   // Set the callee in the CallExpr.
885   // FIXME: This leaks the original parens and implicit casts.
886   ExprResult PromotedCall = UsualUnaryConversions(NewDRE);
887   if (PromotedCall.isInvalid())
888     return ExprError();
889   TheCall->setCallee(PromotedCall.take());
890 
891   // Change the result type of the call to match the original value type. This
892   // is arbitrary, but the codegen for these builtins ins design to handle it
893   // gracefully.
894   TheCall->setType(ResultType);
895 
896   return move(TheCallResult);
897 }
898 
899 /// CheckObjCString - Checks that the argument to the builtin
900 /// CFString constructor is correct
901 /// Note: It might also make sense to do the UTF-16 conversion here (would
902 /// simplify the backend).
903 bool Sema::CheckObjCString(Expr *Arg) {
904   Arg = Arg->IgnoreParenCasts();
905   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
906 
907   if (!Literal || !Literal->isAscii()) {
908     Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
909       << Arg->getSourceRange();
910     return true;
911   }
912 
913   if (Literal->containsNonAsciiOrNull()) {
914     StringRef String = Literal->getString();
915     unsigned NumBytes = String.size();
916     SmallVector<UTF16, 128> ToBuf(NumBytes);
917     const UTF8 *FromPtr = (UTF8 *)String.data();
918     UTF16 *ToPtr = &ToBuf[0];
919 
920     ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
921                                                  &ToPtr, ToPtr + NumBytes,
922                                                  strictConversion);
923     // Check for conversion failure.
924     if (Result != conversionOK)
925       Diag(Arg->getLocStart(),
926            diag::warn_cfstring_truncated) << Arg->getSourceRange();
927   }
928   return false;
929 }
930 
931 /// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
932 /// Emit an error and return true on failure, return false on success.
933 bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
934   Expr *Fn = TheCall->getCallee();
935   if (TheCall->getNumArgs() > 2) {
936     Diag(TheCall->getArg(2)->getLocStart(),
937          diag::err_typecheck_call_too_many_args)
938       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
939       << Fn->getSourceRange()
940       << SourceRange(TheCall->getArg(2)->getLocStart(),
941                      (*(TheCall->arg_end()-1))->getLocEnd());
942     return true;
943   }
944 
945   if (TheCall->getNumArgs() < 2) {
946     return Diag(TheCall->getLocEnd(),
947       diag::err_typecheck_call_too_few_args_at_least)
948       << 0 /*function call*/ << 2 << TheCall->getNumArgs();
949   }
950 
951   // Type-check the first argument normally.
952   if (checkBuiltinArgument(*this, TheCall, 0))
953     return true;
954 
955   // Determine whether the current function is variadic or not.
956   BlockScopeInfo *CurBlock = getCurBlock();
957   bool isVariadic;
958   if (CurBlock)
959     isVariadic = CurBlock->TheDecl->isVariadic();
960   else if (FunctionDecl *FD = getCurFunctionDecl())
961     isVariadic = FD->isVariadic();
962   else
963     isVariadic = getCurMethodDecl()->isVariadic();
964 
965   if (!isVariadic) {
966     Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
967     return true;
968   }
969 
970   // Verify that the second argument to the builtin is the last argument of the
971   // current function or method.
972   bool SecondArgIsLastNamedArgument = false;
973   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
974 
975   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
976     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
977       // FIXME: This isn't correct for methods (results in bogus warning).
978       // Get the last formal in the current function.
979       const ParmVarDecl *LastArg;
980       if (CurBlock)
981         LastArg = *(CurBlock->TheDecl->param_end()-1);
982       else if (FunctionDecl *FD = getCurFunctionDecl())
983         LastArg = *(FD->param_end()-1);
984       else
985         LastArg = *(getCurMethodDecl()->param_end()-1);
986       SecondArgIsLastNamedArgument = PV == LastArg;
987     }
988   }
989 
990   if (!SecondArgIsLastNamedArgument)
991     Diag(TheCall->getArg(1)->getLocStart(),
992          diag::warn_second_parameter_of_va_start_not_last_named_argument);
993   return false;
994 }
995 
996 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
997 /// friends.  This is declared to take (...), so we have to check everything.
998 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
999   if (TheCall->getNumArgs() < 2)
1000     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
1001       << 0 << 2 << TheCall->getNumArgs()/*function call*/;
1002   if (TheCall->getNumArgs() > 2)
1003     return Diag(TheCall->getArg(2)->getLocStart(),
1004                 diag::err_typecheck_call_too_many_args)
1005       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1006       << SourceRange(TheCall->getArg(2)->getLocStart(),
1007                      (*(TheCall->arg_end()-1))->getLocEnd());
1008 
1009   ExprResult OrigArg0 = TheCall->getArg(0);
1010   ExprResult OrigArg1 = TheCall->getArg(1);
1011 
1012   // Do standard promotions between the two arguments, returning their common
1013   // type.
1014   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
1015   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1016     return true;
1017 
1018   // Make sure any conversions are pushed back into the call; this is
1019   // type safe since unordered compare builtins are declared as "_Bool
1020   // foo(...)".
1021   TheCall->setArg(0, OrigArg0.get());
1022   TheCall->setArg(1, OrigArg1.get());
1023 
1024   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
1025     return false;
1026 
1027   // If the common type isn't a real floating type, then the arguments were
1028   // invalid for this operation.
1029   if (!Res->isRealFloatingType())
1030     return Diag(OrigArg0.get()->getLocStart(),
1031                 diag::err_typecheck_call_invalid_ordered_compare)
1032       << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1033       << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
1034 
1035   return false;
1036 }
1037 
1038 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1039 /// __builtin_isnan and friends.  This is declared to take (...), so we have
1040 /// to check everything. We expect the last argument to be a floating point
1041 /// value.
1042 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1043   if (TheCall->getNumArgs() < NumArgs)
1044     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
1045       << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
1046   if (TheCall->getNumArgs() > NumArgs)
1047     return Diag(TheCall->getArg(NumArgs)->getLocStart(),
1048                 diag::err_typecheck_call_too_many_args)
1049       << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
1050       << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
1051                      (*(TheCall->arg_end()-1))->getLocEnd());
1052 
1053   Expr *OrigArg = TheCall->getArg(NumArgs-1);
1054 
1055   if (OrigArg->isTypeDependent())
1056     return false;
1057 
1058   // This operation requires a non-_Complex floating-point number.
1059   if (!OrigArg->getType()->isRealFloatingType())
1060     return Diag(OrigArg->getLocStart(),
1061                 diag::err_typecheck_call_invalid_unary_fp)
1062       << OrigArg->getType() << OrigArg->getSourceRange();
1063 
1064   // If this is an implicit conversion from float -> double, remove it.
1065   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1066     Expr *CastArg = Cast->getSubExpr();
1067     if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1068       assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1069              "promotion from float to double is the only expected cast here");
1070       Cast->setSubExpr(0);
1071       TheCall->setArg(NumArgs-1, CastArg);
1072       OrigArg = CastArg;
1073     }
1074   }
1075 
1076   return false;
1077 }
1078 
1079 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1080 // This is declared to take (...), so we have to check everything.
1081 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
1082   if (TheCall->getNumArgs() < 2)
1083     return ExprError(Diag(TheCall->getLocEnd(),
1084                           diag::err_typecheck_call_too_few_args_at_least)
1085       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1086       << TheCall->getSourceRange());
1087 
1088   // Determine which of the following types of shufflevector we're checking:
1089   // 1) unary, vector mask: (lhs, mask)
1090   // 2) binary, vector mask: (lhs, rhs, mask)
1091   // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1092   QualType resType = TheCall->getArg(0)->getType();
1093   unsigned numElements = 0;
1094 
1095   if (!TheCall->getArg(0)->isTypeDependent() &&
1096       !TheCall->getArg(1)->isTypeDependent()) {
1097     QualType LHSType = TheCall->getArg(0)->getType();
1098     QualType RHSType = TheCall->getArg(1)->getType();
1099 
1100     if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
1101       Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
1102         << SourceRange(TheCall->getArg(0)->getLocStart(),
1103                        TheCall->getArg(1)->getLocEnd());
1104       return ExprError();
1105     }
1106 
1107     numElements = LHSType->getAs<VectorType>()->getNumElements();
1108     unsigned numResElements = TheCall->getNumArgs() - 2;
1109 
1110     // Check to see if we have a call with 2 vector arguments, the unary shuffle
1111     // with mask.  If so, verify that RHS is an integer vector type with the
1112     // same number of elts as lhs.
1113     if (TheCall->getNumArgs() == 2) {
1114       if (!RHSType->hasIntegerRepresentation() ||
1115           RHSType->getAs<VectorType>()->getNumElements() != numElements)
1116         Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1117           << SourceRange(TheCall->getArg(1)->getLocStart(),
1118                          TheCall->getArg(1)->getLocEnd());
1119       numResElements = numElements;
1120     }
1121     else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
1122       Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1123         << SourceRange(TheCall->getArg(0)->getLocStart(),
1124                        TheCall->getArg(1)->getLocEnd());
1125       return ExprError();
1126     } else if (numElements != numResElements) {
1127       QualType eltType = LHSType->getAs<VectorType>()->getElementType();
1128       resType = Context.getVectorType(eltType, numResElements,
1129                                       VectorType::GenericVector);
1130     }
1131   }
1132 
1133   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
1134     if (TheCall->getArg(i)->isTypeDependent() ||
1135         TheCall->getArg(i)->isValueDependent())
1136       continue;
1137 
1138     llvm::APSInt Result(32);
1139     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1140       return ExprError(Diag(TheCall->getLocStart(),
1141                   diag::err_shufflevector_nonconstant_argument)
1142                 << TheCall->getArg(i)->getSourceRange());
1143 
1144     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
1145       return ExprError(Diag(TheCall->getLocStart(),
1146                   diag::err_shufflevector_argument_too_large)
1147                << TheCall->getArg(i)->getSourceRange());
1148   }
1149 
1150   SmallVector<Expr*, 32> exprs;
1151 
1152   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
1153     exprs.push_back(TheCall->getArg(i));
1154     TheCall->setArg(i, 0);
1155   }
1156 
1157   return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
1158                                             exprs.size(), resType,
1159                                             TheCall->getCallee()->getLocStart(),
1160                                             TheCall->getRParenLoc()));
1161 }
1162 
1163 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1164 // This is declared to take (const void*, ...) and can take two
1165 // optional constant int args.
1166 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
1167   unsigned NumArgs = TheCall->getNumArgs();
1168 
1169   if (NumArgs > 3)
1170     return Diag(TheCall->getLocEnd(),
1171              diag::err_typecheck_call_too_many_args_at_most)
1172              << 0 /*function call*/ << 3 << NumArgs
1173              << TheCall->getSourceRange();
1174 
1175   // Argument 0 is checked for us and the remaining arguments must be
1176   // constant integers.
1177   for (unsigned i = 1; i != NumArgs; ++i) {
1178     Expr *Arg = TheCall->getArg(i);
1179 
1180     llvm::APSInt Result;
1181     if (SemaBuiltinConstantArg(TheCall, i, Result))
1182       return true;
1183 
1184     // FIXME: gcc issues a warning and rewrites these to 0. These
1185     // seems especially odd for the third argument since the default
1186     // is 3.
1187     if (i == 1) {
1188       if (Result.getLimitedValue() > 1)
1189         return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1190              << "0" << "1" << Arg->getSourceRange();
1191     } else {
1192       if (Result.getLimitedValue() > 3)
1193         return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1194             << "0" << "3" << Arg->getSourceRange();
1195     }
1196   }
1197 
1198   return false;
1199 }
1200 
1201 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1202 /// TheCall is a constant expression.
1203 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1204                                   llvm::APSInt &Result) {
1205   Expr *Arg = TheCall->getArg(ArgNum);
1206   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1207   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1208 
1209   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1210 
1211   if (!Arg->isIntegerConstantExpr(Result, Context))
1212     return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
1213                 << FDecl->getDeclName() <<  Arg->getSourceRange();
1214 
1215   return false;
1216 }
1217 
1218 /// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1219 /// int type). This simply type checks that type is one of the defined
1220 /// constants (0-3).
1221 // For compatibility check 0-3, llvm only handles 0 and 2.
1222 bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
1223   llvm::APSInt Result;
1224 
1225   // Check constant-ness first.
1226   if (SemaBuiltinConstantArg(TheCall, 1, Result))
1227     return true;
1228 
1229   Expr *Arg = TheCall->getArg(1);
1230   if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
1231     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1232              << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1233   }
1234 
1235   return false;
1236 }
1237 
1238 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
1239 /// This checks that val is a constant 1.
1240 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1241   Expr *Arg = TheCall->getArg(1);
1242   llvm::APSInt Result;
1243 
1244   // TODO: This is less than ideal. Overload this to take a value.
1245   if (SemaBuiltinConstantArg(TheCall, 1, Result))
1246     return true;
1247 
1248   if (Result != 1)
1249     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1250              << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1251 
1252   return false;
1253 }
1254 
1255 // Handle i > 1 ? "x" : "y", recursively.
1256 bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
1257                                   bool HasVAListArg,
1258                                   unsigned format_idx, unsigned firstDataArg,
1259                                   bool isPrintf, bool inFunctionCall) {
1260  tryAgain:
1261   if (E->isTypeDependent() || E->isValueDependent())
1262     return false;
1263 
1264   E = E->IgnoreParens();
1265 
1266   switch (E->getStmtClass()) {
1267   case Stmt::BinaryConditionalOperatorClass:
1268   case Stmt::ConditionalOperatorClass: {
1269     const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
1270     return SemaCheckStringLiteral(C->getTrueExpr(), TheCall, HasVAListArg,
1271                                   format_idx, firstDataArg, isPrintf,
1272                                   inFunctionCall)
1273         && SemaCheckStringLiteral(C->getFalseExpr(), TheCall, HasVAListArg,
1274                                   format_idx, firstDataArg, isPrintf,
1275                                   inFunctionCall);
1276   }
1277 
1278   case Stmt::IntegerLiteralClass:
1279     // Technically -Wformat-nonliteral does not warn about this case.
1280     // The behavior of printf and friends in this case is implementation
1281     // dependent.  Ideally if the format string cannot be null then
1282     // it should have a 'nonnull' attribute in the function prototype.
1283     return true;
1284 
1285   case Stmt::ImplicitCastExprClass: {
1286     E = cast<ImplicitCastExpr>(E)->getSubExpr();
1287     goto tryAgain;
1288   }
1289 
1290   case Stmt::OpaqueValueExprClass:
1291     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1292       E = src;
1293       goto tryAgain;
1294     }
1295     return false;
1296 
1297   case Stmt::PredefinedExprClass:
1298     // While __func__, etc., are technically not string literals, they
1299     // cannot contain format specifiers and thus are not a security
1300     // liability.
1301     return true;
1302 
1303   case Stmt::DeclRefExprClass: {
1304     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
1305 
1306     // As an exception, do not flag errors for variables binding to
1307     // const string literals.
1308     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1309       bool isConstant = false;
1310       QualType T = DR->getType();
1311 
1312       if (const ArrayType *AT = Context.getAsArrayType(T)) {
1313         isConstant = AT->getElementType().isConstant(Context);
1314       } else if (const PointerType *PT = T->getAs<PointerType>()) {
1315         isConstant = T.isConstant(Context) &&
1316                      PT->getPointeeType().isConstant(Context);
1317       }
1318 
1319       if (isConstant) {
1320         if (const Expr *Init = VD->getAnyInitializer())
1321           return SemaCheckStringLiteral(Init, TheCall,
1322                                         HasVAListArg, format_idx, firstDataArg,
1323                                         isPrintf, /*inFunctionCall*/false);
1324       }
1325 
1326       // For vprintf* functions (i.e., HasVAListArg==true), we add a
1327       // special check to see if the format string is a function parameter
1328       // of the function calling the printf function.  If the function
1329       // has an attribute indicating it is a printf-like function, then we
1330       // should suppress warnings concerning non-literals being used in a call
1331       // to a vprintf function.  For example:
1332       //
1333       // void
1334       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1335       //      va_list ap;
1336       //      va_start(ap, fmt);
1337       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
1338       //      ...
1339       //
1340       //
1341       //  FIXME: We don't have full attribute support yet, so just check to see
1342       //    if the argument is a DeclRefExpr that references a parameter.  We'll
1343       //    add proper support for checking the attribute later.
1344       if (HasVAListArg)
1345         if (isa<ParmVarDecl>(VD))
1346           return true;
1347     }
1348 
1349     return false;
1350   }
1351 
1352   case Stmt::CallExprClass: {
1353     const CallExpr *CE = cast<CallExpr>(E);
1354     if (const ImplicitCastExpr *ICE
1355           = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
1356       if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
1357         if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1358           if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
1359             unsigned ArgIndex = FA->getFormatIdx();
1360             const Expr *Arg = CE->getArg(ArgIndex - 1);
1361 
1362             return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
1363                                           format_idx, firstDataArg, isPrintf,
1364                                           inFunctionCall);
1365           }
1366         }
1367       }
1368     }
1369 
1370     return false;
1371   }
1372   case Stmt::ObjCStringLiteralClass:
1373   case Stmt::StringLiteralClass: {
1374     const StringLiteral *StrE = NULL;
1375 
1376     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
1377       StrE = ObjCFExpr->getString();
1378     else
1379       StrE = cast<StringLiteral>(E);
1380 
1381     if (StrE) {
1382       CheckFormatString(StrE, E, TheCall, HasVAListArg, format_idx,
1383                         firstDataArg, isPrintf, inFunctionCall);
1384       return true;
1385     }
1386 
1387     return false;
1388   }
1389 
1390   default:
1391     return false;
1392   }
1393 }
1394 
1395 void
1396 Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
1397                             const Expr * const *ExprArgs,
1398                             SourceLocation CallSiteLoc) {
1399   for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1400                                   e = NonNull->args_end();
1401        i != e; ++i) {
1402     const Expr *ArgExpr = ExprArgs[*i];
1403     if (ArgExpr->isNullPointerConstant(Context,
1404                                        Expr::NPC_ValueDependentIsNotNull))
1405       Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
1406   }
1407 }
1408 
1409 /// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1410 /// functions) for correct use of format strings.
1411 void
1412 Sema::CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg,
1413                                 unsigned format_idx, unsigned firstDataArg,
1414                                 bool isPrintf) {
1415 
1416   const Expr *Fn = TheCall->getCallee();
1417 
1418   // The way the format attribute works in GCC, the implicit this argument
1419   // of member functions is counted. However, it doesn't appear in our own
1420   // lists, so decrement format_idx in that case.
1421   if (isa<CXXMemberCallExpr>(TheCall)) {
1422     const CXXMethodDecl *method_decl =
1423       dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl());
1424     if (method_decl && method_decl->isInstance()) {
1425       // Catch a format attribute mistakenly referring to the object argument.
1426       if (format_idx == 0)
1427         return;
1428       --format_idx;
1429       if(firstDataArg != 0)
1430         --firstDataArg;
1431     }
1432   }
1433 
1434   // CHECK: printf/scanf-like function is called with no format string.
1435   if (format_idx >= TheCall->getNumArgs()) {
1436     Diag(TheCall->getRParenLoc(), diag::warn_missing_format_string)
1437       << Fn->getSourceRange();
1438     return;
1439   }
1440 
1441   const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
1442 
1443   // CHECK: format string is not a string literal.
1444   //
1445   // Dynamically generated format strings are difficult to
1446   // automatically vet at compile time.  Requiring that format strings
1447   // are string literals: (1) permits the checking of format strings by
1448   // the compiler and thereby (2) can practically remove the source of
1449   // many format string exploits.
1450 
1451   // Format string can be either ObjC string (e.g. @"%d") or
1452   // C string (e.g. "%d")
1453   // ObjC string uses the same format specifiers as C string, so we can use
1454   // the same format string checking logic for both ObjC and C strings.
1455   if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
1456                              firstDataArg, isPrintf))
1457     return;  // Literal format string found, check done!
1458 
1459   // If there are no arguments specified, warn with -Wformat-security, otherwise
1460   // warn only with -Wformat-nonliteral.
1461   if (TheCall->getNumArgs() == format_idx+1)
1462     Diag(TheCall->getArg(format_idx)->getLocStart(),
1463          diag::warn_format_nonliteral_noargs)
1464       << OrigFormatExpr->getSourceRange();
1465   else
1466     Diag(TheCall->getArg(format_idx)->getLocStart(),
1467          diag::warn_format_nonliteral)
1468            << OrigFormatExpr->getSourceRange();
1469 }
1470 
1471 namespace {
1472 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1473 protected:
1474   Sema &S;
1475   const StringLiteral *FExpr;
1476   const Expr *OrigFormatExpr;
1477   const unsigned FirstDataArg;
1478   const unsigned NumDataArgs;
1479   const bool IsObjCLiteral;
1480   const char *Beg; // Start of format string.
1481   const bool HasVAListArg;
1482   const CallExpr *TheCall;
1483   unsigned FormatIdx;
1484   llvm::BitVector CoveredArgs;
1485   bool usesPositionalArgs;
1486   bool atFirstArg;
1487   bool inFunctionCall;
1488 public:
1489   CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
1490                      const Expr *origFormatExpr, unsigned firstDataArg,
1491                      unsigned numDataArgs, bool isObjCLiteral,
1492                      const char *beg, bool hasVAListArg,
1493                      const CallExpr *theCall, unsigned formatIdx,
1494                      bool inFunctionCall)
1495     : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
1496       FirstDataArg(firstDataArg),
1497       NumDataArgs(numDataArgs),
1498       IsObjCLiteral(isObjCLiteral), Beg(beg),
1499       HasVAListArg(hasVAListArg),
1500       TheCall(theCall), FormatIdx(formatIdx),
1501       usesPositionalArgs(false), atFirstArg(true),
1502       inFunctionCall(inFunctionCall) {
1503         CoveredArgs.resize(numDataArgs);
1504         CoveredArgs.reset();
1505       }
1506 
1507   void DoneProcessing();
1508 
1509   void HandleIncompleteSpecifier(const char *startSpecifier,
1510                                  unsigned specifierLen);
1511 
1512   virtual void HandleInvalidPosition(const char *startSpecifier,
1513                                      unsigned specifierLen,
1514                                      analyze_format_string::PositionContext p);
1515 
1516   virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1517 
1518   void HandleNullChar(const char *nullCharacter);
1519 
1520   template <typename Range>
1521   static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
1522                                    const Expr *ArgumentExpr,
1523                                    PartialDiagnostic PDiag,
1524                                    SourceLocation StringLoc,
1525                                    bool IsStringLocation, Range StringRange,
1526                                    FixItHint Fixit = FixItHint());
1527 
1528 protected:
1529   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1530                                         const char *startSpec,
1531                                         unsigned specifierLen,
1532                                         const char *csStart, unsigned csLen);
1533 
1534   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
1535                                          const char *startSpec,
1536                                          unsigned specifierLen);
1537 
1538   SourceRange getFormatStringRange();
1539   CharSourceRange getSpecifierRange(const char *startSpecifier,
1540                                     unsigned specifierLen);
1541   SourceLocation getLocationOfByte(const char *x);
1542 
1543   const Expr *getDataArg(unsigned i) const;
1544 
1545   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1546                     const analyze_format_string::ConversionSpecifier &CS,
1547                     const char *startSpecifier, unsigned specifierLen,
1548                     unsigned argIndex);
1549 
1550   template <typename Range>
1551   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
1552                             bool IsStringLocation, Range StringRange,
1553                             FixItHint Fixit = FixItHint());
1554 
1555   void CheckPositionalAndNonpositionalArgs(
1556       const analyze_format_string::FormatSpecifier *FS);
1557 };
1558 }
1559 
1560 SourceRange CheckFormatHandler::getFormatStringRange() {
1561   return OrigFormatExpr->getSourceRange();
1562 }
1563 
1564 CharSourceRange CheckFormatHandler::
1565 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
1566   SourceLocation Start = getLocationOfByte(startSpecifier);
1567   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
1568 
1569   // Advance the end SourceLocation by one due to half-open ranges.
1570   End = End.getLocWithOffset(1);
1571 
1572   return CharSourceRange::getCharRange(Start, End);
1573 }
1574 
1575 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
1576   return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
1577 }
1578 
1579 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1580                                                    unsigned specifierLen){
1581   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
1582                        getLocationOfByte(startSpecifier),
1583                        /*IsStringLocation*/true,
1584                        getSpecifierRange(startSpecifier, specifierLen));
1585 }
1586 
1587 void
1588 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1589                                      analyze_format_string::PositionContext p) {
1590   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
1591                          << (unsigned) p,
1592                        getLocationOfByte(startPos), /*IsStringLocation*/true,
1593                        getSpecifierRange(startPos, posLen));
1594 }
1595 
1596 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
1597                                             unsigned posLen) {
1598   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
1599                                getLocationOfByte(startPos),
1600                                /*IsStringLocation*/true,
1601                                getSpecifierRange(startPos, posLen));
1602 }
1603 
1604 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
1605   if (!IsObjCLiteral) {
1606     // The presence of a null character is likely an error.
1607     EmitFormatDiagnostic(
1608       S.PDiag(diag::warn_printf_format_string_contains_null_char),
1609       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
1610       getFormatStringRange());
1611   }
1612 }
1613 
1614 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
1615   return TheCall->getArg(FirstDataArg + i);
1616 }
1617 
1618 void CheckFormatHandler::DoneProcessing() {
1619     // Does the number of data arguments exceed the number of
1620     // format conversions in the format string?
1621   if (!HasVAListArg) {
1622       // Find any arguments that weren't covered.
1623     CoveredArgs.flip();
1624     signed notCoveredArg = CoveredArgs.find_first();
1625     if (notCoveredArg >= 0) {
1626       assert((unsigned)notCoveredArg < NumDataArgs);
1627       EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
1628                            getDataArg((unsigned) notCoveredArg)->getLocStart(),
1629                            /*IsStringLocation*/false, getFormatStringRange());
1630     }
1631   }
1632 }
1633 
1634 bool
1635 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1636                                                      SourceLocation Loc,
1637                                                      const char *startSpec,
1638                                                      unsigned specifierLen,
1639                                                      const char *csStart,
1640                                                      unsigned csLen) {
1641 
1642   bool keepGoing = true;
1643   if (argIndex < NumDataArgs) {
1644     // Consider the argument coverered, even though the specifier doesn't
1645     // make sense.
1646     CoveredArgs.set(argIndex);
1647   }
1648   else {
1649     // If argIndex exceeds the number of data arguments we
1650     // don't issue a warning because that is just a cascade of warnings (and
1651     // they may have intended '%%' anyway). We don't want to continue processing
1652     // the format string after this point, however, as we will like just get
1653     // gibberish when trying to match arguments.
1654     keepGoing = false;
1655   }
1656 
1657   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
1658                          << StringRef(csStart, csLen),
1659                        Loc, /*IsStringLocation*/true,
1660                        getSpecifierRange(startSpec, specifierLen));
1661 
1662   return keepGoing;
1663 }
1664 
1665 void
1666 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
1667                                                       const char *startSpec,
1668                                                       unsigned specifierLen) {
1669   EmitFormatDiagnostic(
1670     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
1671     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
1672 }
1673 
1674 bool
1675 CheckFormatHandler::CheckNumArgs(
1676   const analyze_format_string::FormatSpecifier &FS,
1677   const analyze_format_string::ConversionSpecifier &CS,
1678   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1679 
1680   if (argIndex >= NumDataArgs) {
1681     PartialDiagnostic PDiag = FS.usesPositionalArg()
1682       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
1683            << (argIndex+1) << NumDataArgs)
1684       : S.PDiag(diag::warn_printf_insufficient_data_args);
1685     EmitFormatDiagnostic(
1686       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
1687       getSpecifierRange(startSpecifier, specifierLen));
1688     return false;
1689   }
1690   return true;
1691 }
1692 
1693 template<typename Range>
1694 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
1695                                               SourceLocation Loc,
1696                                               bool IsStringLocation,
1697                                               Range StringRange,
1698                                               FixItHint FixIt) {
1699   EmitFormatDiagnostic(S, inFunctionCall, TheCall->getArg(FormatIdx), PDiag,
1700                        Loc, IsStringLocation, StringRange, FixIt);
1701 }
1702 
1703 /// \brief If the format string is not within the funcion call, emit a note
1704 /// so that the function call and string are in diagnostic messages.
1705 ///
1706 /// \param inFunctionCall if true, the format string is within the function
1707 /// call and only one diagnostic message will be produced.  Otherwise, an
1708 /// extra note will be emitted pointing to location of the format string.
1709 ///
1710 /// \param ArgumentExpr the expression that is passed as the format string
1711 /// argument in the function call.  Used for getting locations when two
1712 /// diagnostics are emitted.
1713 ///
1714 /// \param PDiag the callee should already have provided any strings for the
1715 /// diagnostic message.  This function only adds locations and fixits
1716 /// to diagnostics.
1717 ///
1718 /// \param Loc primary location for diagnostic.  If two diagnostics are
1719 /// required, one will be at Loc and a new SourceLocation will be created for
1720 /// the other one.
1721 ///
1722 /// \param IsStringLocation if true, Loc points to the format string should be
1723 /// used for the note.  Otherwise, Loc points to the argument list and will
1724 /// be used with PDiag.
1725 ///
1726 /// \param StringRange some or all of the string to highlight.  This is
1727 /// templated so it can accept either a CharSourceRange or a SourceRange.
1728 ///
1729 /// \param Fixit optional fix it hint for the format string.
1730 template<typename Range>
1731 void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
1732                                               const Expr *ArgumentExpr,
1733                                               PartialDiagnostic PDiag,
1734                                               SourceLocation Loc,
1735                                               bool IsStringLocation,
1736                                               Range StringRange,
1737                                               FixItHint FixIt) {
1738   if (InFunctionCall)
1739     S.Diag(Loc, PDiag) << StringRange << FixIt;
1740   else {
1741     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
1742       << ArgumentExpr->getSourceRange();
1743     S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
1744            diag::note_format_string_defined)
1745       << StringRange << FixIt;
1746   }
1747 }
1748 
1749 //===--- CHECK: Printf format string checking ------------------------------===//
1750 
1751 namespace {
1752 class CheckPrintfHandler : public CheckFormatHandler {
1753 public:
1754   CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1755                      const Expr *origFormatExpr, unsigned firstDataArg,
1756                      unsigned numDataArgs, bool isObjCLiteral,
1757                      const char *beg, bool hasVAListArg,
1758                      const CallExpr *theCall, unsigned formatIdx,
1759                      bool inFunctionCall)
1760   : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1761                        numDataArgs, isObjCLiteral, beg, hasVAListArg,
1762                        theCall, formatIdx, inFunctionCall) {}
1763 
1764 
1765   bool HandleInvalidPrintfConversionSpecifier(
1766                                       const analyze_printf::PrintfSpecifier &FS,
1767                                       const char *startSpecifier,
1768                                       unsigned specifierLen);
1769 
1770   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1771                              const char *startSpecifier,
1772                              unsigned specifierLen);
1773 
1774   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1775                     const char *startSpecifier, unsigned specifierLen);
1776   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1777                            const analyze_printf::OptionalAmount &Amt,
1778                            unsigned type,
1779                            const char *startSpecifier, unsigned specifierLen);
1780   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1781                   const analyze_printf::OptionalFlag &flag,
1782                   const char *startSpecifier, unsigned specifierLen);
1783   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1784                          const analyze_printf::OptionalFlag &ignoredFlag,
1785                          const analyze_printf::OptionalFlag &flag,
1786                          const char *startSpecifier, unsigned specifierLen);
1787 };
1788 }
1789 
1790 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1791                                       const analyze_printf::PrintfSpecifier &FS,
1792                                       const char *startSpecifier,
1793                                       unsigned specifierLen) {
1794   const analyze_printf::PrintfConversionSpecifier &CS =
1795     FS.getConversionSpecifier();
1796 
1797   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1798                                           getLocationOfByte(CS.getStart()),
1799                                           startSpecifier, specifierLen,
1800                                           CS.getStart(), CS.getLength());
1801 }
1802 
1803 bool CheckPrintfHandler::HandleAmount(
1804                                const analyze_format_string::OptionalAmount &Amt,
1805                                unsigned k, const char *startSpecifier,
1806                                unsigned specifierLen) {
1807 
1808   if (Amt.hasDataArgument()) {
1809     if (!HasVAListArg) {
1810       unsigned argIndex = Amt.getArgIndex();
1811       if (argIndex >= NumDataArgs) {
1812         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
1813                                << k,
1814                              getLocationOfByte(Amt.getStart()),
1815                              /*IsStringLocation*/true,
1816                              getSpecifierRange(startSpecifier, specifierLen));
1817         // Don't do any more checking.  We will just emit
1818         // spurious errors.
1819         return false;
1820       }
1821 
1822       // Type check the data argument.  It should be an 'int'.
1823       // Although not in conformance with C99, we also allow the argument to be
1824       // an 'unsigned int' as that is a reasonably safe case.  GCC also
1825       // doesn't emit a warning for that case.
1826       CoveredArgs.set(argIndex);
1827       const Expr *Arg = getDataArg(argIndex);
1828       QualType T = Arg->getType();
1829 
1830       const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1831       assert(ATR.isValid());
1832 
1833       if (!ATR.matchesType(S.Context, T)) {
1834         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
1835                                << k << ATR.getRepresentativeType(S.Context)
1836                                << T << Arg->getSourceRange(),
1837                              getLocationOfByte(Amt.getStart()),
1838                              /*IsStringLocation*/true,
1839                              getSpecifierRange(startSpecifier, specifierLen));
1840         // Don't do any more checking.  We will just emit
1841         // spurious errors.
1842         return false;
1843       }
1844     }
1845   }
1846   return true;
1847 }
1848 
1849 void CheckPrintfHandler::HandleInvalidAmount(
1850                                       const analyze_printf::PrintfSpecifier &FS,
1851                                       const analyze_printf::OptionalAmount &Amt,
1852                                       unsigned type,
1853                                       const char *startSpecifier,
1854                                       unsigned specifierLen) {
1855   const analyze_printf::PrintfConversionSpecifier &CS =
1856     FS.getConversionSpecifier();
1857 
1858   FixItHint fixit =
1859     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
1860       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
1861                                  Amt.getConstantLength()))
1862       : FixItHint();
1863 
1864   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
1865                          << type << CS.toString(),
1866                        getLocationOfByte(Amt.getStart()),
1867                        /*IsStringLocation*/true,
1868                        getSpecifierRange(startSpecifier, specifierLen),
1869                        fixit);
1870 }
1871 
1872 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1873                                     const analyze_printf::OptionalFlag &flag,
1874                                     const char *startSpecifier,
1875                                     unsigned specifierLen) {
1876   // Warn about pointless flag with a fixit removal.
1877   const analyze_printf::PrintfConversionSpecifier &CS =
1878     FS.getConversionSpecifier();
1879   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
1880                          << flag.toString() << CS.toString(),
1881                        getLocationOfByte(flag.getPosition()),
1882                        /*IsStringLocation*/true,
1883                        getSpecifierRange(startSpecifier, specifierLen),
1884                        FixItHint::CreateRemoval(
1885                          getSpecifierRange(flag.getPosition(), 1)));
1886 }
1887 
1888 void CheckPrintfHandler::HandleIgnoredFlag(
1889                                 const analyze_printf::PrintfSpecifier &FS,
1890                                 const analyze_printf::OptionalFlag &ignoredFlag,
1891                                 const analyze_printf::OptionalFlag &flag,
1892                                 const char *startSpecifier,
1893                                 unsigned specifierLen) {
1894   // Warn about ignored flag with a fixit removal.
1895   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
1896                          << ignoredFlag.toString() << flag.toString(),
1897                        getLocationOfByte(ignoredFlag.getPosition()),
1898                        /*IsStringLocation*/true,
1899                        getSpecifierRange(startSpecifier, specifierLen),
1900                        FixItHint::CreateRemoval(
1901                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
1902 }
1903 
1904 bool
1905 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
1906                                             &FS,
1907                                           const char *startSpecifier,
1908                                           unsigned specifierLen) {
1909 
1910   using namespace analyze_format_string;
1911   using namespace analyze_printf;
1912   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
1913 
1914   if (FS.consumesDataArgument()) {
1915     if (atFirstArg) {
1916         atFirstArg = false;
1917         usesPositionalArgs = FS.usesPositionalArg();
1918     }
1919     else if (usesPositionalArgs != FS.usesPositionalArg()) {
1920       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
1921                                         startSpecifier, specifierLen);
1922       return false;
1923     }
1924   }
1925 
1926   // First check if the field width, precision, and conversion specifier
1927   // have matching data arguments.
1928   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
1929                     startSpecifier, specifierLen)) {
1930     return false;
1931   }
1932 
1933   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
1934                     startSpecifier, specifierLen)) {
1935     return false;
1936   }
1937 
1938   if (!CS.consumesDataArgument()) {
1939     // FIXME: Technically specifying a precision or field width here
1940     // makes no sense.  Worth issuing a warning at some point.
1941     return true;
1942   }
1943 
1944   // Consume the argument.
1945   unsigned argIndex = FS.getArgIndex();
1946   if (argIndex < NumDataArgs) {
1947     // The check to see if the argIndex is valid will come later.
1948     // We set the bit here because we may exit early from this
1949     // function if we encounter some other error.
1950     CoveredArgs.set(argIndex);
1951   }
1952 
1953   // Check for using an Objective-C specific conversion specifier
1954   // in a non-ObjC literal.
1955   if (!IsObjCLiteral && CS.isObjCArg()) {
1956     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
1957                                                   specifierLen);
1958   }
1959 
1960   // Check for invalid use of field width
1961   if (!FS.hasValidFieldWidth()) {
1962     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
1963         startSpecifier, specifierLen);
1964   }
1965 
1966   // Check for invalid use of precision
1967   if (!FS.hasValidPrecision()) {
1968     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
1969         startSpecifier, specifierLen);
1970   }
1971 
1972   // Check each flag does not conflict with any other component.
1973   if (!FS.hasValidThousandsGroupingPrefix())
1974     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
1975   if (!FS.hasValidLeadingZeros())
1976     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
1977   if (!FS.hasValidPlusPrefix())
1978     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
1979   if (!FS.hasValidSpacePrefix())
1980     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
1981   if (!FS.hasValidAlternativeForm())
1982     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
1983   if (!FS.hasValidLeftJustified())
1984     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
1985 
1986   // Check that flags are not ignored by another flag
1987   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
1988     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
1989         startSpecifier, specifierLen);
1990   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
1991     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
1992             startSpecifier, specifierLen);
1993 
1994   // Check the length modifier is valid with the given conversion specifier.
1995   const LengthModifier &LM = FS.getLengthModifier();
1996   if (!FS.hasValidLengthModifier())
1997     EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
1998                            << LM.toString() << CS.toString(),
1999                          getLocationOfByte(LM.getStart()),
2000                          /*IsStringLocation*/true,
2001                          getSpecifierRange(startSpecifier, specifierLen),
2002                          FixItHint::CreateRemoval(
2003                            getSpecifierRange(LM.getStart(),
2004                                              LM.getLength())));
2005 
2006   // Are we using '%n'?
2007   if (CS.getKind() == ConversionSpecifier::nArg) {
2008     // Issue a warning about this being a possible security issue.
2009     EmitFormatDiagnostic(S.PDiag(diag::warn_printf_write_back),
2010                          getLocationOfByte(CS.getStart()),
2011                          /*IsStringLocation*/true,
2012                          getSpecifierRange(startSpecifier, specifierLen));
2013     // Continue checking the other format specifiers.
2014     return true;
2015   }
2016 
2017   // The remaining checks depend on the data arguments.
2018   if (HasVAListArg)
2019     return true;
2020 
2021   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
2022     return false;
2023 
2024   // Now type check the data expression that matches the
2025   // format specifier.
2026   const Expr *Ex = getDataArg(argIndex);
2027   const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
2028   if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
2029     // Check if we didn't match because of an implicit cast from a 'char'
2030     // or 'short' to an 'int'.  This is done because printf is a varargs
2031     // function.
2032     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
2033       if (ICE->getType() == S.Context.IntTy) {
2034         // All further checking is done on the subexpression.
2035         Ex = ICE->getSubExpr();
2036         if (ATR.matchesType(S.Context, Ex->getType()))
2037           return true;
2038       }
2039 
2040     // We may be able to offer a FixItHint if it is a supported type.
2041     PrintfSpecifier fixedFS = FS;
2042     bool success = fixedFS.fixType(Ex->getType(), S.getLangOptions());
2043 
2044     if (success) {
2045       // Get the fix string from the fixed format specifier
2046       llvm::SmallString<128> buf;
2047       llvm::raw_svector_ostream os(buf);
2048       fixedFS.toString(os);
2049 
2050       // FIXME: getRepresentativeType() perhaps should return a string
2051       // instead of a QualType to better handle when the representative
2052       // type is 'wint_t' (which is defined in the system headers).
2053       EmitFormatDiagnostic(
2054         S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2055           << ATR.getRepresentativeType(S.Context) << Ex->getType()
2056           << Ex->getSourceRange(),
2057         getLocationOfByte(CS.getStart()),
2058         /*IsStringLocation*/true,
2059         getSpecifierRange(startSpecifier, specifierLen),
2060         FixItHint::CreateReplacement(
2061           getSpecifierRange(startSpecifier, specifierLen),
2062           os.str()));
2063     }
2064     else {
2065       S.Diag(getLocationOfByte(CS.getStart()),
2066              diag::warn_printf_conversion_argument_type_mismatch)
2067         << ATR.getRepresentativeType(S.Context) << Ex->getType()
2068         << getSpecifierRange(startSpecifier, specifierLen)
2069         << Ex->getSourceRange();
2070     }
2071   }
2072 
2073   return true;
2074 }
2075 
2076 //===--- CHECK: Scanf format string checking ------------------------------===//
2077 
2078 namespace {
2079 class CheckScanfHandler : public CheckFormatHandler {
2080 public:
2081   CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
2082                     const Expr *origFormatExpr, unsigned firstDataArg,
2083                     unsigned numDataArgs, bool isObjCLiteral,
2084                     const char *beg, bool hasVAListArg,
2085                     const CallExpr *theCall, unsigned formatIdx,
2086                     bool inFunctionCall)
2087   : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2088                        numDataArgs, isObjCLiteral, beg, hasVAListArg,
2089                        theCall, formatIdx, inFunctionCall) {}
2090 
2091   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
2092                             const char *startSpecifier,
2093                             unsigned specifierLen);
2094 
2095   bool HandleInvalidScanfConversionSpecifier(
2096           const analyze_scanf::ScanfSpecifier &FS,
2097           const char *startSpecifier,
2098           unsigned specifierLen);
2099 
2100   void HandleIncompleteScanList(const char *start, const char *end);
2101 };
2102 }
2103 
2104 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
2105                                                  const char *end) {
2106   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
2107                        getLocationOfByte(end), /*IsStringLocation*/true,
2108                        getSpecifierRange(start, end - start));
2109 }
2110 
2111 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
2112                                         const analyze_scanf::ScanfSpecifier &FS,
2113                                         const char *startSpecifier,
2114                                         unsigned specifierLen) {
2115 
2116   const analyze_scanf::ScanfConversionSpecifier &CS =
2117     FS.getConversionSpecifier();
2118 
2119   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2120                                           getLocationOfByte(CS.getStart()),
2121                                           startSpecifier, specifierLen,
2122                                           CS.getStart(), CS.getLength());
2123 }
2124 
2125 bool CheckScanfHandler::HandleScanfSpecifier(
2126                                        const analyze_scanf::ScanfSpecifier &FS,
2127                                        const char *startSpecifier,
2128                                        unsigned specifierLen) {
2129 
2130   using namespace analyze_scanf;
2131   using namespace analyze_format_string;
2132 
2133   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
2134 
2135   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
2136   // be used to decide if we are using positional arguments consistently.
2137   if (FS.consumesDataArgument()) {
2138     if (atFirstArg) {
2139       atFirstArg = false;
2140       usesPositionalArgs = FS.usesPositionalArg();
2141     }
2142     else if (usesPositionalArgs != FS.usesPositionalArg()) {
2143       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2144                                         startSpecifier, specifierLen);
2145       return false;
2146     }
2147   }
2148 
2149   // Check if the field with is non-zero.
2150   const OptionalAmount &Amt = FS.getFieldWidth();
2151   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
2152     if (Amt.getConstantAmount() == 0) {
2153       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
2154                                                    Amt.getConstantLength());
2155       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
2156                            getLocationOfByte(Amt.getStart()),
2157                            /*IsStringLocation*/true, R,
2158                            FixItHint::CreateRemoval(R));
2159     }
2160   }
2161 
2162   if (!FS.consumesDataArgument()) {
2163     // FIXME: Technically specifying a precision or field width here
2164     // makes no sense.  Worth issuing a warning at some point.
2165     return true;
2166   }
2167 
2168   // Consume the argument.
2169   unsigned argIndex = FS.getArgIndex();
2170   if (argIndex < NumDataArgs) {
2171       // The check to see if the argIndex is valid will come later.
2172       // We set the bit here because we may exit early from this
2173       // function if we encounter some other error.
2174     CoveredArgs.set(argIndex);
2175   }
2176 
2177   // Check the length modifier is valid with the given conversion specifier.
2178   const LengthModifier &LM = FS.getLengthModifier();
2179   if (!FS.hasValidLengthModifier()) {
2180     S.Diag(getLocationOfByte(LM.getStart()),
2181            diag::warn_format_nonsensical_length)
2182       << LM.toString() << CS.toString()
2183       << getSpecifierRange(startSpecifier, specifierLen)
2184       << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
2185                                                     LM.getLength()));
2186   }
2187 
2188   // The remaining checks depend on the data arguments.
2189   if (HasVAListArg)
2190     return true;
2191 
2192   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
2193     return false;
2194 
2195   // FIXME: Check that the argument type matches the format specifier.
2196 
2197   return true;
2198 }
2199 
2200 void Sema::CheckFormatString(const StringLiteral *FExpr,
2201                              const Expr *OrigFormatExpr,
2202                              const CallExpr *TheCall, bool HasVAListArg,
2203                              unsigned format_idx, unsigned firstDataArg,
2204                              bool isPrintf, bool inFunctionCall) {
2205 
2206   // CHECK: is the format string a wide literal?
2207   if (!FExpr->isAscii()) {
2208     CheckFormatHandler::EmitFormatDiagnostic(
2209       *this, inFunctionCall, TheCall->getArg(format_idx),
2210       PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
2211       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
2212     return;
2213   }
2214 
2215   // Str - The format string.  NOTE: this is NOT null-terminated!
2216   StringRef StrRef = FExpr->getString();
2217   const char *Str = StrRef.data();
2218   unsigned StrLen = StrRef.size();
2219   const unsigned numDataArgs = TheCall->getNumArgs() - firstDataArg;
2220 
2221   // CHECK: empty format string?
2222   if (StrLen == 0 && numDataArgs > 0) {
2223     CheckFormatHandler::EmitFormatDiagnostic(
2224       *this, inFunctionCall, TheCall->getArg(format_idx),
2225       PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
2226       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
2227     return;
2228   }
2229 
2230   if (isPrintf) {
2231     CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
2232                          numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
2233                          Str, HasVAListArg, TheCall, format_idx,
2234                          inFunctionCall);
2235 
2236     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen))
2237       H.DoneProcessing();
2238   }
2239   else {
2240     CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
2241                         numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
2242                         Str, HasVAListArg, TheCall, format_idx,
2243                         inFunctionCall);
2244 
2245     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen))
2246       H.DoneProcessing();
2247   }
2248 }
2249 
2250 //===--- CHECK: Standard memory functions ---------------------------------===//
2251 
2252 /// \brief Determine whether the given type is a dynamic class type (e.g.,
2253 /// whether it has a vtable).
2254 static bool isDynamicClassType(QualType T) {
2255   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
2256     if (CXXRecordDecl *Definition = Record->getDefinition())
2257       if (Definition->isDynamicClass())
2258         return true;
2259 
2260   return false;
2261 }
2262 
2263 /// \brief If E is a sizeof expression, returns its argument expression,
2264 /// otherwise returns NULL.
2265 static const Expr *getSizeOfExprArg(const Expr* E) {
2266   if (const UnaryExprOrTypeTraitExpr *SizeOf =
2267       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2268     if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
2269       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
2270 
2271   return 0;
2272 }
2273 
2274 /// \brief If E is a sizeof expression, returns its argument type.
2275 static QualType getSizeOfArgType(const Expr* E) {
2276   if (const UnaryExprOrTypeTraitExpr *SizeOf =
2277       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2278     if (SizeOf->getKind() == clang::UETT_SizeOf)
2279       return SizeOf->getTypeOfArgument();
2280 
2281   return QualType();
2282 }
2283 
2284 /// \brief Check for dangerous or invalid arguments to memset().
2285 ///
2286 /// This issues warnings on known problematic, dangerous or unspecified
2287 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
2288 /// function calls.
2289 ///
2290 /// \param Call The call expression to diagnose.
2291 void Sema::CheckMemaccessArguments(const CallExpr *Call,
2292                                    CheckedMemoryFunction CMF,
2293                                    IdentifierInfo *FnName) {
2294   // It is possible to have a non-standard definition of memset.  Validate
2295   // we have enough arguments, and if not, abort further checking.
2296   unsigned ExpectedNumArgs = (CMF == CMF_Strndup ? 2 : 3);
2297   if (Call->getNumArgs() < ExpectedNumArgs)
2298     return;
2299 
2300   unsigned LastArg = (CMF == CMF_Memset || CMF == CMF_Strndup ? 1 : 2);
2301   unsigned LenArg = (CMF == CMF_Strndup ? 1 : 2);
2302   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
2303 
2304   // We have special checking when the length is a sizeof expression.
2305   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
2306   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
2307   llvm::FoldingSetNodeID SizeOfArgID;
2308 
2309   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
2310     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
2311     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
2312 
2313     QualType DestTy = Dest->getType();
2314     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
2315       QualType PointeeTy = DestPtrTy->getPointeeType();
2316 
2317       // Never warn about void type pointers. This can be used to suppress
2318       // false positives.
2319       if (PointeeTy->isVoidType())
2320         continue;
2321 
2322       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
2323       // actually comparing the expressions for equality. Because computing the
2324       // expression IDs can be expensive, we only do this if the diagnostic is
2325       // enabled.
2326       if (SizeOfArg &&
2327           Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
2328                                    SizeOfArg->getExprLoc())) {
2329         // We only compute IDs for expressions if the warning is enabled, and
2330         // cache the sizeof arg's ID.
2331         if (SizeOfArgID == llvm::FoldingSetNodeID())
2332           SizeOfArg->Profile(SizeOfArgID, Context, true);
2333         llvm::FoldingSetNodeID DestID;
2334         Dest->Profile(DestID, Context, true);
2335         if (DestID == SizeOfArgID) {
2336           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
2337           //       over sizeof(src) as well.
2338           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
2339           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
2340             if (UnaryOp->getOpcode() == UO_AddrOf)
2341               ActionIdx = 1; // If its an address-of operator, just remove it.
2342           if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
2343             ActionIdx = 2; // If the pointee's size is sizeof(char),
2344                            // suggest an explicit length.
2345           unsigned DestSrcSelect = (CMF == CMF_Strndup ? 1 : ArgIdx);
2346           DiagRuntimeBehavior(SizeOfArg->getExprLoc(), Dest,
2347                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
2348                                 << FnName << DestSrcSelect << ActionIdx
2349                                 << Dest->getSourceRange()
2350                                 << SizeOfArg->getSourceRange());
2351           break;
2352         }
2353       }
2354 
2355       // Also check for cases where the sizeof argument is the exact same
2356       // type as the memory argument, and where it points to a user-defined
2357       // record type.
2358       if (SizeOfArgTy != QualType()) {
2359         if (PointeeTy->isRecordType() &&
2360             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
2361           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
2362                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
2363                                 << FnName << SizeOfArgTy << ArgIdx
2364                                 << PointeeTy << Dest->getSourceRange()
2365                                 << LenExpr->getSourceRange());
2366           break;
2367         }
2368       }
2369 
2370       // Always complain about dynamic classes.
2371       if (isDynamicClassType(PointeeTy))
2372         DiagRuntimeBehavior(
2373           Dest->getExprLoc(), Dest,
2374           PDiag(diag::warn_dyn_class_memaccess)
2375             << (CMF == CMF_Memcmp ? ArgIdx + 2 : ArgIdx) << FnName << PointeeTy
2376             // "overwritten" if we're warning about the destination for any call
2377             // but memcmp; otherwise a verb appropriate to the call.
2378             << (ArgIdx == 0 && CMF != CMF_Memcmp ? 0 : (unsigned)CMF)
2379             << Call->getCallee()->getSourceRange());
2380       else if (PointeeTy.hasNonTrivialObjCLifetime() && CMF != CMF_Memset)
2381         DiagRuntimeBehavior(
2382           Dest->getExprLoc(), Dest,
2383           PDiag(diag::warn_arc_object_memaccess)
2384             << ArgIdx << FnName << PointeeTy
2385             << Call->getCallee()->getSourceRange());
2386       else
2387         continue;
2388 
2389       DiagRuntimeBehavior(
2390         Dest->getExprLoc(), Dest,
2391         PDiag(diag::note_bad_memaccess_silence)
2392           << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
2393       break;
2394     }
2395   }
2396 }
2397 
2398 // A little helper routine: ignore addition and subtraction of integer literals.
2399 // This intentionally does not ignore all integer constant expressions because
2400 // we don't want to remove sizeof().
2401 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
2402   Ex = Ex->IgnoreParenCasts();
2403 
2404   for (;;) {
2405     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
2406     if (!BO || !BO->isAdditiveOp())
2407       break;
2408 
2409     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
2410     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
2411 
2412     if (isa<IntegerLiteral>(RHS))
2413       Ex = LHS;
2414     else if (isa<IntegerLiteral>(LHS))
2415       Ex = RHS;
2416     else
2417       break;
2418   }
2419 
2420   return Ex;
2421 }
2422 
2423 // Warn if the user has made the 'size' argument to strlcpy or strlcat
2424 // be the size of the source, instead of the destination.
2425 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
2426                                     IdentifierInfo *FnName) {
2427 
2428   // Don't crash if the user has the wrong number of arguments
2429   if (Call->getNumArgs() != 3)
2430     return;
2431 
2432   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
2433   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
2434   const Expr *CompareWithSrc = NULL;
2435 
2436   // Look for 'strlcpy(dst, x, sizeof(x))'
2437   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
2438     CompareWithSrc = Ex;
2439   else {
2440     // Look for 'strlcpy(dst, x, strlen(x))'
2441     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
2442       if (SizeCall->isBuiltinCall(Context) == Builtin::BIstrlen
2443           && SizeCall->getNumArgs() == 1)
2444         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
2445     }
2446   }
2447 
2448   if (!CompareWithSrc)
2449     return;
2450 
2451   // Determine if the argument to sizeof/strlen is equal to the source
2452   // argument.  In principle there's all kinds of things you could do
2453   // here, for instance creating an == expression and evaluating it with
2454   // EvaluateAsBooleanCondition, but this uses a more direct technique:
2455   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
2456   if (!SrcArgDRE)
2457     return;
2458 
2459   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
2460   if (!CompareWithSrcDRE ||
2461       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
2462     return;
2463 
2464   const Expr *OriginalSizeArg = Call->getArg(2);
2465   Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
2466     << OriginalSizeArg->getSourceRange() << FnName;
2467 
2468   // Output a FIXIT hint if the destination is an array (rather than a
2469   // pointer to an array).  This could be enhanced to handle some
2470   // pointers if we know the actual size, like if DstArg is 'array+2'
2471   // we could say 'sizeof(array)-2'.
2472   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
2473   QualType DstArgTy = DstArg->getType();
2474 
2475   // Only handle constant-sized or VLAs, but not flexible members.
2476   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
2477     // Only issue the FIXIT for arrays of size > 1.
2478     if (CAT->getSize().getSExtValue() <= 1)
2479       return;
2480   } else if (!DstArgTy->isVariableArrayType()) {
2481     return;
2482   }
2483 
2484   llvm::SmallString<128> sizeString;
2485   llvm::raw_svector_ostream OS(sizeString);
2486   OS << "sizeof(";
2487   DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
2488   OS << ")";
2489 
2490   Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
2491     << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
2492                                     OS.str());
2493 }
2494 
2495 //===--- CHECK: Return Address of Stack Variable --------------------------===//
2496 
2497 static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars);
2498 static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars);
2499 
2500 /// CheckReturnStackAddr - Check if a return statement returns the address
2501 ///   of a stack variable.
2502 void
2503 Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
2504                            SourceLocation ReturnLoc) {
2505 
2506   Expr *stackE = 0;
2507   SmallVector<DeclRefExpr *, 8> refVars;
2508 
2509   // Perform checking for returned stack addresses, local blocks,
2510   // label addresses or references to temporaries.
2511   if (lhsType->isPointerType() ||
2512       (!getLangOptions().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
2513     stackE = EvalAddr(RetValExp, refVars);
2514   } else if (lhsType->isReferenceType()) {
2515     stackE = EvalVal(RetValExp, refVars);
2516   }
2517 
2518   if (stackE == 0)
2519     return; // Nothing suspicious was found.
2520 
2521   SourceLocation diagLoc;
2522   SourceRange diagRange;
2523   if (refVars.empty()) {
2524     diagLoc = stackE->getLocStart();
2525     diagRange = stackE->getSourceRange();
2526   } else {
2527     // We followed through a reference variable. 'stackE' contains the
2528     // problematic expression but we will warn at the return statement pointing
2529     // at the reference variable. We will later display the "trail" of
2530     // reference variables using notes.
2531     diagLoc = refVars[0]->getLocStart();
2532     diagRange = refVars[0]->getSourceRange();
2533   }
2534 
2535   if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
2536     Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
2537                                              : diag::warn_ret_stack_addr)
2538      << DR->getDecl()->getDeclName() << diagRange;
2539   } else if (isa<BlockExpr>(stackE)) { // local block.
2540     Diag(diagLoc, diag::err_ret_local_block) << diagRange;
2541   } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
2542     Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
2543   } else { // local temporary.
2544     Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
2545                                              : diag::warn_ret_local_temp_addr)
2546      << diagRange;
2547   }
2548 
2549   // Display the "trail" of reference variables that we followed until we
2550   // found the problematic expression using notes.
2551   for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
2552     VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
2553     // If this var binds to another reference var, show the range of the next
2554     // var, otherwise the var binds to the problematic expression, in which case
2555     // show the range of the expression.
2556     SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
2557                                   : stackE->getSourceRange();
2558     Diag(VD->getLocation(), diag::note_ref_var_local_bind)
2559       << VD->getDeclName() << range;
2560   }
2561 }
2562 
2563 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
2564 ///  check if the expression in a return statement evaluates to an address
2565 ///  to a location on the stack, a local block, an address of a label, or a
2566 ///  reference to local temporary. The recursion is used to traverse the
2567 ///  AST of the return expression, with recursion backtracking when we
2568 ///  encounter a subexpression that (1) clearly does not lead to one of the
2569 ///  above problematic expressions (2) is something we cannot determine leads to
2570 ///  a problematic expression based on such local checking.
2571 ///
2572 ///  Both EvalAddr and EvalVal follow through reference variables to evaluate
2573 ///  the expression that they point to. Such variables are added to the
2574 ///  'refVars' vector so that we know what the reference variable "trail" was.
2575 ///
2576 ///  EvalAddr processes expressions that are pointers that are used as
2577 ///  references (and not L-values).  EvalVal handles all other values.
2578 ///  At the base case of the recursion is a check for the above problematic
2579 ///  expressions.
2580 ///
2581 ///  This implementation handles:
2582 ///
2583 ///   * pointer-to-pointer casts
2584 ///   * implicit conversions from array references to pointers
2585 ///   * taking the address of fields
2586 ///   * arbitrary interplay between "&" and "*" operators
2587 ///   * pointer arithmetic from an address of a stack variable
2588 ///   * taking the address of an array element where the array is on the stack
2589 static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
2590   if (E->isTypeDependent())
2591       return NULL;
2592 
2593   // We should only be called for evaluating pointer expressions.
2594   assert((E->getType()->isAnyPointerType() ||
2595           E->getType()->isBlockPointerType() ||
2596           E->getType()->isObjCQualifiedIdType()) &&
2597          "EvalAddr only works on pointers");
2598 
2599   E = E->IgnoreParens();
2600 
2601   // Our "symbolic interpreter" is just a dispatch off the currently
2602   // viewed AST node.  We then recursively traverse the AST by calling
2603   // EvalAddr and EvalVal appropriately.
2604   switch (E->getStmtClass()) {
2605   case Stmt::DeclRefExprClass: {
2606     DeclRefExpr *DR = cast<DeclRefExpr>(E);
2607 
2608     if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
2609       // If this is a reference variable, follow through to the expression that
2610       // it points to.
2611       if (V->hasLocalStorage() &&
2612           V->getType()->isReferenceType() && V->hasInit()) {
2613         // Add the reference variable to the "trail".
2614         refVars.push_back(DR);
2615         return EvalAddr(V->getInit(), refVars);
2616       }
2617 
2618     return NULL;
2619   }
2620 
2621   case Stmt::UnaryOperatorClass: {
2622     // The only unary operator that make sense to handle here
2623     // is AddrOf.  All others don't make sense as pointers.
2624     UnaryOperator *U = cast<UnaryOperator>(E);
2625 
2626     if (U->getOpcode() == UO_AddrOf)
2627       return EvalVal(U->getSubExpr(), refVars);
2628     else
2629       return NULL;
2630   }
2631 
2632   case Stmt::BinaryOperatorClass: {
2633     // Handle pointer arithmetic.  All other binary operators are not valid
2634     // in this context.
2635     BinaryOperator *B = cast<BinaryOperator>(E);
2636     BinaryOperatorKind op = B->getOpcode();
2637 
2638     if (op != BO_Add && op != BO_Sub)
2639       return NULL;
2640 
2641     Expr *Base = B->getLHS();
2642 
2643     // Determine which argument is the real pointer base.  It could be
2644     // the RHS argument instead of the LHS.
2645     if (!Base->getType()->isPointerType()) Base = B->getRHS();
2646 
2647     assert (Base->getType()->isPointerType());
2648     return EvalAddr(Base, refVars);
2649   }
2650 
2651   // For conditional operators we need to see if either the LHS or RHS are
2652   // valid DeclRefExpr*s.  If one of them is valid, we return it.
2653   case Stmt::ConditionalOperatorClass: {
2654     ConditionalOperator *C = cast<ConditionalOperator>(E);
2655 
2656     // Handle the GNU extension for missing LHS.
2657     if (Expr *lhsExpr = C->getLHS()) {
2658     // In C++, we can have a throw-expression, which has 'void' type.
2659       if (!lhsExpr->getType()->isVoidType())
2660         if (Expr* LHS = EvalAddr(lhsExpr, refVars))
2661           return LHS;
2662     }
2663 
2664     // In C++, we can have a throw-expression, which has 'void' type.
2665     if (C->getRHS()->getType()->isVoidType())
2666       return NULL;
2667 
2668     return EvalAddr(C->getRHS(), refVars);
2669   }
2670 
2671   case Stmt::BlockExprClass:
2672     if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
2673       return E; // local block.
2674     return NULL;
2675 
2676   case Stmt::AddrLabelExprClass:
2677     return E; // address of label.
2678 
2679   // For casts, we need to handle conversions from arrays to
2680   // pointer values, and pointer-to-pointer conversions.
2681   case Stmt::ImplicitCastExprClass:
2682   case Stmt::CStyleCastExprClass:
2683   case Stmt::CXXFunctionalCastExprClass:
2684   case Stmt::ObjCBridgedCastExprClass: {
2685     Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
2686     QualType T = SubExpr->getType();
2687 
2688     if (SubExpr->getType()->isPointerType() ||
2689         SubExpr->getType()->isBlockPointerType() ||
2690         SubExpr->getType()->isObjCQualifiedIdType())
2691       return EvalAddr(SubExpr, refVars);
2692     else if (T->isArrayType())
2693       return EvalVal(SubExpr, refVars);
2694     else
2695       return 0;
2696   }
2697 
2698   // C++ casts.  For dynamic casts, static casts, and const casts, we
2699   // are always converting from a pointer-to-pointer, so we just blow
2700   // through the cast.  In the case the dynamic cast doesn't fail (and
2701   // return NULL), we take the conservative route and report cases
2702   // where we return the address of a stack variable.  For Reinterpre
2703   // FIXME: The comment about is wrong; we're not always converting
2704   // from pointer to pointer. I'm guessing that this code should also
2705   // handle references to objects.
2706   case Stmt::CXXStaticCastExprClass:
2707   case Stmt::CXXDynamicCastExprClass:
2708   case Stmt::CXXConstCastExprClass:
2709   case Stmt::CXXReinterpretCastExprClass: {
2710       Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
2711       if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
2712         return EvalAddr(S, refVars);
2713       else
2714         return NULL;
2715   }
2716 
2717   case Stmt::MaterializeTemporaryExprClass:
2718     if (Expr *Result = EvalAddr(
2719                          cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
2720                                 refVars))
2721       return Result;
2722 
2723     return E;
2724 
2725   // Everything else: we simply don't reason about them.
2726   default:
2727     return NULL;
2728   }
2729 }
2730 
2731 
2732 ///  EvalVal - This function is complements EvalAddr in the mutual recursion.
2733 ///   See the comments for EvalAddr for more details.
2734 static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
2735 do {
2736   // We should only be called for evaluating non-pointer expressions, or
2737   // expressions with a pointer type that are not used as references but instead
2738   // are l-values (e.g., DeclRefExpr with a pointer type).
2739 
2740   // Our "symbolic interpreter" is just a dispatch off the currently
2741   // viewed AST node.  We then recursively traverse the AST by calling
2742   // EvalAddr and EvalVal appropriately.
2743 
2744   E = E->IgnoreParens();
2745   switch (E->getStmtClass()) {
2746   case Stmt::ImplicitCastExprClass: {
2747     ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
2748     if (IE->getValueKind() == VK_LValue) {
2749       E = IE->getSubExpr();
2750       continue;
2751     }
2752     return NULL;
2753   }
2754 
2755   case Stmt::DeclRefExprClass: {
2756     // When we hit a DeclRefExpr we are looking at code that refers to a
2757     // variable's name. If it's not a reference variable we check if it has
2758     // local storage within the function, and if so, return the expression.
2759     DeclRefExpr *DR = cast<DeclRefExpr>(E);
2760 
2761     if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
2762       if (V->hasLocalStorage()) {
2763         if (!V->getType()->isReferenceType())
2764           return DR;
2765 
2766         // Reference variable, follow through to the expression that
2767         // it points to.
2768         if (V->hasInit()) {
2769           // Add the reference variable to the "trail".
2770           refVars.push_back(DR);
2771           return EvalVal(V->getInit(), refVars);
2772         }
2773       }
2774 
2775     return NULL;
2776   }
2777 
2778   case Stmt::UnaryOperatorClass: {
2779     // The only unary operator that make sense to handle here
2780     // is Deref.  All others don't resolve to a "name."  This includes
2781     // handling all sorts of rvalues passed to a unary operator.
2782     UnaryOperator *U = cast<UnaryOperator>(E);
2783 
2784     if (U->getOpcode() == UO_Deref)
2785       return EvalAddr(U->getSubExpr(), refVars);
2786 
2787     return NULL;
2788   }
2789 
2790   case Stmt::ArraySubscriptExprClass: {
2791     // Array subscripts are potential references to data on the stack.  We
2792     // retrieve the DeclRefExpr* for the array variable if it indeed
2793     // has local storage.
2794     return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
2795   }
2796 
2797   case Stmt::ConditionalOperatorClass: {
2798     // For conditional operators we need to see if either the LHS or RHS are
2799     // non-NULL Expr's.  If one is non-NULL, we return it.
2800     ConditionalOperator *C = cast<ConditionalOperator>(E);
2801 
2802     // Handle the GNU extension for missing LHS.
2803     if (Expr *lhsExpr = C->getLHS())
2804       if (Expr *LHS = EvalVal(lhsExpr, refVars))
2805         return LHS;
2806 
2807     return EvalVal(C->getRHS(), refVars);
2808   }
2809 
2810   // Accesses to members are potential references to data on the stack.
2811   case Stmt::MemberExprClass: {
2812     MemberExpr *M = cast<MemberExpr>(E);
2813 
2814     // Check for indirect access.  We only want direct field accesses.
2815     if (M->isArrow())
2816       return NULL;
2817 
2818     // Check whether the member type is itself a reference, in which case
2819     // we're not going to refer to the member, but to what the member refers to.
2820     if (M->getMemberDecl()->getType()->isReferenceType())
2821       return NULL;
2822 
2823     return EvalVal(M->getBase(), refVars);
2824   }
2825 
2826   case Stmt::MaterializeTemporaryExprClass:
2827     if (Expr *Result = EvalVal(
2828                           cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
2829                                refVars))
2830       return Result;
2831 
2832     return E;
2833 
2834   default:
2835     // Check that we don't return or take the address of a reference to a
2836     // temporary. This is only useful in C++.
2837     if (!E->isTypeDependent() && E->isRValue())
2838       return E;
2839 
2840     // Everything else: we simply don't reason about them.
2841     return NULL;
2842   }
2843 } while (true);
2844 }
2845 
2846 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
2847 
2848 /// Check for comparisons of floating point operands using != and ==.
2849 /// Issue a warning if these are no self-comparisons, as they are not likely
2850 /// to do what the programmer intended.
2851 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
2852   bool EmitWarning = true;
2853 
2854   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
2855   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
2856 
2857   // Special case: check for x == x (which is OK).
2858   // Do not emit warnings for such cases.
2859   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
2860     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
2861       if (DRL->getDecl() == DRR->getDecl())
2862         EmitWarning = false;
2863 
2864 
2865   // Special case: check for comparisons against literals that can be exactly
2866   //  represented by APFloat.  In such cases, do not emit a warning.  This
2867   //  is a heuristic: often comparison against such literals are used to
2868   //  detect if a value in a variable has not changed.  This clearly can
2869   //  lead to false negatives.
2870   if (EmitWarning) {
2871     if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
2872       if (FLL->isExact())
2873         EmitWarning = false;
2874     } else
2875       if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
2876         if (FLR->isExact())
2877           EmitWarning = false;
2878     }
2879   }
2880 
2881   // Check for comparisons with builtin types.
2882   if (EmitWarning)
2883     if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
2884       if (CL->isBuiltinCall(Context))
2885         EmitWarning = false;
2886 
2887   if (EmitWarning)
2888     if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
2889       if (CR->isBuiltinCall(Context))
2890         EmitWarning = false;
2891 
2892   // Emit the diagnostic.
2893   if (EmitWarning)
2894     Diag(Loc, diag::warn_floatingpoint_eq)
2895       << LHS->getSourceRange() << RHS->getSourceRange();
2896 }
2897 
2898 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
2899 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
2900 
2901 namespace {
2902 
2903 /// Structure recording the 'active' range of an integer-valued
2904 /// expression.
2905 struct IntRange {
2906   /// The number of bits active in the int.
2907   unsigned Width;
2908 
2909   /// True if the int is known not to have negative values.
2910   bool NonNegative;
2911 
2912   IntRange(unsigned Width, bool NonNegative)
2913     : Width(Width), NonNegative(NonNegative)
2914   {}
2915 
2916   /// Returns the range of the bool type.
2917   static IntRange forBoolType() {
2918     return IntRange(1, true);
2919   }
2920 
2921   /// Returns the range of an opaque value of the given integral type.
2922   static IntRange forValueOfType(ASTContext &C, QualType T) {
2923     return forValueOfCanonicalType(C,
2924                           T->getCanonicalTypeInternal().getTypePtr());
2925   }
2926 
2927   /// Returns the range of an opaque value of a canonical integral type.
2928   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
2929     assert(T->isCanonicalUnqualified());
2930 
2931     if (const VectorType *VT = dyn_cast<VectorType>(T))
2932       T = VT->getElementType().getTypePtr();
2933     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2934       T = CT->getElementType().getTypePtr();
2935 
2936     // For enum types, use the known bit width of the enumerators.
2937     if (const EnumType *ET = dyn_cast<EnumType>(T)) {
2938       EnumDecl *Enum = ET->getDecl();
2939       if (!Enum->isCompleteDefinition())
2940         return IntRange(C.getIntWidth(QualType(T, 0)), false);
2941 
2942       unsigned NumPositive = Enum->getNumPositiveBits();
2943       unsigned NumNegative = Enum->getNumNegativeBits();
2944 
2945       return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
2946     }
2947 
2948     const BuiltinType *BT = cast<BuiltinType>(T);
2949     assert(BT->isInteger());
2950 
2951     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2952   }
2953 
2954   /// Returns the "target" range of a canonical integral type, i.e.
2955   /// the range of values expressible in the type.
2956   ///
2957   /// This matches forValueOfCanonicalType except that enums have the
2958   /// full range of their type, not the range of their enumerators.
2959   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
2960     assert(T->isCanonicalUnqualified());
2961 
2962     if (const VectorType *VT = dyn_cast<VectorType>(T))
2963       T = VT->getElementType().getTypePtr();
2964     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2965       T = CT->getElementType().getTypePtr();
2966     if (const EnumType *ET = dyn_cast<EnumType>(T))
2967       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
2968 
2969     const BuiltinType *BT = cast<BuiltinType>(T);
2970     assert(BT->isInteger());
2971 
2972     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2973   }
2974 
2975   /// Returns the supremum of two ranges: i.e. their conservative merge.
2976   static IntRange join(IntRange L, IntRange R) {
2977     return IntRange(std::max(L.Width, R.Width),
2978                     L.NonNegative && R.NonNegative);
2979   }
2980 
2981   /// Returns the infinum of two ranges: i.e. their aggressive merge.
2982   static IntRange meet(IntRange L, IntRange R) {
2983     return IntRange(std::min(L.Width, R.Width),
2984                     L.NonNegative || R.NonNegative);
2985   }
2986 };
2987 
2988 IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
2989   if (value.isSigned() && value.isNegative())
2990     return IntRange(value.getMinSignedBits(), false);
2991 
2992   if (value.getBitWidth() > MaxWidth)
2993     value = value.trunc(MaxWidth);
2994 
2995   // isNonNegative() just checks the sign bit without considering
2996   // signedness.
2997   return IntRange(value.getActiveBits(), true);
2998 }
2999 
3000 IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
3001                        unsigned MaxWidth) {
3002   if (result.isInt())
3003     return GetValueRange(C, result.getInt(), MaxWidth);
3004 
3005   if (result.isVector()) {
3006     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
3007     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
3008       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
3009       R = IntRange::join(R, El);
3010     }
3011     return R;
3012   }
3013 
3014   if (result.isComplexInt()) {
3015     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
3016     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
3017     return IntRange::join(R, I);
3018   }
3019 
3020   // This can happen with lossless casts to intptr_t of "based" lvalues.
3021   // Assume it might use arbitrary bits.
3022   // FIXME: The only reason we need to pass the type in here is to get
3023   // the sign right on this one case.  It would be nice if APValue
3024   // preserved this.
3025   assert(result.isLValue());
3026   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
3027 }
3028 
3029 /// Pseudo-evaluate the given integer expression, estimating the
3030 /// range of values it might take.
3031 ///
3032 /// \param MaxWidth - the width to which the value will be truncated
3033 IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
3034   E = E->IgnoreParens();
3035 
3036   // Try a full evaluation first.
3037   Expr::EvalResult result;
3038   if (E->EvaluateAsRValue(result, C))
3039     return GetValueRange(C, result.Val, E->getType(), MaxWidth);
3040 
3041   // I think we only want to look through implicit casts here; if the
3042   // user has an explicit widening cast, we should treat the value as
3043   // being of the new, wider type.
3044   if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
3045     if (CE->getCastKind() == CK_NoOp)
3046       return GetExprRange(C, CE->getSubExpr(), MaxWidth);
3047 
3048     IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
3049 
3050     bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
3051 
3052     // Assume that non-integer casts can span the full range of the type.
3053     if (!isIntegerCast)
3054       return OutputTypeRange;
3055 
3056     IntRange SubRange
3057       = GetExprRange(C, CE->getSubExpr(),
3058                      std::min(MaxWidth, OutputTypeRange.Width));
3059 
3060     // Bail out if the subexpr's range is as wide as the cast type.
3061     if (SubRange.Width >= OutputTypeRange.Width)
3062       return OutputTypeRange;
3063 
3064     // Otherwise, we take the smaller width, and we're non-negative if
3065     // either the output type or the subexpr is.
3066     return IntRange(SubRange.Width,
3067                     SubRange.NonNegative || OutputTypeRange.NonNegative);
3068   }
3069 
3070   if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3071     // If we can fold the condition, just take that operand.
3072     bool CondResult;
3073     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
3074       return GetExprRange(C, CondResult ? CO->getTrueExpr()
3075                                         : CO->getFalseExpr(),
3076                           MaxWidth);
3077 
3078     // Otherwise, conservatively merge.
3079     IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
3080     IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
3081     return IntRange::join(L, R);
3082   }
3083 
3084   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3085     switch (BO->getOpcode()) {
3086 
3087     // Boolean-valued operations are single-bit and positive.
3088     case BO_LAnd:
3089     case BO_LOr:
3090     case BO_LT:
3091     case BO_GT:
3092     case BO_LE:
3093     case BO_GE:
3094     case BO_EQ:
3095     case BO_NE:
3096       return IntRange::forBoolType();
3097 
3098     // The type of the assignments is the type of the LHS, so the RHS
3099     // is not necessarily the same type.
3100     case BO_MulAssign:
3101     case BO_DivAssign:
3102     case BO_RemAssign:
3103     case BO_AddAssign:
3104     case BO_SubAssign:
3105     case BO_XorAssign:
3106     case BO_OrAssign:
3107       // TODO: bitfields?
3108       return IntRange::forValueOfType(C, E->getType());
3109 
3110     // Simple assignments just pass through the RHS, which will have
3111     // been coerced to the LHS type.
3112     case BO_Assign:
3113       // TODO: bitfields?
3114       return GetExprRange(C, BO->getRHS(), MaxWidth);
3115 
3116     // Operations with opaque sources are black-listed.
3117     case BO_PtrMemD:
3118     case BO_PtrMemI:
3119       return IntRange::forValueOfType(C, E->getType());
3120 
3121     // Bitwise-and uses the *infinum* of the two source ranges.
3122     case BO_And:
3123     case BO_AndAssign:
3124       return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
3125                             GetExprRange(C, BO->getRHS(), MaxWidth));
3126 
3127     // Left shift gets black-listed based on a judgement call.
3128     case BO_Shl:
3129       // ...except that we want to treat '1 << (blah)' as logically
3130       // positive.  It's an important idiom.
3131       if (IntegerLiteral *I
3132             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
3133         if (I->getValue() == 1) {
3134           IntRange R = IntRange::forValueOfType(C, E->getType());
3135           return IntRange(R.Width, /*NonNegative*/ true);
3136         }
3137       }
3138       // fallthrough
3139 
3140     case BO_ShlAssign:
3141       return IntRange::forValueOfType(C, E->getType());
3142 
3143     // Right shift by a constant can narrow its left argument.
3144     case BO_Shr:
3145     case BO_ShrAssign: {
3146       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3147 
3148       // If the shift amount is a positive constant, drop the width by
3149       // that much.
3150       llvm::APSInt shift;
3151       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
3152           shift.isNonNegative()) {
3153         unsigned zext = shift.getZExtValue();
3154         if (zext >= L.Width)
3155           L.Width = (L.NonNegative ? 0 : 1);
3156         else
3157           L.Width -= zext;
3158       }
3159 
3160       return L;
3161     }
3162 
3163     // Comma acts as its right operand.
3164     case BO_Comma:
3165       return GetExprRange(C, BO->getRHS(), MaxWidth);
3166 
3167     // Black-list pointer subtractions.
3168     case BO_Sub:
3169       if (BO->getLHS()->getType()->isPointerType())
3170         return IntRange::forValueOfType(C, E->getType());
3171       break;
3172 
3173     // The width of a division result is mostly determined by the size
3174     // of the LHS.
3175     case BO_Div: {
3176       // Don't 'pre-truncate' the operands.
3177       unsigned opWidth = C.getIntWidth(E->getType());
3178       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3179 
3180       // If the divisor is constant, use that.
3181       llvm::APSInt divisor;
3182       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
3183         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
3184         if (log2 >= L.Width)
3185           L.Width = (L.NonNegative ? 0 : 1);
3186         else
3187           L.Width = std::min(L.Width - log2, MaxWidth);
3188         return L;
3189       }
3190 
3191       // Otherwise, just use the LHS's width.
3192       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3193       return IntRange(L.Width, L.NonNegative && R.NonNegative);
3194     }
3195 
3196     // The result of a remainder can't be larger than the result of
3197     // either side.
3198     case BO_Rem: {
3199       // Don't 'pre-truncate' the operands.
3200       unsigned opWidth = C.getIntWidth(E->getType());
3201       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3202       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3203 
3204       IntRange meet = IntRange::meet(L, R);
3205       meet.Width = std::min(meet.Width, MaxWidth);
3206       return meet;
3207     }
3208 
3209     // The default behavior is okay for these.
3210     case BO_Mul:
3211     case BO_Add:
3212     case BO_Xor:
3213     case BO_Or:
3214       break;
3215     }
3216 
3217     // The default case is to treat the operation as if it were closed
3218     // on the narrowest type that encompasses both operands.
3219     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3220     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
3221     return IntRange::join(L, R);
3222   }
3223 
3224   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
3225     switch (UO->getOpcode()) {
3226     // Boolean-valued operations are white-listed.
3227     case UO_LNot:
3228       return IntRange::forBoolType();
3229 
3230     // Operations with opaque sources are black-listed.
3231     case UO_Deref:
3232     case UO_AddrOf: // should be impossible
3233       return IntRange::forValueOfType(C, E->getType());
3234 
3235     default:
3236       return GetExprRange(C, UO->getSubExpr(), MaxWidth);
3237     }
3238   }
3239 
3240   if (dyn_cast<OffsetOfExpr>(E)) {
3241     IntRange::forValueOfType(C, E->getType());
3242   }
3243 
3244   if (FieldDecl *BitField = E->getBitField())
3245     return IntRange(BitField->getBitWidthValue(C),
3246                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
3247 
3248   return IntRange::forValueOfType(C, E->getType());
3249 }
3250 
3251 IntRange GetExprRange(ASTContext &C, Expr *E) {
3252   return GetExprRange(C, E, C.getIntWidth(E->getType()));
3253 }
3254 
3255 /// Checks whether the given value, which currently has the given
3256 /// source semantics, has the same value when coerced through the
3257 /// target semantics.
3258 bool IsSameFloatAfterCast(const llvm::APFloat &value,
3259                           const llvm::fltSemantics &Src,
3260                           const llvm::fltSemantics &Tgt) {
3261   llvm::APFloat truncated = value;
3262 
3263   bool ignored;
3264   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
3265   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
3266 
3267   return truncated.bitwiseIsEqual(value);
3268 }
3269 
3270 /// Checks whether the given value, which currently has the given
3271 /// source semantics, has the same value when coerced through the
3272 /// target semantics.
3273 ///
3274 /// The value might be a vector of floats (or a complex number).
3275 bool IsSameFloatAfterCast(const APValue &value,
3276                           const llvm::fltSemantics &Src,
3277                           const llvm::fltSemantics &Tgt) {
3278   if (value.isFloat())
3279     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
3280 
3281   if (value.isVector()) {
3282     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
3283       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
3284         return false;
3285     return true;
3286   }
3287 
3288   assert(value.isComplexFloat());
3289   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
3290           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
3291 }
3292 
3293 void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
3294 
3295 static bool IsZero(Sema &S, Expr *E) {
3296   // Suppress cases where we are comparing against an enum constant.
3297   if (const DeclRefExpr *DR =
3298       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
3299     if (isa<EnumConstantDecl>(DR->getDecl()))
3300       return false;
3301 
3302   // Suppress cases where the '0' value is expanded from a macro.
3303   if (E->getLocStart().isMacroID())
3304     return false;
3305 
3306   llvm::APSInt Value;
3307   return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
3308 }
3309 
3310 static bool HasEnumType(Expr *E) {
3311   // Strip off implicit integral promotions.
3312   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3313     if (ICE->getCastKind() != CK_IntegralCast &&
3314         ICE->getCastKind() != CK_NoOp)
3315       break;
3316     E = ICE->getSubExpr();
3317   }
3318 
3319   return E->getType()->isEnumeralType();
3320 }
3321 
3322 void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
3323   BinaryOperatorKind op = E->getOpcode();
3324   if (E->isValueDependent())
3325     return;
3326 
3327   if (op == BO_LT && IsZero(S, E->getRHS())) {
3328     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
3329       << "< 0" << "false" << HasEnumType(E->getLHS())
3330       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3331   } else if (op == BO_GE && IsZero(S, E->getRHS())) {
3332     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
3333       << ">= 0" << "true" << HasEnumType(E->getLHS())
3334       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3335   } else if (op == BO_GT && IsZero(S, E->getLHS())) {
3336     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
3337       << "0 >" << "false" << HasEnumType(E->getRHS())
3338       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3339   } else if (op == BO_LE && IsZero(S, E->getLHS())) {
3340     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
3341       << "0 <=" << "true" << HasEnumType(E->getRHS())
3342       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3343   }
3344 }
3345 
3346 /// Analyze the operands of the given comparison.  Implements the
3347 /// fallback case from AnalyzeComparison.
3348 void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
3349   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3350   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
3351 }
3352 
3353 /// \brief Implements -Wsign-compare.
3354 ///
3355 /// \param E the binary operator to check for warnings
3356 void AnalyzeComparison(Sema &S, BinaryOperator *E) {
3357   // The type the comparison is being performed in.
3358   QualType T = E->getLHS()->getType();
3359   assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
3360          && "comparison with mismatched types");
3361 
3362   // We don't do anything special if this isn't an unsigned integral
3363   // comparison:  we're only interested in integral comparisons, and
3364   // signed comparisons only happen in cases we don't care to warn about.
3365   //
3366   // We also don't care about value-dependent expressions or expressions
3367   // whose result is a constant.
3368   if (!T->hasUnsignedIntegerRepresentation()
3369       || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
3370     return AnalyzeImpConvsInComparison(S, E);
3371 
3372   Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
3373   Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
3374 
3375   // Check to see if one of the (unmodified) operands is of different
3376   // signedness.
3377   Expr *signedOperand, *unsignedOperand;
3378   if (LHS->getType()->hasSignedIntegerRepresentation()) {
3379     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
3380            "unsigned comparison between two signed integer expressions?");
3381     signedOperand = LHS;
3382     unsignedOperand = RHS;
3383   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
3384     signedOperand = RHS;
3385     unsignedOperand = LHS;
3386   } else {
3387     CheckTrivialUnsignedComparison(S, E);
3388     return AnalyzeImpConvsInComparison(S, E);
3389   }
3390 
3391   // Otherwise, calculate the effective range of the signed operand.
3392   IntRange signedRange = GetExprRange(S.Context, signedOperand);
3393 
3394   // Go ahead and analyze implicit conversions in the operands.  Note
3395   // that we skip the implicit conversions on both sides.
3396   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
3397   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
3398 
3399   // If the signed range is non-negative, -Wsign-compare won't fire,
3400   // but we should still check for comparisons which are always true
3401   // or false.
3402   if (signedRange.NonNegative)
3403     return CheckTrivialUnsignedComparison(S, E);
3404 
3405   // For (in)equality comparisons, if the unsigned operand is a
3406   // constant which cannot collide with a overflowed signed operand,
3407   // then reinterpreting the signed operand as unsigned will not
3408   // change the result of the comparison.
3409   if (E->isEqualityOp()) {
3410     unsigned comparisonWidth = S.Context.getIntWidth(T);
3411     IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
3412 
3413     // We should never be unable to prove that the unsigned operand is
3414     // non-negative.
3415     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
3416 
3417     if (unsignedRange.Width < comparisonWidth)
3418       return;
3419   }
3420 
3421   S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
3422     << LHS->getType() << RHS->getType()
3423     << LHS->getSourceRange() << RHS->getSourceRange();
3424 }
3425 
3426 /// Analyzes an attempt to assign the given value to a bitfield.
3427 ///
3428 /// Returns true if there was something fishy about the attempt.
3429 bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
3430                                SourceLocation InitLoc) {
3431   assert(Bitfield->isBitField());
3432   if (Bitfield->isInvalidDecl())
3433     return false;
3434 
3435   // White-list bool bitfields.
3436   if (Bitfield->getType()->isBooleanType())
3437     return false;
3438 
3439   // Ignore value- or type-dependent expressions.
3440   if (Bitfield->getBitWidth()->isValueDependent() ||
3441       Bitfield->getBitWidth()->isTypeDependent() ||
3442       Init->isValueDependent() ||
3443       Init->isTypeDependent())
3444     return false;
3445 
3446   Expr *OriginalInit = Init->IgnoreParenImpCasts();
3447 
3448   Expr::EvalResult InitValue;
3449   if (!OriginalInit->EvaluateAsRValue(InitValue, S.Context) ||
3450       !InitValue.Val.isInt())
3451     return false;
3452 
3453   const llvm::APSInt &Value = InitValue.Val.getInt();
3454   unsigned OriginalWidth = Value.getBitWidth();
3455   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
3456 
3457   if (OriginalWidth <= FieldWidth)
3458     return false;
3459 
3460   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
3461 
3462   // It's fairly common to write values into signed bitfields
3463   // that, if sign-extended, would end up becoming a different
3464   // value.  We don't want to warn about that.
3465   if (Value.isSigned() && Value.isNegative())
3466     TruncatedValue = TruncatedValue.sext(OriginalWidth);
3467   else
3468     TruncatedValue = TruncatedValue.zext(OriginalWidth);
3469 
3470   if (Value == TruncatedValue)
3471     return false;
3472 
3473   std::string PrettyValue = Value.toString(10);
3474   std::string PrettyTrunc = TruncatedValue.toString(10);
3475 
3476   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
3477     << PrettyValue << PrettyTrunc << OriginalInit->getType()
3478     << Init->getSourceRange();
3479 
3480   return true;
3481 }
3482 
3483 /// Analyze the given simple or compound assignment for warning-worthy
3484 /// operations.
3485 void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
3486   // Just recurse on the LHS.
3487   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3488 
3489   // We want to recurse on the RHS as normal unless we're assigning to
3490   // a bitfield.
3491   if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
3492     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
3493                                   E->getOperatorLoc())) {
3494       // Recurse, ignoring any implicit conversions on the RHS.
3495       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
3496                                         E->getOperatorLoc());
3497     }
3498   }
3499 
3500   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
3501 }
3502 
3503 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
3504 void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
3505                      SourceLocation CContext, unsigned diag) {
3506   S.Diag(E->getExprLoc(), diag)
3507     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
3508 }
3509 
3510 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
3511 void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
3512                      unsigned diag) {
3513   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag);
3514 }
3515 
3516 /// Diagnose an implicit cast from a literal expression. Does not warn when the
3517 /// cast wouldn't lose information.
3518 void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
3519                                     SourceLocation CContext) {
3520   // Try to convert the literal exactly to an integer. If we can, don't warn.
3521   bool isExact = false;
3522   const llvm::APFloat &Value = FL->getValue();
3523   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
3524                             T->hasUnsignedIntegerRepresentation());
3525   if (Value.convertToInteger(IntegerValue,
3526                              llvm::APFloat::rmTowardZero, &isExact)
3527       == llvm::APFloat::opOK && isExact)
3528     return;
3529 
3530   S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
3531     << FL->getType() << T << FL->getSourceRange() << SourceRange(CContext);
3532 }
3533 
3534 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
3535   if (!Range.Width) return "0";
3536 
3537   llvm::APSInt ValueInRange = Value;
3538   ValueInRange.setIsSigned(!Range.NonNegative);
3539   ValueInRange = ValueInRange.trunc(Range.Width);
3540   return ValueInRange.toString(10);
3541 }
3542 
3543 static bool isFromSystemMacro(Sema &S, SourceLocation loc) {
3544   SourceManager &smgr = S.Context.getSourceManager();
3545   return loc.isMacroID() && smgr.isInSystemHeader(smgr.getSpellingLoc(loc));
3546 }
3547 
3548 void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
3549                              SourceLocation CC, bool *ICContext = 0) {
3550   if (E->isTypeDependent() || E->isValueDependent()) return;
3551 
3552   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
3553   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
3554   if (Source == Target) return;
3555   if (Target->isDependentType()) return;
3556 
3557   // If the conversion context location is invalid don't complain. We also
3558   // don't want to emit a warning if the issue occurs from the expansion of
3559   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
3560   // delay this check as long as possible. Once we detect we are in that
3561   // scenario, we just return.
3562   if (CC.isInvalid())
3563     return;
3564 
3565   // Diagnose implicit casts to bool.
3566   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
3567     if (isa<StringLiteral>(E))
3568       // Warn on string literal to bool.  Checks for string literals in logical
3569       // expressions, for instances, assert(0 && "error here"), is prevented
3570       // by a check in AnalyzeImplicitConversions().
3571       return DiagnoseImpCast(S, E, T, CC,
3572                              diag::warn_impcast_string_literal_to_bool);
3573     return; // Other casts to bool are not checked.
3574   }
3575 
3576   // Strip vector types.
3577   if (isa<VectorType>(Source)) {
3578     if (!isa<VectorType>(Target)) {
3579       if (isFromSystemMacro(S, CC))
3580         return;
3581       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
3582     }
3583 
3584     // If the vector cast is cast between two vectors of the same size, it is
3585     // a bitcast, not a conversion.
3586     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
3587       return;
3588 
3589     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
3590     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
3591   }
3592 
3593   // Strip complex types.
3594   if (isa<ComplexType>(Source)) {
3595     if (!isa<ComplexType>(Target)) {
3596       if (isFromSystemMacro(S, CC))
3597         return;
3598 
3599       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
3600     }
3601 
3602     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
3603     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
3604   }
3605 
3606   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
3607   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
3608 
3609   // If the source is floating point...
3610   if (SourceBT && SourceBT->isFloatingPoint()) {
3611     // ...and the target is floating point...
3612     if (TargetBT && TargetBT->isFloatingPoint()) {
3613       // ...then warn if we're dropping FP rank.
3614 
3615       // Builtin FP kinds are ordered by increasing FP rank.
3616       if (SourceBT->getKind() > TargetBT->getKind()) {
3617         // Don't warn about float constants that are precisely
3618         // representable in the target type.
3619         Expr::EvalResult result;
3620         if (E->EvaluateAsRValue(result, S.Context)) {
3621           // Value might be a float, a float vector, or a float complex.
3622           if (IsSameFloatAfterCast(result.Val,
3623                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
3624                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
3625             return;
3626         }
3627 
3628         if (isFromSystemMacro(S, CC))
3629           return;
3630 
3631         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
3632       }
3633       return;
3634     }
3635 
3636     // If the target is integral, always warn.
3637     if ((TargetBT && TargetBT->isInteger())) {
3638       if (isFromSystemMacro(S, CC))
3639         return;
3640 
3641       Expr *InnerE = E->IgnoreParenImpCasts();
3642       // We also want to warn on, e.g., "int i = -1.234"
3643       if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
3644         if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
3645           InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
3646 
3647       if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
3648         DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
3649       } else {
3650         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
3651       }
3652     }
3653 
3654     return;
3655   }
3656 
3657   if (!Source->isIntegerType() || !Target->isIntegerType())
3658     return;
3659 
3660   if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
3661            == Expr::NPCK_GNUNull) && Target->isIntegerType()) {
3662     S.Diag(E->getExprLoc(), diag::warn_impcast_null_pointer_to_integer)
3663         << E->getSourceRange() << clang::SourceRange(CC);
3664     return;
3665   }
3666 
3667   IntRange SourceRange = GetExprRange(S.Context, E);
3668   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
3669 
3670   if (SourceRange.Width > TargetRange.Width) {
3671     // If the source is a constant, use a default-on diagnostic.
3672     // TODO: this should happen for bitfield stores, too.
3673     llvm::APSInt Value(32);
3674     if (E->isIntegerConstantExpr(Value, S.Context)) {
3675       if (isFromSystemMacro(S, CC))
3676         return;
3677 
3678       std::string PrettySourceValue = Value.toString(10);
3679       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
3680 
3681       S.DiagRuntimeBehavior(E->getExprLoc(), E,
3682         S.PDiag(diag::warn_impcast_integer_precision_constant)
3683             << PrettySourceValue << PrettyTargetValue
3684             << E->getType() << T << E->getSourceRange()
3685             << clang::SourceRange(CC));
3686       return;
3687     }
3688 
3689     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
3690     if (isFromSystemMacro(S, CC))
3691       return;
3692 
3693     if (SourceRange.Width == 64 && TargetRange.Width == 32)
3694       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32);
3695     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
3696   }
3697 
3698   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
3699       (!TargetRange.NonNegative && SourceRange.NonNegative &&
3700        SourceRange.Width == TargetRange.Width)) {
3701 
3702     if (isFromSystemMacro(S, CC))
3703       return;
3704 
3705     unsigned DiagID = diag::warn_impcast_integer_sign;
3706 
3707     // Traditionally, gcc has warned about this under -Wsign-compare.
3708     // We also want to warn about it in -Wconversion.
3709     // So if -Wconversion is off, use a completely identical diagnostic
3710     // in the sign-compare group.
3711     // The conditional-checking code will
3712     if (ICContext) {
3713       DiagID = diag::warn_impcast_integer_sign_conditional;
3714       *ICContext = true;
3715     }
3716 
3717     return DiagnoseImpCast(S, E, T, CC, DiagID);
3718   }
3719 
3720   // Diagnose conversions between different enumeration types.
3721   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
3722   // type, to give us better diagnostics.
3723   QualType SourceType = E->getType();
3724   if (!S.getLangOptions().CPlusPlus) {
3725     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3726       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3727         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
3728         SourceType = S.Context.getTypeDeclType(Enum);
3729         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
3730       }
3731   }
3732 
3733   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
3734     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
3735       if ((SourceEnum->getDecl()->getIdentifier() ||
3736            SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
3737           (TargetEnum->getDecl()->getIdentifier() ||
3738            TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
3739           SourceEnum != TargetEnum) {
3740         if (isFromSystemMacro(S, CC))
3741           return;
3742 
3743         return DiagnoseImpCast(S, E, SourceType, T, CC,
3744                                diag::warn_impcast_different_enum_types);
3745       }
3746 
3747   return;
3748 }
3749 
3750 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
3751 
3752 void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
3753                              SourceLocation CC, bool &ICContext) {
3754   E = E->IgnoreParenImpCasts();
3755 
3756   if (isa<ConditionalOperator>(E))
3757     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
3758 
3759   AnalyzeImplicitConversions(S, E, CC);
3760   if (E->getType() != T)
3761     return CheckImplicitConversion(S, E, T, CC, &ICContext);
3762   return;
3763 }
3764 
3765 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
3766   SourceLocation CC = E->getQuestionLoc();
3767 
3768   AnalyzeImplicitConversions(S, E->getCond(), CC);
3769 
3770   bool Suspicious = false;
3771   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
3772   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
3773 
3774   // If -Wconversion would have warned about either of the candidates
3775   // for a signedness conversion to the context type...
3776   if (!Suspicious) return;
3777 
3778   // ...but it's currently ignored...
3779   if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
3780                                  CC))
3781     return;
3782 
3783   // ...then check whether it would have warned about either of the
3784   // candidates for a signedness conversion to the condition type.
3785   if (E->getType() == T) return;
3786 
3787   Suspicious = false;
3788   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
3789                           E->getType(), CC, &Suspicious);
3790   if (!Suspicious)
3791     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
3792                             E->getType(), CC, &Suspicious);
3793 }
3794 
3795 /// AnalyzeImplicitConversions - Find and report any interesting
3796 /// implicit conversions in the given expression.  There are a couple
3797 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
3798 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
3799   QualType T = OrigE->getType();
3800   Expr *E = OrigE->IgnoreParenImpCasts();
3801 
3802   if (E->isTypeDependent() || E->isValueDependent())
3803     return;
3804 
3805   // For conditional operators, we analyze the arguments as if they
3806   // were being fed directly into the output.
3807   if (isa<ConditionalOperator>(E)) {
3808     ConditionalOperator *CO = cast<ConditionalOperator>(E);
3809     CheckConditionalOperator(S, CO, T);
3810     return;
3811   }
3812 
3813   // Go ahead and check any implicit conversions we might have skipped.
3814   // The non-canonical typecheck is just an optimization;
3815   // CheckImplicitConversion will filter out dead implicit conversions.
3816   if (E->getType() != T)
3817     CheckImplicitConversion(S, E, T, CC);
3818 
3819   // Now continue drilling into this expression.
3820 
3821   // Skip past explicit casts.
3822   if (isa<ExplicitCastExpr>(E)) {
3823     E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
3824     return AnalyzeImplicitConversions(S, E, CC);
3825   }
3826 
3827   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3828     // Do a somewhat different check with comparison operators.
3829     if (BO->isComparisonOp())
3830       return AnalyzeComparison(S, BO);
3831 
3832     // And with assignments and compound assignments.
3833     if (BO->isAssignmentOp())
3834       return AnalyzeAssignment(S, BO);
3835   }
3836 
3837   // These break the otherwise-useful invariant below.  Fortunately,
3838   // we don't really need to recurse into them, because any internal
3839   // expressions should have been analyzed already when they were
3840   // built into statements.
3841   if (isa<StmtExpr>(E)) return;
3842 
3843   // Don't descend into unevaluated contexts.
3844   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
3845 
3846   // Now just recurse over the expression's children.
3847   CC = E->getExprLoc();
3848   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
3849   bool IsLogicalOperator = BO && BO->isLogicalOp();
3850   for (Stmt::child_range I = E->children(); I; ++I) {
3851     Expr *ChildExpr = cast<Expr>(*I);
3852     if (IsLogicalOperator &&
3853         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
3854       // Ignore checking string literals that are in logical operators.
3855       continue;
3856     AnalyzeImplicitConversions(S, ChildExpr, CC);
3857   }
3858 }
3859 
3860 } // end anonymous namespace
3861 
3862 /// Diagnoses "dangerous" implicit conversions within the given
3863 /// expression (which is a full expression).  Implements -Wconversion
3864 /// and -Wsign-compare.
3865 ///
3866 /// \param CC the "context" location of the implicit conversion, i.e.
3867 ///   the most location of the syntactic entity requiring the implicit
3868 ///   conversion
3869 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
3870   // Don't diagnose in unevaluated contexts.
3871   if (ExprEvalContexts.back().Context == Sema::Unevaluated)
3872     return;
3873 
3874   // Don't diagnose for value- or type-dependent expressions.
3875   if (E->isTypeDependent() || E->isValueDependent())
3876     return;
3877 
3878   // Check for array bounds violations in cases where the check isn't triggered
3879   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
3880   // ArraySubscriptExpr is on the RHS of a variable initialization.
3881   CheckArrayAccess(E);
3882 
3883   // This is not the right CC for (e.g.) a variable initialization.
3884   AnalyzeImplicitConversions(*this, E, CC);
3885 }
3886 
3887 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
3888                                        FieldDecl *BitField,
3889                                        Expr *Init) {
3890   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
3891 }
3892 
3893 /// CheckParmsForFunctionDef - Check that the parameters of the given
3894 /// function are appropriate for the definition of a function. This
3895 /// takes care of any checks that cannot be performed on the
3896 /// declaration itself, e.g., that the types of each of the function
3897 /// parameters are complete.
3898 bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
3899                                     bool CheckParameterNames) {
3900   bool HasInvalidParm = false;
3901   for (; P != PEnd; ++P) {
3902     ParmVarDecl *Param = *P;
3903 
3904     // C99 6.7.5.3p4: the parameters in a parameter type list in a
3905     // function declarator that is part of a function definition of
3906     // that function shall not have incomplete type.
3907     //
3908     // This is also C++ [dcl.fct]p6.
3909     if (!Param->isInvalidDecl() &&
3910         RequireCompleteType(Param->getLocation(), Param->getType(),
3911                                diag::err_typecheck_decl_incomplete_type)) {
3912       Param->setInvalidDecl();
3913       HasInvalidParm = true;
3914     }
3915 
3916     // C99 6.9.1p5: If the declarator includes a parameter type list, the
3917     // declaration of each parameter shall include an identifier.
3918     if (CheckParameterNames &&
3919         Param->getIdentifier() == 0 &&
3920         !Param->isImplicit() &&
3921         !getLangOptions().CPlusPlus)
3922       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
3923 
3924     // C99 6.7.5.3p12:
3925     //   If the function declarator is not part of a definition of that
3926     //   function, parameters may have incomplete type and may use the [*]
3927     //   notation in their sequences of declarator specifiers to specify
3928     //   variable length array types.
3929     QualType PType = Param->getOriginalType();
3930     if (const ArrayType *AT = Context.getAsArrayType(PType)) {
3931       if (AT->getSizeModifier() == ArrayType::Star) {
3932         // FIXME: This diagnosic should point the the '[*]' if source-location
3933         // information is added for it.
3934         Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
3935       }
3936     }
3937   }
3938 
3939   return HasInvalidParm;
3940 }
3941 
3942 /// CheckCastAlign - Implements -Wcast-align, which warns when a
3943 /// pointer cast increases the alignment requirements.
3944 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
3945   // This is actually a lot of work to potentially be doing on every
3946   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
3947   if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
3948                                           TRange.getBegin())
3949         == DiagnosticsEngine::Ignored)
3950     return;
3951 
3952   // Ignore dependent types.
3953   if (T->isDependentType() || Op->getType()->isDependentType())
3954     return;
3955 
3956   // Require that the destination be a pointer type.
3957   const PointerType *DestPtr = T->getAs<PointerType>();
3958   if (!DestPtr) return;
3959 
3960   // If the destination has alignment 1, we're done.
3961   QualType DestPointee = DestPtr->getPointeeType();
3962   if (DestPointee->isIncompleteType()) return;
3963   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
3964   if (DestAlign.isOne()) return;
3965 
3966   // Require that the source be a pointer type.
3967   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
3968   if (!SrcPtr) return;
3969   QualType SrcPointee = SrcPtr->getPointeeType();
3970 
3971   // Whitelist casts from cv void*.  We already implicitly
3972   // whitelisted casts to cv void*, since they have alignment 1.
3973   // Also whitelist casts involving incomplete types, which implicitly
3974   // includes 'void'.
3975   if (SrcPointee->isIncompleteType()) return;
3976 
3977   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
3978   if (SrcAlign >= DestAlign) return;
3979 
3980   Diag(TRange.getBegin(), diag::warn_cast_align)
3981     << Op->getType() << T
3982     << static_cast<unsigned>(SrcAlign.getQuantity())
3983     << static_cast<unsigned>(DestAlign.getQuantity())
3984     << TRange << Op->getSourceRange();
3985 }
3986 
3987 static const Type* getElementType(const Expr *BaseExpr) {
3988   const Type* EltType = BaseExpr->getType().getTypePtr();
3989   if (EltType->isAnyPointerType())
3990     return EltType->getPointeeType().getTypePtr();
3991   else if (EltType->isArrayType())
3992     return EltType->getBaseElementTypeUnsafe();
3993   return EltType;
3994 }
3995 
3996 /// \brief Check whether this array fits the idiom of a size-one tail padded
3997 /// array member of a struct.
3998 ///
3999 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
4000 /// commonly used to emulate flexible arrays in C89 code.
4001 static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
4002                                     const NamedDecl *ND) {
4003   if (Size != 1 || !ND) return false;
4004 
4005   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
4006   if (!FD) return false;
4007 
4008   // Don't consider sizes resulting from macro expansions or template argument
4009   // substitution to form C89 tail-padded arrays.
4010   ConstantArrayTypeLoc TL =
4011     cast<ConstantArrayTypeLoc>(FD->getTypeSourceInfo()->getTypeLoc());
4012   const Expr *SizeExpr = dyn_cast<IntegerLiteral>(TL.getSizeExpr());
4013   if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
4014     return false;
4015 
4016   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
4017   if (!RD || !RD->isStruct())
4018     return false;
4019 
4020   // See if this is the last field decl in the record.
4021   const Decl *D = FD;
4022   while ((D = D->getNextDeclInContext()))
4023     if (isa<FieldDecl>(D))
4024       return false;
4025   return true;
4026 }
4027 
4028 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
4029                             bool isSubscript, bool AllowOnePastEnd) {
4030   const Type* EffectiveType = getElementType(BaseExpr);
4031   BaseExpr = BaseExpr->IgnoreParenCasts();
4032   IndexExpr = IndexExpr->IgnoreParenCasts();
4033 
4034   const ConstantArrayType *ArrayTy =
4035     Context.getAsConstantArrayType(BaseExpr->getType());
4036   if (!ArrayTy)
4037     return;
4038 
4039   if (IndexExpr->isValueDependent())
4040     return;
4041   llvm::APSInt index;
4042   if (!IndexExpr->isIntegerConstantExpr(index, Context))
4043     return;
4044 
4045   const NamedDecl *ND = NULL;
4046   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4047     ND = dyn_cast<NamedDecl>(DRE->getDecl());
4048   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
4049     ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
4050 
4051   if (index.isUnsigned() || !index.isNegative()) {
4052     llvm::APInt size = ArrayTy->getSize();
4053     if (!size.isStrictlyPositive())
4054       return;
4055 
4056     const Type* BaseType = getElementType(BaseExpr);
4057     if (BaseType != EffectiveType) {
4058       // Make sure we're comparing apples to apples when comparing index to size
4059       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
4060       uint64_t array_typesize = Context.getTypeSize(BaseType);
4061       // Handle ptrarith_typesize being zero, such as when casting to void*
4062       if (!ptrarith_typesize) ptrarith_typesize = 1;
4063       if (ptrarith_typesize != array_typesize) {
4064         // There's a cast to a different size type involved
4065         uint64_t ratio = array_typesize / ptrarith_typesize;
4066         // TODO: Be smarter about handling cases where array_typesize is not a
4067         // multiple of ptrarith_typesize
4068         if (ptrarith_typesize * ratio == array_typesize)
4069           size *= llvm::APInt(size.getBitWidth(), ratio);
4070       }
4071     }
4072 
4073     if (size.getBitWidth() > index.getBitWidth())
4074       index = index.sext(size.getBitWidth());
4075     else if (size.getBitWidth() < index.getBitWidth())
4076       size = size.sext(index.getBitWidth());
4077 
4078     // For array subscripting the index must be less than size, but for pointer
4079     // arithmetic also allow the index (offset) to be equal to size since
4080     // computing the next address after the end of the array is legal and
4081     // commonly done e.g. in C++ iterators and range-based for loops.
4082     if (AllowOnePastEnd ? index.sle(size) : index.slt(size))
4083       return;
4084 
4085     // Also don't warn for arrays of size 1 which are members of some
4086     // structure. These are often used to approximate flexible arrays in C89
4087     // code.
4088     if (IsTailPaddedMemberArray(*this, size, ND))
4089       return;
4090 
4091     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
4092     if (isSubscript)
4093       DiagID = diag::warn_array_index_exceeds_bounds;
4094 
4095     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4096                         PDiag(DiagID) << index.toString(10, true)
4097                           << size.toString(10, true)
4098                           << (unsigned)size.getLimitedValue(~0U)
4099                           << IndexExpr->getSourceRange());
4100   } else {
4101     unsigned DiagID = diag::warn_array_index_precedes_bounds;
4102     if (!isSubscript) {
4103       DiagID = diag::warn_ptr_arith_precedes_bounds;
4104       if (index.isNegative()) index = -index;
4105     }
4106 
4107     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4108                         PDiag(DiagID) << index.toString(10, true)
4109                           << IndexExpr->getSourceRange());
4110   }
4111 
4112   if (ND)
4113     DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
4114                         PDiag(diag::note_array_index_out_of_bounds)
4115                           << ND->getDeclName());
4116 }
4117 
4118 void Sema::CheckArrayAccess(const Expr *expr) {
4119   int AllowOnePastEnd = 0;
4120   while (expr) {
4121     expr = expr->IgnoreParenImpCasts();
4122     switch (expr->getStmtClass()) {
4123       case Stmt::ArraySubscriptExprClass: {
4124         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
4125         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), true,
4126                          AllowOnePastEnd > 0);
4127         return;
4128       }
4129       case Stmt::UnaryOperatorClass: {
4130         // Only unwrap the * and & unary operators
4131         const UnaryOperator *UO = cast<UnaryOperator>(expr);
4132         expr = UO->getSubExpr();
4133         switch (UO->getOpcode()) {
4134           case UO_AddrOf:
4135             AllowOnePastEnd++;
4136             break;
4137           case UO_Deref:
4138             AllowOnePastEnd--;
4139             break;
4140           default:
4141             return;
4142         }
4143         break;
4144       }
4145       case Stmt::ConditionalOperatorClass: {
4146         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
4147         if (const Expr *lhs = cond->getLHS())
4148           CheckArrayAccess(lhs);
4149         if (const Expr *rhs = cond->getRHS())
4150           CheckArrayAccess(rhs);
4151         return;
4152       }
4153       default:
4154         return;
4155     }
4156   }
4157 }
4158 
4159 //===--- CHECK: Objective-C retain cycles ----------------------------------//
4160 
4161 namespace {
4162   struct RetainCycleOwner {
4163     RetainCycleOwner() : Variable(0), Indirect(false) {}
4164     VarDecl *Variable;
4165     SourceRange Range;
4166     SourceLocation Loc;
4167     bool Indirect;
4168 
4169     void setLocsFrom(Expr *e) {
4170       Loc = e->getExprLoc();
4171       Range = e->getSourceRange();
4172     }
4173   };
4174 }
4175 
4176 /// Consider whether capturing the given variable can possibly lead to
4177 /// a retain cycle.
4178 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
4179   // In ARC, it's captured strongly iff the variable has __strong
4180   // lifetime.  In MRR, it's captured strongly if the variable is
4181   // __block and has an appropriate type.
4182   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4183     return false;
4184 
4185   owner.Variable = var;
4186   owner.setLocsFrom(ref);
4187   return true;
4188 }
4189 
4190 static bool findRetainCycleOwner(Expr *e, RetainCycleOwner &owner) {
4191   while (true) {
4192     e = e->IgnoreParens();
4193     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
4194       switch (cast->getCastKind()) {
4195       case CK_BitCast:
4196       case CK_LValueBitCast:
4197       case CK_LValueToRValue:
4198       case CK_ARCReclaimReturnedObject:
4199         e = cast->getSubExpr();
4200         continue;
4201 
4202       default:
4203         return false;
4204       }
4205     }
4206 
4207     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
4208       ObjCIvarDecl *ivar = ref->getDecl();
4209       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4210         return false;
4211 
4212       // Try to find a retain cycle in the base.
4213       if (!findRetainCycleOwner(ref->getBase(), owner))
4214         return false;
4215 
4216       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
4217       owner.Indirect = true;
4218       return true;
4219     }
4220 
4221     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
4222       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
4223       if (!var) return false;
4224       return considerVariable(var, ref, owner);
4225     }
4226 
4227     if (BlockDeclRefExpr *ref = dyn_cast<BlockDeclRefExpr>(e)) {
4228       owner.Variable = ref->getDecl();
4229       owner.setLocsFrom(ref);
4230       return true;
4231     }
4232 
4233     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
4234       if (member->isArrow()) return false;
4235 
4236       // Don't count this as an indirect ownership.
4237       e = member->getBase();
4238       continue;
4239     }
4240 
4241     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
4242       // Only pay attention to pseudo-objects on property references.
4243       ObjCPropertyRefExpr *pre
4244         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
4245                                               ->IgnoreParens());
4246       if (!pre) return false;
4247       if (pre->isImplicitProperty()) return false;
4248       ObjCPropertyDecl *property = pre->getExplicitProperty();
4249       if (!property->isRetaining() &&
4250           !(property->getPropertyIvarDecl() &&
4251             property->getPropertyIvarDecl()->getType()
4252               .getObjCLifetime() == Qualifiers::OCL_Strong))
4253           return false;
4254 
4255       owner.Indirect = true;
4256       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
4257                               ->getSourceExpr());
4258       continue;
4259     }
4260 
4261     // Array ivars?
4262 
4263     return false;
4264   }
4265 }
4266 
4267 namespace {
4268   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
4269     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
4270       : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
4271         Variable(variable), Capturer(0) {}
4272 
4273     VarDecl *Variable;
4274     Expr *Capturer;
4275 
4276     void VisitDeclRefExpr(DeclRefExpr *ref) {
4277       if (ref->getDecl() == Variable && !Capturer)
4278         Capturer = ref;
4279     }
4280 
4281     void VisitBlockDeclRefExpr(BlockDeclRefExpr *ref) {
4282       if (ref->getDecl() == Variable && !Capturer)
4283         Capturer = ref;
4284     }
4285 
4286     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
4287       if (Capturer) return;
4288       Visit(ref->getBase());
4289       if (Capturer && ref->isFreeIvar())
4290         Capturer = ref;
4291     }
4292 
4293     void VisitBlockExpr(BlockExpr *block) {
4294       // Look inside nested blocks
4295       if (block->getBlockDecl()->capturesVariable(Variable))
4296         Visit(block->getBlockDecl()->getBody());
4297     }
4298   };
4299 }
4300 
4301 /// Check whether the given argument is a block which captures a
4302 /// variable.
4303 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
4304   assert(owner.Variable && owner.Loc.isValid());
4305 
4306   e = e->IgnoreParenCasts();
4307   BlockExpr *block = dyn_cast<BlockExpr>(e);
4308   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
4309     return 0;
4310 
4311   FindCaptureVisitor visitor(S.Context, owner.Variable);
4312   visitor.Visit(block->getBlockDecl()->getBody());
4313   return visitor.Capturer;
4314 }
4315 
4316 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
4317                                 RetainCycleOwner &owner) {
4318   assert(capturer);
4319   assert(owner.Variable && owner.Loc.isValid());
4320 
4321   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
4322     << owner.Variable << capturer->getSourceRange();
4323   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
4324     << owner.Indirect << owner.Range;
4325 }
4326 
4327 /// Check for a keyword selector that starts with the word 'add' or
4328 /// 'set'.
4329 static bool isSetterLikeSelector(Selector sel) {
4330   if (sel.isUnarySelector()) return false;
4331 
4332   StringRef str = sel.getNameForSlot(0);
4333   while (!str.empty() && str.front() == '_') str = str.substr(1);
4334   if (str.startswith("set") || str.startswith("add"))
4335     str = str.substr(3);
4336   else
4337     return false;
4338 
4339   if (str.empty()) return true;
4340   return !islower(str.front());
4341 }
4342 
4343 /// Check a message send to see if it's likely to cause a retain cycle.
4344 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
4345   // Only check instance methods whose selector looks like a setter.
4346   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
4347     return;
4348 
4349   // Try to find a variable that the receiver is strongly owned by.
4350   RetainCycleOwner owner;
4351   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
4352     if (!findRetainCycleOwner(msg->getInstanceReceiver(), owner))
4353       return;
4354   } else {
4355     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
4356     owner.Variable = getCurMethodDecl()->getSelfDecl();
4357     owner.Loc = msg->getSuperLoc();
4358     owner.Range = msg->getSuperLoc();
4359   }
4360 
4361   // Check whether the receiver is captured by any of the arguments.
4362   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
4363     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
4364       return diagnoseRetainCycle(*this, capturer, owner);
4365 }
4366 
4367 /// Check a property assign to see if it's likely to cause a retain cycle.
4368 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
4369   RetainCycleOwner owner;
4370   if (!findRetainCycleOwner(receiver, owner))
4371     return;
4372 
4373   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
4374     diagnoseRetainCycle(*this, capturer, owner);
4375 }
4376 
4377 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
4378                               QualType LHS, Expr *RHS) {
4379   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
4380   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
4381     return false;
4382   // strip off any implicit cast added to get to the one arc-specific
4383   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
4384     if (cast->getCastKind() == CK_ARCConsumeObject) {
4385       Diag(Loc, diag::warn_arc_retained_assign)
4386         << (LT == Qualifiers::OCL_ExplicitNone)
4387         << RHS->getSourceRange();
4388       return true;
4389     }
4390     RHS = cast->getSubExpr();
4391   }
4392   return false;
4393 }
4394 
4395 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
4396                               Expr *LHS, Expr *RHS) {
4397   QualType LHSType = LHS->getType();
4398   if (checkUnsafeAssigns(Loc, LHSType, RHS))
4399     return;
4400   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
4401   // FIXME. Check for other life times.
4402   if (LT != Qualifiers::OCL_None)
4403     return;
4404 
4405   if (ObjCPropertyRefExpr *PRE
4406         = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens())) {
4407     if (PRE->isImplicitProperty())
4408       return;
4409     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
4410     if (!PD)
4411       return;
4412 
4413     unsigned Attributes = PD->getPropertyAttributes();
4414     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign)
4415       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
4416         if (cast->getCastKind() == CK_ARCConsumeObject) {
4417           Diag(Loc, diag::warn_arc_retained_property_assign)
4418           << RHS->getSourceRange();
4419           return;
4420         }
4421         RHS = cast->getSubExpr();
4422       }
4423   }
4424 }
4425