clang  20.0.0git
RewriteModernObjC.cpp
Go to the documentation of this file.
1 //===-- RewriteModernObjC.cpp - Playground for the code rewriter ----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Hacks and fun related to the code rewriter.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/AST/AST.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/Attr.h"
16 #include "clang/AST/ParentMap.h"
17 #include "clang/Basic/CharInfo.h"
18 #include "clang/Basic/Diagnostic.h"
21 #include "clang/Basic/TargetInfo.h"
22 #include "clang/Config/config.h"
23 #include "clang/Lex/Lexer.h"
26 #include "llvm/ADT/DenseSet.h"
27 #include "llvm/ADT/SetVector.h"
28 #include "llvm/ADT/SmallPtrSet.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/Support/MemoryBuffer.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include <memory>
33 
34 #if CLANG_ENABLE_OBJC_REWRITER
35 
36 using namespace clang;
37 using llvm::RewriteBuffer;
38 using llvm::utostr;
39 
40 namespace {
41  class RewriteModernObjC : public ASTConsumer {
42  protected:
43 
44  enum {
45  BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
46  block, ... */
47  BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
48  BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
49  __block variable */
50  BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
51  helpers */
52  BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
53  support routines */
55  };
56 
57  enum {
58  BLOCK_NEEDS_FREE = (1 << 24),
59  BLOCK_HAS_COPY_DISPOSE = (1 << 25),
60  BLOCK_HAS_CXX_OBJ = (1 << 26),
61  BLOCK_IS_GC = (1 << 27),
62  BLOCK_IS_GLOBAL = (1 << 28),
63  BLOCK_HAS_DESCRIPTOR = (1 << 29)
64  };
65 
67  DiagnosticsEngine &Diags;
68  const LangOptions &LangOpts;
69  ASTContext *Context;
71  TranslationUnitDecl *TUDecl;
72  FileID MainFileID;
73  const char *MainFileStart, *MainFileEnd;
74  Stmt *CurrentBody;
75  ParentMap *PropParentMap; // created lazily.
76  std::string InFileName;
77  std::unique_ptr<raw_ostream> OutFile;
78  std::string Preamble;
79 
80  TypeDecl *ProtocolTypeDecl;
81  VarDecl *GlobalVarDecl;
82  Expr *GlobalConstructionExp;
83  unsigned RewriteFailedDiag;
84  unsigned GlobalBlockRewriteFailedDiag;
85  // ObjC string constant support.
86  unsigned NumObjCStringLiterals;
87  VarDecl *ConstantStringClassReference;
88  RecordDecl *NSStringRecord;
89 
90  // ObjC foreach break/continue generation support.
91  int BcLabelCount;
92 
93  unsigned TryFinallyContainsReturnDiag;
94  // Needed for super.
95  ObjCMethodDecl *CurMethodDef;
96  RecordDecl *SuperStructDecl;
97  RecordDecl *ConstantStringDecl;
98 
99  FunctionDecl *MsgSendFunctionDecl;
100  FunctionDecl *MsgSendSuperFunctionDecl;
101  FunctionDecl *MsgSendStretFunctionDecl;
102  FunctionDecl *MsgSendSuperStretFunctionDecl;
103  FunctionDecl *MsgSendFpretFunctionDecl;
104  FunctionDecl *GetClassFunctionDecl;
105  FunctionDecl *GetMetaClassFunctionDecl;
106  FunctionDecl *GetSuperClassFunctionDecl;
107  FunctionDecl *SelGetUidFunctionDecl;
108  FunctionDecl *CFStringFunctionDecl;
109  FunctionDecl *SuperConstructorFunctionDecl;
110  FunctionDecl *CurFunctionDef;
111 
112  /* Misc. containers needed for meta-data rewrite. */
113  SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
114  SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
115  llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
116  llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
117  llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
118  llvm::SmallPtrSet<TagDecl*, 32> GlobalDefinedTags;
119  SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
120  /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
121  SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
122 
123  /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
124  SmallVector<ObjCCategoryDecl *, 8> DefinedNonLazyCategories;
125 
127  SmallVector<int, 8> ObjCBcLabelNo;
128  // Remember all the @protocol(<expr>) expressions.
130 
131  llvm::DenseSet<uint64_t> CopyDestroyCache;
132 
133  // Block expressions.
135  SmallVector<int, 32> InnerDeclRefsCount;
136  SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
137 
138  SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
139 
140  // Block related declarations.
141  SmallVector<ValueDecl *, 8> BlockByCopyDecls;
142  llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
143  SmallVector<ValueDecl *, 8> BlockByRefDecls;
144  llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
145  llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
146  llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
147  llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
148 
149  llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
150  llvm::DenseMap<ObjCInterfaceDecl *,
151  llvm::SmallSetVector<ObjCIvarDecl *, 8> > ReferencedIvars;
152 
153  // ivar bitfield grouping containers
154  llvm::DenseSet<const ObjCInterfaceDecl *> ObjCInterefaceHasBitfieldGroups;
155  llvm::DenseMap<const ObjCIvarDecl* , unsigned> IvarGroupNumber;
156  // This container maps an <class, group number for ivar> tuple to the type
157  // of the struct where the bitfield belongs.
158  llvm::DenseMap<std::pair<const ObjCInterfaceDecl*, unsigned>, QualType> GroupRecordType;
159  SmallVector<FunctionDecl*, 32> FunctionDefinitionsSeen;
160 
161  // This maps an original source AST to it's rewritten form. This allows
162  // us to avoid rewriting the same node twice (which is very uncommon).
163  // This is needed to support some of the exotic property rewriting.
164  llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
165 
166  // Needed for header files being rewritten
167  bool IsHeader;
168  bool SilenceRewriteMacroWarning;
169  bool GenerateLineInfo;
170  bool objc_impl_method;
171 
172  bool DisableReplaceStmt;
173  class DisableReplaceStmtScope {
174  RewriteModernObjC &R;
175  bool SavedValue;
176 
177  public:
178  DisableReplaceStmtScope(RewriteModernObjC &R)
179  : R(R), SavedValue(R.DisableReplaceStmt) {
180  R.DisableReplaceStmt = true;
181  }
182  ~DisableReplaceStmtScope() {
183  R.DisableReplaceStmt = SavedValue;
184  }
185  };
186  void InitializeCommon(ASTContext &context);
187 
188  public:
189  llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
190 
191  // Top Level Driver code.
192  bool HandleTopLevelDecl(DeclGroupRef D) override {
193  for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
194  if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
195  if (!Class->isThisDeclarationADefinition()) {
196  RewriteForwardClassDecl(D);
197  break;
198  } else {
199  // Keep track of all interface declarations seen.
200  ObjCInterfacesSeen.push_back(Class);
201  break;
202  }
203  }
204 
205  if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
206  if (!Proto->isThisDeclarationADefinition()) {
207  RewriteForwardProtocolDecl(D);
208  break;
209  }
210  }
211 
212  if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(*I)) {
213  // Under modern abi, we cannot translate body of the function
214  // yet until all class extensions and its implementation is seen.
215  // This is because they may introduce new bitfields which must go
216  // into their grouping struct.
217  if (FDecl->isThisDeclarationADefinition() &&
218  // Not c functions defined inside an objc container.
219  !FDecl->isTopLevelDeclInObjCContainer()) {
220  FunctionDefinitionsSeen.push_back(FDecl);
221  break;
222  }
223  }
224  HandleTopLevelSingleDecl(*I);
225  }
226  return true;
227  }
228 
229  void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
230  for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
231  if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(*I)) {
232  if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
233  RewriteBlockPointerDecl(TD);
234  else if (TD->getUnderlyingType()->isFunctionPointerType())
235  CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
236  else
237  RewriteObjCQualifiedInterfaceTypes(TD);
238  }
239  }
240  }
241 
242  void HandleTopLevelSingleDecl(Decl *D);
243  void HandleDeclInMainFile(Decl *D);
244  RewriteModernObjC(std::string inFile, std::unique_ptr<raw_ostream> OS,
245  DiagnosticsEngine &D, const LangOptions &LOpts,
246  bool silenceMacroWarn, bool LineInfo);
247 
248  ~RewriteModernObjC() override {}
249 
250  void HandleTranslationUnit(ASTContext &C) override;
251 
252  void ReplaceStmt(Stmt *Old, Stmt *New) {
253  ReplaceStmtWithRange(Old, New, Old->getSourceRange());
254  }
255 
256  void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
257  assert(Old != nullptr && New != nullptr && "Expected non-null Stmt's");
258 
259  Stmt *ReplacingStmt = ReplacedNodes[Old];
260  if (ReplacingStmt)
261  return; // We can't rewrite the same node twice.
262 
263  if (DisableReplaceStmt)
264  return;
265 
266  // Measure the old text.
267  int Size = Rewrite.getRangeSize(SrcRange);
268  if (Size == -1) {
269  Diags.Report(Context->getFullLoc(Old->getBeginLoc()), RewriteFailedDiag)
270  << Old->getSourceRange();
271  return;
272  }
273  // Get the new text.
274  std::string SStr;
275  llvm::raw_string_ostream S(SStr);
276  New->printPretty(S, nullptr, PrintingPolicy(LangOpts));
277 
278  // If replacement succeeded or warning disabled return with no warning.
279  if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, SStr)) {
280  ReplacedNodes[Old] = New;
281  return;
282  }
283  if (SilenceRewriteMacroWarning)
284  return;
285  Diags.Report(Context->getFullLoc(Old->getBeginLoc()), RewriteFailedDiag)
286  << Old->getSourceRange();
287  }
288 
289  void InsertText(SourceLocation Loc, StringRef Str,
290  bool InsertAfter = true) {
291  // If insertion succeeded or warning disabled return with no warning.
292  if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
293  SilenceRewriteMacroWarning)
294  return;
295 
296  Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
297  }
298 
299  void ReplaceText(SourceLocation Start, unsigned OrigLength,
300  StringRef Str) {
301  // If removal succeeded or warning disabled return with no warning.
302  if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
303  SilenceRewriteMacroWarning)
304  return;
305 
306  Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
307  }
308 
309  // Syntactic Rewriting.
310  void RewriteRecordBody(RecordDecl *RD);
311  void RewriteInclude();
312  void RewriteLineDirective(const Decl *D);
313  void ConvertSourceLocationToLineDirective(SourceLocation Loc,
314  std::string &LineString);
315  void RewriteForwardClassDecl(DeclGroupRef D);
316  void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG);
317  void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
318  const std::string &typedefString);
319  void RewriteImplementations();
320  void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
322  ObjCCategoryImplDecl *CID);
323  void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
324  void RewriteImplementationDecl(Decl *Dcl);
325  void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
326  ObjCMethodDecl *MDecl, std::string &ResultStr);
327  void RewriteTypeIntoString(QualType T, std::string &ResultStr,
328  const FunctionType *&FPRetType);
329  void RewriteByRefString(std::string &ResultStr, const std::string &Name,
330  ValueDecl *VD, bool def=false);
331  void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
332  void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
333  void RewriteForwardProtocolDecl(DeclGroupRef D);
334  void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG);
335  void RewriteMethodDeclaration(ObjCMethodDecl *Method);
336  void RewriteProperty(ObjCPropertyDecl *prop);
337  void RewriteFunctionDecl(FunctionDecl *FD);
338  void RewriteBlockPointerType(std::string& Str, QualType Type);
339  void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
340  void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
341  void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
342  void RewriteTypeOfDecl(VarDecl *VD);
343  void RewriteObjCQualifiedInterfaceTypes(Expr *E);
344 
345  std::string getIvarAccessString(ObjCIvarDecl *D);
346 
347  // Expression Rewriting.
348  Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
349  Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
350  Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
351  Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
352  Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
353  Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
354  Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
355  Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
356  Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
357  Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
358  Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
359  Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
360  Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
361  Stmt *RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
362  Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
363  Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
364  Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
365  SourceLocation OrigEnd);
366  Stmt *RewriteBreakStmt(BreakStmt *S);
367  Stmt *RewriteContinueStmt(ContinueStmt *S);
368  void RewriteCastExpr(CStyleCastExpr *CE);
369  void RewriteImplicitCastObjCExpr(CastExpr *IE);
370 
371  // Computes ivar bitfield group no.
372  unsigned ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV);
373  // Names field decl. for ivar bitfield group.
374  void ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV, std::string &Result);
375  // Names struct type for ivar bitfield group.
376  void ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV, std::string &Result);
377  // Names symbol for ivar bitfield group field offset.
378  void ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV, std::string &Result);
379  // Given an ivar bitfield, it builds (or finds) its group record type.
380  QualType GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV);
381  QualType SynthesizeBitfieldGroupStructType(
382  ObjCIvarDecl *IV,
384 
385  // Block rewriting.
386  void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
387 
388  // Block specific rewrite rules.
389  void RewriteBlockPointerDecl(NamedDecl *VD);
390  void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl);
391  Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
392  Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
393  void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
394 
395  void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
396  std::string &Result);
397 
398  void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
399  bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag,
400  bool &IsNamedDefinition);
401  void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
402  std::string &Result);
403 
404  bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
405 
406  void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
407  std::string &Result);
408 
409  void Initialize(ASTContext &context) override;
410 
411  // Misc. AST transformation routines. Sometimes they end up calling
412  // rewriting routines on the new ASTs.
413  CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
414  ArrayRef<Expr *> Args,
415  SourceLocation StartLoc=SourceLocation(),
416  SourceLocation EndLoc=SourceLocation());
417 
418  Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
419  QualType returnType,
420  SmallVectorImpl<QualType> &ArgTypes,
421  SmallVectorImpl<Expr*> &MsgExprs,
422  ObjCMethodDecl *Method);
423 
424  Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
425  SourceLocation StartLoc=SourceLocation(),
426  SourceLocation EndLoc=SourceLocation());
427 
428  void SynthCountByEnumWithState(std::string &buf);
429  void SynthMsgSendFunctionDecl();
430  void SynthMsgSendSuperFunctionDecl();
431  void SynthMsgSendStretFunctionDecl();
432  void SynthMsgSendFpretFunctionDecl();
433  void SynthMsgSendSuperStretFunctionDecl();
434  void SynthGetClassFunctionDecl();
435  void SynthGetMetaClassFunctionDecl();
436  void SynthGetSuperClassFunctionDecl();
437  void SynthSelGetUidFunctionDecl();
438  void SynthSuperConstructorFunctionDecl();
439 
440  // Rewriting metadata
441  template<typename MethodIterator>
442  void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
443  MethodIterator MethodEnd,
444  bool IsInstanceMethod,
445  StringRef prefix,
446  StringRef ClassName,
447  std::string &Result);
448  void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
449  std::string &Result);
450  void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
451  std::string &Result);
452  void RewriteClassSetupInitHook(std::string &Result);
453 
454  void RewriteMetaDataIntoBuffer(std::string &Result);
455  void WriteImageInfo(std::string &Result);
456  void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
457  std::string &Result);
458  void RewriteCategorySetupInitHook(std::string &Result);
459 
460  // Rewriting ivar
461  void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
462  std::string &Result);
463  Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
464 
465 
466  std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
467  std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
468  StringRef funcName,
469  const std::string &Tag);
470  std::string SynthesizeBlockFunc(BlockExpr *CE, int i, StringRef funcName,
471  const std::string &Tag);
472  std::string SynthesizeBlockImpl(BlockExpr *CE, const std::string &Tag,
473  const std::string &Desc);
474  std::string SynthesizeBlockDescriptor(const std::string &DescTag,
475  const std::string &ImplTag, int i,
476  StringRef funcName, unsigned hasCopy);
477  Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
478  void SynthesizeBlockLiterals(SourceLocation FunLocStart,
479  StringRef FunName);
480  FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
481  Stmt *SynthBlockInitExpr(BlockExpr *Exp,
482  const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
483 
484  // Misc. helper routines.
485  QualType getProtocolType();
486  void WarnAboutReturnGotoStmts(Stmt *S);
487  void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
488  void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
489  void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
490 
491  bool IsDeclStmtInForeachHeader(DeclStmt *DS);
492  void CollectBlockDeclRefInfo(BlockExpr *Exp);
493  void GetBlockDeclRefExprs(Stmt *S);
494  void GetInnerBlockDeclRefExprs(Stmt *S,
495  SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
496  llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts);
497 
498  // We avoid calling Type::isBlockPointerType(), since it operates on the
499  // canonical type. We only care if the top-level type is a closure pointer.
500  bool isTopLevelBlockPointerType(QualType T) {
501  return isa<BlockPointerType>(T);
502  }
503 
504  /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
505  /// to a function pointer type and upon success, returns true; false
506  /// otherwise.
507  bool convertBlockPointerToFunctionPointer(QualType &T) {
508  if (isTopLevelBlockPointerType(T)) {
509  const auto *BPT = T->castAs<BlockPointerType>();
510  T = Context->getPointerType(BPT->getPointeeType());
511  return true;
512  }
513  return false;
514  }
515 
516  bool convertObjCTypeToCStyleType(QualType &T);
517 
518  bool needToScanForQualifiers(QualType T);
519  QualType getSuperStructType();
520  QualType getConstantStringStructType();
521  QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
522 
523  void convertToUnqualifiedObjCType(QualType &T) {
524  if (T->isObjCQualifiedIdType()) {
525  bool isConst = T.isConstQualified();
526  T = isConst ? Context->getObjCIdType().withConst()
527  : Context->getObjCIdType();
528  }
529  else if (T->isObjCQualifiedClassType())
530  T = Context->getObjCClassType();
531  else if (T->isObjCObjectPointerType() &&
533  if (const ObjCObjectPointerType * OBJPT =
535  const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
536  T = QualType(IFaceT, 0);
537  T = Context->getPointerType(T);
538  }
539  }
540  }
541 
542  // FIXME: This predicate seems like it would be useful to add to ASTContext.
543  bool isObjCType(QualType T) {
544  if (!LangOpts.ObjC)
545  return false;
546 
547  QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
548 
549  if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
550  OCT == Context->getCanonicalType(Context->getObjCClassType()))
551  return true;
552 
553  if (const PointerType *PT = OCT->getAs<PointerType>()) {
554  if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
555  PT->getPointeeType()->isObjCQualifiedIdType())
556  return true;
557  }
558  return false;
559  }
560 
561  bool PointerTypeTakesAnyBlockArguments(QualType QT);
562  bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
563  void GetExtentOfArgList(const char *Name, const char *&LParen,
564  const char *&RParen);
565 
566  void QuoteDoublequotes(std::string &From, std::string &To) {
567  for (unsigned i = 0; i < From.length(); i++) {
568  if (From[i] == '"')
569  To += "\\\"";
570  else
571  To += From[i];
572  }
573  }
574 
575  QualType getSimpleFunctionType(QualType result,
576  ArrayRef<QualType> args,
577  bool variadic = false) {
578  if (result == Context->getObjCInstanceType())
579  result = Context->getObjCIdType();
581  fpi.Variadic = variadic;
582  return Context->getFunctionType(result, args, fpi);
583  }
584 
585  // Helper function: create a CStyleCastExpr with trivial type source info.
586  CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
587  CastKind Kind, Expr *E) {
589  return CStyleCastExpr::Create(*Ctx, Ty, VK_PRValue, Kind, E, nullptr,
590  FPOptionsOverride(), TInfo,
592  }
593 
594  bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
595  const IdentifierInfo *II = &Context->Idents.get("load");
596  Selector LoadSel = Context->Selectors.getSelector(0, &II);
597  return OD->getClassMethod(LoadSel) != nullptr;
598  }
599 
600  StringLiteral *getStringLiteral(StringRef Str) {
601  QualType StrType = Context->getConstantArrayType(
602  Context->CharTy, llvm::APInt(32, Str.size() + 1), nullptr,
605  /*Pascal=*/false, StrType, SourceLocation());
606  }
607  };
608 } // end anonymous namespace
609 
610 void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
611  NamedDecl *D) {
612  if (const FunctionProtoType *fproto
613  = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
614  for (const auto &I : fproto->param_types())
615  if (isTopLevelBlockPointerType(I)) {
616  // All the args are checked/rewritten. Don't call twice!
617  RewriteBlockPointerDecl(D);
618  break;
619  }
620  }
621 }
622 
623 void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
624  const PointerType *PT = funcType->getAs<PointerType>();
625  if (PT && PointerTypeTakesAnyBlockArguments(funcType))
626  RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
627 }
628 
629 static bool IsHeaderFile(const std::string &Filename) {
630  std::string::size_type DotPos = Filename.rfind('.');
631 
632  if (DotPos == std::string::npos) {
633  // no file extension
634  return false;
635  }
636 
637  std::string Ext = Filename.substr(DotPos + 1);
638  // C header: .h
639  // C++ header: .hh or .H;
640  return Ext == "h" || Ext == "hh" || Ext == "H";
641 }
642 
643 RewriteModernObjC::RewriteModernObjC(std::string inFile,
644  std::unique_ptr<raw_ostream> OS,
646  const LangOptions &LOpts,
647  bool silenceMacroWarn, bool LineInfo)
648  : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(std::move(OS)),
649  SilenceRewriteMacroWarning(silenceMacroWarn), GenerateLineInfo(LineInfo) {
650  IsHeader = IsHeaderFile(inFile);
651  RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
652  "rewriting sub-expression within a macro (may not be correct)");
653  // FIXME. This should be an error. But if block is not called, it is OK. And it
654  // may break including some headers.
655  GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
656  "rewriting block literal declared in global scope is not implemented");
657 
658  TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
660  "rewriter doesn't support user-specified control flow semantics "
661  "for @try/@finally (code may not execute properly)");
662 }
663 
664 std::unique_ptr<ASTConsumer> clang::CreateModernObjCRewriter(
665  const std::string &InFile, std::unique_ptr<raw_ostream> OS,
666  DiagnosticsEngine &Diags, const LangOptions &LOpts,
667  bool SilenceRewriteMacroWarning, bool LineInfo) {
668  return std::make_unique<RewriteModernObjC>(InFile, std::move(OS), Diags,
669  LOpts, SilenceRewriteMacroWarning,
670  LineInfo);
671 }
672 
673 void RewriteModernObjC::InitializeCommon(ASTContext &context) {
674  Context = &context;
675  SM = &Context->getSourceManager();
676  TUDecl = Context->getTranslationUnitDecl();
677  MsgSendFunctionDecl = nullptr;
678  MsgSendSuperFunctionDecl = nullptr;
679  MsgSendStretFunctionDecl = nullptr;
680  MsgSendSuperStretFunctionDecl = nullptr;
681  MsgSendFpretFunctionDecl = nullptr;
682  GetClassFunctionDecl = nullptr;
683  GetMetaClassFunctionDecl = nullptr;
684  GetSuperClassFunctionDecl = nullptr;
685  SelGetUidFunctionDecl = nullptr;
686  CFStringFunctionDecl = nullptr;
687  ConstantStringClassReference = nullptr;
688  NSStringRecord = nullptr;
689  CurMethodDef = nullptr;
690  CurFunctionDef = nullptr;
691  GlobalVarDecl = nullptr;
692  GlobalConstructionExp = nullptr;
693  SuperStructDecl = nullptr;
694  ProtocolTypeDecl = nullptr;
695  ConstantStringDecl = nullptr;
696  BcLabelCount = 0;
697  SuperConstructorFunctionDecl = nullptr;
698  NumObjCStringLiterals = 0;
699  PropParentMap = nullptr;
700  CurrentBody = nullptr;
701  DisableReplaceStmt = false;
702  objc_impl_method = false;
703 
704  // Get the ID and start/end of the main file.
705  MainFileID = SM->getMainFileID();
706  llvm::MemoryBufferRef MainBuf = SM->getBufferOrFake(MainFileID);
707  MainFileStart = MainBuf.getBufferStart();
708  MainFileEnd = MainBuf.getBufferEnd();
709 
710  Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
711 }
712 
713 //===----------------------------------------------------------------------===//
714 // Top Level Driver Code
715 //===----------------------------------------------------------------------===//
716 
717 void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
718  if (Diags.hasErrorOccurred())
719  return;
720 
721  // Two cases: either the decl could be in the main file, or it could be in a
722  // #included file. If the former, rewrite it now. If the later, check to see
723  // if we rewrote the #include/#import.
725  Loc = SM->getExpansionLoc(Loc);
726 
727  // If this is for a builtin, ignore it.
728  if (Loc.isInvalid()) return;
729 
730  // Look for built-in declarations that we need to refer during the rewrite.
731  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
732  RewriteFunctionDecl(FD);
733  } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
734  // declared in <Foundation/NSString.h>
735  if (FVD->getName() == "_NSConstantStringClassReference") {
736  ConstantStringClassReference = FVD;
737  return;
738  }
739  } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
740  RewriteCategoryDecl(CD);
741  } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
742  if (PD->isThisDeclarationADefinition())
743  RewriteProtocolDecl(PD);
744  } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
745  // Recurse into linkage specifications
746  for (DeclContext::decl_iterator DI = LSD->decls_begin(),
747  DIEnd = LSD->decls_end();
748  DI != DIEnd; ) {
749  if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
750  if (!IFace->isThisDeclarationADefinition()) {
752  SourceLocation StartLoc = IFace->getBeginLoc();
753  do {
754  if (isa<ObjCInterfaceDecl>(*DI) &&
755  !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
756  StartLoc == (*DI)->getBeginLoc())
757  DG.push_back(*DI);
758  else
759  break;
760 
761  ++DI;
762  } while (DI != DIEnd);
763  RewriteForwardClassDecl(DG);
764  continue;
765  }
766  else {
767  // Keep track of all interface declarations seen.
768  ObjCInterfacesSeen.push_back(IFace);
769  ++DI;
770  continue;
771  }
772  }
773 
774  if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
775  if (!Proto->isThisDeclarationADefinition()) {
777  SourceLocation StartLoc = Proto->getBeginLoc();
778  do {
779  if (isa<ObjCProtocolDecl>(*DI) &&
780  !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
781  StartLoc == (*DI)->getBeginLoc())
782  DG.push_back(*DI);
783  else
784  break;
785 
786  ++DI;
787  } while (DI != DIEnd);
788  RewriteForwardProtocolDecl(DG);
789  continue;
790  }
791  }
792 
793  HandleTopLevelSingleDecl(*DI);
794  ++DI;
795  }
796  }
797  // If we have a decl in the main file, see if we should rewrite it.
798  if (SM->isWrittenInMainFile(Loc))
799  return HandleDeclInMainFile(D);
800 }
801 
802 //===----------------------------------------------------------------------===//
803 // Syntactic (non-AST) Rewriting Code
804 //===----------------------------------------------------------------------===//
805 
806 void RewriteModernObjC::RewriteInclude() {
807  SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
808  StringRef MainBuf = SM->getBufferData(MainFileID);
809  const char *MainBufStart = MainBuf.begin();
810  const char *MainBufEnd = MainBuf.end();
811  size_t ImportLen = strlen("import");
812 
813  // Loop over the whole file, looking for includes.
814  for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
815  if (*BufPtr == '#') {
816  if (++BufPtr == MainBufEnd)
817  return;
818  while (*BufPtr == ' ' || *BufPtr == '\t')
819  if (++BufPtr == MainBufEnd)
820  return;
821  if (!strncmp(BufPtr, "import", ImportLen)) {
822  // replace import with include
823  SourceLocation ImportLoc =
824  LocStart.getLocWithOffset(BufPtr-MainBufStart);
825  ReplaceText(ImportLoc, ImportLen, "include");
826  BufPtr += ImportLen;
827  }
828  }
829  }
830 }
831 
832 static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl,
833  ObjCIvarDecl *IvarDecl, std::string &Result) {
834  Result += "OBJC_IVAR_$_";
835  Result += IDecl->getName();
836  Result += "$";
837  Result += IvarDecl->getName();
838 }
839 
840 std::string
842  const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
843 
844  // Build name of symbol holding ivar offset.
845  std::string IvarOffsetName;
846  if (D->isBitField())
847  ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
848  else
849  WriteInternalIvarName(ClassDecl, D, IvarOffsetName);
850 
851  std::string S = "(*(";
852  QualType IvarT = D->getType();
853  if (D->isBitField())
854  IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
855 
856  if (!IvarT->getAs<TypedefType>() && IvarT->isRecordType()) {
857  RecordDecl *RD = IvarT->castAs<RecordType>()->getDecl();
858  RD = RD->getDefinition();
859  if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
860  // decltype(((Foo_IMPL*)0)->bar) *
861  auto *CDecl = cast<ObjCContainerDecl>(D->getDeclContext());
862  // ivar in class extensions requires special treatment.
863  if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
864  CDecl = CatDecl->getClassInterface();
865  std::string RecName = std::string(CDecl->getName());
866  RecName += "_IMPL";
867  RecordDecl *RD = RecordDecl::Create(*Context, TagTypeKind::Struct, TUDecl,
869  &Context->Idents.get(RecName));
870  QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
871  unsigned UnsignedIntSize =
872  static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
873  Expr *Zero = IntegerLiteral::Create(*Context,
874  llvm::APInt(UnsignedIntSize, 0),
875  Context->UnsignedIntTy, SourceLocation());
876  Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
877  ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
878  Zero);
879  FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
880  SourceLocation(),
881  &Context->Idents.get(D->getNameAsString()),
882  IvarT, nullptr,
883  /*BitWidth=*/nullptr, /*Mutable=*/true,
884  ICIS_NoInit);
885  MemberExpr *ME = MemberExpr::CreateImplicit(
886  *Context, PE, true, FD, FD->getType(), VK_LValue, OK_Ordinary);
887  IvarT = Context->getDecltypeType(ME, ME->getType());
888  }
889  }
890  convertObjCTypeToCStyleType(IvarT);
891  QualType castT = Context->getPointerType(IvarT);
892  std::string TypeString(castT.getAsString(Context->getPrintingPolicy()));
893  S += TypeString;
894  S += ")";
895 
896  // ((char *)self + IVAR_OFFSET_SYMBOL_NAME)
897  S += "((char *)self + ";
898  S += IvarOffsetName;
899  S += "))";
900  if (D->isBitField()) {
901  S += ".";
902  S += D->getNameAsString();
903  }
904  ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D);
905  return S;
906 }
907 
908 /// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
909 /// been found in the class implementation. In this case, it must be synthesized.
911  ObjCPropertyDecl *PD,
912  bool getter) {
913  auto *OMD = IMP->getInstanceMethod(getter ? PD->getGetterName()
914  : PD->getSetterName());
915  return !OMD || OMD->isSynthesizedAccessorStub();
916 }
917 
918 void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
920  ObjCCategoryImplDecl *CID) {
921  static bool objcGetPropertyDefined = false;
922  static bool objcSetPropertyDefined = false;
923  SourceLocation startGetterSetterLoc;
924 
925  if (PID->getBeginLoc().isValid()) {
926  SourceLocation startLoc = PID->getBeginLoc();
927  InsertText(startLoc, "// ");
928  const char *startBuf = SM->getCharacterData(startLoc);
929  assert((*startBuf == '@') && "bogus @synthesize location");
930  const char *semiBuf = strchr(startBuf, ';');
931  assert((*semiBuf == ';') && "@synthesize: can't find ';'");
932  startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
933  } else
934  startGetterSetterLoc = IMD ? IMD->getEndLoc() : CID->getEndLoc();
935 
936  if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
937  return; // FIXME: is this correct?
938 
939  // Generate the 'getter' function.
940  ObjCPropertyDecl *PD = PID->getPropertyDecl();
941  ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
942  assert(IMD && OID && "Synthesized ivars must be attached to @implementation");
943 
944  unsigned Attributes = PD->getPropertyAttributes();
945  if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
946  bool GenGetProperty =
947  !(Attributes & ObjCPropertyAttribute::kind_nonatomic) &&
948  (Attributes & (ObjCPropertyAttribute::kind_retain |
950  std::string Getr;
951  if (GenGetProperty && !objcGetPropertyDefined) {
952  objcGetPropertyDefined = true;
953  // FIXME. Is this attribute correct in all cases?
954  Getr = "\nextern \"C\" __declspec(dllimport) "
955  "id objc_getProperty(id, SEL, long, bool);\n";
956  }
957  RewriteObjCMethodDecl(OID->getContainingInterface(),
958  PID->getGetterMethodDecl(), Getr);
959  Getr += "{ ";
960  // Synthesize an explicit cast to gain access to the ivar.
961  // See objc-act.c:objc_synthesize_new_getter() for details.
962  if (GenGetProperty) {
963  // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
964  Getr += "typedef ";
965  const FunctionType *FPRetType = nullptr;
966  RewriteTypeIntoString(PID->getGetterMethodDecl()->getReturnType(), Getr,
967  FPRetType);
968  Getr += " _TYPE";
969  if (FPRetType) {
970  Getr += ")"; // close the precedence "scope" for "*".
971 
972  // Now, emit the argument types (if any).
973  if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
974  Getr += "(";
975  for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
976  if (i) Getr += ", ";
977  std::string ParamStr =
978  FT->getParamType(i).getAsString(Context->getPrintingPolicy());
979  Getr += ParamStr;
980  }
981  if (FT->isVariadic()) {
982  if (FT->getNumParams())
983  Getr += ", ";
984  Getr += "...";
985  }
986  Getr += ")";
987  } else
988  Getr += "()";
989  }
990  Getr += ";\n";
991  Getr += "return (_TYPE)";
992  Getr += "objc_getProperty(self, _cmd, ";
993  RewriteIvarOffsetComputation(OID, Getr);
994  Getr += ", 1)";
995  }
996  else
997  Getr += "return " + getIvarAccessString(OID);
998  Getr += "; }";
999  InsertText(startGetterSetterLoc, Getr);
1000  }
1001 
1002  if (PD->isReadOnly() ||
1003  !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
1004  return;
1005 
1006  // Generate the 'setter' function.
1007  std::string Setr;
1008  bool GenSetProperty = Attributes & (ObjCPropertyAttribute::kind_retain |
1010  if (GenSetProperty && !objcSetPropertyDefined) {
1011  objcSetPropertyDefined = true;
1012  // FIXME. Is this attribute correct in all cases?
1013  Setr = "\nextern \"C\" __declspec(dllimport) "
1014  "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
1015  }
1016 
1017  RewriteObjCMethodDecl(OID->getContainingInterface(),
1018  PID->getSetterMethodDecl(), Setr);
1019  Setr += "{ ";
1020  // Synthesize an explicit cast to initialize the ivar.
1021  // See objc-act.c:objc_synthesize_new_setter() for details.
1022  if (GenSetProperty) {
1023  Setr += "objc_setProperty (self, _cmd, ";
1024  RewriteIvarOffsetComputation(OID, Setr);
1025  Setr += ", (id)";
1026  Setr += PD->getName();
1027  Setr += ", ";
1028  if (Attributes & ObjCPropertyAttribute::kind_nonatomic)
1029  Setr += "0, ";
1030  else
1031  Setr += "1, ";
1032  if (Attributes & ObjCPropertyAttribute::kind_copy)
1033  Setr += "1)";
1034  else
1035  Setr += "0)";
1036  }
1037  else {
1038  Setr += getIvarAccessString(OID) + " = ";
1039  Setr += PD->getName();
1040  }
1041  Setr += "; }\n";
1042  InsertText(startGetterSetterLoc, Setr);
1043 }
1044 
1046  std::string &typedefString) {
1047  typedefString += "\n#ifndef _REWRITER_typedef_";
1048  typedefString += ForwardDecl->getNameAsString();
1049  typedefString += "\n";
1050  typedefString += "#define _REWRITER_typedef_";
1051  typedefString += ForwardDecl->getNameAsString();
1052  typedefString += "\n";
1053  typedefString += "typedef struct objc_object ";
1054  typedefString += ForwardDecl->getNameAsString();
1055  // typedef struct { } _objc_exc_Classname;
1056  typedefString += ";\ntypedef struct {} _objc_exc_";
1057  typedefString += ForwardDecl->getNameAsString();
1058  typedefString += ";\n#endif\n";
1059 }
1060 
1061 void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
1062  const std::string &typedefString) {
1063  SourceLocation startLoc = ClassDecl->getBeginLoc();
1064  const char *startBuf = SM->getCharacterData(startLoc);
1065  const char *semiPtr = strchr(startBuf, ';');
1066  // Replace the @class with typedefs corresponding to the classes.
1067  ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
1068 }
1069 
1070 void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
1071  std::string typedefString;
1072  for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
1073  if (ObjCInterfaceDecl *ForwardDecl = dyn_cast<ObjCInterfaceDecl>(*I)) {
1074  if (I == D.begin()) {
1075  // Translate to typedef's that forward reference structs with the same name
1076  // as the class. As a convenience, we include the original declaration
1077  // as a comment.
1078  typedefString += "// @class ";
1079  typedefString += ForwardDecl->getNameAsString();
1080  typedefString += ";";
1081  }
1082  RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1083  }
1084  else
1085  HandleTopLevelSingleDecl(*I);
1086  }
1087  DeclGroupRef::iterator I = D.begin();
1088  RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
1089 }
1090 
1091 void RewriteModernObjC::RewriteForwardClassDecl(
1092  const SmallVectorImpl<Decl *> &D) {
1093  std::string typedefString;
1094  for (unsigned i = 0; i < D.size(); i++) {
1095  ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
1096  if (i == 0) {
1097  typedefString += "// @class ";
1098  typedefString += ForwardDecl->getNameAsString();
1099  typedefString += ";";
1100  }
1101  RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1102  }
1103  RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
1104 }
1105 
1106 void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
1107  // When method is a synthesized one, such as a getter/setter there is
1108  // nothing to rewrite.
1109  if (Method->isImplicit())
1110  return;
1111  SourceLocation LocStart = Method->getBeginLoc();
1112  SourceLocation LocEnd = Method->getEndLoc();
1113 
1114  if (SM->getExpansionLineNumber(LocEnd) >
1115  SM->getExpansionLineNumber(LocStart)) {
1116  InsertText(LocStart, "#if 0\n");
1117  ReplaceText(LocEnd, 1, ";\n#endif\n");
1118  } else {
1119  InsertText(LocStart, "// ");
1120  }
1121 }
1122 
1123 void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
1124  SourceLocation Loc = prop->getAtLoc();
1125 
1126  ReplaceText(Loc, 0, "// ");
1127  // FIXME: handle properties that are declared across multiple lines.
1128 }
1129 
1130 void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
1131  SourceLocation LocStart = CatDecl->getBeginLoc();
1132 
1133  // FIXME: handle category headers that are declared across multiple lines.
1134  if (CatDecl->getIvarRBraceLoc().isValid()) {
1135  ReplaceText(LocStart, 1, "/** ");
1136  ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1137  }
1138  else {
1139  ReplaceText(LocStart, 0, "// ");
1140  }
1141 
1142  for (auto *I : CatDecl->instance_properties())
1143  RewriteProperty(I);
1144 
1145  for (auto *I : CatDecl->instance_methods())
1146  RewriteMethodDeclaration(I);
1147  for (auto *I : CatDecl->class_methods())
1148  RewriteMethodDeclaration(I);
1149 
1150  // Lastly, comment out the @end.
1151  ReplaceText(CatDecl->getAtEndRange().getBegin(),
1152  strlen("@end"), "/* @end */\n");
1153 }
1154 
1155 void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1156  SourceLocation LocStart = PDecl->getBeginLoc();
1157  assert(PDecl->isThisDeclarationADefinition());
1158 
1159  // FIXME: handle protocol headers that are declared across multiple lines.
1160  ReplaceText(LocStart, 0, "// ");
1161 
1162  for (auto *I : PDecl->instance_methods())
1163  RewriteMethodDeclaration(I);
1164  for (auto *I : PDecl->class_methods())
1165  RewriteMethodDeclaration(I);
1166  for (auto *I : PDecl->instance_properties())
1167  RewriteProperty(I);
1168 
1169  // Lastly, comment out the @end.
1170  SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1171  ReplaceText(LocEnd, strlen("@end"), "/* @end */\n");
1172 
1173  // Must comment out @optional/@required
1174  const char *startBuf = SM->getCharacterData(LocStart);
1175  const char *endBuf = SM->getCharacterData(LocEnd);
1176  for (const char *p = startBuf; p < endBuf; p++) {
1177  if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1178  SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1179  ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1180 
1181  }
1182  else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1183  SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1184  ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1185 
1186  }
1187  }
1188 }
1189 
1190 void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1191  SourceLocation LocStart = (*D.begin())->getBeginLoc();
1192  if (LocStart.isInvalid())
1193  llvm_unreachable("Invalid SourceLocation");
1194  // FIXME: handle forward protocol that are declared across multiple lines.
1195  ReplaceText(LocStart, 0, "// ");
1196 }
1197 
1198 void
1199 RewriteModernObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
1200  SourceLocation LocStart = DG[0]->getBeginLoc();
1201  if (LocStart.isInvalid())
1202  llvm_unreachable("Invalid SourceLocation");
1203  // FIXME: handle forward protocol that are declared across multiple lines.
1204  ReplaceText(LocStart, 0, "// ");
1205 }
1206 
1207 void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1208  const FunctionType *&FPRetType) {
1209  if (T->isObjCQualifiedIdType())
1210  ResultStr += "id";
1211  else if (T->isFunctionPointerType() ||
1212  T->isBlockPointerType()) {
1213  // needs special handling, since pointer-to-functions have special
1214  // syntax (where a decaration models use).
1215  QualType retType = T;
1216  QualType PointeeTy;
1217  if (const PointerType* PT = retType->getAs<PointerType>())
1218  PointeeTy = PT->getPointeeType();
1219  else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1220  PointeeTy = BPT->getPointeeType();
1221  if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1222  ResultStr +=
1223  FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
1224  ResultStr += "(*";
1225  }
1226  } else
1227  ResultStr += T.getAsString(Context->getPrintingPolicy());
1228 }
1229 
1230 void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1231  ObjCMethodDecl *OMD,
1232  std::string &ResultStr) {
1233  //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1234  const FunctionType *FPRetType = nullptr;
1235  ResultStr += "\nstatic ";
1236  RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
1237  ResultStr += " ";
1238 
1239  // Unique method name
1240  std::string NameStr;
1241 
1242  if (OMD->isInstanceMethod())
1243  NameStr += "_I_";
1244  else
1245  NameStr += "_C_";
1246 
1247  NameStr += IDecl->getNameAsString();
1248  NameStr += "_";
1249 
1250  if (ObjCCategoryImplDecl *CID =
1251  dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1252  NameStr += CID->getNameAsString();
1253  NameStr += "_";
1254  }
1255  // Append selector names, replacing ':' with '_'
1256  {
1257  std::string selString = OMD->getSelector().getAsString();
1258  int len = selString.size();
1259  for (int i = 0; i < len; i++)
1260  if (selString[i] == ':')
1261  selString[i] = '_';
1262  NameStr += selString;
1263  }
1264  // Remember this name for metadata emission
1265  MethodInternalNames[OMD] = NameStr;
1266  ResultStr += NameStr;
1267 
1268  // Rewrite arguments
1269  ResultStr += "(";
1270 
1271  // invisible arguments
1272  if (OMD->isInstanceMethod()) {
1273  QualType selfTy = Context->getObjCInterfaceType(IDecl);
1274  selfTy = Context->getPointerType(selfTy);
1275  if (!LangOpts.MicrosoftExt) {
1276  if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1277  ResultStr += "struct ";
1278  }
1279  // When rewriting for Microsoft, explicitly omit the structure name.
1280  ResultStr += IDecl->getNameAsString();
1281  ResultStr += " *";
1282  }
1283  else
1284  ResultStr += Context->getObjCClassType().getAsString(
1285  Context->getPrintingPolicy());
1286 
1287  ResultStr += " self, ";
1288  ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1289  ResultStr += " _cmd";
1290 
1291  // Method arguments.
1292  for (const auto *PDecl : OMD->parameters()) {
1293  ResultStr += ", ";
1294  if (PDecl->getType()->isObjCQualifiedIdType()) {
1295  ResultStr += "id ";
1296  ResultStr += PDecl->getNameAsString();
1297  } else {
1298  std::string Name = PDecl->getNameAsString();
1299  QualType QT = PDecl->getType();
1300  // Make sure we convert "t (^)(...)" to "t (*)(...)".
1301  (void)convertBlockPointerToFunctionPointer(QT);
1302  QT.getAsStringInternal(Name, Context->getPrintingPolicy());
1303  ResultStr += Name;
1304  }
1305  }
1306  if (OMD->isVariadic())
1307  ResultStr += ", ...";
1308  ResultStr += ") ";
1309 
1310  if (FPRetType) {
1311  ResultStr += ")"; // close the precedence "scope" for "*".
1312 
1313  // Now, emit the argument types (if any).
1314  if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1315  ResultStr += "(";
1316  for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1317  if (i) ResultStr += ", ";
1318  std::string ParamStr =
1319  FT->getParamType(i).getAsString(Context->getPrintingPolicy());
1320  ResultStr += ParamStr;
1321  }
1322  if (FT->isVariadic()) {
1323  if (FT->getNumParams())
1324  ResultStr += ", ";
1325  ResultStr += "...";
1326  }
1327  ResultStr += ")";
1328  } else {
1329  ResultStr += "()";
1330  }
1331  }
1332 }
1333 
1334 void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1335  ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1336  ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1337  assert((IMD || CID) && "Unknown implementation type");
1338 
1339  if (IMD) {
1340  if (IMD->getIvarRBraceLoc().isValid()) {
1341  ReplaceText(IMD->getBeginLoc(), 1, "/** ");
1342  ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
1343  }
1344  else {
1345  InsertText(IMD->getBeginLoc(), "// ");
1346  }
1347  }
1348  else
1349  InsertText(CID->getBeginLoc(), "// ");
1350 
1351  for (auto *OMD : IMD ? IMD->instance_methods() : CID->instance_methods()) {
1352  if (!OMD->getBody())
1353  continue;
1354  std::string ResultStr;
1355  RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1356  SourceLocation LocStart = OMD->getBeginLoc();
1357  SourceLocation LocEnd = OMD->getCompoundBody()->getBeginLoc();
1358 
1359  const char *startBuf = SM->getCharacterData(LocStart);
1360  const char *endBuf = SM->getCharacterData(LocEnd);
1361  ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1362  }
1363 
1364  for (auto *OMD : IMD ? IMD->class_methods() : CID->class_methods()) {
1365  if (!OMD->getBody())
1366  continue;
1367  std::string ResultStr;
1368  RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1369  SourceLocation LocStart = OMD->getBeginLoc();
1370  SourceLocation LocEnd = OMD->getCompoundBody()->getBeginLoc();
1371 
1372  const char *startBuf = SM->getCharacterData(LocStart);
1373  const char *endBuf = SM->getCharacterData(LocEnd);
1374  ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1375  }
1376  for (auto *I : IMD ? IMD->property_impls() : CID->property_impls())
1377  RewritePropertyImplDecl(I, IMD, CID);
1378 
1379  InsertText(IMD ? IMD->getEndLoc() : CID->getEndLoc(), "// ");
1380 }
1381 
1382 void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
1383  // Do not synthesize more than once.
1384  if (ObjCSynthesizedStructs.count(ClassDecl))
1385  return;
1386  // Make sure super class's are written before current class is written.
1387  ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1388  while (SuperClass) {
1389  RewriteInterfaceDecl(SuperClass);
1390  SuperClass = SuperClass->getSuperClass();
1391  }
1392  std::string ResultStr;
1393  if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
1394  // we haven't seen a forward decl - generate a typedef.
1395  RewriteOneForwardClassDecl(ClassDecl, ResultStr);
1396  RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1397 
1398  RewriteObjCInternalStruct(ClassDecl, ResultStr);
1399  // Mark this typedef as having been written into its c++ equivalent.
1400  ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
1401 
1402  for (auto *I : ClassDecl->instance_properties())
1403  RewriteProperty(I);
1404  for (auto *I : ClassDecl->instance_methods())
1405  RewriteMethodDeclaration(I);
1406  for (auto *I : ClassDecl->class_methods())
1407  RewriteMethodDeclaration(I);
1408 
1409  // Lastly, comment out the @end.
1410  ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1411  "/* @end */\n");
1412  }
1413 }
1414 
1415 Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1416  SourceRange OldRange = PseudoOp->getSourceRange();
1417 
1418  // We just magically know some things about the structure of this
1419  // expression.
1420  ObjCMessageExpr *OldMsg =
1421  cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1422  PseudoOp->getNumSemanticExprs() - 1));
1423 
1424  // Because the rewriter doesn't allow us to rewrite rewritten code,
1425  // we need to suppress rewriting the sub-statements.
1426  Expr *Base;
1427  SmallVector<Expr*, 2> Args;
1428  {
1429  DisableReplaceStmtScope S(*this);
1430 
1431  // Rebuild the base expression if we have one.
1432  Base = nullptr;
1433  if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1434  Base = OldMsg->getInstanceReceiver();
1435  Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1436  Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1437  }
1438 
1439  unsigned numArgs = OldMsg->getNumArgs();
1440  for (unsigned i = 0; i < numArgs; i++) {
1441  Expr *Arg = OldMsg->getArg(i);
1442  if (isa<OpaqueValueExpr>(Arg))
1443  Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1444  Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1445  Args.push_back(Arg);
1446  }
1447  }
1448 
1449  // TODO: avoid this copy.
1451  OldMsg->getSelectorLocs(SelLocs);
1452 
1453  ObjCMessageExpr *NewMsg = nullptr;
1454  switch (OldMsg->getReceiverKind()) {
1455  case ObjCMessageExpr::Class:
1456  NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1457  OldMsg->getValueKind(),
1458  OldMsg->getLeftLoc(),
1459  OldMsg->getClassReceiverTypeInfo(),
1460  OldMsg->getSelector(),
1461  SelLocs,
1462  OldMsg->getMethodDecl(),
1463  Args,
1464  OldMsg->getRightLoc(),
1465  OldMsg->isImplicit());
1466  break;
1467 
1468  case ObjCMessageExpr::Instance:
1469  NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1470  OldMsg->getValueKind(),
1471  OldMsg->getLeftLoc(),
1472  Base,
1473  OldMsg->getSelector(),
1474  SelLocs,
1475  OldMsg->getMethodDecl(),
1476  Args,
1477  OldMsg->getRightLoc(),
1478  OldMsg->isImplicit());
1479  break;
1480 
1481  case ObjCMessageExpr::SuperClass:
1482  case ObjCMessageExpr::SuperInstance:
1483  NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1484  OldMsg->getValueKind(),
1485  OldMsg->getLeftLoc(),
1486  OldMsg->getSuperLoc(),
1487  OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1488  OldMsg->getSuperType(),
1489  OldMsg->getSelector(),
1490  SelLocs,
1491  OldMsg->getMethodDecl(),
1492  Args,
1493  OldMsg->getRightLoc(),
1494  OldMsg->isImplicit());
1495  break;
1496  }
1497 
1498  Stmt *Replacement = SynthMessageExpr(NewMsg);
1499  ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1500  return Replacement;
1501 }
1502 
1503 Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1504  SourceRange OldRange = PseudoOp->getSourceRange();
1505 
1506  // We just magically know some things about the structure of this
1507  // expression.
1508  ObjCMessageExpr *OldMsg =
1509  cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1510 
1511  // Because the rewriter doesn't allow us to rewrite rewritten code,
1512  // we need to suppress rewriting the sub-statements.
1513  Expr *Base = nullptr;
1514  SmallVector<Expr*, 1> Args;
1515  {
1516  DisableReplaceStmtScope S(*this);
1517  // Rebuild the base expression if we have one.
1518  if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1519  Base = OldMsg->getInstanceReceiver();
1520  Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1521  Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1522  }
1523  unsigned numArgs = OldMsg->getNumArgs();
1524  for (unsigned i = 0; i < numArgs; i++) {
1525  Expr *Arg = OldMsg->getArg(i);
1526  if (isa<OpaqueValueExpr>(Arg))
1527  Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1528  Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1529  Args.push_back(Arg);
1530  }
1531  }
1532 
1533  // Intentionally empty.
1535 
1536  ObjCMessageExpr *NewMsg = nullptr;
1537  switch (OldMsg->getReceiverKind()) {
1538  case ObjCMessageExpr::Class:
1539  NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1540  OldMsg->getValueKind(),
1541  OldMsg->getLeftLoc(),
1542  OldMsg->getClassReceiverTypeInfo(),
1543  OldMsg->getSelector(),
1544  SelLocs,
1545  OldMsg->getMethodDecl(),
1546  Args,
1547  OldMsg->getRightLoc(),
1548  OldMsg->isImplicit());
1549  break;
1550 
1551  case ObjCMessageExpr::Instance:
1552  NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1553  OldMsg->getValueKind(),
1554  OldMsg->getLeftLoc(),
1555  Base,
1556  OldMsg->getSelector(),
1557  SelLocs,
1558  OldMsg->getMethodDecl(),
1559  Args,
1560  OldMsg->getRightLoc(),
1561  OldMsg->isImplicit());
1562  break;
1563 
1564  case ObjCMessageExpr::SuperClass:
1565  case ObjCMessageExpr::SuperInstance:
1566  NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1567  OldMsg->getValueKind(),
1568  OldMsg->getLeftLoc(),
1569  OldMsg->getSuperLoc(),
1570  OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1571  OldMsg->getSuperType(),
1572  OldMsg->getSelector(),
1573  SelLocs,
1574  OldMsg->getMethodDecl(),
1575  Args,
1576  OldMsg->getRightLoc(),
1577  OldMsg->isImplicit());
1578  break;
1579  }
1580 
1581  Stmt *Replacement = SynthMessageExpr(NewMsg);
1582  ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1583  return Replacement;
1584 }
1585 
1586 /// SynthCountByEnumWithState - To print:
1587 /// ((NSUInteger (*)
1588 /// (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
1589 /// (void *)objc_msgSend)((id)l_collection,
1590 /// sel_registerName(
1591 /// "countByEnumeratingWithState:objects:count:"),
1592 /// &enumState,
1593 /// (id *)__rw_items, (NSUInteger)16)
1594 ///
1595 void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1596  buf += "((_WIN_NSUInteger (*) (id, SEL, struct __objcFastEnumerationState *, "
1597  "id *, _WIN_NSUInteger))(void *)objc_msgSend)";
1598  buf += "\n\t\t";
1599  buf += "((id)l_collection,\n\t\t";
1600  buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1601  buf += "\n\t\t";
1602  buf += "&enumState, "
1603  "(id *)__rw_items, (_WIN_NSUInteger)16)";
1604 }
1605 
1606 /// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1607 /// statement to exit to its outer synthesized loop.
1608 ///
1609 Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1610  if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1611  return S;
1612  // replace break with goto __break_label
1613  std::string buf;
1614 
1615  SourceLocation startLoc = S->getBeginLoc();
1616  buf = "goto __break_label_";
1617  buf += utostr(ObjCBcLabelNo.back());
1618  ReplaceText(startLoc, strlen("break"), buf);
1619 
1620  return nullptr;
1621 }
1622 
1623 void RewriteModernObjC::ConvertSourceLocationToLineDirective(
1625  std::string &LineString) {
1626  if (Loc.isFileID() && GenerateLineInfo) {
1627  LineString += "\n#line ";
1628  PresumedLoc PLoc = SM->getPresumedLoc(Loc);
1629  LineString += utostr(PLoc.getLine());
1630  LineString += " \"";
1631  LineString += Lexer::Stringify(PLoc.getFilename());
1632  LineString += "\"\n";
1633  }
1634 }
1635 
1636 /// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1637 /// statement to continue with its inner synthesized loop.
1638 ///
1639 Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1640  if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1641  return S;
1642  // replace continue with goto __continue_label
1643  std::string buf;
1644 
1645  SourceLocation startLoc = S->getBeginLoc();
1646  buf = "goto __continue_label_";
1647  buf += utostr(ObjCBcLabelNo.back());
1648  ReplaceText(startLoc, strlen("continue"), buf);
1649 
1650  return nullptr;
1651 }
1652 
1653 /// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1654 /// It rewrites:
1655 /// for ( type elem in collection) { stmts; }
1656 
1657 /// Into:
1658 /// {
1659 /// type elem;
1660 /// struct __objcFastEnumerationState enumState = { 0 };
1661 /// id __rw_items[16];
1662 /// id l_collection = (id)collection;
1663 /// NSUInteger limit = [l_collection countByEnumeratingWithState:&enumState
1664 /// objects:__rw_items count:16];
1665 /// if (limit) {
1666 /// unsigned long startMutations = *enumState.mutationsPtr;
1667 /// do {
1668 /// unsigned long counter = 0;
1669 /// do {
1670 /// if (startMutations != *enumState.mutationsPtr)
1671 /// objc_enumerationMutation(l_collection);
1672 /// elem = (type)enumState.itemsPtr[counter++];
1673 /// stmts;
1674 /// __continue_label: ;
1675 /// } while (counter < limit);
1676 /// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1677 /// objects:__rw_items count:16]));
1678 /// elem = nil;
1679 /// __break_label: ;
1680 /// }
1681 /// else
1682 /// elem = nil;
1683 /// }
1684 ///
1685 Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1686  SourceLocation OrigEnd) {
1687  assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1688  assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1689  "ObjCForCollectionStmt Statement stack mismatch");
1690  assert(!ObjCBcLabelNo.empty() &&
1691  "ObjCForCollectionStmt - Label No stack empty");
1692 
1693  SourceLocation startLoc = S->getBeginLoc();
1694  const char *startBuf = SM->getCharacterData(startLoc);
1695  StringRef elementName;
1696  std::string elementTypeAsString;
1697  std::string buf;
1698  // line directive first.
1699  SourceLocation ForEachLoc = S->getForLoc();
1700  ConvertSourceLocationToLineDirective(ForEachLoc, buf);
1701  buf += "{\n\t";
1702  if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1703  // type elem;
1704  NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1705  QualType ElementType = cast<ValueDecl>(D)->getType();
1706  if (ElementType->isObjCQualifiedIdType() ||
1707  ElementType->isObjCQualifiedInterfaceType())
1708  // Simply use 'id' for all qualified types.
1709  elementTypeAsString = "id";
1710  else
1711  elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1712  buf += elementTypeAsString;
1713  buf += " ";
1714  elementName = D->getName();
1715  buf += elementName;
1716  buf += ";\n\t";
1717  }
1718  else {
1719  DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1720  elementName = DR->getDecl()->getName();
1721  ValueDecl *VD = DR->getDecl();
1722  if (VD->getType()->isObjCQualifiedIdType() ||
1724  // Simply use 'id' for all qualified types.
1725  elementTypeAsString = "id";
1726  else
1727  elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1728  }
1729 
1730  // struct __objcFastEnumerationState enumState = { 0 };
1731  buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1732  // id __rw_items[16];
1733  buf += "id __rw_items[16];\n\t";
1734  // id l_collection = (id)
1735  buf += "id l_collection = (id)";
1736  // Find start location of 'collection' the hard way!
1737  const char *startCollectionBuf = startBuf;
1738  startCollectionBuf += 3; // skip 'for'
1739  startCollectionBuf = strchr(startCollectionBuf, '(');
1740  startCollectionBuf++; // skip '('
1741  // find 'in' and skip it.
1742  while (*startCollectionBuf != ' ' ||
1743  *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1744  (*(startCollectionBuf+3) != ' ' &&
1745  *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1746  startCollectionBuf++;
1747  startCollectionBuf += 3;
1748 
1749  // Replace: "for (type element in" with string constructed thus far.
1750  ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1751  // Replace ')' in for '(' type elem in collection ')' with ';'
1752  SourceLocation rightParenLoc = S->getRParenLoc();
1753  const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1754  SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1755  buf = ";\n\t";
1756 
1757  // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1758  // objects:__rw_items count:16];
1759  // which is synthesized into:
1760  // NSUInteger limit =
1761  // ((NSUInteger (*)
1762  // (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
1763  // (void *)objc_msgSend)((id)l_collection,
1764  // sel_registerName(
1765  // "countByEnumeratingWithState:objects:count:"),
1766  // (struct __objcFastEnumerationState *)&state,
1767  // (id *)__rw_items, (NSUInteger)16);
1768  buf += "_WIN_NSUInteger limit =\n\t\t";
1769  SynthCountByEnumWithState(buf);
1770  buf += ";\n\t";
1771  /// if (limit) {
1772  /// unsigned long startMutations = *enumState.mutationsPtr;
1773  /// do {
1774  /// unsigned long counter = 0;
1775  /// do {
1776  /// if (startMutations != *enumState.mutationsPtr)
1777  /// objc_enumerationMutation(l_collection);
1778  /// elem = (type)enumState.itemsPtr[counter++];
1779  buf += "if (limit) {\n\t";
1780  buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1781  buf += "do {\n\t\t";
1782  buf += "unsigned long counter = 0;\n\t\t";
1783  buf += "do {\n\t\t\t";
1784  buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1785  buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1786  buf += elementName;
1787  buf += " = (";
1788  buf += elementTypeAsString;
1789  buf += ")enumState.itemsPtr[counter++];";
1790  // Replace ')' in for '(' type elem in collection ')' with all of these.
1791  ReplaceText(lparenLoc, 1, buf);
1792 
1793  /// __continue_label: ;
1794  /// } while (counter < limit);
1795  /// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1796  /// objects:__rw_items count:16]));
1797  /// elem = nil;
1798  /// __break_label: ;
1799  /// }
1800  /// else
1801  /// elem = nil;
1802  /// }
1803  ///
1804  buf = ";\n\t";
1805  buf += "__continue_label_";
1806  buf += utostr(ObjCBcLabelNo.back());
1807  buf += ": ;";
1808  buf += "\n\t\t";
1809  buf += "} while (counter < limit);\n\t";
1810  buf += "} while ((limit = ";
1811  SynthCountByEnumWithState(buf);
1812  buf += "));\n\t";
1813  buf += elementName;
1814  buf += " = ((";
1815  buf += elementTypeAsString;
1816  buf += ")0);\n\t";
1817  buf += "__break_label_";
1818  buf += utostr(ObjCBcLabelNo.back());
1819  buf += ": ;\n\t";
1820  buf += "}\n\t";
1821  buf += "else\n\t\t";
1822  buf += elementName;
1823  buf += " = ((";
1824  buf += elementTypeAsString;
1825  buf += ")0);\n\t";
1826  buf += "}\n";
1827 
1828  // Insert all these *after* the statement body.
1829  // FIXME: If this should support Obj-C++, support CXXTryStmt
1830  if (isa<CompoundStmt>(S->getBody())) {
1831  SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1832  InsertText(endBodyLoc, buf);
1833  } else {
1834  /* Need to treat single statements specially. For example:
1835  *
1836  * for (A *a in b) if (stuff()) break;
1837  * for (A *a in b) xxxyy;
1838  *
1839  * The following code simply scans ahead to the semi to find the actual end.
1840  */
1841  const char *stmtBuf = SM->getCharacterData(OrigEnd);
1842  const char *semiBuf = strchr(stmtBuf, ';');
1843  assert(semiBuf && "Can't find ';'");
1844  SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1845  InsertText(endBodyLoc, buf);
1846  }
1847  Stmts.pop_back();
1848  ObjCBcLabelNo.pop_back();
1849  return nullptr;
1850 }
1851 
1852 static void Write_RethrowObject(std::string &buf) {
1853  buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1854  buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1855  buf += "\tid rethrow;\n";
1856  buf += "\t} _fin_force_rethow(_rethrow);";
1857 }
1858 
1859 /// RewriteObjCSynchronizedStmt -
1860 /// This routine rewrites @synchronized(expr) stmt;
1861 /// into:
1862 /// objc_sync_enter(expr);
1863 /// @try stmt @finally { objc_sync_exit(expr); }
1864 ///
1865 Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1866  // Get the start location and compute the semi location.
1867  SourceLocation startLoc = S->getBeginLoc();
1868  const char *startBuf = SM->getCharacterData(startLoc);
1869 
1870  assert((*startBuf == '@') && "bogus @synchronized location");
1871 
1872  std::string buf;
1873  SourceLocation SynchLoc = S->getAtSynchronizedLoc();
1874  ConvertSourceLocationToLineDirective(SynchLoc, buf);
1875  buf += "{ id _rethrow = 0; id _sync_obj = (id)";
1876 
1877  const char *lparenBuf = startBuf;
1878  while (*lparenBuf != '(') lparenBuf++;
1879  ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
1880 
1881  buf = "; objc_sync_enter(_sync_obj);\n";
1882  buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1883  buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1884  buf += "\n\tid sync_exit;";
1885  buf += "\n\t} _sync_exit(_sync_obj);\n";
1886 
1887  // We can't use S->getSynchExpr()->getEndLoc() to find the end location, since
1888  // the sync expression is typically a message expression that's already
1889  // been rewritten! (which implies the SourceLocation's are invalid).
1890  SourceLocation RParenExprLoc = S->getSynchBody()->getBeginLoc();
1891  const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1892  while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1893  RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1894 
1895  SourceLocation LBranceLoc = S->getSynchBody()->getBeginLoc();
1896  const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1897  assert (*LBraceLocBuf == '{');
1898  ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
1899 
1900  SourceLocation startRBraceLoc = S->getSynchBody()->getEndLoc();
1901  assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1902  "bogus @synchronized block");
1903 
1904  buf = "} catch (id e) {_rethrow = e;}\n";
1905  Write_RethrowObject(buf);
1906  buf += "}\n";
1907  buf += "}\n";
1908 
1909  ReplaceText(startRBraceLoc, 1, buf);
1910 
1911  return nullptr;
1912 }
1913 
1914 void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1915 {
1916  // Perform a bottom up traversal of all children.
1917  for (Stmt *SubStmt : S->children())
1918  if (SubStmt)
1919  WarnAboutReturnGotoStmts(SubStmt);
1920 
1921  if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1922  Diags.Report(Context->getFullLoc(S->getBeginLoc()),
1923  TryFinallyContainsReturnDiag);
1924  }
1925 }
1926 
1927 Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
1928  SourceLocation startLoc = S->getAtLoc();
1929  ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
1930  ReplaceText(S->getSubStmt()->getBeginLoc(), 1,
1931  "{ __AtAutoreleasePool __autoreleasepool; ");
1932 
1933  return nullptr;
1934 }
1935 
1936 Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
1937  ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
1938  bool noCatch = S->getNumCatchStmts() == 0;
1939  std::string buf;
1940  SourceLocation TryLocation = S->getAtTryLoc();
1941  ConvertSourceLocationToLineDirective(TryLocation, buf);
1942 
1943  if (finalStmt) {
1944  if (noCatch)
1945  buf += "{ id volatile _rethrow = 0;\n";
1946  else {
1947  buf += "{ id volatile _rethrow = 0;\ntry {\n";
1948  }
1949  }
1950  // Get the start location and compute the semi location.
1951  SourceLocation startLoc = S->getBeginLoc();
1952  const char *startBuf = SM->getCharacterData(startLoc);
1953 
1954  assert((*startBuf == '@') && "bogus @try location");
1955  if (finalStmt)
1956  ReplaceText(startLoc, 1, buf);
1957  else
1958  // @try -> try
1959  ReplaceText(startLoc, 1, "");
1960 
1961  for (ObjCAtCatchStmt *Catch : S->catch_stmts()) {
1962  VarDecl *catchDecl = Catch->getCatchParamDecl();
1963 
1964  startLoc = Catch->getBeginLoc();
1965  bool AtRemoved = false;
1966  if (catchDecl) {
1967  QualType t = catchDecl->getType();
1968  if (const ObjCObjectPointerType *Ptr =
1969  t->getAs<ObjCObjectPointerType>()) {
1970  // Should be a pointer to a class.
1971  ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1972  if (IDecl) {
1973  std::string Result;
1974  ConvertSourceLocationToLineDirective(Catch->getBeginLoc(), Result);
1975 
1976  startBuf = SM->getCharacterData(startLoc);
1977  assert((*startBuf == '@') && "bogus @catch location");
1978  SourceLocation rParenLoc = Catch->getRParenLoc();
1979  const char *rParenBuf = SM->getCharacterData(rParenLoc);
1980 
1981  // _objc_exc_Foo *_e as argument to catch.
1982  Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString();
1983  Result += " *_"; Result += catchDecl->getNameAsString();
1984  Result += ")";
1985  ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1986  // Foo *e = (Foo *)_e;
1987  Result.clear();
1988  Result = "{ ";
1989  Result += IDecl->getNameAsString();
1990  Result += " *"; Result += catchDecl->getNameAsString();
1991  Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1992  Result += "_"; Result += catchDecl->getNameAsString();
1993 
1994  Result += "; ";
1995  SourceLocation lBraceLoc = Catch->getCatchBody()->getBeginLoc();
1996  ReplaceText(lBraceLoc, 1, Result);
1997  AtRemoved = true;
1998  }
1999  }
2000  }
2001  if (!AtRemoved)
2002  // @catch -> catch
2003  ReplaceText(startLoc, 1, "");
2004 
2005  }
2006  if (finalStmt) {
2007  buf.clear();
2008  SourceLocation FinallyLoc = finalStmt->getBeginLoc();
2009 
2010  if (noCatch) {
2011  ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2012  buf += "catch (id e) {_rethrow = e;}\n";
2013  }
2014  else {
2015  buf += "}\n";
2016  ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2017  buf += "catch (id e) {_rethrow = e;}\n";
2018  }
2019 
2020  SourceLocation startFinalLoc = finalStmt->getBeginLoc();
2021  ReplaceText(startFinalLoc, 8, buf);
2022  Stmt *body = finalStmt->getFinallyBody();
2023  SourceLocation startFinalBodyLoc = body->getBeginLoc();
2024  buf.clear();
2025  Write_RethrowObject(buf);
2026  ReplaceText(startFinalBodyLoc, 1, buf);
2027 
2028  SourceLocation endFinalBodyLoc = body->getEndLoc();
2029  ReplaceText(endFinalBodyLoc, 1, "}\n}");
2030  // Now check for any return/continue/go statements within the @try.
2031  WarnAboutReturnGotoStmts(S->getTryBody());
2032  }
2033 
2034  return nullptr;
2035 }
2036 
2037 // This can't be done with ReplaceStmt(S, ThrowExpr), since
2038 // the throw expression is typically a message expression that's already
2039 // been rewritten! (which implies the SourceLocation's are invalid).
2040 Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
2041  // Get the start location and compute the semi location.
2042  SourceLocation startLoc = S->getBeginLoc();
2043  const char *startBuf = SM->getCharacterData(startLoc);
2044 
2045  assert((*startBuf == '@') && "bogus @throw location");
2046 
2047  std::string buf;
2048  /* void objc_exception_throw(id) __attribute__((noreturn)); */
2049  if (S->getThrowExpr())
2050  buf = "objc_exception_throw(";
2051  else
2052  buf = "throw";
2053 
2054  // handle "@ throw" correctly.
2055  const char *wBuf = strchr(startBuf, 'w');
2056  assert((*wBuf == 'w') && "@throw: can't find 'w'");
2057  ReplaceText(startLoc, wBuf-startBuf+1, buf);
2058 
2059  SourceLocation endLoc = S->getEndLoc();
2060  const char *endBuf = SM->getCharacterData(endLoc);
2061  const char *semiBuf = strchr(endBuf, ';');
2062  assert((*semiBuf == ';') && "@throw: can't find ';'");
2063  SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
2064  if (S->getThrowExpr())
2065  ReplaceText(semiLoc, 1, ");");
2066  return nullptr;
2067 }
2068 
2069 Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2070  // Create a new string expression.
2071  std::string StrEncoding;
2072  Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
2073  Expr *Replacement = getStringLiteral(StrEncoding);
2074  ReplaceStmt(Exp, Replacement);
2075 
2076  // Replace this subexpr in the parent.
2077  // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2078  return Replacement;
2079 }
2080 
2081 Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2082  if (!SelGetUidFunctionDecl)
2083  SynthSelGetUidFunctionDecl();
2084  assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2085  // Create a call to sel_registerName("selName").
2086  SmallVector<Expr*, 8> SelExprs;
2087  SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
2088  CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2089  SelExprs);
2090  ReplaceStmt(Exp, SelExp);
2091  // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2092  return SelExp;
2093 }
2094 
2095 CallExpr *
2096 RewriteModernObjC::SynthesizeCallToFunctionDecl(FunctionDecl *FD,
2097  ArrayRef<Expr *> Args,
2098  SourceLocation StartLoc,
2099  SourceLocation EndLoc) {
2100  // Get the type, we will need to reference it in a couple spots.
2101  QualType msgSendType = FD->getType();
2102 
2103  // Create a reference to the objc_msgSend() declaration.
2104  DeclRefExpr *DRE = new (Context) DeclRefExpr(*Context, FD, false, msgSendType,
2106 
2107  // Now, we cast the reference to a pointer to the objc_msgSend type.
2108  QualType pToFunc = Context->getPointerType(msgSendType);
2109  ImplicitCastExpr *ICE =
2110  ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2111  DRE, nullptr, VK_PRValue, FPOptionsOverride());
2112 
2113  const auto *FT = msgSendType->castAs<FunctionType>();
2114  CallExpr *Exp =
2115  CallExpr::Create(*Context, ICE, Args, FT->getCallResultType(*Context),
2116  VK_PRValue, EndLoc, FPOptionsOverride());
2117  return Exp;
2118 }
2119 
2120 static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2121  const char *&startRef, const char *&endRef) {
2122  while (startBuf < endBuf) {
2123  if (*startBuf == '<')
2124  startRef = startBuf; // mark the start.
2125  if (*startBuf == '>') {
2126  if (startRef && *startRef == '<') {
2127  endRef = startBuf; // mark the end.
2128  return true;
2129  }
2130  return false;
2131  }
2132  startBuf++;
2133  }
2134  return false;
2135 }
2136 
2137 static void scanToNextArgument(const char *&argRef) {
2138  int angle = 0;
2139  while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2140  if (*argRef == '<')
2141  angle++;
2142  else if (*argRef == '>')
2143  angle--;
2144  argRef++;
2145  }
2146  assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2147 }
2148 
2149 bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2150  if (T->isObjCQualifiedIdType())
2151  return true;
2152  if (const PointerType *PT = T->getAs<PointerType>()) {
2154  return true;
2155  }
2156  if (T->isObjCObjectPointerType()) {
2157  T = T->getPointeeType();
2158  return T->isObjCQualifiedInterfaceType();
2159  }
2160  if (T->isArrayType()) {
2161  QualType ElemTy = Context->getBaseElementType(T);
2162  return needToScanForQualifiers(ElemTy);
2163  }
2164  return false;
2165 }
2166 
2167 void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2168  QualType Type = E->getType();
2169  if (needToScanForQualifiers(Type)) {
2170  SourceLocation Loc, EndLoc;
2171 
2172  if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2173  Loc = ECE->getLParenLoc();
2174  EndLoc = ECE->getRParenLoc();
2175  } else {
2176  Loc = E->getBeginLoc();
2177  EndLoc = E->getEndLoc();
2178  }
2179  // This will defend against trying to rewrite synthesized expressions.
2180  if (Loc.isInvalid() || EndLoc.isInvalid())
2181  return;
2182 
2183  const char *startBuf = SM->getCharacterData(Loc);
2184  const char *endBuf = SM->getCharacterData(EndLoc);
2185  const char *startRef = nullptr, *endRef = nullptr;
2186  if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2187  // Get the locations of the startRef, endRef.
2188  SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2189  SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2190  // Comment out the protocol references.
2191  InsertText(LessLoc, "/*");
2192  InsertText(GreaterLoc, "*/");
2193  }
2194  }
2195 }
2196 
2197 void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2199  QualType Type;
2200  const FunctionProtoType *proto = nullptr;
2201  if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2202  Loc = VD->getLocation();
2203  Type = VD->getType();
2204  }
2205  else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2206  Loc = FD->getLocation();
2207  // Check for ObjC 'id' and class types that have been adorned with protocol
2208  // information (id<p>, C<p>*). The protocol references need to be rewritten!
2209  const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2210  assert(funcType && "missing function type");
2211  proto = dyn_cast<FunctionProtoType>(funcType);
2212  if (!proto)
2213  return;
2214  Type = proto->getReturnType();
2215  }
2216  else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2217  Loc = FD->getLocation();
2218  Type = FD->getType();
2219  }
2220  else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Dcl)) {
2221  Loc = TD->getLocation();
2222  Type = TD->getUnderlyingType();
2223  }
2224  else
2225  return;
2226 
2227  if (needToScanForQualifiers(Type)) {
2228  // Since types are unique, we need to scan the buffer.
2229 
2230  const char *endBuf = SM->getCharacterData(Loc);
2231  const char *startBuf = endBuf;
2232  while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2233  startBuf--; // scan backward (from the decl location) for return type.
2234  const char *startRef = nullptr, *endRef = nullptr;
2235  if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2236  // Get the locations of the startRef, endRef.
2237  SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2238  SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2239  // Comment out the protocol references.
2240  InsertText(LessLoc, "/*");
2241  InsertText(GreaterLoc, "*/");
2242  }
2243  }
2244  if (!proto)
2245  return; // most likely, was a variable
2246  // Now check arguments.
2247  const char *startBuf = SM->getCharacterData(Loc);
2248  const char *startFuncBuf = startBuf;
2249  for (unsigned i = 0; i < proto->getNumParams(); i++) {
2250  if (needToScanForQualifiers(proto->getParamType(i))) {
2251  // Since types are unique, we need to scan the buffer.
2252 
2253  const char *endBuf = startBuf;
2254  // scan forward (from the decl location) for argument types.
2255  scanToNextArgument(endBuf);
2256  const char *startRef = nullptr, *endRef = nullptr;
2257  if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2258  // Get the locations of the startRef, endRef.
2259  SourceLocation LessLoc =
2260  Loc.getLocWithOffset(startRef-startFuncBuf);
2261  SourceLocation GreaterLoc =
2262  Loc.getLocWithOffset(endRef-startFuncBuf+1);
2263  // Comment out the protocol references.
2264  InsertText(LessLoc, "/*");
2265  InsertText(GreaterLoc, "*/");
2266  }
2267  startBuf = ++endBuf;
2268  }
2269  else {
2270  // If the function name is derived from a macro expansion, then the
2271  // argument buffer will not follow the name. Need to speak with Chris.
2272  while (*startBuf && *startBuf != ')' && *startBuf != ',')
2273  startBuf++; // scan forward (from the decl location) for argument types.
2274  startBuf++;
2275  }
2276  }
2277 }
2278 
2279 void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2280  QualType QT = ND->getType();
2281  const Type* TypePtr = QT->getAs<Type>();
2282  if (!isa<TypeOfExprType>(TypePtr))
2283  return;
2284  while (isa<TypeOfExprType>(TypePtr)) {
2285  const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2286  QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2287  TypePtr = QT->getAs<Type>();
2288  }
2289  // FIXME. This will not work for multiple declarators; as in:
2290  // __typeof__(a) b,c,d;
2291  std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2292  SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2293  const char *startBuf = SM->getCharacterData(DeclLoc);
2294  if (ND->getInit()) {
2295  std::string Name(ND->getNameAsString());
2296  TypeAsString += " " + Name + " = ";
2297  Expr *E = ND->getInit();
2298  SourceLocation startLoc;
2299  if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2300  startLoc = ECE->getLParenLoc();
2301  else
2302  startLoc = E->getBeginLoc();
2303  startLoc = SM->getExpansionLoc(startLoc);
2304  const char *endBuf = SM->getCharacterData(startLoc);
2305  ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2306  }
2307  else {
2308  SourceLocation X = ND->getEndLoc();
2309  X = SM->getExpansionLoc(X);
2310  const char *endBuf = SM->getCharacterData(X);
2311  ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2312  }
2313 }
2314 
2315 // SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2316 void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2317  IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2319  ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2320  QualType getFuncType =
2321  getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
2322  SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2323  SourceLocation(),
2324  SourceLocation(),
2325  SelGetUidIdent, getFuncType,
2326  nullptr, SC_Extern);
2327 }
2328 
2329 void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2330  // declared in <objc/objc.h>
2331  if (FD->getIdentifier() &&
2332  FD->getName() == "sel_registerName") {
2333  SelGetUidFunctionDecl = FD;
2334  return;
2335  }
2336  RewriteObjCQualifiedInterfaceTypes(FD);
2337 }
2338 
2339 void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2340  std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2341  const char *argPtr = TypeString.c_str();
2342  if (!strchr(argPtr, '^')) {
2343  Str += TypeString;
2344  return;
2345  }
2346  while (*argPtr) {
2347  Str += (*argPtr == '^' ? '*' : *argPtr);
2348  argPtr++;
2349  }
2350 }
2351 
2352 // FIXME. Consolidate this routine with RewriteBlockPointerType.
2353 void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2354  ValueDecl *VD) {
2355  QualType Type = VD->getType();
2356  std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2357  const char *argPtr = TypeString.c_str();
2358  int paren = 0;
2359  while (*argPtr) {
2360  switch (*argPtr) {
2361  case '(':
2362  Str += *argPtr;
2363  paren++;
2364  break;
2365  case ')':
2366  Str += *argPtr;
2367  paren--;
2368  break;
2369  case '^':
2370  Str += '*';
2371  if (paren == 1)
2372  Str += VD->getNameAsString();
2373  break;
2374  default:
2375  Str += *argPtr;
2376  break;
2377  }
2378  argPtr++;
2379  }
2380 }
2381 
2382 void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2383  SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2384  const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2385  const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2386  if (!proto)
2387  return;
2388  QualType Type = proto->getReturnType();
2389  std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2390  FdStr += " ";
2391  FdStr += FD->getName();
2392  FdStr += "(";
2393  unsigned numArgs = proto->getNumParams();
2394  for (unsigned i = 0; i < numArgs; i++) {
2395  QualType ArgType = proto->getParamType(i);
2396  RewriteBlockPointerType(FdStr, ArgType);
2397  if (i+1 < numArgs)
2398  FdStr += ", ";
2399  }
2400  if (FD->isVariadic()) {
2401  FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2402  }
2403  else
2404  FdStr += ");\n";
2405  InsertText(FunLocStart, FdStr);
2406 }
2407 
2408 // SynthSuperConstructorFunctionDecl - id __rw_objc_super(id obj, id super);
2409 void RewriteModernObjC::SynthSuperConstructorFunctionDecl() {
2410  if (SuperConstructorFunctionDecl)
2411  return;
2412  IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2414  QualType argT = Context->getObjCIdType();
2415  assert(!argT.isNull() && "Can't find 'id' type");
2416  ArgTys.push_back(argT);
2417  ArgTys.push_back(argT);
2418  QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2419  ArgTys);
2420  SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2421  SourceLocation(),
2422  SourceLocation(),
2423  msgSendIdent, msgSendType,
2424  nullptr, SC_Extern);
2425 }
2426 
2427 // SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2428 void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2429  IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2431  QualType argT = Context->getObjCIdType();
2432  assert(!argT.isNull() && "Can't find 'id' type");
2433  ArgTys.push_back(argT);
2434  argT = Context->getObjCSelType();
2435  assert(!argT.isNull() && "Can't find 'SEL' type");
2436  ArgTys.push_back(argT);
2437  QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2438  ArgTys, /*variadic=*/true);
2439  MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2440  SourceLocation(),
2441  SourceLocation(),
2442  msgSendIdent, msgSendType, nullptr,
2443  SC_Extern);
2444 }
2445 
2446 // SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
2447 void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2448  IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2449  SmallVector<QualType, 2> ArgTys;
2450  ArgTys.push_back(Context->VoidTy);
2451  QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2452  ArgTys, /*variadic=*/true);
2453  MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2454  SourceLocation(),
2455  SourceLocation(),
2456  msgSendIdent, msgSendType,
2457  nullptr, SC_Extern);
2458 }
2459 
2460 // SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2461 void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2462  IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2464  QualType argT = Context->getObjCIdType();
2465  assert(!argT.isNull() && "Can't find 'id' type");
2466  ArgTys.push_back(argT);
2467  argT = Context->getObjCSelType();
2468  assert(!argT.isNull() && "Can't find 'SEL' type");
2469  ArgTys.push_back(argT);
2470  QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2471  ArgTys, /*variadic=*/true);
2472  MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2473  SourceLocation(),
2474  SourceLocation(),
2475  msgSendIdent, msgSendType,
2476  nullptr, SC_Extern);
2477 }
2478 
2479 // SynthMsgSendSuperStretFunctionDecl -
2480 // id objc_msgSendSuper_stret(void);
2481 void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2482  IdentifierInfo *msgSendIdent =
2483  &Context->Idents.get("objc_msgSendSuper_stret");
2484  SmallVector<QualType, 2> ArgTys;
2485  ArgTys.push_back(Context->VoidTy);
2486  QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2487  ArgTys, /*variadic=*/true);
2488  MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2489  SourceLocation(),
2490  SourceLocation(),
2491  msgSendIdent,
2492  msgSendType, nullptr,
2493  SC_Extern);
2494 }
2495 
2496 // SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2497 void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2498  IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2500  QualType argT = Context->getObjCIdType();
2501  assert(!argT.isNull() && "Can't find 'id' type");
2502  ArgTys.push_back(argT);
2503  argT = Context->getObjCSelType();
2504  assert(!argT.isNull() && "Can't find 'SEL' type");
2505  ArgTys.push_back(argT);
2506  QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2507  ArgTys, /*variadic=*/true);
2508  MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2509  SourceLocation(),
2510  SourceLocation(),
2511  msgSendIdent, msgSendType,
2512  nullptr, SC_Extern);
2513 }
2514 
2515 // SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
2516 void RewriteModernObjC::SynthGetClassFunctionDecl() {
2517  IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2519  ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2520  QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2521  ArgTys);
2522  GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2523  SourceLocation(),
2524  SourceLocation(),
2525  getClassIdent, getClassType,
2526  nullptr, SC_Extern);
2527 }
2528 
2529 // SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2530 void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2531  IdentifierInfo *getSuperClassIdent =
2532  &Context->Idents.get("class_getSuperclass");
2534  ArgTys.push_back(Context->getObjCClassType());
2535  QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2536  ArgTys);
2537  GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2538  SourceLocation(),
2539  SourceLocation(),
2540  getSuperClassIdent,
2541  getClassType, nullptr,
2542  SC_Extern);
2543 }
2544 
2545 // SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
2546 void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2547  IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2549  ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2550  QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2551  ArgTys);
2552  GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2553  SourceLocation(),
2554  SourceLocation(),
2555  getClassIdent, getClassType,
2556  nullptr, SC_Extern);
2557 }
2558 
2559 Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2560  assert (Exp != nullptr && "Expected non-null ObjCStringLiteral");
2561  QualType strType = getConstantStringStructType();
2562 
2563  std::string S = "__NSConstantStringImpl_";
2564 
2565  std::string tmpName = InFileName;
2566  unsigned i;
2567  for (i=0; i < tmpName.length(); i++) {
2568  char c = tmpName.at(i);
2569  // replace any non-alphanumeric characters with '_'.
2570  if (!isAlphanumeric(c))
2571  tmpName[i] = '_';
2572  }
2573  S += tmpName;
2574  S += "_";
2575  S += utostr(NumObjCStringLiterals++);
2576 
2577  Preamble += "static __NSConstantStringImpl " + S;
2578  Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2579  Preamble += "0x000007c8,"; // utf8_str
2580  // The pretty printer for StringLiteral handles escape characters properly.
2581  std::string prettyBufS;
2582  llvm::raw_string_ostream prettyBuf(prettyBufS);
2583  Exp->getString()->printPretty(prettyBuf, nullptr, PrintingPolicy(LangOpts));
2584  Preamble += prettyBufS;
2585  Preamble += ",";
2586  Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2587 
2588  VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2589  SourceLocation(), &Context->Idents.get(S),
2590  strType, nullptr, SC_Static);
2591  DeclRefExpr *DRE = new (Context)
2592  DeclRefExpr(*Context, NewVD, false, strType, VK_LValue, SourceLocation());
2593  Expr *Unop = UnaryOperator::Create(
2594  const_cast<ASTContext &>(*Context), DRE, UO_AddrOf,
2595  Context->getPointerType(DRE->getType()), VK_PRValue, OK_Ordinary,
2596  SourceLocation(), false, FPOptionsOverride());
2597  // cast to NSConstantString *
2598  CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2599  CK_CPointerToObjCPointerCast, Unop);
2600  ReplaceStmt(Exp, cast);
2601  // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2602  return cast;
2603 }
2604 
2605 Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2606  unsigned IntSize =
2607  static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2608 
2609  Expr *FlagExp = IntegerLiteral::Create(*Context,
2610  llvm::APInt(IntSize, Exp->getValue()),
2611  Context->IntTy, Exp->getLocation());
2612  CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2613  CK_BitCast, FlagExp);
2614  ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2615  cast);
2616  ReplaceStmt(Exp, PE);
2617  return PE;
2618 }
2619 
2620 Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
2621  // synthesize declaration of helper functions needed in this routine.
2622  if (!SelGetUidFunctionDecl)
2623  SynthSelGetUidFunctionDecl();
2624  // use objc_msgSend() for all.
2625  if (!MsgSendFunctionDecl)
2626  SynthMsgSendFunctionDecl();
2627  if (!GetClassFunctionDecl)
2628  SynthGetClassFunctionDecl();
2629 
2630  FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2631  SourceLocation StartLoc = Exp->getBeginLoc();
2632  SourceLocation EndLoc = Exp->getEndLoc();
2633 
2634  // Synthesize a call to objc_msgSend().
2635  SmallVector<Expr*, 4> MsgExprs;
2636  SmallVector<Expr*, 4> ClsExprs;
2637 
2638  // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2639  ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2640  ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
2641 
2642  IdentifierInfo *clsName = BoxingClass->getIdentifier();
2643  ClsExprs.push_back(getStringLiteral(clsName->getName()));
2644  CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
2645  StartLoc, EndLoc);
2646  MsgExprs.push_back(Cls);
2647 
2648  // Create a call to sel_registerName("<BoxingMethod>:"), etc.
2649  // it will be the 2nd argument.
2650  SmallVector<Expr*, 4> SelExprs;
2651  SelExprs.push_back(
2652  getStringLiteral(BoxingMethod->getSelector().getAsString()));
2653  CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2654  SelExprs, StartLoc, EndLoc);
2655  MsgExprs.push_back(SelExp);
2656 
2657  // User provided sub-expression is the 3rd, and last, argument.
2658  Expr *subExpr = Exp->getSubExpr();
2659  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
2660  QualType type = ICE->getType();
2661  const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2662  CastKind CK = CK_BitCast;
2663  if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2664  CK = CK_IntegralToBoolean;
2665  subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
2666  }
2667  MsgExprs.push_back(subExpr);
2668 
2669  SmallVector<QualType, 4> ArgTypes;
2670  ArgTypes.push_back(Context->getObjCClassType());
2671  ArgTypes.push_back(Context->getObjCSelType());
2672  for (const auto PI : BoxingMethod->parameters())
2673  ArgTypes.push_back(PI->getType());
2674 
2675  QualType returnType = Exp->getType();
2676  // Get the type, we will need to reference it in a couple spots.
2677  QualType msgSendType = MsgSendFlavor->getType();
2678 
2679  // Create a reference to the objc_msgSend() declaration.
2680  DeclRefExpr *DRE = new (Context) DeclRefExpr(
2681  *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
2682 
2683  CastExpr *cast = NoTypeInfoCStyleCastExpr(
2684  Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE);
2685 
2686  // Now do the "normal" pointer to function cast.
2687  QualType castType =
2688  getSimpleFunctionType(returnType, ArgTypes, BoxingMethod->isVariadic());
2689  castType = Context->getPointerType(castType);
2690  cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2691  cast);
2692 
2693  // Don't forget the parens to enforce the proper binding.
2694  ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2695 
2696  auto *FT = msgSendType->castAs<FunctionType>();
2697  CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
2698  VK_PRValue, EndLoc, FPOptionsOverride());
2699  ReplaceStmt(Exp, CE);
2700  return CE;
2701 }
2702 
2703 Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2704  // synthesize declaration of helper functions needed in this routine.
2705  if (!SelGetUidFunctionDecl)
2706  SynthSelGetUidFunctionDecl();
2707  // use objc_msgSend() for all.
2708  if (!MsgSendFunctionDecl)
2709  SynthMsgSendFunctionDecl();
2710  if (!GetClassFunctionDecl)
2711  SynthGetClassFunctionDecl();
2712 
2713  FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2714  SourceLocation StartLoc = Exp->getBeginLoc();
2715  SourceLocation EndLoc = Exp->getEndLoc();
2716 
2717  // Build the expression: __NSContainer_literal(int, ...).arr
2718  QualType IntQT = Context->IntTy;
2719  QualType NSArrayFType =
2720  getSimpleFunctionType(Context->VoidTy, IntQT, true);
2721  std::string NSArrayFName("__NSContainer_literal");
2722  FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2723  DeclRefExpr *NSArrayDRE = new (Context) DeclRefExpr(
2724  *Context, NSArrayFD, false, NSArrayFType, VK_PRValue, SourceLocation());
2725 
2726  SmallVector<Expr*, 16> InitExprs;
2727  unsigned NumElements = Exp->getNumElements();
2728  unsigned UnsignedIntSize =
2729  static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2730  Expr *count = IntegerLiteral::Create(*Context,
2731  llvm::APInt(UnsignedIntSize, NumElements),
2732  Context->UnsignedIntTy, SourceLocation());
2733  InitExprs.push_back(count);
2734  for (unsigned i = 0; i < NumElements; i++)
2735  InitExprs.push_back(Exp->getElement(i));
2736  Expr *NSArrayCallExpr =
2737  CallExpr::Create(*Context, NSArrayDRE, InitExprs, NSArrayFType, VK_LValue,
2739 
2740  FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
2741  SourceLocation(),
2742  &Context->Idents.get("arr"),
2743  Context->getPointerType(Context->VoidPtrTy),
2744  nullptr, /*BitWidth=*/nullptr,
2745  /*Mutable=*/true, ICIS_NoInit);
2746  MemberExpr *ArrayLiteralME =
2747  MemberExpr::CreateImplicit(*Context, NSArrayCallExpr, false, ARRFD,
2748  ARRFD->getType(), VK_LValue, OK_Ordinary);
2749  QualType ConstIdT = Context->getObjCIdType().withConst();
2750  CStyleCastExpr * ArrayLiteralObjects =
2751  NoTypeInfoCStyleCastExpr(Context,
2752  Context->getPointerType(ConstIdT),
2753  CK_BitCast,
2754  ArrayLiteralME);
2755 
2756  // Synthesize a call to objc_msgSend().
2757  SmallVector<Expr*, 32> MsgExprs;
2758  SmallVector<Expr*, 4> ClsExprs;
2759  QualType expType = Exp->getType();
2760 
2761  // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2763  expType->getPointeeType()->castAs<ObjCObjectType>()->getInterface();
2764 
2765  IdentifierInfo *clsName = Class->getIdentifier();
2766  ClsExprs.push_back(getStringLiteral(clsName->getName()));
2767  CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
2768  StartLoc, EndLoc);
2769  MsgExprs.push_back(Cls);
2770 
2771  // Create a call to sel_registerName("arrayWithObjects:count:").
2772  // it will be the 2nd argument.
2773  SmallVector<Expr*, 4> SelExprs;
2774  ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
2775  SelExprs.push_back(
2776  getStringLiteral(ArrayMethod->getSelector().getAsString()));
2777  CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2778  SelExprs, StartLoc, EndLoc);
2779  MsgExprs.push_back(SelExp);
2780 
2781  // (const id [])objects
2782  MsgExprs.push_back(ArrayLiteralObjects);
2783 
2784  // (NSUInteger)cnt
2785  Expr *cnt = IntegerLiteral::Create(*Context,
2786  llvm::APInt(UnsignedIntSize, NumElements),
2787  Context->UnsignedIntTy, SourceLocation());
2788  MsgExprs.push_back(cnt);
2789 
2790  SmallVector<QualType, 4> ArgTypes;
2791  ArgTypes.push_back(Context->getObjCClassType());
2792  ArgTypes.push_back(Context->getObjCSelType());
2793  for (const auto *PI : ArrayMethod->parameters())
2794  ArgTypes.push_back(PI->getType());
2795 
2796  QualType returnType = Exp->getType();
2797  // Get the type, we will need to reference it in a couple spots.
2798  QualType msgSendType = MsgSendFlavor->getType();
2799 
2800  // Create a reference to the objc_msgSend() declaration.
2801  DeclRefExpr *DRE = new (Context) DeclRefExpr(
2802  *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
2803 
2804  CastExpr *cast = NoTypeInfoCStyleCastExpr(
2805  Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE);
2806 
2807  // Now do the "normal" pointer to function cast.
2808  QualType castType =
2809  getSimpleFunctionType(returnType, ArgTypes, ArrayMethod->isVariadic());
2810  castType = Context->getPointerType(castType);
2811  cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2812  cast);
2813 
2814  // Don't forget the parens to enforce the proper binding.
2815  ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2816 
2817  const FunctionType *FT = msgSendType->castAs<FunctionType>();
2818  CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
2819  VK_PRValue, EndLoc, FPOptionsOverride());
2820  ReplaceStmt(Exp, CE);
2821  return CE;
2822 }
2823 
2824 Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2825  // synthesize declaration of helper functions needed in this routine.
2826  if (!SelGetUidFunctionDecl)
2827  SynthSelGetUidFunctionDecl();
2828  // use objc_msgSend() for all.
2829  if (!MsgSendFunctionDecl)
2830  SynthMsgSendFunctionDecl();
2831  if (!GetClassFunctionDecl)
2832  SynthGetClassFunctionDecl();
2833 
2834  FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2835  SourceLocation StartLoc = Exp->getBeginLoc();
2836  SourceLocation EndLoc = Exp->getEndLoc();
2837 
2838  // Build the expression: __NSContainer_literal(int, ...).arr
2839  QualType IntQT = Context->IntTy;
2840  QualType NSDictFType =
2841  getSimpleFunctionType(Context->VoidTy, IntQT, true);
2842  std::string NSDictFName("__NSContainer_literal");
2843  FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2844  DeclRefExpr *NSDictDRE = new (Context) DeclRefExpr(
2845  *Context, NSDictFD, false, NSDictFType, VK_PRValue, SourceLocation());
2846 
2847  SmallVector<Expr*, 16> KeyExprs;
2848  SmallVector<Expr*, 16> ValueExprs;
2849 
2850  unsigned NumElements = Exp->getNumElements();
2851  unsigned UnsignedIntSize =
2852  static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2853  Expr *count = IntegerLiteral::Create(*Context,
2854  llvm::APInt(UnsignedIntSize, NumElements),
2855  Context->UnsignedIntTy, SourceLocation());
2856  KeyExprs.push_back(count);
2857  ValueExprs.push_back(count);
2858  for (unsigned i = 0; i < NumElements; i++) {
2859  ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2860  KeyExprs.push_back(Element.Key);
2861  ValueExprs.push_back(Element.Value);
2862  }
2863 
2864  // (const id [])objects
2865  Expr *NSValueCallExpr =
2866  CallExpr::Create(*Context, NSDictDRE, ValueExprs, NSDictFType, VK_LValue,
2868 
2869  FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
2870  SourceLocation(),
2871  &Context->Idents.get("arr"),
2872  Context->getPointerType(Context->VoidPtrTy),
2873  nullptr, /*BitWidth=*/nullptr,
2874  /*Mutable=*/true, ICIS_NoInit);
2875  MemberExpr *DictLiteralValueME =
2876  MemberExpr::CreateImplicit(*Context, NSValueCallExpr, false, ARRFD,
2877  ARRFD->getType(), VK_LValue, OK_Ordinary);
2878  QualType ConstIdT = Context->getObjCIdType().withConst();
2879  CStyleCastExpr * DictValueObjects =
2880  NoTypeInfoCStyleCastExpr(Context,
2881  Context->getPointerType(ConstIdT),
2882  CK_BitCast,
2883  DictLiteralValueME);
2884  // (const id <NSCopying> [])keys
2885  Expr *NSKeyCallExpr =
2886  CallExpr::Create(*Context, NSDictDRE, KeyExprs, NSDictFType, VK_LValue,
2888 
2889  MemberExpr *DictLiteralKeyME =
2890  MemberExpr::CreateImplicit(*Context, NSKeyCallExpr, false, ARRFD,
2891  ARRFD->getType(), VK_LValue, OK_Ordinary);
2892 
2893  CStyleCastExpr * DictKeyObjects =
2894  NoTypeInfoCStyleCastExpr(Context,
2895  Context->getPointerType(ConstIdT),
2896  CK_BitCast,
2897  DictLiteralKeyME);
2898 
2899  // Synthesize a call to objc_msgSend().
2900  SmallVector<Expr*, 32> MsgExprs;
2901  SmallVector<Expr*, 4> ClsExprs;
2902  QualType expType = Exp->getType();
2903 
2904  // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2906  expType->getPointeeType()->castAs<ObjCObjectType>()->getInterface();
2907 
2908  IdentifierInfo *clsName = Class->getIdentifier();
2909  ClsExprs.push_back(getStringLiteral(clsName->getName()));
2910  CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
2911  StartLoc, EndLoc);
2912  MsgExprs.push_back(Cls);
2913 
2914  // Create a call to sel_registerName("arrayWithObjects:count:").
2915  // it will be the 2nd argument.
2916  SmallVector<Expr*, 4> SelExprs;
2917  ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
2918  SelExprs.push_back(getStringLiteral(DictMethod->getSelector().getAsString()));
2919  CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2920  SelExprs, StartLoc, EndLoc);
2921  MsgExprs.push_back(SelExp);
2922 
2923  // (const id [])objects
2924  MsgExprs.push_back(DictValueObjects);
2925 
2926  // (const id <NSCopying> [])keys
2927  MsgExprs.push_back(DictKeyObjects);
2928 
2929  // (NSUInteger)cnt
2930  Expr *cnt = IntegerLiteral::Create(*Context,
2931  llvm::APInt(UnsignedIntSize, NumElements),
2932  Context->UnsignedIntTy, SourceLocation());
2933  MsgExprs.push_back(cnt);
2934 
2935  SmallVector<QualType, 8> ArgTypes;
2936  ArgTypes.push_back(Context->getObjCClassType());
2937  ArgTypes.push_back(Context->getObjCSelType());
2938  for (const auto *PI : DictMethod->parameters()) {
2939  QualType T = PI->getType();
2940  if (const PointerType* PT = T->getAs<PointerType>()) {
2941  QualType PointeeTy = PT->getPointeeType();
2942  convertToUnqualifiedObjCType(PointeeTy);
2943  T = Context->getPointerType(PointeeTy);
2944  }
2945  ArgTypes.push_back(T);
2946  }
2947 
2948  QualType returnType = Exp->getType();
2949  // Get the type, we will need to reference it in a couple spots.
2950  QualType msgSendType = MsgSendFlavor->getType();
2951 
2952  // Create a reference to the objc_msgSend() declaration.
2953  DeclRefExpr *DRE = new (Context) DeclRefExpr(
2954  *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
2955 
2956  CastExpr *cast = NoTypeInfoCStyleCastExpr(
2957  Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE);
2958 
2959  // Now do the "normal" pointer to function cast.
2960  QualType castType =
2961  getSimpleFunctionType(returnType, ArgTypes, DictMethod->isVariadic());
2962  castType = Context->getPointerType(castType);
2963  cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2964  cast);
2965 
2966  // Don't forget the parens to enforce the proper binding.
2967  ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2968 
2969  const FunctionType *FT = msgSendType->castAs<FunctionType>();
2970  CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
2971  VK_PRValue, EndLoc, FPOptionsOverride());
2972  ReplaceStmt(Exp, CE);
2973  return CE;
2974 }
2975 
2976 // struct __rw_objc_super {
2977 // struct objc_object *object; struct objc_object *superClass;
2978 // };
2979 QualType RewriteModernObjC::getSuperStructType() {
2980  if (!SuperStructDecl) {
2981  SuperStructDecl = RecordDecl::Create(
2982  *Context, TagTypeKind::Struct, TUDecl, SourceLocation(),
2983  SourceLocation(), &Context->Idents.get("__rw_objc_super"));
2984  QualType FieldTypes[2];
2985 
2986  // struct objc_object *object;
2987  FieldTypes[0] = Context->getObjCIdType();
2988  // struct objc_object *superClass;
2989  FieldTypes[1] = Context->getObjCIdType();
2990 
2991  // Create fields
2992  for (unsigned i = 0; i < 2; ++i) {
2993  SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2994  SourceLocation(),
2995  SourceLocation(), nullptr,
2996  FieldTypes[i], nullptr,
2997  /*BitWidth=*/nullptr,
2998  /*Mutable=*/false,
2999  ICIS_NoInit));
3000  }
3001 
3002  SuperStructDecl->completeDefinition();
3003  }
3004  return Context->getTagDeclType(SuperStructDecl);
3005 }
3006 
3007 QualType RewriteModernObjC::getConstantStringStructType() {
3008  if (!ConstantStringDecl) {
3009  ConstantStringDecl = RecordDecl::Create(
3010  *Context, TagTypeKind::Struct, TUDecl, SourceLocation(),
3011  SourceLocation(), &Context->Idents.get("__NSConstantStringImpl"));
3012  QualType FieldTypes[4];
3013 
3014  // struct objc_object *receiver;
3015  FieldTypes[0] = Context->getObjCIdType();
3016  // int flags;
3017  FieldTypes[1] = Context->IntTy;
3018  // char *str;
3019  FieldTypes[2] = Context->getPointerType(Context->CharTy);
3020  // long length;
3021  FieldTypes[3] = Context->LongTy;
3022 
3023  // Create fields
3024  for (unsigned i = 0; i < 4; ++i) {
3025  ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3026  ConstantStringDecl,
3027  SourceLocation(),
3028  SourceLocation(), nullptr,
3029  FieldTypes[i], nullptr,
3030  /*BitWidth=*/nullptr,
3031  /*Mutable=*/true,
3032  ICIS_NoInit));
3033  }
3034 
3035  ConstantStringDecl->completeDefinition();
3036  }
3037  return Context->getTagDeclType(ConstantStringDecl);
3038 }
3039 
3040 /// getFunctionSourceLocation - returns start location of a function
3041 /// definition. Complication arises when function has declared as
3042 /// extern "C" or extern "C" {...}
3043 static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
3044  FunctionDecl *FD) {
3045  if (FD->isExternC() && !FD->isMain()) {
3046  const DeclContext *DC = FD->getDeclContext();
3047  if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3048  // if it is extern "C" {...}, return function decl's own location.
3049  if (!LSD->getRBraceLoc().isValid())
3050  return LSD->getExternLoc();
3051  }
3052  if (FD->getStorageClass() != SC_None)
3053  R.RewriteBlockLiteralFunctionDecl(FD);
3054  return FD->getTypeSpecStartLoc();
3055 }
3056 
3057 void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
3058 
3059  SourceLocation Location = D->getLocation();
3060 
3061  if (Location.isFileID() && GenerateLineInfo) {
3062  std::string LineString("\n#line ");
3063  PresumedLoc PLoc = SM->getPresumedLoc(Location);
3064  LineString += utostr(PLoc.getLine());
3065  LineString += " \"";
3066  LineString += Lexer::Stringify(PLoc.getFilename());
3067  if (isa<ObjCMethodDecl>(D))
3068  LineString += "\"";
3069  else LineString += "\"\n";
3070 
3071  Location = D->getBeginLoc();
3072  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3073  if (FD->isExternC() && !FD->isMain()) {
3074  const DeclContext *DC = FD->getDeclContext();
3075  if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3076  // if it is extern "C" {...}, return function decl's own location.
3077  if (!LSD->getRBraceLoc().isValid())
3078  Location = LSD->getExternLoc();
3079  }
3080  }
3081  InsertText(Location, LineString);
3082  }
3083 }
3084 
3085 /// SynthMsgSendStretCallExpr - This routine translates message expression
3086 /// into a call to objc_msgSend_stret() entry point. Tricky part is that
3087 /// nil check on receiver must be performed before calling objc_msgSend_stret.
3088 /// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
3089 /// msgSendType - function type of objc_msgSend_stret(...)
3090 /// returnType - Result type of the method being synthesized.
3091 /// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
3092 /// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
3093 /// starting with receiver.
3094 /// Method - Method being rewritten.
3095 Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
3096  QualType returnType,
3097  SmallVectorImpl<QualType> &ArgTypes,
3098  SmallVectorImpl<Expr*> &MsgExprs,
3099  ObjCMethodDecl *Method) {
3100  // Now do the "normal" pointer to function cast.
3101  QualType FuncType = getSimpleFunctionType(
3102  returnType, ArgTypes, Method ? Method->isVariadic() : false);
3103  QualType castType = Context->getPointerType(FuncType);
3104 
3105  // build type for containing the objc_msgSend_stret object.
3106  static unsigned stretCount=0;
3107  std::string name = "__Stret"; name += utostr(stretCount);
3108  std::string str =
3109  "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
3110  str += "namespace {\n";
3111  str += "struct "; str += name;
3112  str += " {\n\t";
3113  str += name;
3114  str += "(id receiver, SEL sel";
3115  for (unsigned i = 2; i < ArgTypes.size(); i++) {
3116  std::string ArgName = "arg"; ArgName += utostr(i);
3117  ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
3118  str += ", "; str += ArgName;
3119  }
3120  // could be vararg.
3121  for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3122  std::string ArgName = "arg"; ArgName += utostr(i);
3123  MsgExprs[i]->getType().getAsStringInternal(ArgName,
3124  Context->getPrintingPolicy());
3125  str += ", "; str += ArgName;
3126  }
3127 
3128  str += ") {\n";
3129  str += "\t unsigned size = sizeof(";
3130  str += returnType.getAsString(Context->getPrintingPolicy()); str += ");\n";
3131 
3132  str += "\t if (size == 1 || size == 2 || size == 4 || size == 8)\n";
3133 
3134  str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3135  str += ")(void *)objc_msgSend)(receiver, sel";
3136  for (unsigned i = 2; i < ArgTypes.size(); i++) {
3137  str += ", arg"; str += utostr(i);
3138  }
3139  // could be vararg.
3140  for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3141  str += ", arg"; str += utostr(i);
3142  }
3143  str+= ");\n";
3144 
3145  str += "\t else if (receiver == 0)\n";
3146  str += "\t memset((void*)&s, 0, sizeof(s));\n";
3147  str += "\t else\n";
3148 
3149  str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3150  str += ")(void *)objc_msgSend_stret)(receiver, sel";
3151  for (unsigned i = 2; i < ArgTypes.size(); i++) {
3152  str += ", arg"; str += utostr(i);
3153  }
3154  // could be vararg.
3155  for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3156  str += ", arg"; str += utostr(i);
3157  }
3158  str += ");\n";
3159 
3160  str += "\t}\n";
3161  str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
3162  str += " s;\n";
3163  str += "};\n};\n\n";
3164  SourceLocation FunLocStart;
3165  if (CurFunctionDef)
3166  FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
3167  else {
3168  assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
3169  FunLocStart = CurMethodDef->getBeginLoc();
3170  }
3171 
3172  InsertText(FunLocStart, str);
3173  ++stretCount;
3174 
3175  // AST for __Stretn(receiver, args).s;
3176  IdentifierInfo *ID = &Context->Idents.get(name);
3177  FunctionDecl *FD =
3178  FunctionDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(),
3179  ID, FuncType, nullptr, SC_Extern, false, false);
3180  DeclRefExpr *DRE = new (Context)
3181  DeclRefExpr(*Context, FD, false, castType, VK_PRValue, SourceLocation());
3182  CallExpr *STCE =
3183  CallExpr::Create(*Context, DRE, MsgExprs, castType, VK_LValue,
3185 
3186  FieldDecl *FieldD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
3187  SourceLocation(),
3188  &Context->Idents.get("s"),
3189  returnType, nullptr,
3190  /*BitWidth=*/nullptr,
3191  /*Mutable=*/true, ICIS_NoInit);
3192  MemberExpr *ME = MemberExpr::CreateImplicit(
3193  *Context, STCE, false, FieldD, FieldD->getType(), VK_LValue, OK_Ordinary);
3194 
3195  return ME;
3196 }
3197 
3198 Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3199  SourceLocation StartLoc,
3200  SourceLocation EndLoc) {
3201  if (!SelGetUidFunctionDecl)
3202  SynthSelGetUidFunctionDecl();
3203  if (!MsgSendFunctionDecl)
3204  SynthMsgSendFunctionDecl();
3205  if (!MsgSendSuperFunctionDecl)
3206  SynthMsgSendSuperFunctionDecl();
3207  if (!MsgSendStretFunctionDecl)
3208  SynthMsgSendStretFunctionDecl();
3209  if (!MsgSendSuperStretFunctionDecl)
3210  SynthMsgSendSuperStretFunctionDecl();
3211  if (!MsgSendFpretFunctionDecl)
3212  SynthMsgSendFpretFunctionDecl();
3213  if (!GetClassFunctionDecl)
3214  SynthGetClassFunctionDecl();
3215  if (!GetSuperClassFunctionDecl)
3216  SynthGetSuperClassFunctionDecl();
3217  if (!GetMetaClassFunctionDecl)
3218  SynthGetMetaClassFunctionDecl();
3219 
3220  // default to objc_msgSend().
3221  FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3222  // May need to use objc_msgSend_stret() as well.
3223  FunctionDecl *MsgSendStretFlavor = nullptr;
3224  if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
3225  QualType resultType = mDecl->getReturnType();
3226  if (resultType->isRecordType())
3227  MsgSendStretFlavor = MsgSendStretFunctionDecl;
3228  else if (resultType->isRealFloatingType())
3229  MsgSendFlavor = MsgSendFpretFunctionDecl;
3230  }
3231 
3232  // Synthesize a call to objc_msgSend().
3233  SmallVector<Expr*, 8> MsgExprs;
3234  switch (Exp->getReceiverKind()) {
3235  case ObjCMessageExpr::SuperClass: {
3236  MsgSendFlavor = MsgSendSuperFunctionDecl;
3237  if (MsgSendStretFlavor)
3238  MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3239  assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3240 
3241  ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3242 
3243  SmallVector<Expr*, 4> InitExprs;
3244 
3245  // set the receiver to self, the first argument to all methods.
3246  InitExprs.push_back(NoTypeInfoCStyleCastExpr(
3247  Context, Context->getObjCIdType(), CK_BitCast,
3248  new (Context) DeclRefExpr(*Context, CurMethodDef->getSelfDecl(), false,
3249  Context->getObjCIdType(), VK_PRValue,
3250  SourceLocation()))); // set the 'receiver'.
3251 
3252  // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3253  SmallVector<Expr*, 8> ClsExprs;
3254  ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
3255  // (Class)objc_getClass("CurrentClass")
3256  CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3257  ClsExprs, StartLoc, EndLoc);
3258  ClsExprs.clear();
3259  ClsExprs.push_back(Cls);
3260  Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
3261  StartLoc, EndLoc);
3262 
3263  // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3264  // To turn off a warning, type-cast to 'id'
3265  InitExprs.push_back( // set 'super class', using class_getSuperclass().
3266  NoTypeInfoCStyleCastExpr(Context,
3267  Context->getObjCIdType(),
3268  CK_BitCast, Cls));
3269  // struct __rw_objc_super
3270  QualType superType = getSuperStructType();
3271  Expr *SuperRep;
3272 
3273  if (LangOpts.MicrosoftExt) {
3274  SynthSuperConstructorFunctionDecl();
3275  // Simulate a constructor call...
3276  DeclRefExpr *DRE = new (Context)
3277  DeclRefExpr(*Context, SuperConstructorFunctionDecl, false, superType,
3279  SuperRep =
3280  CallExpr::Create(*Context, DRE, InitExprs, superType, VK_LValue,
3282  // The code for super is a little tricky to prevent collision with
3283  // the structure definition in the header. The rewriter has it's own
3284  // internal definition (__rw_objc_super) that is uses. This is why
3285  // we need the cast below. For example:
3286  // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
3287  //
3288  SuperRep = UnaryOperator::Create(
3289  const_cast<ASTContext &>(*Context), SuperRep, UO_AddrOf,
3290  Context->getPointerType(SuperRep->getType()), VK_PRValue, OK_Ordinary,
3291  SourceLocation(), false, FPOptionsOverride());
3292  SuperRep = NoTypeInfoCStyleCastExpr(Context,
3293  Context->getPointerType(superType),
3294  CK_BitCast, SuperRep);
3295  } else {
3296  // (struct __rw_objc_super) { <exprs from above> }
3297  InitListExpr *ILE =
3298  new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
3299  SourceLocation());
3300  TypeSourceInfo *superTInfo
3301  = Context->getTrivialTypeSourceInfo(superType);
3302  SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3303  superType, VK_LValue,
3304  ILE, false);
3305  // struct __rw_objc_super *
3306  SuperRep = UnaryOperator::Create(
3307  const_cast<ASTContext &>(*Context), SuperRep, UO_AddrOf,
3308  Context->getPointerType(SuperRep->getType()), VK_PRValue, OK_Ordinary,
3309  SourceLocation(), false, FPOptionsOverride());
3310  }
3311  MsgExprs.push_back(SuperRep);
3312  break;
3313  }
3314 
3315  case ObjCMessageExpr::Class: {
3316  SmallVector<Expr*, 8> ClsExprs;
3318  = Exp->getClassReceiver()->castAs<ObjCObjectType>()->getInterface();
3319  IdentifierInfo *clsName = Class->getIdentifier();
3320  ClsExprs.push_back(getStringLiteral(clsName->getName()));
3321  CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
3322  StartLoc, EndLoc);
3323  CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3324  Context->getObjCIdType(),
3325  CK_BitCast, Cls);
3326  MsgExprs.push_back(ArgExpr);
3327  break;
3328  }
3329 
3330  case ObjCMessageExpr::SuperInstance:{
3331  MsgSendFlavor = MsgSendSuperFunctionDecl;
3332  if (MsgSendStretFlavor)
3333  MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3334  assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3335  ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3336  SmallVector<Expr*, 4> InitExprs;
3337 
3338  InitExprs.push_back(NoTypeInfoCStyleCastExpr(
3339  Context, Context->getObjCIdType(), CK_BitCast,
3340  new (Context) DeclRefExpr(*Context, CurMethodDef->getSelfDecl(), false,
3341  Context->getObjCIdType(), VK_PRValue,
3342  SourceLocation()))); // set the 'receiver'.
3343 
3344  // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3345  SmallVector<Expr*, 8> ClsExprs;
3346  ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
3347  // (Class)objc_getClass("CurrentClass")
3348  CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
3349  StartLoc, EndLoc);
3350  ClsExprs.clear();
3351  ClsExprs.push_back(Cls);
3352  Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
3353  StartLoc, EndLoc);
3354 
3355  // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3356  // To turn off a warning, type-cast to 'id'
3357  InitExprs.push_back(
3358  // set 'super class', using class_getSuperclass().
3359  NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3360  CK_BitCast, Cls));
3361  // struct __rw_objc_super
3362  QualType superType = getSuperStructType();
3363  Expr *SuperRep;
3364 
3365  if (LangOpts.MicrosoftExt) {
3366  SynthSuperConstructorFunctionDecl();
3367  // Simulate a constructor call...
3368  DeclRefExpr *DRE = new (Context)
3369  DeclRefExpr(*Context, SuperConstructorFunctionDecl, false, superType,
3371  SuperRep =
3372  CallExpr::Create(*Context, DRE, InitExprs, superType, VK_LValue,
3374  // The code for super is a little tricky to prevent collision with
3375  // the structure definition in the header. The rewriter has it's own
3376  // internal definition (__rw_objc_super) that is uses. This is why
3377  // we need the cast below. For example:
3378  // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
3379  //
3380  SuperRep = UnaryOperator::Create(
3381  const_cast<ASTContext &>(*Context), SuperRep, UO_AddrOf,
3382  Context->getPointerType(SuperRep->getType()), VK_PRValue, OK_Ordinary,
3383  SourceLocation(), false, FPOptionsOverride());
3384  SuperRep = NoTypeInfoCStyleCastExpr(Context,
3385  Context->getPointerType(superType),
3386  CK_BitCast, SuperRep);
3387  } else {
3388  // (struct __rw_objc_super) { <exprs from above> }
3389  InitListExpr *ILE =
3390  new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
3391  SourceLocation());
3392  TypeSourceInfo *superTInfo
3393  = Context->getTrivialTypeSourceInfo(superType);
3394  SuperRep = new (Context) CompoundLiteralExpr(
3395  SourceLocation(), superTInfo, superType, VK_PRValue, ILE, false);
3396  }
3397  MsgExprs.push_back(SuperRep);
3398  break;
3399  }
3400 
3401  case ObjCMessageExpr::Instance: {
3402  // Remove all type-casts because it may contain objc-style types; e.g.
3403  // Foo<Proto> *.
3404  Expr *recExpr = Exp->getInstanceReceiver();
3405  while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3406  recExpr = CE->getSubExpr();
3407  CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3408  ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3409  ? CK_BlockPointerToObjCPointerCast
3410  : CK_CPointerToObjCPointerCast;
3411 
3412  recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3413  CK, recExpr);
3414  MsgExprs.push_back(recExpr);
3415  break;
3416  }
3417  }
3418 
3419  // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3420  SmallVector<Expr*, 8> SelExprs;
3421  SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
3422  CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3423  SelExprs, StartLoc, EndLoc);
3424  MsgExprs.push_back(SelExp);
3425 
3426  // Now push any user supplied arguments.
3427  for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3428  Expr *userExpr = Exp->getArg(i);
3429  // Make all implicit casts explicit...ICE comes in handy:-)
3430  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3431  // Reuse the ICE type, it is exactly what the doctor ordered.
3432  QualType type = ICE->getType();
3433  if (needToScanForQualifiers(type))
3434  type = Context->getObjCIdType();
3435  // Make sure we convert "type (^)(...)" to "type (*)(...)".
3436  (void)convertBlockPointerToFunctionPointer(type);
3437  const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3438  CastKind CK;
3439  if (SubExpr->getType()->isIntegralType(*Context) &&
3440  type->isBooleanType()) {
3441  CK = CK_IntegralToBoolean;
3442  } else if (type->isObjCObjectPointerType()) {
3443  if (SubExpr->getType()->isBlockPointerType()) {
3444  CK = CK_BlockPointerToObjCPointerCast;
3445  } else if (SubExpr->getType()->isPointerType()) {
3446  CK = CK_CPointerToObjCPointerCast;
3447  } else {
3448  CK = CK_BitCast;
3449  }
3450  } else {
3451  CK = CK_BitCast;
3452  }
3453 
3454  userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3455  }
3456  // Make id<P...> cast into an 'id' cast.
3457  else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3458  if (CE->getType()->isObjCQualifiedIdType()) {
3459  while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3460  userExpr = CE->getSubExpr();
3461  CastKind CK;
3462  if (userExpr->getType()->isIntegralType(*Context)) {
3463  CK = CK_IntegralToPointer;
3464  } else if (userExpr->getType()->isBlockPointerType()) {
3465  CK = CK_BlockPointerToObjCPointerCast;
3466  } else if (userExpr->getType()->isPointerType()) {
3467  CK = CK_CPointerToObjCPointerCast;
3468  } else {
3469  CK = CK_BitCast;
3470  }
3471  userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3472  CK, userExpr);
3473  }
3474  }
3475  MsgExprs.push_back(userExpr);
3476  // We've transferred the ownership to MsgExprs. For now, we *don't* null
3477  // out the argument in the original expression (since we aren't deleting
3478  // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3479  //Exp->setArg(i, 0);
3480  }
3481  // Generate the funky cast.
3482  CastExpr *cast;
3483  SmallVector<QualType, 8> ArgTypes;
3484  QualType returnType;
3485 
3486  // Push 'id' and 'SEL', the 2 implicit arguments.
3487  if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3488  ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3489  else
3490  ArgTypes.push_back(Context->getObjCIdType());
3491  ArgTypes.push_back(Context->getObjCSelType());
3492  if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3493  // Push any user argument types.
3494  for (const auto *PI : OMD->parameters()) {
3495  QualType t = PI->getType()->isObjCQualifiedIdType()
3496  ? Context->getObjCIdType()
3497  : PI->getType();
3498  // Make sure we convert "t (^)(...)" to "t (*)(...)".
3499  (void)convertBlockPointerToFunctionPointer(t);
3500  ArgTypes.push_back(t);
3501  }
3502  returnType = Exp->getType();
3503  convertToUnqualifiedObjCType(returnType);
3504  (void)convertBlockPointerToFunctionPointer(returnType);
3505  } else {
3506  returnType = Context->getObjCIdType();
3507  }
3508  // Get the type, we will need to reference it in a couple spots.
3509  QualType msgSendType = MsgSendFlavor->getType();
3510 
3511  // Create a reference to the objc_msgSend() declaration.
3512  DeclRefExpr *DRE = new (Context) DeclRefExpr(
3513  *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
3514 
3515  // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3516  // If we don't do this cast, we get the following bizarre warning/note:
3517  // xx.m:13: warning: function called through a non-compatible type
3518  // xx.m:13: note: if this code is reached, the program will abort
3519  cast = NoTypeInfoCStyleCastExpr(Context,
3520  Context->getPointerType(Context->VoidTy),
3521  CK_BitCast, DRE);
3522 
3523  // Now do the "normal" pointer to function cast.
3524  // If we don't have a method decl, force a variadic cast.
3525  const ObjCMethodDecl *MD = Exp->getMethodDecl();
3526  QualType castType =
3527  getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
3528  castType = Context->getPointerType(castType);
3529  cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3530  cast);
3531 
3532  // Don't forget the parens to enforce the proper binding.
3533  ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3534 
3535  const FunctionType *FT = msgSendType->castAs<FunctionType>();
3536  CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
3537  VK_PRValue, EndLoc, FPOptionsOverride());
3538  Stmt *ReplacingStmt = CE;
3539  if (MsgSendStretFlavor) {
3540  // We have the method which returns a struct/union. Must also generate
3541  // call to objc_msgSend_stret and hang both varieties on a conditional
3542  // expression which dictate which one to envoke depending on size of
3543  // method's return type.
3544 
3545  Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3546  returnType,
3547  ArgTypes, MsgExprs,
3548  Exp->getMethodDecl());
3549  ReplacingStmt = STCE;
3550  }
3551  // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3552  return ReplacingStmt;
3553 }
3554 
3555 Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3556  Stmt *ReplacingStmt =
3557  SynthMessageExpr(Exp, Exp->getBeginLoc(), Exp->getEndLoc());
3558 
3559  // Now do the actual rewrite.
3560  ReplaceStmt(Exp, ReplacingStmt);
3561 
3562  // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3563  return ReplacingStmt;
3564 }
3565 
3566 // typedef struct objc_object Protocol;
3567 QualType RewriteModernObjC::getProtocolType() {
3568  if (!ProtocolTypeDecl) {
3569  TypeSourceInfo *TInfo
3570  = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3571  ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3573  &Context->Idents.get("Protocol"),
3574  TInfo);
3575  }
3576  return Context->getTypeDeclType(ProtocolTypeDecl);
3577 }
3578 
3579 /// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3580 /// a synthesized/forward data reference (to the protocol's metadata).
3581 /// The forward references (and metadata) are generated in
3582 /// RewriteModernObjC::HandleTranslationUnit().
3583 Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
3584  std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3585  Exp->getProtocol()->getNameAsString();
3586  IdentifierInfo *ID = &Context->Idents.get(Name);
3587  VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3588  SourceLocation(), ID, getProtocolType(),
3589  nullptr, SC_Extern);
3590  DeclRefExpr *DRE = new (Context) DeclRefExpr(
3591  *Context, VD, false, getProtocolType(), VK_LValue, SourceLocation());
3592  CastExpr *castExpr = NoTypeInfoCStyleCastExpr(
3593  Context, Context->getPointerType(DRE->getType()), CK_BitCast, DRE);
3594  ReplaceStmt(Exp, castExpr);
3595  ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3596  // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3597  return castExpr;
3598 }
3599 
3600 /// IsTagDefinedInsideClass - This routine checks that a named tagged type
3601 /// is defined inside an objective-c class. If so, it returns true.
3602 bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
3603  TagDecl *Tag,
3604  bool &IsNamedDefinition) {
3605  if (!IDecl)
3606  return false;
3607  SourceLocation TagLocation;
3608  if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3609  RD = RD->getDefinition();
3610  if (!RD || !RD->getDeclName().getAsIdentifierInfo())
3611  return false;
3612  IsNamedDefinition = true;
3613  TagLocation = RD->getLocation();
3614  return Context->getSourceManager().isBeforeInTranslationUnit(
3615  IDecl->getLocation(), TagLocation);
3616  }
3617  if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3618  if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3619  return false;
3620  IsNamedDefinition = true;
3621  TagLocation = ED->getLocation();
3622  return Context->getSourceManager().isBeforeInTranslationUnit(
3623  IDecl->getLocation(), TagLocation);
3624  }
3625  return false;
3626 }
3627 
3628 /// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
3629 /// It handles elaborated types, as well as enum types in the process.
3630 bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3631  std::string &Result) {
3632  if (Type->getAs<TypedefType>()) {
3633  Result += "\t";
3634  return false;
3635  }
3636 
3637  if (Type->isArrayType()) {
3638  QualType ElemTy = Context->getBaseElementType(Type);
3639  return RewriteObjCFieldDeclType(ElemTy, Result);
3640  }
3641  else if (Type->isRecordType()) {
3642  RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
3643  if (RD->isCompleteDefinition()) {
3644  if (RD->isStruct())
3645  Result += "\n\tstruct ";
3646  else if (RD->isUnion())
3647  Result += "\n\tunion ";
3648  else
3649  assert(false && "class not allowed as an ivar type");
3650 
3651  Result += RD->getName();
3652  if (GlobalDefinedTags.count(RD)) {
3653  // struct/union is defined globally, use it.
3654  Result += " ";
3655  return true;
3656  }
3657  Result += " {\n";
3658  for (auto *FD : RD->fields())
3659  RewriteObjCFieldDecl(FD, Result);
3660  Result += "\t} ";
3661  return true;
3662  }
3663  }
3664  else if (Type->isEnumeralType()) {
3665  EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
3666  if (ED->isCompleteDefinition()) {
3667  Result += "\n\tenum ";
3668  Result += ED->getName();
3669  if (GlobalDefinedTags.count(ED)) {
3670  // Enum is globall defined, use it.
3671  Result += " ";
3672  return true;
3673  }
3674 
3675  Result += " {\n";
3676  for (const auto *EC : ED->enumerators()) {
3677  Result += "\t"; Result += EC->getName(); Result += " = ";
3678  Result += toString(EC->getInitVal(), 10);
3679  Result += ",\n";
3680  }
3681  Result += "\t} ";
3682  return true;
3683  }
3684  }
3685 
3686  Result += "\t";
3687  convertObjCTypeToCStyleType(Type);
3688  return false;
3689 }
3690 
3691 
3692 /// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3693 /// It handles elaborated types, as well as enum types in the process.
3694 void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3695  std::string &Result) {
3696  QualType Type = fieldDecl->getType();
3697  std::string Name = fieldDecl->getNameAsString();
3698 
3699  bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3700  if (!EleboratedType)
3701  Type.getAsStringInternal(Name, Context->getPrintingPolicy());
3702  Result += Name;
3703  if (fieldDecl->isBitField()) {
3704  Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3705  }
3706  else if (EleboratedType && Type->isArrayType()) {
3707  const ArrayType *AT = Context->getAsArrayType(Type);
3708  do {
3709  if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
3710  Result += "[";
3711  llvm::APInt Dim = CAT->getSize();
3712  Result += utostr(Dim.getZExtValue());
3713  Result += "]";
3714  }
3715  AT = Context->getAsArrayType(AT->getElementType());
3716  } while (AT);
3717  }
3718 
3719  Result += ";\n";
3720 }
3721 
3722 /// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3723 /// named aggregate types into the input buffer.
3724 void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3725  std::string &Result) {
3726  QualType Type = fieldDecl->getType();
3727  if (Type->getAs<TypedefType>())
3728  return;
3729  if (Type->isArrayType())
3730  Type = Context->getBaseElementType(Type);
3731 
3732  auto *IDecl = dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
3733 
3734  TagDecl *TD = nullptr;
3735  if (Type->isRecordType()) {
3736  TD = Type->castAs<RecordType>()->getDecl();
3737  }
3738  else if (Type->isEnumeralType()) {
3739  TD = Type->castAs<EnumType>()->getDecl();
3740  }
3741 
3742  if (TD) {
3743  if (GlobalDefinedTags.count(TD))
3744  return;
3745 
3746  bool IsNamedDefinition = false;
3747  if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3748  RewriteObjCFieldDeclType(Type, Result);
3749  Result += ";";
3750  }
3751  if (IsNamedDefinition)
3752  GlobalDefinedTags.insert(TD);
3753  }
3754 }
3755 
3756 unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) {
3757  const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3758  if (ObjCInterefaceHasBitfieldGroups.count(CDecl)) {
3759  return IvarGroupNumber[IV];
3760  }
3761  unsigned GroupNo = 0;
3763  for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3764  IVD; IVD = IVD->getNextIvar())
3765  IVars.push_back(IVD);
3766 
3767  for (unsigned i = 0, e = IVars.size(); i < e; i++)
3768  if (IVars[i]->isBitField()) {
3769  IvarGroupNumber[IVars[i++]] = ++GroupNo;
3770  while (i < e && IVars[i]->isBitField())
3771  IvarGroupNumber[IVars[i++]] = GroupNo;
3772  if (i < e)
3773  --i;
3774  }
3775 
3776  ObjCInterefaceHasBitfieldGroups.insert(CDecl);
3777  return IvarGroupNumber[IV];
3778 }
3779 
3780 QualType RewriteModernObjC::SynthesizeBitfieldGroupStructType(
3781  ObjCIvarDecl *IV,
3783  std::string StructTagName;
3784  ObjCIvarBitfieldGroupType(IV, StructTagName);
3785  RecordDecl *RD = RecordDecl::Create(
3786  *Context, TagTypeKind::Struct, Context->getTranslationUnitDecl(),
3787  SourceLocation(), SourceLocation(), &Context->Idents.get(StructTagName));
3788  for (unsigned i=0, e = IVars.size(); i < e; i++) {
3789  ObjCIvarDecl *Ivar = IVars[i];
3790  RD->addDecl(FieldDecl::Create(*Context, RD, SourceLocation(), SourceLocation(),
3791  &Context->Idents.get(Ivar->getName()),
3792  Ivar->getType(),
3793  nullptr, /*Expr *BW */Ivar->getBitWidth(),
3794  false, ICIS_NoInit));
3795  }
3796  RD->completeDefinition();
3797  return Context->getTagDeclType(RD);
3798 }
3799 
3800 QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV) {
3801  const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3802  unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3803  std::pair<const ObjCInterfaceDecl*, unsigned> tuple = std::make_pair(CDecl, GroupNo);
3804  if (GroupRecordType.count(tuple))
3805  return GroupRecordType[tuple];
3806 
3808  for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3809  IVD; IVD = IVD->getNextIvar()) {
3810  if (IVD->isBitField())
3811  IVars.push_back(const_cast<ObjCIvarDecl *>(IVD));
3812  else {
3813  if (!IVars.empty()) {
3814  unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3815  // Generate the struct type for this group of bitfield ivars.
3816  GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3817  SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3818  IVars.clear();
3819  }
3820  }
3821  }
3822  if (!IVars.empty()) {
3823  // Do the last one.
3824  unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3825  GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3826  SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3827  }
3828  QualType RetQT = GroupRecordType[tuple];
3829  assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL");
3830 
3831  return RetQT;
3832 }
3833 
3834 /// ObjCIvarBitfieldGroupDecl - Names field decl. for ivar bitfield group.
3835 /// Name would be: classname__GRBF_n where n is the group number for this ivar.
3836 void RewriteModernObjC::ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV,
3837  std::string &Result) {
3838  const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3839  Result += CDecl->getName();
3840  Result += "__GRBF_";
3841  unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3842  Result += utostr(GroupNo);
3843 }
3844 
3845 /// ObjCIvarBitfieldGroupType - Names struct type for ivar bitfield group.
3846 /// Name of the struct would be: classname__T_n where n is the group number for
3847 /// this ivar.
3848 void RewriteModernObjC::ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV,
3849  std::string &Result) {
3850  const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3851  Result += CDecl->getName();
3852  Result += "__T_";
3853  unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3854  Result += utostr(GroupNo);
3855 }
3856 
3857 /// ObjCIvarBitfieldGroupOffset - Names symbol for ivar bitfield group field offset.
3858 /// Name would be: OBJC_IVAR_$_classname__GRBF_n where n is the group number for
3859 /// this ivar.
3860 void RewriteModernObjC::ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV,
3861  std::string &Result) {
3862  Result += "OBJC_IVAR_$_";
3863  ObjCIvarBitfieldGroupDecl(IV, Result);
3864 }
3865 
3866 #define SKIP_BITFIELDS(IX, ENDIX, VEC) { \
3867  while ((IX < ENDIX) && VEC[IX]->isBitField()) \
3868  ++IX; \
3869  if (IX < ENDIX) \
3870  --IX; \
3871 }
3872 
3873 /// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3874 /// an objective-c class with ivars.
3875 void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3876  std::string &Result) {
3877  assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3878  assert(CDecl->getName() != "" &&
3879  "Name missing in SynthesizeObjCInternalStruct");
3880  ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
3882  for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3883  IVD; IVD = IVD->getNextIvar())
3884  IVars.push_back(IVD);
3885 
3886  SourceLocation LocStart = CDecl->getBeginLoc();
3887  SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
3888 
3889  const char *startBuf = SM->getCharacterData(LocStart);
3890  const char *endBuf = SM->getCharacterData(LocEnd);
3891 
3892  // If no ivars and no root or if its root, directly or indirectly,
3893  // have no ivars (thus not synthesized) then no need to synthesize this class.
3894  if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
3895  (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3896  endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3897  ReplaceText(LocStart, endBuf-startBuf, Result);
3898  return;
3899  }
3900 
3901  // Insert named struct/union definitions inside class to
3902  // outer scope. This follows semantics of locally defined
3903  // struct/unions in objective-c classes.
3904  for (unsigned i = 0, e = IVars.size(); i < e; i++)
3905  RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
3906 
3907  // Insert named structs which are syntheized to group ivar bitfields
3908  // to outer scope as well.
3909  for (unsigned i = 0, e = IVars.size(); i < e; i++)
3910  if (IVars[i]->isBitField()) {
3911  ObjCIvarDecl *IV = IVars[i];
3912  QualType QT = GetGroupRecordTypeForObjCIvarBitfield(IV);
3913  RewriteObjCFieldDeclType(QT, Result);
3914  Result += ";";
3915  // skip over ivar bitfields in this group.
3916  SKIP_BITFIELDS(i , e, IVars);
3917  }
3918 
3919  Result += "\nstruct ";
3920  Result += CDecl->getNameAsString();
3921  Result += "_IMPL {\n";
3922 
3923  if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
3924  Result += "\tstruct "; Result += RCDecl->getNameAsString();
3925  Result += "_IMPL "; Result += RCDecl->getNameAsString();
3926  Result += "_IVARS;\n";
3927  }
3928 
3929  for (unsigned i = 0, e = IVars.size(); i < e; i++) {
3930  if (IVars[i]->isBitField()) {
3931  ObjCIvarDecl *IV = IVars[i];
3932  Result += "\tstruct ";
3933  ObjCIvarBitfieldGroupType(IV, Result); Result += " ";
3934  ObjCIvarBitfieldGroupDecl(IV, Result); Result += ";\n";
3935  // skip over ivar bitfields in this group.
3936  SKIP_BITFIELDS(i , e, IVars);
3937  }
3938  else
3939  RewriteObjCFieldDecl(IVars[i], Result);
3940  }
3941 
3942  Result += "};\n";
3943  endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3944  ReplaceText(LocStart, endBuf-startBuf, Result);
3945  // Mark this struct as having been generated.
3946  if (!ObjCSynthesizedStructs.insert(CDecl).second)
3947  llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
3948 }
3949 
3950 /// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3951 /// have been referenced in an ivar access expression.
3952 void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3953  std::string &Result) {
3954  // write out ivar offset symbols which have been referenced in an ivar
3955  // access expression.
3956  llvm::SmallSetVector<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3957 
3958  if (Ivars.empty())
3959  return;
3960 
3961  llvm::DenseSet<std::pair<const ObjCInterfaceDecl*, unsigned> > GroupSymbolOutput;
3962  for (ObjCIvarDecl *IvarDecl : Ivars) {
3963  const ObjCInterfaceDecl *IDecl = IvarDecl->getContainingInterface();
3964  unsigned GroupNo = 0;
3965  if (IvarDecl->isBitField()) {
3966  GroupNo = ObjCIvarBitfieldGroupNo(IvarDecl);
3967  if (GroupSymbolOutput.count(std::make_pair(IDecl, GroupNo)))
3968  continue;
3969  }
3970  Result += "\n";
3971  if (LangOpts.MicrosoftExt)
3972  Result += "__declspec(allocate(\".objc_ivar$B\")) ";
3973  Result += "extern \"C\" ";
3974  if (LangOpts.MicrosoftExt &&
3975  IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
3976  IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
3977  Result += "__declspec(dllimport) ";
3978 
3979  Result += "unsigned long ";
3980  if (IvarDecl->isBitField()) {
3981  ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
3982  GroupSymbolOutput.insert(std::make_pair(IDecl, GroupNo));
3983  }
3984  else
3985  WriteInternalIvarName(CDecl, IvarDecl, Result);
3986  Result += ";";
3987  }
3988 }
3989 
3990 //===----------------------------------------------------------------------===//
3991 // Meta Data Emission
3992 //===----------------------------------------------------------------------===//
3993 
3994 /// RewriteImplementations - This routine rewrites all method implementations
3995 /// and emits meta-data.
3996 
3997 void RewriteModernObjC::RewriteImplementations() {
3998  int ClsDefCount = ClassImplementation.size();
3999  int CatDefCount = CategoryImplementation.size();
4000 
4001  // Rewrite implemented methods
4002  for (int i = 0; i < ClsDefCount; i++) {
4003  ObjCImplementationDecl *OIMP = ClassImplementation[i];
4004  ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
4005  if (CDecl->isImplicitInterfaceDecl())
4006  assert(false &&
4007  "Legacy implicit interface rewriting not supported in moder abi");
4008  RewriteImplementationDecl(OIMP);
4009  }
4010 
4011  for (int i = 0; i < CatDefCount; i++) {
4012  ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
4013  ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
4014  if (CDecl->isImplicitInterfaceDecl())
4015  assert(false &&
4016  "Legacy implicit interface rewriting not supported in moder abi");
4017  RewriteImplementationDecl(CIMP);
4018  }
4019 }
4020 
4021 void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
4022  const std::string &Name,
4023  ValueDecl *VD, bool def) {
4024  assert(BlockByRefDeclNo.count(VD) &&
4025  "RewriteByRefString: ByRef decl missing");
4026  if (def)
4027  ResultStr += "struct ";
4028  ResultStr += "__Block_byref_" + Name +
4029  "_" + utostr(BlockByRefDeclNo[VD]) ;
4030 }
4031 
4033  if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4034  return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4035  return false;
4036 }
4037 
4038 std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4039  StringRef funcName,
4040  const std::string &Tag) {
4041  const FunctionType *AFT = CE->getFunctionType();
4042  QualType RT = AFT->getReturnType();
4043  std::string StructRef = "struct " + Tag;
4044  SourceLocation BlockLoc = CE->getExprLoc();
4045  std::string S;
4046  ConvertSourceLocationToLineDirective(BlockLoc, S);
4047 
4048  S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
4049  funcName.str() + "_block_func_" + utostr(i);
4050 
4051  BlockDecl *BD = CE->getBlockDecl();
4052 
4053  if (isa<FunctionNoProtoType>(AFT)) {
4054  // No user-supplied arguments. Still need to pass in a pointer to the
4055  // block (to reference imported block decl refs).
4056  S += "(" + StructRef + " *__cself)";
4057  } else if (BD->param_empty()) {
4058  S += "(" + StructRef + " *__cself)";
4059  } else {
4060  const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4061  assert(FT && "SynthesizeBlockFunc: No function proto");
4062  S += '(';
4063  // first add the implicit argument.
4064  S += StructRef + " *__cself, ";
4065  std::string ParamStr;
4066  for (BlockDecl::param_iterator AI = BD->param_begin(),
4067  E = BD->param_end(); AI != E; ++AI) {
4068  if (AI != BD->param_begin()) S += ", ";
4069  ParamStr = (*AI)->getNameAsString();
4070  QualType QT = (*AI)->getType();
4071  (void)convertBlockPointerToFunctionPointer(QT);
4072  QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
4073  S += ParamStr;
4074  }
4075  if (FT->isVariadic()) {
4076  if (!BD->param_empty()) S += ", ";
4077  S += "...";
4078  }
4079  S += ')';
4080  }
4081  S += " {\n";
4082 
4083  // Create local declarations to avoid rewriting all closure decl ref exprs.
4084  // First, emit a declaration for all "by ref" decls.
4085  for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
4086  E = BlockByRefDecls.end(); I != E; ++I) {
4087  S += " ";
4088  std::string Name = (*I)->getNameAsString();
4089  std::string TypeString;
4090  RewriteByRefString(TypeString, Name, (*I));
4091  TypeString += " *";
4092  Name = TypeString + Name;
4093  S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4094  }
4095  // Next, emit a declaration for all "by copy" declarations.
4096  for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
4097  E = BlockByCopyDecls.end(); I != E; ++I) {
4098  S += " ";
4099  // Handle nested closure invocation. For example:
4100  //
4101  // void (^myImportedClosure)(void);
4102  // myImportedClosure = ^(void) { setGlobalInt(x + y); };
4103  //
4104  // void (^anotherClosure)(void);
4105  // anotherClosure = ^(void) {
4106  // myImportedClosure(); // import and invoke the closure
4107  // };
4108  //
4109  if (isTopLevelBlockPointerType((*I)->getType())) {
4110  RewriteBlockPointerTypeVariable(S, (*I));
4111  S += " = (";
4112  RewriteBlockPointerType(S, (*I)->getType());
4113  S += ")";
4114  S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4115  }
4116  else {
4117  std::string Name = (*I)->getNameAsString();
4118  QualType QT = (*I)->getType();
4120  QT = Context->getPointerType(QT);
4121  QT.getAsStringInternal(Name, Context->getPrintingPolicy());
4122  S += Name + " = __cself->" +
4123  (*I)->getNameAsString() + "; // bound by copy\n";
4124  }
4125  }
4126  std::string RewrittenStr = RewrittenBlockExprs[CE];
4127  const char *cstr = RewrittenStr.c_str();
4128  while (*cstr++ != '{') ;
4129  S += cstr;
4130  S += "\n";
4131  return S;
4132 }
4133 
4134 std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(
4135  BlockExpr *CE, int i, StringRef funcName, const std::string &Tag) {
4136  std::string StructRef = "struct " + Tag;
4137  std::string S = "static void __";
4138 
4139  S += funcName;
4140  S += "_block_copy_" + utostr(i);
4141  S += "(" + StructRef;
4142  S += "*dst, " + StructRef;
4143  S += "*src) {";
4144  for (ValueDecl *VD : ImportedBlockDecls) {
4145  S += "_Block_object_assign((void*)&dst->";
4146  S += VD->getNameAsString();
4147  S += ", (void*)src->";
4148  S += VD->getNameAsString();
4149  if (BlockByRefDeclsPtrSet.count(VD))
4150  S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4151  else if (VD->getType()->isBlockPointerType())
4152  S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4153  else
4154  S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4155  }
4156  S += "}\n";
4157 
4158  S += "\nstatic void __";
4159  S += funcName;
4160  S += "_block_dispose_" + utostr(i);
4161  S += "(" + StructRef;
4162  S += "*src) {";
4163  for (ValueDecl *VD : ImportedBlockDecls) {
4164  S += "_Block_object_dispose((void*)src->";
4165  S += VD->getNameAsString();
4166  if (BlockByRefDeclsPtrSet.count(VD))
4167  S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4168  else if (VD->getType()->isBlockPointerType())
4169  S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4170  else
4171  S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4172  }
4173  S += "}\n";
4174  return S;
4175 }
4176 
4177 std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE,
4178  const std::string &Tag,
4179  const std::string &Desc) {
4180  std::string S = "\nstruct " + Tag;
4181  std::string Constructor = " " + Tag;
4182 
4183  S += " {\n struct __block_impl impl;\n";
4184  S += " struct " + Desc;
4185  S += "* Desc;\n";
4186 
4187  Constructor += "(void *fp, "; // Invoke function pointer.
4188  Constructor += "struct " + Desc; // Descriptor pointer.
4189  Constructor += " *desc";
4190 
4191  if (BlockDeclRefs.size()) {
4192  // Output all "by copy" declarations.
4193  for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
4194  E = BlockByCopyDecls.end(); I != E; ++I) {
4195  S += " ";
4196  std::string FieldName = (*I)->getNameAsString();
4197  std::string ArgName = "_" + FieldName;
4198  // Handle nested closure invocation. For example:
4199  //
4200  // void (^myImportedBlock)(void);
4201  // myImportedBlock = ^(void) { setGlobalInt(x + y); };
4202  //
4203  // void (^anotherBlock)(void);
4204  // anotherBlock = ^(void) {
4205  // myImportedBlock(); // import and invoke the closure
4206  // };
4207  //
4208  if (isTopLevelBlockPointerType((*I)->getType())) {
4209  S += "struct __block_impl *";
4210  Constructor += ", void *" + ArgName;
4211  } else {
4212  QualType QT = (*I)->getType();
4214  QT = Context->getPointerType(QT);
4215  QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4216  QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4217  Constructor += ", " + ArgName;
4218  }
4219  S += FieldName + ";\n";
4220  }
4221  // Output all "by ref" declarations.
4222  for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
4223  E = BlockByRefDecls.end(); I != E; ++I) {
4224  S += " ";
4225  std::string FieldName = (*I)->getNameAsString();
4226  std::string ArgName = "_" + FieldName;
4227  {
4228  std::string TypeString;
4229  RewriteByRefString(TypeString, FieldName, (*I));
4230  TypeString += " *";
4231  FieldName = TypeString + FieldName;
4232  ArgName = TypeString + ArgName;
4233  Constructor += ", " + ArgName;
4234  }
4235  S += FieldName + "; // by ref\n";
4236  }
4237  // Finish writing the constructor.
4238  Constructor += ", int flags=0)";
4239  // Initialize all "by copy" arguments.
4240  bool firsTime = true;
4241  for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
4242  E = BlockByCopyDecls.end(); I != E; ++I) {
4243  std::string Name = (*I)->getNameAsString();
4244  if (firsTime) {
4245  Constructor += " : ";
4246  firsTime = false;
4247  }
4248  else
4249  Constructor += ", ";
4250  if (isTopLevelBlockPointerType((*I)->getType()))
4251  Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4252  else
4253  Constructor += Name + "(_" + Name + ")";
4254  }
4255  // Initialize all "by ref" arguments.
4256  for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
4257  E = BlockByRefDecls.end(); I != E; ++I) {
4258  std::string Name = (*I)->getNameAsString();
4259  if (firsTime) {
4260  Constructor += " : ";
4261  firsTime = false;
4262  }
4263  else
4264  Constructor += ", ";
4265  Constructor += Name + "(_" + Name + "->__forwarding)";
4266  }
4267 
4268  Constructor += " {\n";
4269  if (GlobalVarDecl)
4270  Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4271  else
4272  Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4273  Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4274 
4275  Constructor += " Desc = desc;\n";
4276  } else {
4277  // Finish writing the constructor.
4278  Constructor += ", int flags=0) {\n";
4279  if (GlobalVarDecl)
4280  Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4281  else
4282  Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4283  Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4284  Constructor += " Desc = desc;\n";
4285  }
4286  Constructor += " ";
4287  Constructor += "}\n";
4288  S += Constructor;
4289  S += "};\n";
4290  return S;
4291 }
4292 
4293 std::string RewriteModernObjC::SynthesizeBlockDescriptor(
4294  const std::string &DescTag, const std::string &ImplTag, int i,
4295  StringRef FunName, unsigned hasCopy) {
4296  std::string S = "\nstatic struct " + DescTag;
4297 
4298  S += " {\n size_t reserved;\n";
4299  S += " size_t Block_size;\n";
4300  if (hasCopy) {
4301  S += " void (*copy)(struct ";
4302  S += ImplTag; S += "*, struct ";
4303  S += ImplTag; S += "*);\n";
4304 
4305  S += " void (*dispose)(struct ";
4306  S += ImplTag; S += "*);\n";
4307  }
4308  S += "} ";
4309 
4310  S += DescTag + "_DATA = { 0, sizeof(struct ";
4311  S += ImplTag + ")";
4312  if (hasCopy) {
4313  S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4314  S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4315  }
4316  S += "};\n";
4317  return S;
4318 }
4319 
4320 void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4321  StringRef FunName) {
4322  bool RewriteSC = (GlobalVarDecl &&
4323  !Blocks.empty() &&
4324  GlobalVarDecl->getStorageClass() == SC_Static &&
4325  GlobalVarDecl->getType().getCVRQualifiers());
4326  if (RewriteSC) {
4327  std::string SC(" void __");
4328  SC += GlobalVarDecl->getNameAsString();
4329  SC += "() {}";
4330  InsertText(FunLocStart, SC);
4331  }
4332 
4333  // Insert closures that were part of the function.
4334  for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4335  CollectBlockDeclRefInfo(Blocks[i]);
4336  // Need to copy-in the inner copied-in variables not actually used in this
4337  // block.
4338  for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4339  DeclRefExpr *Exp = InnerDeclRefs[count++];
4340  ValueDecl *VD = Exp->getDecl();
4341  BlockDeclRefs.push_back(Exp);
4342  if (!VD->hasAttr<BlocksAttr>()) {
4343  if (!BlockByCopyDeclsPtrSet.count(VD)) {
4344  BlockByCopyDeclsPtrSet.insert(VD);
4345  BlockByCopyDecls.push_back(VD);
4346  }
4347  continue;
4348  }
4349 
4350  if (!BlockByRefDeclsPtrSet.count(VD)) {
4351  BlockByRefDeclsPtrSet.insert(VD);
4352  BlockByRefDecls.push_back(VD);
4353  }
4354 
4355  // imported objects in the inner blocks not used in the outer
4356  // blocks must be copied/disposed in the outer block as well.
4357  if (VD->getType()->isObjCObjectPointerType() ||
4358  VD->getType()->isBlockPointerType())
4359  ImportedBlockDecls.insert(VD);
4360  }
4361 
4362  std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4363  std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4364 
4365  std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4366 
4367  InsertText(FunLocStart, CI);
4368 
4369  std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4370 
4371  InsertText(FunLocStart, CF);
4372 
4373  if (ImportedBlockDecls.size()) {
4374  std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4375  InsertText(FunLocStart, HF);
4376  }
4377  std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4378  ImportedBlockDecls.size() > 0);
4379  InsertText(FunLocStart, BD);
4380 
4381  BlockDeclRefs.clear();
4382  BlockByRefDecls.clear();
4383  BlockByRefDeclsPtrSet.clear();
4384  BlockByCopyDecls.clear();
4385  BlockByCopyDeclsPtrSet.clear();
4386  ImportedBlockDecls.clear();
4387  }
4388  if (RewriteSC) {
4389  // Must insert any 'const/volatile/static here. Since it has been
4390  // removed as result of rewriting of block literals.
4391  std::string SC;
4392  if (GlobalVarDecl->getStorageClass() == SC_Static)
4393  SC = "static ";
4394  if (GlobalVarDecl->getType().isConstQualified())
4395  SC += "const ";
4396  if (GlobalVarDecl->getType().isVolatileQualified())
4397  SC += "volatile ";
4398  if (GlobalVarDecl->getType().isRestrictQualified())
4399  SC += "restrict ";
4400  InsertText(FunLocStart, SC);
4401  }
4402  if (GlobalConstructionExp) {
4403  // extra fancy dance for global literal expression.
4404 
4405  // Always the latest block expression on the block stack.
4406  std::string Tag = "__";
4407  Tag += FunName;
4408  Tag += "_block_impl_";
4409  Tag += utostr(Blocks.size()-1);
4410  std::string globalBuf = "static ";
4411  globalBuf += Tag; globalBuf += " ";
4412  std::string SStr;
4413 
4414  llvm::raw_string_ostream constructorExprBuf(SStr);
4415  GlobalConstructionExp->printPretty(constructorExprBuf, nullptr,
4416  PrintingPolicy(LangOpts));
4417  globalBuf += SStr;
4418  globalBuf += ";\n";
4419  InsertText(FunLocStart, globalBuf);
4420  GlobalConstructionExp = nullptr;
4421  }
4422 
4423  Blocks.clear();
4424  InnerDeclRefsCount.clear();
4425  InnerDeclRefs.clear();
4426  RewrittenBlockExprs.clear();
4427 }
4428 
4429 void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4430  SourceLocation FunLocStart =
4431  (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4432  : FD->getTypeSpecStartLoc();
4433  StringRef FuncName = FD->getName();
4434 
4435  SynthesizeBlockLiterals(FunLocStart, FuncName);
4436 }
4437 
4438 static void BuildUniqueMethodName(std::string &Name,
4439  ObjCMethodDecl *MD) {
4440  ObjCInterfaceDecl *IFace = MD->getClassInterface();
4441  Name = std::string(IFace->getName());
4442  Name += "__" + MD->getSelector().getAsString();
4443  // Convert colons to underscores.
4444  std::string::size_type loc = 0;
4445  while ((loc = Name.find(':', loc)) != std::string::npos)
4446  Name.replace(loc, 1, "_");
4447 }
4448 
4449 void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4450  // fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4451  // SourceLocation FunLocStart = MD->getBeginLoc();
4452  SourceLocation FunLocStart = MD->getBeginLoc();
4453  std::string FuncName;
4454  BuildUniqueMethodName(FuncName, MD);
4455  SynthesizeBlockLiterals(FunLocStart, FuncName);
4456 }
4457 
4458 void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4459  for (Stmt *SubStmt : S->children())
4460  if (SubStmt) {
4461  if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt))
4462  GetBlockDeclRefExprs(CBE->getBody());
4463  else
4464  GetBlockDeclRefExprs(SubStmt);
4465  }
4466  // Handle specific things.
4467  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4470  // FIXME: Handle enums.
4471  BlockDeclRefs.push_back(DRE);
4472 }
4473 
4474 void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4475  SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
4476  llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts) {
4477  for (Stmt *SubStmt : S->children())
4478  if (SubStmt) {
4479  if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt)) {
4480  InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4481  GetInnerBlockDeclRefExprs(CBE->getBody(),
4482  InnerBlockDeclRefs,
4483  InnerContexts);
4484  }
4485  else
4486  GetInnerBlockDeclRefExprs(SubStmt, InnerBlockDeclRefs, InnerContexts);
4487  }
4488  // Handle specific things.
4489  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4492  if (!InnerContexts.count(DRE->getDecl()->getDeclContext()))
4493  InnerBlockDeclRefs.push_back(DRE);
4494  if (VarDecl *Var = cast<VarDecl>(DRE->getDecl()))
4495  if (Var->isFunctionOrMethodVarDecl())
4496  ImportedLocalExternalDecls.insert(Var);
4497  }
4498  }
4499 }
4500 
4501 /// convertObjCTypeToCStyleType - This routine converts such objc types
4502 /// as qualified objects, and blocks to their closest c/c++ types that
4503 /// it can. It returns true if input type was modified.
4504 bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4505  QualType oldT = T;
4506  convertBlockPointerToFunctionPointer(T);
4507  if (T->isFunctionPointerType()) {
4508  QualType PointeeTy;
4509  if (const PointerType* PT = T->getAs<PointerType>()) {
4510  PointeeTy = PT->getPointeeType();
4511  if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4512  T = convertFunctionTypeOfBlocks(FT);
4513  T = Context->getPointerType(T);
4514  }
4515  }
4516  }
4517 
4518  convertToUnqualifiedObjCType(T);
4519  return T != oldT;
4520 }
4521 
4522 /// convertFunctionTypeOfBlocks - This routine converts a function type
4523 /// whose result type may be a block pointer or whose argument type(s)
4524 /// might be block pointers to an equivalent function type replacing
4525 /// all block pointers to function pointers.
4526 QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4527  const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4528  // FTP will be null for closures that don't take arguments.
4529  // Generate a funky cast.
4530  SmallVector<QualType, 8> ArgTypes;
4531  QualType Res = FT->getReturnType();
4532  bool modified = convertObjCTypeToCStyleType(Res);
4533 
4534  if (FTP) {
4535  for (auto &I : FTP->param_types()) {
4536  QualType t = I;
4537  // Make sure we convert "t (^)(...)" to "t (*)(...)".
4538  if (convertObjCTypeToCStyleType(t))
4539  modified = true;
4540  ArgTypes.push_back(t);
4541  }
4542  }
4543  QualType FuncType;
4544  if (modified)
4545  FuncType = getSimpleFunctionType(Res, ArgTypes);
4546  else FuncType = QualType(FT, 0);
4547  return FuncType;
4548 }
4549 
4550 Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4551  // Navigate to relevant type information.
4552  const BlockPointerType *CPT = nullptr;
4553 
4554  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4555  CPT = DRE->getType()->getAs<BlockPointerType>();
4556  } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4557  CPT = MExpr->getType()->getAs<BlockPointerType>();
4558  }
4559  else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4560  return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4561  }
4562  else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4563  CPT = IEXPR->getType()->getAs<BlockPointerType>();
4564  else if (const ConditionalOperator *CEXPR =
4565  dyn_cast<ConditionalOperator>(BlockExp)) {
4566  Expr *LHSExp = CEXPR->getLHS();
4567  Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4568  Expr *RHSExp = CEXPR->getRHS();
4569  Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4570  Expr *CONDExp = CEXPR->getCond();
4571  ConditionalOperator *CondExpr = new (Context) ConditionalOperator(
4572  CONDExp, SourceLocation(), cast<Expr>(LHSStmt), SourceLocation(),
4573  cast<Expr>(RHSStmt), Exp->getType(), VK_PRValue, OK_Ordinary);
4574  return CondExpr;
4575  } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4576  CPT = IRE->getType()->getAs<BlockPointerType>();
4577  } else if (const PseudoObjectExpr *POE
4578  = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4579  CPT = POE->getType()->castAs<BlockPointerType>();
4580  } else {
4581  assert(false && "RewriteBlockClass: Bad type");
4582  }
4583  assert(CPT && "RewriteBlockClass: Bad type");
4584  const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4585  assert(FT && "RewriteBlockClass: Bad type");
4586  const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4587  // FTP will be null for closures that don't take arguments.
4588 
4589  RecordDecl *RD = RecordDecl::Create(*Context, TagTypeKind::Struct, TUDecl,
4591  &Context->Idents.get("__block_impl"));
4592  QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4593 
4594  // Generate a funky cast.
4595  SmallVector<QualType, 8> ArgTypes;
4596 
4597  // Push the block argument type.
4598  ArgTypes.push_back(PtrBlock);
4599  if (FTP) {
4600  for (auto &I : FTP->param_types()) {
4601  QualType t = I;
4602  // Make sure we convert "t (^)(...)" to "t (*)(...)".
4603  if (!convertBlockPointerToFunctionPointer(t))
4604  convertToUnqualifiedObjCType(t);
4605  ArgTypes.push_back(t);
4606  }
4607  }
4608  // Now do the pointer to function cast.
4609  QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
4610 
4611  PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4612 
4613  CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4614  CK_BitCast,
4615  const_cast<Expr*>(BlockExp));
4616  // Don't forget the parens to enforce the proper binding.
4617  ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4618  BlkCast);
4619  //PE->dump();
4620 
4621  FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
4622  SourceLocation(),
4623  &Context->Idents.get("FuncPtr"),
4624  Context->VoidPtrTy, nullptr,
4625  /*BitWidth=*/nullptr, /*Mutable=*/true,
4626  ICIS_NoInit);
4627  MemberExpr *ME = MemberExpr::CreateImplicit(
4628  *Context, PE, true, FD, FD->getType(), VK_LValue, OK_Ordinary);
4629 
4630  CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4631  CK_BitCast, ME);
4632  PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4633 
4634  SmallVector<Expr*, 8> BlkExprs;
4635  // Add the implicit argument.
4636  BlkExprs.push_back(BlkCast);
4637  // Add the user arguments.
4638  for (CallExpr::arg_iterator I = Exp->arg_begin(),
4639  E = Exp->arg_end(); I != E; ++I) {
4640  BlkExprs.push_back(*I);
4641  }
4642  CallExpr *CE =
4643  CallExpr::Create(*Context, PE, BlkExprs, Exp->getType(), VK_PRValue,
4645  return CE;
4646 }
4647 
4648 // We need to return the rewritten expression to handle cases where the
4649 // DeclRefExpr is embedded in another expression being rewritten.
4650 // For example:
4651 //
4652 // int main() {
4653 // __block Foo *f;
4654 // __block int i;
4655 //
4656 // void (^myblock)() = ^() {
4657 // [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
4658 // i = 77;
4659 // };
4660 //}
4661 Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
4662  // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4663  // for each DeclRefExp where BYREFVAR is name of the variable.
4664  ValueDecl *VD = DeclRefExp->getDecl();
4665  bool isArrow = DeclRefExp->refersToEnclosingVariableOrCapture() ||
4667 
4668  FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
4669  SourceLocation(),
4670  &Context->Idents.get("__forwarding"),
4671  Context->VoidPtrTy, nullptr,
4672  /*BitWidth=*/nullptr, /*Mutable=*/true,
4673  ICIS_NoInit);
4674  MemberExpr *ME = MemberExpr::CreateImplicit(
4675  *Context, DeclRefExp, isArrow, FD, FD->getType(), VK_LValue, OK_Ordinary);
4676 
4677  StringRef Name = VD->getName();
4678  FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(),
4679  &Context->Idents.get(Name),
4680  Context->VoidPtrTy, nullptr,
4681  /*BitWidth=*/nullptr, /*Mutable=*/true,
4682  ICIS_NoInit);
4683  ME = MemberExpr::CreateImplicit(*Context, ME, true, FD, DeclRefExp->getType(),
4685 
4686  // Need parens to enforce precedence.
4687  ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4688  DeclRefExp->getExprLoc(),
4689  ME);
4690  ReplaceStmt(DeclRefExp, PE);
4691  return PE;
4692 }
4693 
4694 // Rewrites the imported local variable V with external storage
4695 // (static, extern, etc.) as *V
4696 //
4697 Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4698  ValueDecl *VD = DRE->getDecl();
4699  if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4700  if (!ImportedLocalExternalDecls.count(Var))
4701  return DRE;
4702  Expr *Exp = UnaryOperator::Create(
4703  const_cast<ASTContext &>(*Context), DRE, UO_Deref, DRE->getType(),
4704  VK_LValue, OK_Ordinary, DRE->getLocation(), false, FPOptionsOverride());
4705  // Need parens to enforce precedence.
4706  ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4707  Exp);
4708  ReplaceStmt(DRE, PE);
4709  return PE;
4710 }
4711 
4712 void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4713  SourceLocation LocStart = CE->getLParenLoc();
4714  SourceLocation LocEnd = CE->getRParenLoc();
4715 
4716  // Need to avoid trying to rewrite synthesized casts.
4717  if (LocStart.isInvalid())
4718  return;
4719  // Need to avoid trying to rewrite casts contained in macros.
4720  if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4721  return;
4722 
4723  const char *startBuf = SM->getCharacterData(LocStart);
4724  const char *endBuf = SM->getCharacterData(LocEnd);
4725  QualType QT = CE->getType();
4726  const Type* TypePtr = QT->getAs<Type>();
4727  if (isa<TypeOfExprType>(TypePtr)) {
4728  const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4729  QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4730  std::string TypeAsString = "(";
4731  RewriteBlockPointerType(TypeAsString, QT);
4732  TypeAsString += ")";
4733  ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4734  return;
4735  }
4736  // advance the location to startArgList.
4737  const char *argPtr = startBuf;
4738 
4739  while (*argPtr++ && (argPtr < endBuf)) {
4740  switch (*argPtr) {
4741  case '^':
4742  // Replace the '^' with '*'.
4743  LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4744  ReplaceText(LocStart, 1, "*");
4745  break;
4746  }
4747  }
4748 }
4749 
4750 void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4751  CastKind CastKind = IC->getCastKind();
4752  if (CastKind != CK_BlockPointerToObjCPointerCast &&
4753  CastKind != CK_AnyPointerToBlockPointerCast)
4754  return;
4755 
4756  QualType QT = IC->getType();
4757  (void)convertBlockPointerToFunctionPointer(QT);
4758  std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4759  std::string Str = "(";
4760  Str += TypeString;
4761  Str += ")";
4762  InsertText(IC->getSubExpr()->getBeginLoc(), Str);
4763 }
4764 
4765 void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4766  SourceLocation DeclLoc = FD->getLocation();
4767  unsigned parenCount = 0;
4768 
4769  // We have 1 or more arguments that have closure pointers.
4770  const char *startBuf = SM->getCharacterData(DeclLoc);
4771  const char *startArgList = strchr(startBuf, '(');
4772 
4773  assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4774 
4775  parenCount++;
4776  // advance the location to startArgList.
4777  DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4778  assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4779 
4780  const char *argPtr = startArgList;
4781 
4782  while (*argPtr++ && parenCount) {
4783  switch (*argPtr) {
4784  case '^':
4785  // Replace the '^' with '*'.
4786  DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4787  ReplaceText(DeclLoc, 1, "*");
4788  break;
4789  case '(':
4790  parenCount++;
4791  break;
4792  case ')':
4793  parenCount--;
4794  break;
4795  }
4796  }
4797 }
4798 
4799 bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4800  const FunctionProtoType *FTP;
4801  const PointerType *PT = QT->getAs<PointerType>();
4802  if (PT) {
4803  FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4804  } else {
4805  const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4806  assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4807  FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4808  }
4809  if (FTP) {
4810  for (const auto &I : FTP->param_types())
4811  if (isTopLevelBlockPointerType(I))
4812  return true;
4813  }
4814  return false;
4815 }
4816 
4817 bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4818  const FunctionProtoType *FTP;
4819  const PointerType *PT = QT->getAs<PointerType>();
4820  if (PT) {
4821  FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4822  } else {
4823  const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4824  assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4825  FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4826  }
4827  if (FTP) {
4828  for (const auto &I : FTP->param_types()) {
4829  if (I->isObjCQualifiedIdType())
4830  return true;
4831  if (I->isObjCObjectPointerType() &&
4832  I->getPointeeType()->isObjCQualifiedInterfaceType())
4833  return true;
4834  }
4835 
4836  }
4837  return false;
4838 }
4839 
4840 void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4841  const char *&RParen) {
4842  const char *argPtr = strchr(Name, '(');
4843  assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4844 
4845  LParen = argPtr; // output the start.
4846  argPtr++; // skip past the left paren.
4847  unsigned parenCount = 1;
4848 
4849  while (*argPtr && parenCount) {
4850  switch (*argPtr) {
4851  case '(': parenCount++; break;
4852  case ')': parenCount--; break;
4853  default: break;
4854  }
4855  if (parenCount) argPtr++;
4856  }
4857  assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4858  RParen = argPtr; // output the end
4859 }
4860 
4861 void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4862  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4863  RewriteBlockPointerFunctionArgs(FD);
4864  return;
4865  }
4866  // Handle Variables and Typedefs.
4867  SourceLocation DeclLoc = ND->getLocation();
4868  QualType DeclT;
4869  if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4870  DeclT = VD->getType();
4871  else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4872  DeclT = TDD->getUnderlyingType();
4873  else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4874  DeclT = FD->getType();
4875  else
4876  llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4877 
4878  const char *startBuf = SM->getCharacterData(DeclLoc);
4879  const char *endBuf = startBuf;
4880  // scan backward (from the decl location) for the end of the previous decl.
4881  while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4882  startBuf--;
4883  SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4884  std::string buf;
4885  unsigned OrigLength=0;
4886  // *startBuf != '^' if we are dealing with a pointer to function that
4887  // may take block argument types (which will be handled below).
4888  if (*startBuf == '^') {
4889  // Replace the '^' with '*', computing a negative offset.
4890  buf = '*';
4891  startBuf++;
4892  OrigLength++;
4893  }
4894  while (*startBuf != ')') {
4895  buf += *startBuf;
4896  startBuf++;
4897  OrigLength++;
4898  }
4899  buf += ')';
4900  OrigLength++;
4901 
4902  if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4903  PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4904  // Replace the '^' with '*' for arguments.
4905  // Replace id<P> with id/*<>*/
4906  DeclLoc = ND->getLocation();
4907  startBuf = SM->getCharacterData(DeclLoc);
4908  const char *argListBegin, *argListEnd;
4909  GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4910  while (argListBegin < argListEnd) {
4911  if (*argListBegin == '^')
4912  buf += '*';
4913  else if (*argListBegin == '<') {
4914  buf += "/*";
4915  buf += *argListBegin++;
4916  OrigLength++;
4917  while (*argListBegin != '>') {
4918  buf += *argListBegin++;
4919  OrigLength++;
4920  }
4921  buf += *argListBegin;
4922  buf += "*/";
4923  }
4924  else
4925  buf += *argListBegin;
4926  argListBegin++;
4927  OrigLength++;
4928  }
4929  buf += ')';
4930  OrigLength++;
4931  }
4932  ReplaceText(Start, OrigLength, buf);
4933 }
4934 
4935 /// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4936 /// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4937 /// struct Block_byref_id_object *src) {
4938 /// _Block_object_assign (&_dest->object, _src->object,
4939 /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4940 /// [|BLOCK_FIELD_IS_WEAK]) // object
4941 /// _Block_object_assign(&_dest->object, _src->object,
4942 /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4943 /// [|BLOCK_FIELD_IS_WEAK]) // block
4944 /// }
4945 /// And:
4946 /// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4947 /// _Block_object_dispose(_src->object,
4948 /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4949 /// [|BLOCK_FIELD_IS_WEAK]) // object
4950 /// _Block_object_dispose(_src->object,
4951 /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4952 /// [|BLOCK_FIELD_IS_WEAK]) // block
4953 /// }
4954 
4955 std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4956  int flag) {
4957  std::string S;
4958  if (CopyDestroyCache.count(flag))
4959  return S;
4960  CopyDestroyCache.insert(flag);
4961  S = "static void __Block_byref_id_object_copy_";
4962  S += utostr(flag);
4963  S += "(void *dst, void *src) {\n";
4964 
4965  // offset into the object pointer is computed as:
4966  // void * + void* + int + int + void* + void *
4967  unsigned IntSize =
4968  static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4969  unsigned VoidPtrSize =
4970  static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4971 
4972  unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4973  S += " _Block_object_assign((char*)dst + ";
4974  S += utostr(offset);
4975  S += ", *(void * *) ((char*)src + ";
4976  S += utostr(offset);
4977  S += "), ";
4978  S += utostr(flag);
4979  S += ");\n}\n";
4980 
4981  S += "static void __Block_byref_id_object_dispose_";
4982  S += utostr(flag);
4983  S += "(void *src) {\n";
4984  S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4985  S += utostr(offset);
4986  S += "), ";
4987  S += utostr(flag);
4988  S += ");\n}\n";
4989  return S;
4990 }
4991 
4992 /// RewriteByRefVar - For each __block typex ND variable this routine transforms
4993 /// the declaration into:
4994 /// struct __Block_byref_ND {
4995 /// void *__isa; // NULL for everything except __weak pointers
4996 /// struct __Block_byref_ND *__forwarding;
4997 /// int32_t __flags;
4998 /// int32_t __size;
4999 /// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5000 /// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
5001 /// typex ND;
5002 /// };
5003 ///
5004 /// It then replaces declaration of ND variable with:
5005 /// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5006 /// __size=sizeof(struct __Block_byref_ND),
5007 /// ND=initializer-if-any};
5008 ///
5009 ///
5010 void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
5011  bool lastDecl) {
5012  int flag = 0;
5013  int isa = 0;
5014  SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
5015  if (DeclLoc.isInvalid())
5016  // If type location is missing, it is because of missing type (a warning).
5017  // Use variable's location which is good for this case.
5018  DeclLoc = ND->getLocation();
5019  const char *startBuf = SM->getCharacterData(DeclLoc);
5020  SourceLocation X = ND->getEndLoc();
5021  X = SM->getExpansionLoc(X);
5022  const char *endBuf = SM->getCharacterData(X);
5023  std::string Name(ND->getNameAsString());
5024  std::string ByrefType;
5025  RewriteByRefString(ByrefType, Name, ND, true);
5026  ByrefType += " {\n";
5027  ByrefType += " void *__isa;\n";
5028  RewriteByRefString(ByrefType, Name, ND);
5029  ByrefType += " *__forwarding;\n";
5030  ByrefType += " int __flags;\n";
5031  ByrefType += " int __size;\n";
5032  // Add void *__Block_byref_id_object_copy;
5033  // void *__Block_byref_id_object_dispose; if needed.
5034  QualType Ty = ND->getType();
5035  bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
5036  if (HasCopyAndDispose) {
5037  ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5038  ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5039  }
5040 
5041  QualType T = Ty;
5042  (void)convertBlockPointerToFunctionPointer(T);
5043  T.getAsStringInternal(Name, Context->getPrintingPolicy());
5044 
5045  ByrefType += " " + Name + ";\n";
5046  ByrefType += "};\n";
5047  // Insert this type in global scope. It is needed by helper function.
5048  SourceLocation FunLocStart;
5049  if (CurFunctionDef)
5050  FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
5051  else {
5052  assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5053  FunLocStart = CurMethodDef->getBeginLoc();
5054  }
5055  InsertText(FunLocStart, ByrefType);
5056 
5057  if (Ty.isObjCGCWeak()) {
5058  flag |= BLOCK_FIELD_IS_WEAK;
5059  isa = 1;
5060  }
5061  if (HasCopyAndDispose) {
5062  flag = BLOCK_BYREF_CALLER;
5063  QualType Ty = ND->getType();
5064  // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5065  if (Ty->isBlockPointerType())
5066  flag |= BLOCK_FIELD_IS_BLOCK;
5067  else
5068  flag |= BLOCK_FIELD_IS_OBJECT;
5069  std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5070  if (!HF.empty())
5071  Preamble += HF;
5072  }
5073 
5074  // struct __Block_byref_ND ND =
5075  // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5076  // initializer-if-any};
5077  bool hasInit = (ND->getInit() != nullptr);
5078  // FIXME. rewriter does not support __block c++ objects which
5079  // require construction.
5080  if (hasInit)
5081  if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
5082  CXXConstructorDecl *CXXDecl = CExp->getConstructor();
5083  if (CXXDecl && CXXDecl->isDefaultConstructor())
5084  hasInit = false;
5085  }
5086 
5087  unsigned flags = 0;
5088  if (HasCopyAndDispose)
5089  flags |= BLOCK_HAS_COPY_DISPOSE;
5090  Name = ND->getNameAsString();
5091  ByrefType.clear();
5092  RewriteByRefString(ByrefType, Name, ND);
5093  std::string ForwardingCastType("(");
5094  ForwardingCastType += ByrefType + " *)";
5095  ByrefType += " " + Name + " = {(void*)";
5096  ByrefType += utostr(isa);
5097  ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
5098  ByrefType += utostr(flags);
5099  ByrefType += ", ";
5100  ByrefType += "sizeof(";
5101  RewriteByRefString(ByrefType, Name, ND);
5102  ByrefType += ")";
5103  if (HasCopyAndDispose) {
5104  ByrefType += ", __Block_byref_id_object_copy_";
5105  ByrefType += utostr(flag);
5106  ByrefType += ", __Block_byref_id_object_dispose_";
5107  ByrefType += utostr(flag);
5108  }
5109 
5110  if (!firstDecl) {
5111  // In multiple __block declarations, and for all but 1st declaration,
5112  // find location of the separating comma. This would be start location
5113  // where new text is to be inserted.
5114  DeclLoc = ND->getLocation();
5115  const char *startDeclBuf = SM->getCharacterData(DeclLoc);
5116  const char *commaBuf = startDeclBuf;
5117  while (*commaBuf != ',')
5118  commaBuf--;
5119  assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
5120  DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5121  startBuf = commaBuf;
5122  }
5123 
5124  if (!hasInit) {
5125  ByrefType += "};\n";
5126  unsigned nameSize = Name.size();
5127  // for block or function pointer declaration. Name is already
5128  // part of the declaration.
5129  if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5130  nameSize = 1;
5131  ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5132  }
5133  else {
5134  ByrefType += ", ";
5135  SourceLocation startLoc;
5136  Expr *E = ND->getInit();
5137  if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5138  startLoc = ECE->getLParenLoc();
5139  else
5140  startLoc = E->getBeginLoc();
5141  startLoc = SM->getExpansionLoc(startLoc);
5142  endBuf = SM->getCharacterData(startLoc);
5143  ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
5144 
5145  const char separator = lastDecl ? ';' : ',';
5146  const char *startInitializerBuf = SM->getCharacterData(startLoc);
5147  const char *separatorBuf = strchr(startInitializerBuf, separator);
5148  assert((*separatorBuf == separator) &&
5149  "RewriteByRefVar: can't find ';' or ','");
5150  SourceLocation separatorLoc =
5151  startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
5152 
5153  InsertText(separatorLoc, lastDecl ? "}" : "};\n");
5154  }
5155 }
5156 
5157 void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5158  // Add initializers for any closure decl refs.
5159  GetBlockDeclRefExprs(Exp->getBody());
5160  if (BlockDeclRefs.size()) {
5161  // Unique all "by copy" declarations.
5162  for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5163  if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
5164  if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5165  BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5166  BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5167  }
5168  }
5169  // Unique all "by ref" declarations.
5170  for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5171  if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
5172  if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5173  BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5174  BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5175  }
5176  }
5177  // Find any imported blocks...they will need special attention.
5178  for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5179  if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
5180  BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5181  BlockDeclRefs[i]->getType()->isBlockPointerType())
5182  ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5183  }
5184 }
5185 
5186 FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5187  IdentifierInfo *ID = &Context->Idents.get(name);
5188  QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5189  return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5190  SourceLocation(), ID, FType, nullptr, SC_Extern,
5191  false, false);
5192 }
5193 
5194 Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
5195  const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
5196  const BlockDecl *block = Exp->getBlockDecl();
5197 
5198  Blocks.push_back(Exp);
5199 
5200  CollectBlockDeclRefInfo(Exp);
5201 
5202  // Add inner imported variables now used in current block.
5203  int countOfInnerDecls = 0;
5204  if (!InnerBlockDeclRefs.empty()) {
5205  for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5206  DeclRefExpr *Exp = InnerBlockDeclRefs[i];
5207  ValueDecl *VD = Exp->getDecl();
5208  if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
5209  // We need to save the copied-in variables in nested
5210  // blocks because it is needed at the end for some of the API generations.
5211  // See SynthesizeBlockLiterals routine.
5212  InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5213  BlockDeclRefs.push_back(Exp);
5214  BlockByCopyDeclsPtrSet.insert(VD);
5215  BlockByCopyDecls.push_back(VD);
5216  }
5217  if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
5218  InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5219  BlockDeclRefs.push_back(Exp);
5220  BlockByRefDeclsPtrSet.insert(VD);
5221  BlockByRefDecls.push_back(VD);
5222  }
5223  }
5224  // Find any imported blocks...they will need special attention.
5225  for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5226  if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
5227  InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5228  InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5229  ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5230  }
5231  InnerDeclRefsCount.push_back(countOfInnerDecls);
5232 
5233  std::string FuncName;
5234 
5235  if (CurFunctionDef)
5236  FuncName = CurFunctionDef->getNameAsString();
5237  else if (CurMethodDef)
5238  BuildUniqueMethodName(FuncName, CurMethodDef);
5239  else if (GlobalVarDecl)
5240  FuncName = std::string(GlobalVarDecl->getNameAsString());
5241 
5242  bool GlobalBlockExpr =
5244 
5245  if (GlobalBlockExpr && !GlobalVarDecl) {
5246  Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5247  GlobalBlockExpr = false;
5248  }
5249 
5250  std::string BlockNumber = utostr(Blocks.size()-1);
5251 
5252  std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5253 
5254  // Get a pointer to the function type so we can cast appropriately.
5255  QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5256  QualType FType = Context->getPointerType(BFT);
5257 
5258  FunctionDecl *FD;
5259  Expr *NewRep;
5260 
5261  // Simulate a constructor call...
5262  std::string Tag;
5263 
5264  if (GlobalBlockExpr)
5265  Tag = "__global_";
5266  else
5267  Tag = "__";
5268  Tag += FuncName + "_block_impl_" + BlockNumber;
5269 
5270  FD = SynthBlockInitFunctionDecl(Tag);
5271  DeclRefExpr *DRE = new (Context)
5272  DeclRefExpr(*Context, FD, false, FType, VK_PRValue, SourceLocation());
5273 
5274  SmallVector<Expr*, 4> InitExprs;
5275 
5276  // Initialize the block function.
5277  FD = SynthBlockInitFunctionDecl(Func);
5278  DeclRefExpr *Arg = new (Context) DeclRefExpr(
5279  *Context, FD, false, FD->getType(), VK_LValue, SourceLocation());
5280  CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5281  CK_BitCast, Arg);
5282  InitExprs.push_back(castExpr);
5283 
5284  // Initialize the block descriptor.
5285  std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5286 
5287  VarDecl *NewVD = VarDecl::Create(
5288  *Context, TUDecl, SourceLocation(), SourceLocation(),
5289  &Context->Idents.get(DescData), Context->VoidPtrTy, nullptr, SC_Static);
5290  UnaryOperator *DescRefExpr = UnaryOperator::Create(
5291  const_cast<ASTContext &>(*Context),
5292  new (Context) DeclRefExpr(*Context, NewVD, false, Context->VoidPtrTy,
5294  UO_AddrOf, Context->getPointerType(Context->VoidPtrTy), VK_PRValue,
5296  InitExprs.push_back(DescRefExpr);
5297 
5298  // Add initializers for any closure decl refs.
5299  if (BlockDeclRefs.size()) {
5300  Expr *Exp;
5301  // Output all "by copy" declarations.
5302  for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
5303  E = BlockByCopyDecls.end(); I != E; ++I) {
5304  if (isObjCType((*I)->getType())) {
5305  // FIXME: Conform to ABI ([[obj retain] autorelease]).
5306  FD = SynthBlockInitFunctionDecl((*I)->getName());
5307  Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
5310  QualType QT = (*I)->getType();
5311  QT = Context->getPointerType(QT);
5312  Exp = UnaryOperator::Create(const_cast<ASTContext &>(*Context), Exp,
5313  UO_AddrOf, QT, VK_PRValue, OK_Ordinary,
5314  SourceLocation(), false,
5315  FPOptionsOverride());
5316  }
5317  } else if (isTopLevelBlockPointerType((*I)->getType())) {
5318  FD = SynthBlockInitFunctionDecl((*I)->getName());
5319  Arg = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
5321  Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5322  CK_BitCast, Arg);
5323  } else {
5324  FD = SynthBlockInitFunctionDecl((*I)->getName());
5325  Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
5328  QualType QT = (*I)->getType();
5329  QT = Context->getPointerType(QT);
5330  Exp = UnaryOperator::Create(const_cast<ASTContext &>(*Context), Exp,
5331  UO_AddrOf, QT, VK_PRValue, OK_Ordinary,
5332  SourceLocation(), false,
5333  FPOptionsOverride());
5334  }
5335 
5336  }
5337  InitExprs.push_back(Exp);
5338  }
5339  // Output all "by ref" declarations.
5340  for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
5341  E = BlockByRefDecls.end(); I != E; ++I) {
5342  ValueDecl *ND = (*I);
5343  std::string Name(ND->getNameAsString());
5344  std::string RecName;
5345  RewriteByRefString(RecName, Name, ND, true);
5346  IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5347  + sizeof("struct"));
5348  RecordDecl *RD =
5349  RecordDecl::Create(*Context, TagTypeKind::Struct, TUDecl,
5350  SourceLocation(), SourceLocation(), II);
5351  assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5352  QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5353 
5354  FD = SynthBlockInitFunctionDecl((*I)->getName());
5355  Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
5357  bool isNestedCapturedVar = false;
5358  for (const auto &CI : block->captures()) {
5359  const VarDecl *variable = CI.getVariable();
5360  if (variable == ND && CI.isNested()) {
5361  assert(CI.isByRef() &&
5362  "SynthBlockInitExpr - captured block variable is not byref");
5363  isNestedCapturedVar = true;
5364  break;
5365  }
5366  }
5367  // captured nested byref variable has its address passed. Do not take
5368  // its address again.
5369  if (!isNestedCapturedVar)
5370  Exp = UnaryOperator::Create(
5371  const_cast<ASTContext &>(*Context), Exp, UO_AddrOf,
5372  Context->getPointerType(Exp->getType()), VK_PRValue, OK_Ordinary,
5373  SourceLocation(), false, FPOptionsOverride());
5374  Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5375  InitExprs.push_back(Exp);
5376  }
5377  }
5378  if (ImportedBlockDecls.size()) {
5379  // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5380  int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5381  unsigned IntSize =
5382  static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5383  Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5384  Context->IntTy, SourceLocation());
5385  InitExprs.push_back(FlagExp);
5386  }
5387  NewRep = CallExpr::Create(*Context, DRE, InitExprs, FType, VK_LValue,
5389 
5390  if (GlobalBlockExpr) {
5391  assert (!GlobalConstructionExp &&
5392  "SynthBlockInitExpr - GlobalConstructionExp must be null");
5393  GlobalConstructionExp = NewRep;
5394  NewRep = DRE;
5395  }
5396 
5397  NewRep = UnaryOperator::Create(
5398  const_cast<ASTContext &>(*Context), NewRep, UO_AddrOf,
5399  Context->getPointerType(NewRep->getType()), VK_PRValue, OK_Ordinary,
5400  SourceLocation(), false, FPOptionsOverride());
5401  NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5402  NewRep);
5403  // Put Paren around the call.
5404  NewRep = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
5405  NewRep);
5406 
5407  BlockDeclRefs.clear();
5408  BlockByRefDecls.clear();
5409  BlockByRefDeclsPtrSet.clear();
5410  BlockByCopyDecls.clear();
5411  BlockByCopyDeclsPtrSet.clear();
5412  ImportedBlockDecls.clear();
5413  return NewRep;
5414 }
5415 
5416 bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5417  if (const ObjCForCollectionStmt * CS =
5418  dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5419  return CS->getElement() == DS;
5420  return false;
5421 }
5422 
5423 //===----------------------------------------------------------------------===//
5424 // Function Body / Expression rewriting
5425 //===----------------------------------------------------------------------===//
5426 
5427 Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5428  if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5429  isa<DoStmt>(S) || isa<ForStmt>(S))
5430  Stmts.push_back(S);
5431  else if (isa<ObjCForCollectionStmt>(S)) {
5432  Stmts.push_back(S);
5433  ObjCBcLabelNo.push_back(++BcLabelCount);
5434  }
5435 
5436  // Pseudo-object operations and ivar references need special
5437  // treatment because we're going to recursively rewrite them.
5438  if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5439  if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5440  return RewritePropertyOrImplicitSetter(PseudoOp);
5441  } else {
5442  return RewritePropertyOrImplicitGetter(PseudoOp);
5443  }
5444  } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5445  return RewriteObjCIvarRefExpr(IvarRefExpr);
5446  }
5447  else if (isa<OpaqueValueExpr>(S))
5448  S = cast<OpaqueValueExpr>(S)->getSourceExpr();
5449 
5450  SourceRange OrigStmtRange = S->getSourceRange();
5451 
5452  // Perform a bottom up rewrite of all children.
5453  for (Stmt *&childStmt : S->children())
5454  if (childStmt) {
5455  Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5456  if (newStmt) {
5457  childStmt = newStmt;
5458  }
5459  }
5460 
5461  if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
5462  SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
5464  InnerContexts.insert(BE->getBlockDecl());
5465  ImportedLocalExternalDecls.clear();
5466  GetInnerBlockDeclRefExprs(BE->getBody(),
5467  InnerBlockDeclRefs, InnerContexts);
5468  // Rewrite the block body in place.
5469  Stmt *SaveCurrentBody = CurrentBody;
5470  CurrentBody = BE->getBody();
5471  PropParentMap = nullptr;
5472  // block literal on rhs of a property-dot-sytax assignment
5473  // must be replaced by its synthesize ast so getRewrittenText
5474  // works as expected. In this case, what actually ends up on RHS
5475  // is the blockTranscribed which is the helper function for the
5476  // block literal; as in: self.c = ^() {[ace ARR];};
5477  bool saveDisableReplaceStmt = DisableReplaceStmt;
5478  DisableReplaceStmt = false;
5479  RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5480  DisableReplaceStmt = saveDisableReplaceStmt;
5481  CurrentBody = SaveCurrentBody;
5482  PropParentMap = nullptr;
5483  ImportedLocalExternalDecls.clear();
5484  // Now we snarf the rewritten text and stash it away for later use.
5485  std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5486  RewrittenBlockExprs[BE] = Str;
5487 
5488  Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5489 
5490  //blockTranscribed->dump();
5491  ReplaceStmt(S, blockTranscribed);
5492  return blockTranscribed;
5493  }
5494  // Handle specific things.
5495  if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5496  return RewriteAtEncode(AtEncode);
5497 
5498  if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5499  return RewriteAtSelector(AtSelector);
5500 
5501  if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5502  return RewriteObjCStringLiteral(AtString);
5503 
5504  if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5505  return RewriteObjCBoolLiteralExpr(BoolLitExpr);
5506 
5507  if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5508  return RewriteObjCBoxedExpr(BoxedExpr);
5509 
5510  if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5511  return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
5512 
5513  if (ObjCDictionaryLiteral *DictionaryLitExpr =
5514  dyn_cast<ObjCDictionaryLiteral>(S))
5515  return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
5516 
5517  if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5518 #if 0
5519  // Before we rewrite it, put the original message expression in a comment.
5520  SourceLocation startLoc = MessExpr->getBeginLoc();
5521  SourceLocation endLoc = MessExpr->getEndLoc();
5522 
5523  const char *startBuf = SM->getCharacterData(startLoc);
5524  const char *endBuf = SM->getCharacterData(endLoc);
5525 
5526  std::string messString;
5527  messString += "// ";
5528  messString.append(startBuf, endBuf-startBuf+1);
5529  messString += "\n";
5530 
5531  // FIXME: Missing definition of
5532  // InsertText(clang::SourceLocation, char const*, unsigned int).
5533  // InsertText(startLoc, messString);
5534  // Tried this, but it didn't work either...
5535  // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5536 #endif
5537  return RewriteMessageExpr(MessExpr);
5538  }
5539 
5540  if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
5541  dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5542  return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5543  }
5544 
5545  if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5546  return RewriteObjCTryStmt(StmtTry);
5547 
5548  if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5549  return RewriteObjCSynchronizedStmt(StmtTry);
5550 
5551  if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5552  return RewriteObjCThrowStmt(StmtThrow);
5553 
5554  if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5555  return RewriteObjCProtocolExpr(ProtocolExp);
5556 
5557  if (ObjCForCollectionStmt *StmtForCollection =
5558  dyn_cast<ObjCForCollectionStmt>(S))
5559  return RewriteObjCForCollectionStmt(StmtForCollection,
5560  OrigStmtRange.getEnd());
5561  if (BreakStmt *StmtBreakStmt =
5562  dyn_cast<BreakStmt>(S))
5563  return RewriteBreakStmt(StmtBreakStmt);
5564  if (ContinueStmt *StmtContinueStmt =
5565  dyn_cast<ContinueStmt>(S))
5566  return RewriteContinueStmt(StmtContinueStmt);
5567 
5568  // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5569  // and cast exprs.
5570  if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5571  // FIXME: What we're doing here is modifying the type-specifier that
5572  // precedes the first Decl. In the future the DeclGroup should have
5573  // a separate type-specifier that we can rewrite.
5574  // NOTE: We need to avoid rewriting the DeclStmt if it is within
5575  // the context of an ObjCForCollectionStmt. For example:
5576  // NSArray *someArray;
5577  // for (id <FooProtocol> index in someArray) ;
5578  // This is because RewriteObjCForCollectionStmt() does textual rewriting
5579  // and it depends on the original text locations/positions.
5580  if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5581  RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5582 
5583  // Blocks rewrite rules.
5584  for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5585  DI != DE; ++DI) {
5586  Decl *SD = *DI;
5587  if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5588  if (isTopLevelBlockPointerType(ND->getType()))
5589  RewriteBlockPointerDecl(ND);
5590  else if (ND->getType()->isFunctionPointerType())
5591  CheckFunctionPointerDecl(ND->getType(), ND);
5592  if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5593  if (VD->hasAttr<BlocksAttr>()) {
5594  static unsigned uniqueByrefDeclCount = 0;
5595  assert(!BlockByRefDeclNo.count(ND) &&
5596  "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5597  BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
5598  RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
5599  }
5600  else
5601  RewriteTypeOfDecl(VD);
5602  }
5603  }
5604  if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5605  if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5606  RewriteBlockPointerDecl(TD);
5607  else if (TD->getUnderlyingType()->isFunctionPointerType())
5608  CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5609  }
5610  }
5611  }
5612 
5613  if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5614  RewriteObjCQualifiedInterfaceTypes(CE);
5615 
5616  if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5617  isa<DoStmt>(S) || isa<ForStmt>(S)) {
5618  assert(!Stmts.empty() && "Statement stack is empty");
5619  assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5620  isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5621  && "Statement stack mismatch");
5622  Stmts.pop_back();
5623  }
5624  // Handle blocks rewriting.
5625  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5626  ValueDecl *VD = DRE->getDecl();
5627  if (VD->hasAttr<BlocksAttr>())
5628  return RewriteBlockDeclRefExpr(DRE);
5630  return RewriteLocalVariableExternalStorage(DRE);
5631  }
5632 
5633  if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5634  if (CE->getCallee()->getType()->isBlockPointerType()) {
5635  Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5636  ReplaceStmt(S, BlockCall);
5637  return BlockCall;
5638  }
5639  }
5640  if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5641  RewriteCastExpr(CE);
5642  }
5643  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5644  RewriteImplicitCastObjCExpr(ICE);
5645  }
5646 #if 0
5647 
5648  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5649  CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5650  ICE->getSubExpr(),
5651  SourceLocation());
5652  // Get the new text.
5653  std::string SStr;
5654  llvm::raw_string_ostream Buf(SStr);
5655  Replacement->printPretty(Buf);
5656  const std::string &Str = Buf.str();
5657 
5658  printf("CAST = %s\n", &Str[0]);
5659  InsertText(ICE->getSubExpr()->getBeginLoc(), Str);
5660  delete S;
5661  return Replacement;
5662  }
5663 #endif
5664  // Return this stmt unmodified.
5665  return S;
5666 }
5667 
5668 void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5669  for (auto *FD : RD->fields()) {
5670  if (isTopLevelBlockPointerType(FD->getType()))
5671  RewriteBlockPointerDecl(FD);
5672  if (FD->getType()->isObjCQualifiedIdType() ||
5674  RewriteObjCQualifiedInterfaceTypes(FD);
5675  }
5676 }
5677 
5678 /// HandleDeclInMainFile - This is called for each top-level decl defined in the
5679 /// main file of the input.
5680 void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5681  switch (D->getKind()) {
5682  case Decl::Function: {
5683  FunctionDecl *FD = cast<FunctionDecl>(D);
5684  if (FD->isOverloadedOperator())
5685  return;
5686 
5687  // Since function prototypes don't have ParmDecl's, we check the function
5688  // prototype. This enables us to rewrite function declarations and
5689  // definitions using the same code.
5690  RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5691 
5692  if (!FD->isThisDeclarationADefinition())
5693  break;
5694 
5695  // FIXME: If this should support Obj-C++, support CXXTryStmt
5696  if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5697  CurFunctionDef = FD;
5698  CurrentBody = Body;
5699  Body =
5700  cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5701  FD->setBody(Body);
5702  CurrentBody = nullptr;
5703  if (PropParentMap) {
5704  delete PropParentMap;
5705  PropParentMap = nullptr;
5706  }
5707  // This synthesizes and inserts the block "impl" struct, invoke function,
5708  // and any copy/dispose helper functions.
5709  InsertBlockLiteralsWithinFunction(FD);
5710  RewriteLineDirective(D);
5711  CurFunctionDef = nullptr;
5712  }
5713  break;
5714  }
5715  case Decl::ObjCMethod: {
5716  ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5717  if (CompoundStmt *Body = MD->getCompoundBody()) {
5718  CurMethodDef = MD;
5719  CurrentBody = Body;
5720  Body =
5721  cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5722  MD->setBody(Body);
5723  CurrentBody = nullptr;
5724  if (PropParentMap) {
5725  delete PropParentMap;
5726  PropParentMap = nullptr;
5727  }
5728  InsertBlockLiteralsWithinMethod(MD);
5729  RewriteLineDirective(D);
5730  CurMethodDef = nullptr;
5731  }
5732  break;
5733  }
5734  case Decl::ObjCImplementation: {
5735  ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5736  ClassImplementation.push_back(CI);
5737  break;
5738  }
5739  case Decl::ObjCCategoryImpl: {
5740  ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5741  CategoryImplementation.push_back(CI);
5742  break;
5743  }
5744  case Decl::Var: {
5745  VarDecl *VD = cast<VarDecl>(D);
5746  RewriteObjCQualifiedInterfaceTypes(VD);
5747  if (isTopLevelBlockPointerType(VD->getType()))
5748  RewriteBlockPointerDecl(VD);
5749  else if (VD->getType()->isFunctionPointerType()) {
5750  CheckFunctionPointerDecl(VD->getType(), VD);
5751  if (VD->getInit()) {
5752  if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5753  RewriteCastExpr(CE);
5754  }
5755  }
5756  } else if (VD->getType()->isRecordType()) {
5757  RecordDecl *RD = VD->getType()->castAs<RecordType>()->getDecl();
5758  if (RD->isCompleteDefinition())
5759  RewriteRecordBody(RD);
5760  }
5761  if (VD->getInit()) {
5762  GlobalVarDecl = VD;
5763  CurrentBody = VD->getInit();
5764  RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5765  CurrentBody = nullptr;
5766  if (PropParentMap) {
5767  delete PropParentMap;
5768  PropParentMap = nullptr;
5769  }
5770  SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5771  GlobalVarDecl = nullptr;
5772 
5773  // This is needed for blocks.
5774  if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5775  RewriteCastExpr(CE);
5776  }
5777  }
5778  break;
5779  }
5780  case Decl::TypeAlias:
5781  case Decl::Typedef: {
5782  if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5783  if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5784  RewriteBlockPointerDecl(TD);
5785  else if (TD->getUnderlyingType()->isFunctionPointerType())
5786  CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5787  else
5788  RewriteObjCQualifiedInterfaceTypes(TD);
5789  }
5790  break;
5791  }
5792  case Decl::CXXRecord:
5793  case Decl::Record: {
5794  RecordDecl *RD = cast<RecordDecl>(D);
5795  if (RD->isCompleteDefinition())
5796  RewriteRecordBody(RD);
5797  break;
5798  }
5799  default:
5800  break;
5801  }
5802  // Nothing yet.
5803 }
5804 
5805 /// Write_ProtocolExprReferencedMetadata - This routine writer out the
5806 /// protocol reference symbols in the for of:
5807 /// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5809  ObjCProtocolDecl *PDecl,
5810  std::string &Result) {
5811  // Also output .objc_protorefs$B section and its meta-data.
5812  if (Context->getLangOpts().MicrosoftExt)
5813  Result += "static ";
5814  Result += "struct _protocol_t *";
5815  Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5816  Result += PDecl->getNameAsString();
5817  Result += " = &";
5818  Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5819  Result += ";\n";
5820 }
5821 
5822 void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5823  if (Diags.hasErrorOccurred())
5824  return;
5825 
5826  RewriteInclude();
5827 
5828  for (unsigned i = 0, e = FunctionDefinitionsSeen.size(); i < e; i++) {
5829  // translation of function bodies were postponed until all class and
5830  // their extensions and implementations are seen. This is because, we
5831  // cannot build grouping structs for bitfields until they are all seen.
5832  FunctionDecl *FDecl = FunctionDefinitionsSeen[i];
5833  HandleTopLevelSingleDecl(FDecl);
5834  }
5835 
5836  // Here's a great place to add any extra declarations that may be needed.
5837  // Write out meta data for each @protocol(<expr>).
5838  for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls) {
5839  RewriteObjCProtocolMetaData(ProtDecl, Preamble);
5840  Write_ProtocolExprReferencedMetadata(Context, ProtDecl, Preamble);
5841  }
5842 
5843  InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
5844 
5845  if (ClassImplementation.size() || CategoryImplementation.size())
5846  RewriteImplementations();
5847 
5848  for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5849  ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5850  // Write struct declaration for the class matching its ivar declarations.
5851  // Note that for modern abi, this is postponed until the end of TU
5852  // because class extensions and the implementation might declare their own
5853  // private ivars.
5854  RewriteInterfaceDecl(CDecl);
5855  }
5856 
5857  // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5858  // we are done.
5859  if (const RewriteBuffer *RewriteBuf =
5860  Rewrite.getRewriteBufferFor(MainFileID)) {
5861  //printf("Changed:\n");
5862  *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5863  } else {
5864  llvm::errs() << "No changes\n";
5865  }
5866 
5867  if (ClassImplementation.size() || CategoryImplementation.size() ||
5868  ProtocolExprDecls.size()) {
5869  // Rewrite Objective-c meta data*
5870  std::string ResultStr;
5871  RewriteMetaDataIntoBuffer(ResultStr);
5872  // Emit metadata.
5873  *OutFile << ResultStr;
5874  }
5875  // Emit ImageInfo;
5876  {
5877  std::string ResultStr;
5878  WriteImageInfo(ResultStr);
5879  *OutFile << ResultStr;
5880  }
5881  OutFile->flush();
5882 }
5883 
5884 void RewriteModernObjC::Initialize(ASTContext &context) {
5885  InitializeCommon(context);
5886 
5887  Preamble += "#ifndef __OBJC2__\n";
5888  Preamble += "#define __OBJC2__\n";
5889  Preamble += "#endif\n";
5890 
5891  // declaring objc_selector outside the parameter list removes a silly
5892  // scope related warning...
5893  if (IsHeader)
5894  Preamble = "#pragma once\n";
5895  Preamble += "struct objc_selector; struct objc_class;\n";
5896  Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
5897  Preamble += "\n\tstruct objc_object *superClass; ";
5898  // Add a constructor for creating temporary objects.
5899  Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
5900  Preamble += ": object(o), superClass(s) {} ";
5901  Preamble += "\n};\n";
5902 
5903  if (LangOpts.MicrosoftExt) {
5904  // Define all sections using syntax that makes sense.
5905  // These are currently generated.
5906  Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
5907  Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
5908  Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
5909  Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5910  Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
5911  // These are generated but not necessary for functionality.
5912  Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
5913  Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5914  Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
5915  Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
5916 
5917  // These need be generated for performance. Currently they are not,
5918  // using API calls instead.
5919  Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5920  Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5921  Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5922 
5923  }
5924  Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5925  Preamble += "typedef struct objc_object Protocol;\n";
5926  Preamble += "#define _REWRITER_typedef_Protocol\n";
5927  Preamble += "#endif\n";
5928  if (LangOpts.MicrosoftExt) {
5929  Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5930  Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
5931  }
5932  else
5933  Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
5934 
5935  Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
5936  Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
5937  Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
5938  Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
5939  Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
5940 
5941  Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
5942  Preamble += "(const char *);\n";
5943  Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5944  Preamble += "(struct objc_class *);\n";
5945  Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
5946  Preamble += "(const char *);\n";
5947  Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
5948  // @synchronized hooks.
5949  Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
5950  Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
5951  Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5952  Preamble += "#ifdef _WIN64\n";
5953  Preamble += "typedef unsigned long long _WIN_NSUInteger;\n";
5954  Preamble += "#else\n";
5955  Preamble += "typedef unsigned int _WIN_NSUInteger;\n";
5956  Preamble += "#endif\n";
5957  Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5958  Preamble += "struct __objcFastEnumerationState {\n\t";
5959  Preamble += "unsigned long state;\n\t";
5960  Preamble += "void **itemsPtr;\n\t";
5961  Preamble += "unsigned long *mutationsPtr;\n\t";
5962  Preamble += "unsigned long extra[5];\n};\n";
5963  Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5964  Preamble += "#define __FASTENUMERATIONSTATE\n";
5965  Preamble += "#endif\n";
5966  Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5967  Preamble += "struct __NSConstantStringImpl {\n";
5968  Preamble += " int *isa;\n";
5969  Preamble += " int flags;\n";
5970  Preamble += " char *str;\n";
5971  Preamble += "#if _WIN64\n";
5972  Preamble += " long long length;\n";
5973  Preamble += "#else\n";
5974  Preamble += " long length;\n";
5975  Preamble += "#endif\n";
5976  Preamble += "};\n";
5977  Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5978  Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5979  Preamble += "#else\n";
5980  Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5981  Preamble += "#endif\n";
5982  Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5983  Preamble += "#endif\n";
5984  // Blocks preamble.
5985  Preamble += "#ifndef BLOCK_IMPL\n";
5986  Preamble += "#define BLOCK_IMPL\n";
5987  Preamble += "struct __block_impl {\n";
5988  Preamble += " void *isa;\n";
5989  Preamble += " int Flags;\n";
5990  Preamble += " int Reserved;\n";
5991  Preamble += " void *FuncPtr;\n";
5992  Preamble += "};\n";
5993  Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5994  Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5995  Preamble += "extern \"C\" __declspec(dllexport) "
5996  "void _Block_object_assign(void *, const void *, const int);\n";
5997  Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5998  Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5999  Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
6000  Preamble += "#else\n";
6001  Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
6002  Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
6003  Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
6004  Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
6005  Preamble += "#endif\n";
6006  Preamble += "#endif\n";
6007  if (LangOpts.MicrosoftExt) {
6008  Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
6009  Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
6010  Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
6011  Preamble += "#define __attribute__(X)\n";
6012  Preamble += "#endif\n";
6013  Preamble += "#ifndef __weak\n";
6014  Preamble += "#define __weak\n";
6015  Preamble += "#endif\n";
6016  Preamble += "#ifndef __block\n";
6017  Preamble += "#define __block\n";
6018  Preamble += "#endif\n";
6019  }
6020  else {
6021  Preamble += "#define __block\n";
6022  Preamble += "#define __weak\n";
6023  }
6024 
6025  // Declarations required for modern objective-c array and dictionary literals.
6026  Preamble += "\n#include <stdarg.h>\n";
6027  Preamble += "struct __NSContainer_literal {\n";
6028  Preamble += " void * *arr;\n";
6029  Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
6030  Preamble += "\tva_list marker;\n";
6031  Preamble += "\tva_start(marker, count);\n";
6032  Preamble += "\tarr = new void *[count];\n";
6033  Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
6034  Preamble += "\t arr[i] = va_arg(marker, void *);\n";
6035  Preamble += "\tva_end( marker );\n";
6036  Preamble += " };\n";
6037  Preamble += " ~__NSContainer_literal() {\n";
6038  Preamble += "\tdelete[] arr;\n";
6039  Preamble += " }\n";
6040  Preamble += "};\n";
6041 
6042  // Declaration required for implementation of @autoreleasepool statement.
6043  Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
6044  Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
6045  Preamble += "struct __AtAutoreleasePool {\n";
6046  Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
6047  Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
6048  Preamble += " void * atautoreleasepoolobj;\n";
6049  Preamble += "};\n";
6050 
6051  // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
6052  // as this avoids warning in any 64bit/32bit compilation model.
6053  Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
6054 }
6055 
6056 /// RewriteIvarOffsetComputation - This routine synthesizes computation of
6057 /// ivar offset.
6058 void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
6059  std::string &Result) {
6060  Result += "__OFFSETOFIVAR__(struct ";
6061  Result += ivar->getContainingInterface()->getNameAsString();
6062  if (LangOpts.MicrosoftExt)
6063  Result += "_IMPL";
6064  Result += ", ";
6065  if (ivar->isBitField())
6066  ObjCIvarBitfieldGroupDecl(ivar, Result);
6067  else
6068  Result += ivar->getNameAsString();
6069  Result += ")";
6070 }
6071 
6072 /// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
6073 /// struct _prop_t {
6074 /// const char *name;
6075 /// char *attributes;
6076 /// }
6077 
6078 /// struct _prop_list_t {
6079 /// uint32_t entsize; // sizeof(struct _prop_t)
6080 /// uint32_t count_of_properties;
6081 /// struct _prop_t prop_list[count_of_properties];
6082 /// }
6083 
6084 /// struct _protocol_t;
6085 
6086 /// struct _protocol_list_t {
6087 /// long protocol_count; // Note, this is 32/64 bit
6088 /// struct _protocol_t * protocol_list[protocol_count];
6089 /// }
6090 
6091 /// struct _objc_method {
6092 /// SEL _cmd;
6093 /// const char *method_type;
6094 /// char *_imp;
6095 /// }
6096 
6097 /// struct _method_list_t {
6098 /// uint32_t entsize; // sizeof(struct _objc_method)
6099 /// uint32_t method_count;
6100 /// struct _objc_method method_list[method_count];
6101 /// }
6102 
6103 /// struct _protocol_t {
6104 /// id isa; // NULL
6105 /// const char *protocol_name;
6106 /// const struct _protocol_list_t * protocol_list; // super protocols
6107 /// const struct method_list_t *instance_methods;
6108 /// const struct method_list_t *class_methods;
6109 /// const struct method_list_t *optionalInstanceMethods;
6110 /// const struct method_list_t *optionalClassMethods;
6111 /// const struct _prop_list_t * properties;
6112 /// const uint32_t size; // sizeof(struct _protocol_t)
6113 /// const uint32_t flags; // = 0
6114 /// const char ** extendedMethodTypes;
6115 /// }
6116 
6117 /// struct _ivar_t {
6118 /// unsigned long int *offset; // pointer to ivar offset location
6119 /// const char *name;
6120 /// const char *type;
6121 /// uint32_t alignment;
6122 /// uint32_t size;
6123 /// }
6124 
6125 /// struct _ivar_list_t {
6126 /// uint32 entsize; // sizeof(struct _ivar_t)
6127 /// uint32 count;
6128 /// struct _ivar_t list[count];
6129 /// }
6130 
6131 /// struct _class_ro_t {
6132 /// uint32_t flags;
6133 /// uint32_t instanceStart;
6134 /// uint32_t instanceSize;
6135 /// uint32_t reserved; // only when building for 64bit targets
6136 /// const uint8_t *ivarLayout;
6137 /// const char *name;
6138 /// const struct _method_list_t *baseMethods;
6139 /// const struct _protocol_list_t *baseProtocols;
6140 /// const struct _ivar_list_t *ivars;
6141 /// const uint8_t *weakIvarLayout;
6142 /// const struct _prop_list_t *properties;
6143 /// }
6144 
6145 /// struct _class_t {
6146 /// struct _class_t *isa;
6147 /// struct _class_t *superclass;
6148 /// void *cache;
6149 /// IMP *vtable;
6150 /// struct _class_ro_t *ro;
6151 /// }
6152 
6153 /// struct _category_t {
6154 /// const char *name;
6155 /// struct _class_t *cls;
6156 /// const struct _method_list_t *instance_methods;
6157 /// const struct _method_list_t *class_methods;
6158 /// const struct _protocol_list_t *protocols;
6159 /// const struct _prop_list_t *properties;
6160 /// }
6161 
6162 /// MessageRefTy - LLVM for:
6163 /// struct _message_ref_t {
6164 /// IMP messenger;
6165 /// SEL name;
6166 /// };
6167 
6168 /// SuperMessageRefTy - LLVM for:
6169 /// struct _super_message_ref_t {
6170 /// SUPER_IMP messenger;
6171 /// SEL name;
6172 /// };
6173 
6174 static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
6175  static bool meta_data_declared = false;
6176  if (meta_data_declared)
6177  return;
6178 
6179  Result += "\nstruct _prop_t {\n";
6180  Result += "\tconst char *name;\n";
6181  Result += "\tconst char *attributes;\n";
6182  Result += "};\n";
6183 
6184  Result += "\nstruct _protocol_t;\n";
6185 
6186  Result += "\nstruct _objc_method {\n";
6187  Result += "\tstruct objc_selector * _cmd;\n";
6188  Result += "\tconst char *method_type;\n";
6189  Result += "\tvoid *_imp;\n";
6190  Result += "};\n";
6191 
6192  Result += "\nstruct _protocol_t {\n";
6193  Result += "\tvoid * isa; // NULL\n";
6194  Result += "\tconst char *protocol_name;\n";
6195  Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
6196  Result += "\tconst struct method_list_t *instance_methods;\n";
6197  Result += "\tconst struct method_list_t *class_methods;\n";
6198  Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6199  Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6200  Result += "\tconst struct _prop_list_t * properties;\n";
6201  Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
6202  Result += "\tconst unsigned int flags; // = 0\n";
6203  Result += "\tconst char ** extendedMethodTypes;\n";
6204  Result += "};\n";
6205 
6206  Result += "\nstruct _ivar_t {\n";
6207  Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
6208  Result += "\tconst char *name;\n";
6209  Result += "\tconst char *type;\n";
6210  Result += "\tunsigned int alignment;\n";
6211  Result += "\tunsigned int size;\n";
6212  Result += "};\n";
6213 
6214  Result += "\nstruct _class_ro_t {\n";
6215  Result += "\tunsigned int flags;\n";
6216  Result += "\tunsigned int instanceStart;\n";
6217  Result += "\tunsigned int instanceSize;\n";
6218  const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6219  if (Triple.getArch() == llvm::Triple::x86_64)
6220  Result += "\tunsigned int reserved;\n";
6221  Result += "\tconst unsigned char *ivarLayout;\n";
6222  Result += "\tconst char *name;\n";
6223  Result += "\tconst struct _method_list_t *baseMethods;\n";
6224  Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6225  Result += "\tconst struct _ivar_list_t *ivars;\n";
6226  Result += "\tconst unsigned char *weakIvarLayout;\n";
6227  Result += "\tconst struct _prop_list_t *properties;\n";
6228  Result += "};\n";
6229 
6230  Result += "\nstruct _class_t {\n";
6231  Result += "\tstruct _class_t *isa;\n";
6232  Result += "\tstruct _class_t *superclass;\n";
6233  Result += "\tvoid *cache;\n";
6234  Result += "\tvoid *vtable;\n";
6235  Result += "\tstruct _class_ro_t *ro;\n";
6236  Result += "};\n";
6237 
6238  Result += "\nstruct _category_t {\n";
6239  Result += "\tconst char *name;\n";
6240  Result += "\tstruct _class_t *cls;\n";
6241  Result += "\tconst struct _method_list_t *instance_methods;\n";
6242  Result += "\tconst struct _method_list_t *class_methods;\n";
6243  Result += "\tconst struct _protocol_list_t *protocols;\n";
6244  Result += "\tconst struct _prop_list_t *properties;\n";
6245  Result += "};\n";
6246 
6247  Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
6248  Result += "#pragma warning(disable:4273)\n";
6249  meta_data_declared = true;
6250 }
6251 
6252 static void Write_protocol_list_t_TypeDecl(std::string &Result,
6253  long super_protocol_count) {
6254  Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6255  Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6256  Result += "\tstruct _protocol_t *super_protocols[";
6257  Result += utostr(super_protocol_count); Result += "];\n";
6258  Result += "}";
6259 }
6260 
6261 static void Write_method_list_t_TypeDecl(std::string &Result,
6262  unsigned int method_count) {
6263  Result += "struct /*_method_list_t*/"; Result += " {\n";
6264  Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6265  Result += "\tunsigned int method_count;\n";
6266  Result += "\tstruct _objc_method method_list[";
6267  Result += utostr(method_count); Result += "];\n";
6268  Result += "}";
6269 }
6270 
6271 static void Write__prop_list_t_TypeDecl(std::string &Result,
6272  unsigned int property_count) {
6273  Result += "struct /*_prop_list_t*/"; Result += " {\n";
6274  Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6275  Result += "\tunsigned int count_of_properties;\n";
6276  Result += "\tstruct _prop_t prop_list[";
6277  Result += utostr(property_count); Result += "];\n";
6278  Result += "}";
6279 }
6280 
6281 static void Write__ivar_list_t_TypeDecl(std::string &Result,
6282  unsigned int ivar_count) {
6283  Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6284  Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6285  Result += "\tunsigned int count;\n";
6286  Result += "\tstruct _ivar_t ivar_list[";
6287  Result += utostr(ivar_count); Result += "];\n";
6288  Result += "}";
6289 }
6290 
6291 static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6292  ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6293  StringRef VarName,
6294  StringRef ProtocolName) {
6295  if (SuperProtocols.size() > 0) {
6296  Result += "\nstatic ";
6297  Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6298  Result += " "; Result += VarName;
6299  Result += ProtocolName;
6300  Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6301  Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6302  for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6303  ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6304  Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6305  Result += SuperPD->getNameAsString();
6306  if (i == e-1)
6307  Result += "\n};\n";
6308  else
6309  Result += ",\n";
6310  }
6311  }
6312 }
6313 
6314 static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6315  ASTContext *Context, std::string &Result,
6317  StringRef VarName,
6318  StringRef TopLevelDeclName,
6319  bool MethodImpl) {
6320  if (Methods.size() > 0) {
6321  Result += "\nstatic ";
6322  Write_method_list_t_TypeDecl(Result, Methods.size());
6323  Result += " "; Result += VarName;
6324  Result += TopLevelDeclName;
6325  Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6326  Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6327  Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6328  for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6329  ObjCMethodDecl *MD = Methods[i];
6330  if (i == 0)
6331  Result += "\t{{(struct objc_selector *)\"";
6332  else
6333  Result += "\t{(struct objc_selector *)\"";
6334  Result += (MD)->getSelector().getAsString(); Result += "\"";
6335  Result += ", ";
6336  std::string MethodTypeString = Context->getObjCEncodingForMethodDecl(MD);
6337  Result += "\""; Result += MethodTypeString; Result += "\"";
6338  Result += ", ";
6339  if (!MethodImpl)
6340  Result += "0";
6341  else {
6342  Result += "(void *)";
6343  Result += RewriteObj.MethodInternalNames[MD];
6344  }
6345  if (i == e-1)
6346  Result += "}}\n";
6347  else
6348  Result += "},\n";
6349  }
6350  Result += "};\n";
6351  }
6352 }
6353 
6354 static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
6355  ASTContext *Context, std::string &Result,
6356  ArrayRef<ObjCPropertyDecl *> Properties,
6357  const Decl *Container,
6358  StringRef VarName,
6359  StringRef ProtocolName) {
6360  if (Properties.size() > 0) {
6361  Result += "\nstatic ";
6362  Write__prop_list_t_TypeDecl(Result, Properties.size());
6363  Result += " "; Result += VarName;
6364  Result += ProtocolName;
6365  Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6366  Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6367  Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6368  for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6369  ObjCPropertyDecl *PropDecl = Properties[i];
6370  if (i == 0)
6371  Result += "\t{{\"";
6372  else
6373  Result += "\t{\"";
6374  Result += PropDecl->getName(); Result += "\",";
6375  std::string PropertyTypeString =
6376  Context->getObjCEncodingForPropertyDecl(PropDecl, Container);
6377  std::string QuotePropertyTypeString;
6378  RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6379  Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6380  if (i == e-1)
6381  Result += "}}\n";
6382  else
6383  Result += "},\n";
6384  }
6385  Result += "};\n";
6386  }
6387 }
6388 
6389 // Metadata flags
6391  CLS = 0x0,
6392  CLS_META = 0x1,
6393  CLS_ROOT = 0x2,
6396 
6397  /// (Obsolete) ARC-specific: this class has a .release_ivars method
6399  /// class was compiled with -fobjc-arr
6400  CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6401 };
6402 
6403 static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6404  unsigned int flags,
6405  const std::string &InstanceStart,
6406  const std::string &InstanceSize,
6407  ArrayRef<ObjCMethodDecl *>baseMethods,
6408  ArrayRef<ObjCProtocolDecl *>baseProtocols,
6410  ArrayRef<ObjCPropertyDecl *>Properties,
6411  StringRef VarName,
6412  StringRef ClassName) {
6413  Result += "\nstatic struct _class_ro_t ";
6414  Result += VarName; Result += ClassName;
6415  Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6416  Result += "\t";
6417  Result += llvm::utostr(flags); Result += ", ";
6418  Result += InstanceStart; Result += ", ";
6419  Result += InstanceSize; Result += ", \n";
6420  Result += "\t";
6421  const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6422  if (Triple.getArch() == llvm::Triple::x86_64)
6423  // uint32_t const reserved; // only when building for 64bit targets
6424  Result += "(unsigned int)0, \n\t";
6425  // const uint8_t * const ivarLayout;
6426  Result += "0, \n\t";
6427  Result += "\""; Result += ClassName; Result += "\",\n\t";
6428  bool metaclass = ((flags & CLS_META) != 0);
6429  if (baseMethods.size() > 0) {
6430  Result += "(const struct _method_list_t *)&";
6431  if (metaclass)
6432  Result += "_OBJC_$_CLASS_METHODS_";
6433  else
6434  Result += "_OBJC_$_INSTANCE_METHODS_";
6435  Result += ClassName;
6436  Result += ",\n\t";
6437  }
6438  else
6439  Result += "0, \n\t";
6440 
6441  if (!metaclass && baseProtocols.size() > 0) {
6442  Result += "(const struct _objc_protocol_list *)&";
6443  Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6444  Result += ",\n\t";
6445  }
6446  else
6447  Result += "0, \n\t";
6448 
6449  if (!metaclass && ivars.size() > 0) {
6450  Result += "(const struct _ivar_list_t *)&";
6451  Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6452  Result += ",\n\t";
6453  }
6454  else
6455  Result += "0, \n\t";
6456 
6457  // weakIvarLayout
6458  Result += "0, \n\t";
6459  if (!metaclass && Properties.size() > 0) {
6460  Result += "(const struct _prop_list_t *)&";
6461  Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
6462  Result += ",\n";
6463  }
6464  else
6465  Result += "0, \n";
6466 
6467  Result += "};\n";
6468 }
6469 
6470 static void Write_class_t(ASTContext *Context, std::string &Result,
6471  StringRef VarName,
6472  const ObjCInterfaceDecl *CDecl, bool metaclass) {
6473  bool rootClass = (!CDecl->getSuperClass());
6474  const ObjCInterfaceDecl *RootClass = CDecl;
6475 
6476  if (!rootClass) {
6477  // Find the Root class
6478  RootClass = CDecl->getSuperClass();
6479  while (RootClass->getSuperClass()) {
6480  RootClass = RootClass->getSuperClass();
6481  }
6482  }
6483 
6484  if (metaclass && rootClass) {
6485  // Need to handle a case of use of forward declaration.
6486  Result += "\n";
6487  Result += "extern \"C\" ";
6488  if (CDecl->getImplementation())
6489  Result += "__declspec(dllexport) ";
6490  else
6491  Result += "__declspec(dllimport) ";
6492 
6493  Result += "struct _class_t OBJC_CLASS_$_";
6494  Result += CDecl->getNameAsString();
6495  Result += ";\n";
6496  }
6497  // Also, for possibility of 'super' metadata class not having been defined yet.
6498  if (!rootClass) {
6499  ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
6500  Result += "\n";
6501  Result += "extern \"C\" ";
6502  if (SuperClass->getImplementation())
6503  Result += "__declspec(dllexport) ";
6504  else
6505  Result += "__declspec(dllimport) ";
6506 
6507  Result += "struct _class_t ";
6508  Result += VarName;
6509  Result += SuperClass->getNameAsString();
6510  Result += ";\n";
6511 
6512  if (metaclass && RootClass != SuperClass) {
6513  Result += "extern \"C\" ";
6514  if (RootClass->getImplementation())
6515  Result += "__declspec(dllexport) ";
6516  else
6517  Result += "__declspec(dllimport) ";
6518 
6519  Result += "struct _class_t ";
6520  Result += VarName;
6521  Result += RootClass->getNameAsString();
6522  Result += ";\n";
6523  }
6524  }
6525 
6526  Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6527  Result += VarName; Result += CDecl->getNameAsString();
6528  Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6529  Result += "\t";
6530  if (metaclass) {
6531  if (!rootClass) {
6532  Result += "0, // &"; Result += VarName;
6533  Result += RootClass->getNameAsString();
6534  Result += ",\n\t";
6535  Result += "0, // &"; Result += VarName;
6536  Result += CDecl->getSuperClass()->getNameAsString();
6537  Result += ",\n\t";
6538  }
6539  else {
6540  Result += "0, // &"; Result += VarName;
6541  Result += CDecl->getNameAsString();
6542  Result += ",\n\t";
6543  Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6544  Result += ",\n\t";
6545  }
6546  }
6547  else {
6548  Result += "0, // &OBJC_METACLASS_$_";
6549  Result += CDecl->getNameAsString();
6550  Result += ",\n\t";
6551  if (!rootClass) {
6552  Result += "0, // &"; Result += VarName;
6553  Result += CDecl->getSuperClass()->getNameAsString();
6554  Result += ",\n\t";
6555  }
6556  else
6557  Result += "0,\n\t";
6558  }
6559  Result += "0, // (void *)&_objc_empty_cache,\n\t";
6560  Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6561  if (metaclass)
6562  Result += "&_OBJC_METACLASS_RO_$_";
6563  else
6564  Result += "&_OBJC_CLASS_RO_$_";
6565  Result += CDecl->getNameAsString();
6566  Result += ",\n};\n";
6567 
6568  // Add static function to initialize some of the meta-data fields.
6569  // avoid doing it twice.
6570  if (metaclass)
6571  return;
6572 
6573  const ObjCInterfaceDecl *SuperClass =
6574  rootClass ? CDecl : CDecl->getSuperClass();
6575 
6576  Result += "static void OBJC_CLASS_SETUP_$_";
6577  Result += CDecl->getNameAsString();
6578  Result += "(void ) {\n";
6579  Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6580  Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6581  Result += RootClass->getNameAsString(); Result += ";\n";
6582 
6583  Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6584  Result += ".superclass = ";
6585  if (rootClass)
6586  Result += "&OBJC_CLASS_$_";
6587  else
6588  Result += "&OBJC_METACLASS_$_";
6589 
6590  Result += SuperClass->getNameAsString(); Result += ";\n";
6591 
6592  Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6593  Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6594 
6595  Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6596  Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6597  Result += CDecl->getNameAsString(); Result += ";\n";
6598 
6599  if (!rootClass) {
6600  Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6601  Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6602  Result += SuperClass->getNameAsString(); Result += ";\n";
6603  }
6604 
6605  Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6606  Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6607  Result += "}\n";
6608 }
6609 
6610 static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6611  std::string &Result,
6612  ObjCCategoryDecl *CatDecl,
6613  ObjCInterfaceDecl *ClassDecl,
6614  ArrayRef<ObjCMethodDecl *> InstanceMethods,
6615  ArrayRef<ObjCMethodDecl *> ClassMethods,
6616  ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6617  ArrayRef<ObjCPropertyDecl *> ClassProperties) {
6618  StringRef CatName = CatDecl->getName();
6619  StringRef ClassName = ClassDecl->getName();
6620  // must declare an extern class object in case this class is not implemented
6621  // in this TU.
6622  Result += "\n";
6623  Result += "extern \"C\" ";
6624  if (ClassDecl->getImplementation())
6625  Result += "__declspec(dllexport) ";
6626  else
6627  Result += "__declspec(dllimport) ";
6628 
6629  Result += "struct _class_t ";
6630  Result += "OBJC_CLASS_$_"; Result += ClassName;
6631  Result += ";\n";
6632 
6633  Result += "\nstatic struct _category_t ";
6634  Result += "_OBJC_$_CATEGORY_";
6635  Result += ClassName; Result += "_$_"; Result += CatName;
6636  Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6637  Result += "{\n";
6638  Result += "\t\""; Result += ClassName; Result += "\",\n";
6639  Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
6640  Result += ",\n";
6641  if (InstanceMethods.size() > 0) {
6642  Result += "\t(const struct _method_list_t *)&";
6643  Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6644  Result += ClassName; Result += "_$_"; Result += CatName;
6645  Result += ",\n";
6646  }
6647  else
6648  Result += "\t0,\n";
6649 
6650  if (ClassMethods.size() > 0) {
6651  Result += "\t(const struct _method_list_t *)&";
6652  Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6653  Result += ClassName; Result += "_$_"; Result += CatName;
6654  Result += ",\n";
6655  }
6656  else
6657  Result += "\t0,\n";
6658 
6659  if (RefedProtocols.size() > 0) {
6660  Result += "\t(const struct _protocol_list_t *)&";
6661  Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6662  Result += ClassName; Result += "_$_"; Result += CatName;
6663  Result += ",\n";
6664  }
6665  else
6666  Result += "\t0,\n";
6667 
6668  if (ClassProperties.size() > 0) {
6669  Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6670  Result += ClassName; Result += "_$_"; Result += CatName;
6671  Result += ",\n";
6672  }
6673  else
6674  Result += "\t0,\n";
6675 
6676  Result += "};\n";
6677 
6678  // Add static function to initialize the class pointer in the category structure.
6679  Result += "static void OBJC_CATEGORY_SETUP_$_";
6680  Result += ClassDecl->getNameAsString();
6681  Result += "_$_";
6682  Result += CatName;
6683  Result += "(void ) {\n";
6684  Result += "\t_OBJC_$_CATEGORY_";
6685  Result += ClassDecl->getNameAsString();
6686  Result += "_$_";
6687  Result += CatName;
6688  Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6689  Result += ";\n}\n";
6690 }
6691 
6692 static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6693  ASTContext *Context, std::string &Result,
6695  StringRef VarName,
6696  StringRef ProtocolName) {
6697  if (Methods.size() == 0)
6698  return;
6699 
6700  Result += "\nstatic const char *";
6701  Result += VarName; Result += ProtocolName;
6702  Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6703  Result += "{\n";
6704  for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6705  ObjCMethodDecl *MD = Methods[i];
6706  std::string MethodTypeString =
6707  Context->getObjCEncodingForMethodDecl(MD, true);
6708  std::string QuoteMethodTypeString;
6709  RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6710  Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6711  if (i == e-1)
6712  Result += "\n};\n";
6713  else {
6714  Result += ",\n";
6715  }
6716  }
6717 }
6718 
6719 static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6720  ASTContext *Context,
6721  std::string &Result,
6723  ObjCInterfaceDecl *CDecl) {
6724  // FIXME. visibility of offset symbols may have to be set; for Darwin
6725  // this is what happens:
6726  /**
6727  if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6728  Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6729  Class->getVisibility() == HiddenVisibility)
6730  Visibility should be: HiddenVisibility;
6731  else
6732  Visibility should be: DefaultVisibility;
6733  */
6734 
6735  Result += "\n";
6736  for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6737  ObjCIvarDecl *IvarDecl = Ivars[i];
6738  if (Context->getLangOpts().MicrosoftExt)
6739  Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6740 
6741  if (!Context->getLangOpts().MicrosoftExt ||
6742  IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
6743  IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
6744  Result += "extern \"C\" unsigned long int ";
6745  else
6746  Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
6747  if (Ivars[i]->isBitField())
6748  RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6749  else
6750  WriteInternalIvarName(CDecl, IvarDecl, Result);
6751  Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6752  Result += " = ";
6753  RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6754  Result += ";\n";
6755  if (Ivars[i]->isBitField()) {
6756  // skip over rest of the ivar bitfields.
6757  SKIP_BITFIELDS(i , e, Ivars);
6758  }
6759  }
6760 }
6761 
6762 static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6763  ASTContext *Context, std::string &Result,
6764  ArrayRef<ObjCIvarDecl *> OriginalIvars,
6765  StringRef VarName,
6766  ObjCInterfaceDecl *CDecl) {
6767  if (OriginalIvars.size() > 0) {
6768  Write_IvarOffsetVar(RewriteObj, Context, Result, OriginalIvars, CDecl);
6770  // strip off all but the first ivar bitfield from each group of ivars.
6771  // Such ivars in the ivar list table will be replaced by their grouping struct
6772  // 'ivar'.
6773  for (unsigned i = 0, e = OriginalIvars.size(); i < e; i++) {
6774  if (OriginalIvars[i]->isBitField()) {
6775  Ivars.push_back(OriginalIvars[i]);
6776  // skip over rest of the ivar bitfields.
6777  SKIP_BITFIELDS(i , e, OriginalIvars);
6778  }
6779  else
6780  Ivars.push_back(OriginalIvars[i]);
6781  }
6782 
6783  Result += "\nstatic ";
6784  Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6785  Result += " "; Result += VarName;
6786  Result += CDecl->getNameAsString();
6787  Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6788  Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6789  Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6790  for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6791  ObjCIvarDecl *IvarDecl = Ivars[i];
6792  if (i == 0)
6793  Result += "\t{{";
6794  else
6795  Result += "\t {";
6796  Result += "(unsigned long int *)&";
6797  if (Ivars[i]->isBitField())
6798  RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6799  else
6800  WriteInternalIvarName(CDecl, IvarDecl, Result);
6801  Result += ", ";
6802 
6803  Result += "\"";
6804  if (Ivars[i]->isBitField())
6805  RewriteObj.ObjCIvarBitfieldGroupDecl(Ivars[i], Result);
6806  else
6807  Result += IvarDecl->getName();
6808  Result += "\", ";
6809 
6810  QualType IVQT = IvarDecl->getType();
6811  if (IvarDecl->isBitField())
6812  IVQT = RewriteObj.GetGroupRecordTypeForObjCIvarBitfield(IvarDecl);
6813 
6814  std::string IvarTypeString, QuoteIvarTypeString;
6815  Context->getObjCEncodingForType(IVQT, IvarTypeString,
6816  IvarDecl);
6817  RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6818  Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6819 
6820  // FIXME. this alignment represents the host alignment and need be changed to
6821  // represent the target alignment.
6822  unsigned Align = Context->getTypeAlign(IVQT)/8;
6823  Align = llvm::Log2_32(Align);
6824  Result += llvm::utostr(Align); Result += ", ";
6825  CharUnits Size = Context->getTypeSizeInChars(IVQT);
6826  Result += llvm::utostr(Size.getQuantity());
6827  if (i == e-1)
6828  Result += "}}\n";
6829  else
6830  Result += "},\n";
6831  }
6832  Result += "};\n";
6833  }
6834 }
6835 
6836 /// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
6837 void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
6838  std::string &Result) {
6839 
6840  // Do not synthesize the protocol more than once.
6841  if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6842  return;
6843  WriteModernMetadataDeclarations(Context, Result);
6844 
6845  if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6846  PDecl = Def;
6847  // Must write out all protocol definitions in current qualifier list,
6848  // and in their nested qualifiers before writing out current definition.
6849  for (auto *I : PDecl->protocols())
6850  RewriteObjCProtocolMetaData(I, Result);
6851 
6852  // Construct method lists.
6853  std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6854  std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
6855  for (auto *MD : PDecl->instance_methods()) {
6856  if (MD->getImplementationControl() == ObjCImplementationControl::Optional) {
6857  OptInstanceMethods.push_back(MD);
6858  } else {
6859  InstanceMethods.push_back(MD);
6860  }
6861  }
6862 
6863  for (auto *MD : PDecl->class_methods()) {
6864  if (MD->getImplementationControl() == ObjCImplementationControl::Optional) {
6865  OptClassMethods.push_back(MD);
6866  } else {
6867  ClassMethods.push_back(MD);
6868  }
6869  }
6870  std::vector<ObjCMethodDecl *> AllMethods;
6871  for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6872  AllMethods.push_back(InstanceMethods[i]);
6873  for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6874  AllMethods.push_back(ClassMethods[i]);
6875  for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6876  AllMethods.push_back(OptInstanceMethods[i]);
6877  for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
6878  AllMethods.push_back(OptClassMethods[i]);
6879 
6880  Write__extendedMethodTypes_initializer(*this, Context, Result,
6881  AllMethods,
6882  "_OBJC_PROTOCOL_METHOD_TYPES_",
6883  PDecl->getNameAsString());
6884  // Protocol's super protocol list
6885  SmallVector<ObjCProtocolDecl *, 8> SuperProtocols(PDecl->protocols());
6886  Write_protocol_list_initializer(Context, Result, SuperProtocols,
6887  "_OBJC_PROTOCOL_REFS_",
6888  PDecl->getNameAsString());
6889 
6890  Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6891  "_OBJC_PROTOCOL_INSTANCE_METHODS_",
6892  PDecl->getNameAsString(), false);
6893 
6894  Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6895  "_OBJC_PROTOCOL_CLASS_METHODS_",
6896  PDecl->getNameAsString(), false);
6897 
6898  Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
6899  "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
6900  PDecl->getNameAsString(), false);
6901 
6902  Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
6903  "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
6904  PDecl->getNameAsString(), false);
6905 
6906  // Protocol's property metadata.
6907  SmallVector<ObjCPropertyDecl *, 8> ProtocolProperties(
6908  PDecl->instance_properties());
6909  Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
6910  /* Container */nullptr,
6911  "_OBJC_PROTOCOL_PROPERTIES_",
6912  PDecl->getNameAsString());
6913 
6914  // Writer out root metadata for current protocol: struct _protocol_t
6915  Result += "\n";
6916  if (LangOpts.MicrosoftExt)
6917  Result += "static ";
6918  Result += "struct _protocol_t _OBJC_PROTOCOL_";
6919  Result += PDecl->getNameAsString();
6920  Result += " __attribute__ ((used)) = {\n";
6921  Result += "\t0,\n"; // id is; is null
6922  Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
6923  if (SuperProtocols.size() > 0) {
6924  Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6925  Result += PDecl->getNameAsString(); Result += ",\n";
6926  }
6927  else
6928  Result += "\t0,\n";
6929  if (InstanceMethods.size() > 0) {
6930  Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
6931  Result += PDecl->getNameAsString(); Result += ",\n";
6932  }
6933  else
6934  Result += "\t0,\n";
6935 
6936  if (ClassMethods.size() > 0) {
6937  Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
6938  Result += PDecl->getNameAsString(); Result += ",\n";
6939  }
6940  else
6941  Result += "\t0,\n";
6942 
6943  if (OptInstanceMethods.size() > 0) {
6944  Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
6945  Result += PDecl->getNameAsString(); Result += ",\n";
6946  }
6947  else
6948  Result += "\t0,\n";
6949 
6950  if (OptClassMethods.size() > 0) {
6951  Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
6952  Result += PDecl->getNameAsString(); Result += ",\n";
6953  }
6954  else
6955  Result += "\t0,\n";
6956 
6957  if (ProtocolProperties.size() > 0) {
6958  Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
6959  Result += PDecl->getNameAsString(); Result += ",\n";
6960  }
6961  else
6962  Result += "\t0,\n";
6963 
6964  Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6965  Result += "\t0,\n";
6966 
6967  if (AllMethods.size() > 0) {
6968  Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6969  Result += PDecl->getNameAsString();
6970  Result += "\n};\n";
6971  }
6972  else
6973  Result += "\t0\n};\n";
6974 
6975  if (LangOpts.MicrosoftExt)
6976  Result += "static ";
6977  Result += "struct _protocol_t *";
6978  Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6979  Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6980  Result += ";\n";
6981 
6982  // Mark this protocol as having been generated.
6983  if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()).second)
6984  llvm_unreachable("protocol already synthesized");
6985 }
6986 
6987 /// hasObjCExceptionAttribute - Return true if this class or any super
6988 /// class has the __objc_exception__ attribute.
6989 /// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
6991  const ObjCInterfaceDecl *OID) {
6992  if (OID->hasAttr<ObjCExceptionAttr>())
6993  return true;
6994  if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
6995  return hasObjCExceptionAttribute(Context, Super);
6996  return false;
6997 }
6998 
6999 void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
7000  std::string &Result) {
7001  ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7002 
7003  // Explicitly declared @interface's are already synthesized.
7004  if (CDecl->isImplicitInterfaceDecl())
7005  assert(false &&
7006  "Legacy implicit interface rewriting not supported in moder abi");
7007 
7008  WriteModernMetadataDeclarations(Context, Result);
7010 
7011  for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7012  IVD; IVD = IVD->getNextIvar()) {
7013  // Ignore unnamed bit-fields.
7014  if (!IVD->getDeclName())
7015  continue;
7016  IVars.push_back(IVD);
7017  }
7018 
7019  Write__ivar_list_t_initializer(*this, Context, Result, IVars,
7020  "_OBJC_$_INSTANCE_VARIABLES_",
7021  CDecl);
7022 
7023  // Build _objc_method_list for class's instance methods if needed
7024  SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
7025 
7026  // If any of our property implementations have associated getters or
7027  // setters, produce metadata for them as well.
7028  for (const auto *Prop : IDecl->property_impls()) {
7029  if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
7030  continue;
7031  if (!Prop->getPropertyIvarDecl())
7032  continue;
7033  ObjCPropertyDecl *PD = Prop->getPropertyDecl();
7034  if (!PD)
7035  continue;
7036  if (ObjCMethodDecl *Getter = Prop->getGetterMethodDecl())
7037  if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
7038  InstanceMethods.push_back(Getter);
7039  if (PD->isReadOnly())
7040  continue;
7041  if (ObjCMethodDecl *Setter = Prop->getSetterMethodDecl())
7042  if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
7043  InstanceMethods.push_back(Setter);
7044  }
7045 
7046  Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7047  "_OBJC_$_INSTANCE_METHODS_",
7048  IDecl->getNameAsString(), true);
7049 
7050  SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
7051 
7052  Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7053  "_OBJC_$_CLASS_METHODS_",
7054  IDecl->getNameAsString(), true);
7055 
7056  // Protocols referenced in class declaration?
7057  // Protocol's super protocol list
7058  std::vector<ObjCProtocolDecl *> RefedProtocols;
7059  const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
7060  for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7061  E = Protocols.end();
7062  I != E; ++I) {
7063  RefedProtocols.push_back(*I);
7064  // Must write out all protocol definitions in current qualifier list,
7065  // and in their nested qualifiers before writing out current definition.
7066  RewriteObjCProtocolMetaData(*I, Result);
7067  }
7068 
7069  Write_protocol_list_initializer(Context, Result,
7070  RefedProtocols,
7071  "_OBJC_CLASS_PROTOCOLS_$_",
7072  IDecl->getNameAsString());
7073 
7074  // Protocol's property metadata.
7075  SmallVector<ObjCPropertyDecl *, 8> ClassProperties(
7076  CDecl->instance_properties());
7077  Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
7078  /* Container */IDecl,
7079  "_OBJC_$_PROP_LIST_",
7080  CDecl->getNameAsString());
7081 
7082  // Data for initializing _class_ro_t metaclass meta-data
7083  uint32_t flags = CLS_META;
7084  std::string InstanceSize;
7085  std::string InstanceStart;
7086 
7087  bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
7088  if (classIsHidden)
7089  flags |= OBJC2_CLS_HIDDEN;
7090 
7091  if (!CDecl->getSuperClass())
7092  // class is root
7093  flags |= CLS_ROOT;
7094  InstanceSize = "sizeof(struct _class_t)";
7095  InstanceStart = InstanceSize;
7096  Write__class_ro_t_initializer(Context, Result, flags,
7097  InstanceStart, InstanceSize,
7098  ClassMethods,
7099  nullptr,
7100  nullptr,
7101  nullptr,
7102  "_OBJC_METACLASS_RO_$_",
7103  CDecl->getNameAsString());
7104 
7105  // Data for initializing _class_ro_t meta-data
7106  flags = CLS;
7107  if (classIsHidden)
7108  flags |= OBJC2_CLS_HIDDEN;
7109 
7110  if (hasObjCExceptionAttribute(*Context, CDecl))
7111  flags |= CLS_EXCEPTION;
7112 
7113  if (!CDecl->getSuperClass())
7114  // class is root
7115  flags |= CLS_ROOT;
7116 
7117  InstanceSize.clear();
7118  InstanceStart.clear();
7119  if (!ObjCSynthesizedStructs.count(CDecl)) {
7120  InstanceSize = "0";
7121  InstanceStart = "0";
7122  }
7123  else {
7124  InstanceSize = "sizeof(struct ";
7125  InstanceSize += CDecl->getNameAsString();
7126  InstanceSize += "_IMPL)";
7127 
7128  ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7129  if (IVD) {
7130  RewriteIvarOffsetComputation(IVD, InstanceStart);
7131  }
7132  else
7133  InstanceStart = InstanceSize;
7134  }
7135  Write__class_ro_t_initializer(Context, Result, flags,
7136  InstanceStart, InstanceSize,
7137  InstanceMethods,
7138  RefedProtocols,
7139  IVars,
7140  ClassProperties,
7141  "_OBJC_CLASS_RO_$_",
7142  CDecl->getNameAsString());
7143 
7144  Write_class_t(Context, Result,
7145  "OBJC_METACLASS_$_",
7146  CDecl, /*metaclass*/true);
7147 
7148  Write_class_t(Context, Result,
7149  "OBJC_CLASS_$_",
7150  CDecl, /*metaclass*/false);
7151 
7152  if (ImplementationIsNonLazy(IDecl))
7153  DefinedNonLazyClasses.push_back(CDecl);
7154 }
7155 
7156 void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7157  int ClsDefCount = ClassImplementation.size();
7158  if (!ClsDefCount)
7159  return;
7160  Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7161  Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7162  Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7163  for (int i = 0; i < ClsDefCount; i++) {
7164  ObjCImplementationDecl *IDecl = ClassImplementation[i];
7165  ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7166  Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7167  Result += CDecl->getName(); Result += ",\n";
7168  }
7169  Result += "};\n";
7170 }
7171 
7172 void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7173  int ClsDefCount = ClassImplementation.size();
7174  int CatDefCount = CategoryImplementation.size();
7175 
7176  // For each implemented class, write out all its meta data.
7177  for (int i = 0; i < ClsDefCount; i++)
7178  RewriteObjCClassMetaData(ClassImplementation[i], Result);
7179 
7180  RewriteClassSetupInitHook(Result);
7181 
7182  // For each implemented category, write out all its meta data.
7183  for (int i = 0; i < CatDefCount; i++)
7184  RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7185 
7186  RewriteCategorySetupInitHook(Result);
7187 
7188  if (ClsDefCount > 0) {
7189  if (LangOpts.MicrosoftExt)
7190  Result += "__declspec(allocate(\".objc_classlist$B\")) ";
7191  Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7192  Result += llvm::utostr(ClsDefCount); Result += "]";
7193  Result +=
7194  " __attribute__((used, section (\"__DATA, __objc_classlist,"
7195  "regular,no_dead_strip\")))= {\n";
7196  for (int i = 0; i < ClsDefCount; i++) {
7197  Result += "\t&OBJC_CLASS_$_";
7198  Result += ClassImplementation[i]->getNameAsString();
7199  Result += ",\n";
7200  }
7201  Result += "};\n";
7202 
7203  if (!DefinedNonLazyClasses.empty()) {
7204  if (LangOpts.MicrosoftExt)
7205  Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7206  Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7207  for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7208  Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7209  Result += ",\n";
7210  }
7211  Result += "};\n";
7212  }
7213  }
7214 
7215  if (CatDefCount > 0) {
7216  if (LangOpts.MicrosoftExt)
7217  Result += "__declspec(allocate(\".objc_catlist$B\")) ";
7218  Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7219  Result += llvm::utostr(CatDefCount); Result += "]";
7220  Result +=
7221  " __attribute__((used, section (\"__DATA, __objc_catlist,"
7222  "regular,no_dead_strip\")))= {\n";
7223  for (int i = 0; i < CatDefCount; i++) {
7224  Result += "\t&_OBJC_$_CATEGORY_";
7225  Result +=
7226  CategoryImplementation[i]->getClassInterface()->getNameAsString();
7227  Result += "_$_";
7228  Result += CategoryImplementation[i]->getNameAsString();
7229  Result += ",\n";
7230  }
7231  Result += "};\n";
7232  }
7233 
7234  if (!DefinedNonLazyCategories.empty()) {
7235  if (LangOpts.MicrosoftExt)
7236  Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7237  Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7238  for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7239  Result += "\t&_OBJC_$_CATEGORY_";
7240  Result +=
7241  DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7242  Result += "_$_";
7243  Result += DefinedNonLazyCategories[i]->getNameAsString();
7244  Result += ",\n";
7245  }
7246  Result += "};\n";
7247  }
7248 }
7249 
7250 void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7251  if (LangOpts.MicrosoftExt)
7252  Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7253 
7254  Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7255  // version 0, ObjCABI is 2
7256  Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
7257 }
7258 
7259 /// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7260 /// implementation.
7261 void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7262  std::string &Result) {
7263  WriteModernMetadataDeclarations(Context, Result);
7264  ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7265  // Find category declaration for this implementation.
7266  ObjCCategoryDecl *CDecl
7267  = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
7268 
7269  std::string FullCategoryName = ClassDecl->getNameAsString();
7270  FullCategoryName += "_$_";
7271  FullCategoryName += CDecl->getNameAsString();
7272 
7273  // Build _objc_method_list for class's instance methods if needed
7274  SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
7275 
7276  // If any of our property implementations have associated getters or
7277  // setters, produce metadata for them as well.
7278  for (const auto *Prop : IDecl->property_impls()) {
7279  if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
7280  continue;
7281  if (!Prop->getPropertyIvarDecl())
7282  continue;
7283  ObjCPropertyDecl *PD = Prop->getPropertyDecl();
7284  if (!PD)
7285  continue;
7286  if (ObjCMethodDecl *Getter = Prop->getGetterMethodDecl())
7287  InstanceMethods.push_back(Getter);
7288  if (PD->isReadOnly())
7289  continue;
7290  if (ObjCMethodDecl *Setter = Prop->getSetterMethodDecl())
7291  InstanceMethods.push_back(Setter);
7292  }
7293 
7294  Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7295  "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7296  FullCategoryName, true);
7297 
7298  SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
7299 
7300  Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7301  "_OBJC_$_CATEGORY_CLASS_METHODS_",
7302  FullCategoryName, true);
7303 
7304  // Protocols referenced in class declaration?
7305  // Protocol's super protocol list
7306  SmallVector<ObjCProtocolDecl *, 8> RefedProtocols(CDecl->protocols());
7307  for (auto *I : CDecl->protocols())
7308  // Must write out all protocol definitions in current qualifier list,
7309  // and in their nested qualifiers before writing out current definition.
7310  RewriteObjCProtocolMetaData(I, Result);
7311 
7312  Write_protocol_list_initializer(Context, Result,
7313  RefedProtocols,
7314  "_OBJC_CATEGORY_PROTOCOLS_$_",
7315  FullCategoryName);
7316 
7317  // Protocol's property metadata.
7318  SmallVector<ObjCPropertyDecl *, 8> ClassProperties(
7319  CDecl->instance_properties());
7320  Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
7321  /* Container */IDecl,
7322  "_OBJC_$_PROP_LIST_",
7323  FullCategoryName);
7324 
7325  Write_category_t(*this, Context, Result,
7326  CDecl,
7327  ClassDecl,
7328  InstanceMethods,
7329  ClassMethods,
7330  RefedProtocols,
7331  ClassProperties);
7332 
7333  // Determine if this category is also "non-lazy".
7334  if (ImplementationIsNonLazy(IDecl))
7335  DefinedNonLazyCategories.push_back(CDecl);
7336 }
7337 
7338 void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7339  int CatDefCount = CategoryImplementation.size();
7340  if (!CatDefCount)
7341  return;
7342  Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7343  Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7344  Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7345  for (int i = 0; i < CatDefCount; i++) {
7346  ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7347  ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7348  ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7349  Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7350  Result += ClassDecl->getName();
7351  Result += "_$_";
7352  Result += CatDecl->getName();
7353  Result += ",\n";
7354  }
7355  Result += "};\n";
7356 }
7357 
7358 // RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7359 /// class methods.
7360 template<typename MethodIterator>
7361 void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7362  MethodIterator MethodEnd,
7363  bool IsInstanceMethod,
7364  StringRef prefix,
7365  StringRef ClassName,
7366  std::string &Result) {
7367  if (MethodBegin == MethodEnd) return;
7368 
7369  if (!objc_impl_method) {
7370  /* struct _objc_method {
7371  SEL _cmd;
7372  char *method_types;
7373  void *_imp;
7374  }
7375  */
7376  Result += "\nstruct _objc_method {\n";
7377  Result += "\tSEL _cmd;\n";
7378  Result += "\tchar *method_types;\n";
7379  Result += "\tvoid *_imp;\n";
7380  Result += "};\n";
7381 
7382  objc_impl_method = true;
7383  }
7384 
7385  // Build _objc_method_list for class's methods if needed
7386 
7387  /* struct {
7388  struct _objc_method_list *next_method;
7389  int method_count;
7390  struct _objc_method method_list[];
7391  }
7392  */
7393  unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
7394  Result += "\n";
7395  if (LangOpts.MicrosoftExt) {
7396  if (IsInstanceMethod)
7397  Result += "__declspec(allocate(\".inst_meth$B\")) ";
7398  else
7399  Result += "__declspec(allocate(\".cls_meth$B\")) ";
7400  }
7401  Result += "static struct {\n";
7402  Result += "\tstruct _objc_method_list *next_method;\n";
7403  Result += "\tint method_count;\n";
7404  Result += "\tstruct _objc_method method_list[";
7405  Result += utostr(NumMethods);
7406  Result += "];\n} _OBJC_";
7407  Result += prefix;
7408  Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7409  Result += "_METHODS_";
7410  Result += ClassName;
7411  Result += " __attribute__ ((used, section (\"__OBJC, __";
7412  Result += IsInstanceMethod ? "inst" : "cls";
7413  Result += "_meth\")))= ";
7414  Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7415 
7416  Result += "\t,{{(SEL)\"";
7417  Result += (*MethodBegin)->getSelector().getAsString().c_str();
7418  std::string MethodTypeString;
7419  Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7420  Result += "\", \"";
7421  Result += MethodTypeString;
7422  Result += "\", (void *)";
7423  Result += MethodInternalNames[*MethodBegin];
7424  Result += "}\n";
7425  for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7426  Result += "\t ,{(SEL)\"";
7427  Result += (*MethodBegin)->getSelector().getAsString().c_str();
7428  std::string MethodTypeString;
7429  Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7430  Result += "\", \"";
7431  Result += MethodTypeString;
7432  Result += "\", (void *)";
7433  Result += MethodInternalNames[*MethodBegin];
7434  Result += "}\n";
7435  }
7436  Result += "\t }\n};\n";
7437 }
7438 
7439 Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7440  SourceRange OldRange = IV->getSourceRange();
7441  Expr *BaseExpr = IV->getBase();
7442 
7443  // Rewrite the base, but without actually doing replaces.
7444  {
7445  DisableReplaceStmtScope S(*this);
7446  BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7447  IV->setBase(BaseExpr);
7448  }
7449 
7450  ObjCIvarDecl *D = IV->getDecl();
7451 
7452  Expr *Replacement = IV;
7453 
7454  if (BaseExpr->getType()->isObjCObjectPointerType()) {
7455  const ObjCInterfaceType *iFaceDecl =
7456  dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
7457  assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7458  // lookup which class implements the instance variable.
7459  ObjCInterfaceDecl *clsDeclared = nullptr;
7460  iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7461  clsDeclared);
7462  assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7463 
7464  // Build name of symbol holding ivar offset.
7465  std::string IvarOffsetName;
7466  if (D->isBitField())
7467  ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
7468  else
7469  WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
7470 
7471  ReferencedIvars[clsDeclared].insert(D);
7472 
7473  // cast offset to "char *".
7474  CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7475  Context->getPointerType(Context->CharTy),
7476  CK_BitCast,
7477  BaseExpr);
7478  VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7479  SourceLocation(), &Context->Idents.get(IvarOffsetName),
7480  Context->UnsignedLongTy, nullptr,
7481  SC_Extern);
7482  DeclRefExpr *DRE = new (Context)
7483  DeclRefExpr(*Context, NewVD, false, Context->UnsignedLongTy,
7485  BinaryOperator *addExpr = BinaryOperator::Create(
7486  *Context, castExpr, DRE, BO_Add,
7487  Context->getPointerType(Context->CharTy), VK_PRValue, OK_Ordinary,
7489  // Don't forget the parens to enforce the proper binding.
7490  ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7491  SourceLocation(),
7492  addExpr);
7493  QualType IvarT = D->getType();
7494  if (D->isBitField())
7495  IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
7496 
7497  if (!IvarT->getAs<TypedefType>() && IvarT->isRecordType()) {
7498  RecordDecl *RD = IvarT->castAs<RecordType>()->getDecl();
7499  RD = RD->getDefinition();
7500  if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
7501  // decltype(((Foo_IMPL*)0)->bar) *
7502  auto *CDecl = cast<ObjCContainerDecl>(D->getDeclContext());
7503  // ivar in class extensions requires special treatment.
7504  if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7505  CDecl = CatDecl->getClassInterface();
7506  std::string RecName = std::string(CDecl->getName());
7507  RecName += "_IMPL";
7508  RecordDecl *RD = RecordDecl::Create(
7509  *Context, TagTypeKind::Struct, TUDecl, SourceLocation(),
7510  SourceLocation(), &Context->Idents.get(RecName));
7511  QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7512  unsigned UnsignedIntSize =
7513  static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7514  Expr *Zero = IntegerLiteral::Create(*Context,
7515  llvm::APInt(UnsignedIntSize, 0),
7516  Context->UnsignedIntTy, SourceLocation());
7517  Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7518  ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7519  Zero);
7520  FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
7521  SourceLocation(),
7522  &Context->Idents.get(D->getNameAsString()),
7523  IvarT, nullptr,
7524  /*BitWidth=*/nullptr,
7525  /*Mutable=*/true, ICIS_NoInit);
7526  MemberExpr *ME = MemberExpr::CreateImplicit(
7527  *Context, PE, true, FD, FD->getType(), VK_LValue, OK_Ordinary);
7528  IvarT = Context->getDecltypeType(ME, ME->getType());
7529  }
7530  }
7531  convertObjCTypeToCStyleType(IvarT);
7532  QualType castT = Context->getPointerType(IvarT);
7533 
7534  castExpr = NoTypeInfoCStyleCastExpr(Context,
7535  castT,
7536  CK_BitCast,
7537  PE);
7538 
7539  Expr *Exp = UnaryOperator::Create(
7540  const_cast<ASTContext &>(*Context), castExpr, UO_Deref, IvarT,
7542  PE = new (Context) ParenExpr(OldRange.getBegin(),
7543  OldRange.getEnd(),
7544  Exp);
7545 
7546  if (D->isBitField()) {
7547  FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
7548  SourceLocation(),
7549  &Context->Idents.get(D->getNameAsString()),
7550  D->getType(), nullptr,
7551  /*BitWidth=*/D->getBitWidth(),
7552  /*Mutable=*/true, ICIS_NoInit);
7553  MemberExpr *ME =
7554  MemberExpr::CreateImplicit(*Context, PE, /*isArrow*/ false, FD,
7555  FD->getType(), VK_LValue, OK_Ordinary);
7556  Replacement = ME;
7557 
7558  }
7559  else
7560  Replacement = PE;
7561  }
7562 
7563  ReplaceStmtWithRange(IV, Replacement, OldRange);
7564  return Replacement;
7565 }
7566 
7567 #endif // CLANG_ENABLE_OBJC_REWRITER
MatchType Type
static char ID
Definition: Arena.cpp:183
#define SM(sm)
Definition: Cuda.cpp:83
Defines the Diagnostic-related interfaces.
const Decl * D
enum clang::sema::@1659::IndirectLocalPathEntry::EntryKind Kind
Expr * E
StringRef Filename
Definition: Format.cpp:3001
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
#define X(type, name)
Definition: Value.h:143
llvm::raw_ostream & OS
Definition: Logger.cpp:24
llvm::MachO::Record Record
Definition: MachO.h:31
static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj, ASTContext *Context, std::string &Result, ArrayRef< ObjCMethodDecl * > Methods, StringRef VarName, StringRef ProtocolName)
static void Write_protocol_list_t_TypeDecl(std::string &Result, long super_protocol_count)
static void Write_ProtocolExprReferencedMetadata(ASTContext *Context, ObjCProtocolDecl *PDecl, std::string &Result)
Write_ProtocolExprReferencedMetadata - This routine writer out the protocol reference symbols in the ...
static void BuildUniqueMethodName(std::string &Name, ObjCMethodDecl *MD)
static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj, ASTContext *Context, std::string &Result, ArrayRef< ObjCMethodDecl * > Methods, StringRef VarName, StringRef TopLevelDeclName, bool MethodImpl)
static void scanToNextArgument(const char *&argRef)
@ CLS_COMPILED_BY_ARC
class was compiled with -fobjc-arr
@ OBJC2_CLS_HIDDEN
@ CLS_HAS_IVAR_RELEASER
(Obsolete) ARC-specific: this class has a .release_ivars method
@ CLS_EXCEPTION
static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj, ASTContext *Context, std::string &Result, ArrayRef< ObjCPropertyDecl * > Properties, const Decl *Container, StringRef VarName, StringRef ProtocolName)
static bool scanForProtocolRefs(const char *startBuf, const char *endBuf, const char *&startRef, const char *&endRef)
static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context, std::string &Result, ObjCCategoryDecl *CatDecl, ObjCInterfaceDecl *ClassDecl, ArrayRef< ObjCMethodDecl * > InstanceMethods, ArrayRef< ObjCMethodDecl * > ClassMethods, ArrayRef< ObjCProtocolDecl * > RefedProtocols, ArrayRef< ObjCPropertyDecl * > ClassProperties)
static void Write__prop_list_t_TypeDecl(std::string &Result, unsigned int property_count)
static void Write_RethrowObject(std::string &buf)
static bool IsHeaderFile(const std::string &Filename)
static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP, ObjCPropertyDecl *PD, bool getter)
mustSynthesizeSetterGetterMethod - returns true if setter or getter has not been found in the class i...
static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result)
WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
static void Write_class_t(ASTContext *Context, std::string &Result, StringRef VarName, const ObjCInterfaceDecl *CDecl, bool metaclass)
static SourceLocation getFunctionSourceLocation(RewriteModernObjC &R, FunctionDecl *FD)
getFunctionSourceLocation - returns start location of a function definition.
static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result, unsigned int flags, const std::string &InstanceStart, const std::string &InstanceSize, ArrayRef< ObjCMethodDecl * >baseMethods, ArrayRef< ObjCProtocolDecl * >baseProtocols, ArrayRef< ObjCIvarDecl * >ivars, ArrayRef< ObjCPropertyDecl * >Properties, StringRef VarName, StringRef ClassName)
static bool HasLocalVariableExternalStorage(ValueDecl *VD)
static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl, std::string &typedefString)
static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj, ASTContext *Context, std::string &Result, ArrayRef< ObjCIvarDecl * > OriginalIvars, StringRef VarName, ObjCInterfaceDecl *CDecl)
static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj, ASTContext *Context, std::string &Result, ArrayRef< ObjCIvarDecl * > Ivars, ObjCInterfaceDecl *CDecl)
static void Write__ivar_list_t_TypeDecl(std::string &Result, unsigned int ivar_count)
static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl, ObjCIvarDecl *IvarDecl, std::string &Result)
static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result, ArrayRef< ObjCProtocolDecl * > SuperProtocols, StringRef VarName, StringRef ProtocolName)
static bool hasObjCExceptionAttribute(ASTContext &Context, const ObjCInterfaceDecl *OID)
hasObjCExceptionAttribute - Return true if this class or any super class has the objc_exception attri...
static void Write_method_list_t_TypeDecl(std::string &Result, unsigned int method_count)
#define SKIP_BITFIELDS(IX, ENDIX, VEC)
static std::string getIvarAccessString(ObjCIvarDecl *OID)
SourceLocation Loc
Definition: SemaObjC.cpp:759
Defines the SourceManager interface.
__device__ __2f16 float c
ASTConsumer - This is an abstract interface that should be implemented by clients that read ASTs.
Definition: ASTConsumer.h:34
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:187
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:713
SourceManager & getSourceManager()
Definition: ASTContext.h:721
CanQualType LongTy
Definition: ASTContext.h:1128
QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl, ObjCInterfaceDecl *PrevDecl=nullptr) const
getObjCInterfaceType - Return the unique reference to the type for the specified ObjC interface decl.
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl.
QualType getObjCClassType() const
Represents the Objective-C Class type.
Definition: ASTContext.h:2144
void getObjCEncodingForType(QualType T, std::string &S, const FieldDecl *Field=nullptr, QualType *NotEncodedT=nullptr) const
Emit the Objective-CC type encoding for the given type T into S.
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2633
FullSourceLoc getFullLoc(SourceLocation Loc) const
Definition: ASTContext.h:817
CanQualType DoubleTy
Definition: ASTContext.h:1131
std::string getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, bool Extended=false) const
Emit the encoded type for the method declaration Decl into S.
std::string getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, const Decl *Container) const
getObjCEncodingForPropertyDecl - Return the encoded type for this method declaration.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType VoidPtrTy
Definition: ASTContext.h:1146
bool BlockRequiresCopying(QualType Ty, const VarDecl *D)
Returns true iff we need copy/dispose helpers for the given type.
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1642
IdentifierTable & Idents
Definition: ASTContext.h:660
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
SelectorTable & Selectors
Definition: ASTContext.h:661
QualType getObjCInstanceType()
Retrieve the Objective-C "instancetype" type, if already known; otherwise, returns a NULL type;.
Definition: ASTContext.h:2003
const LangOptions & getLangOpts() const
Definition: ASTContext.h:797
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
QualType getObjCSelType() const
Retrieve the type that corresponds to the predefined Objective-C 'SEL' type.
Definition: ASTContext.h:2132
CanQualType UnsignedLongTy
Definition: ASTContext.h:1129
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
CanQualType CharTy
Definition: ASTContext.h:1121
CanQualType IntTy
Definition: ASTContext.h:1128
CanQualType ObjCBuiltinBoolTy
Definition: ASTContext.h:1152
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:2122
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2399
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType VoidTy
Definition: ASTContext.h:1119
CanQualType UnsignedIntTy
Definition: ASTContext.h:1129
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1620
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:779
QualType getDecltypeType(Expr *e, QualType UnderlyingType) const
C++11 decltype.
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1101
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
Definition: ASTContext.h:2430
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2403
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3576
QualType getElementType() const
Definition: Type.h:3588
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3912
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4472
param_iterator param_end()
Definition: Decl.h:4571
MutableArrayRef< ParmVarDecl * >::iterator param_iterator
Definition: Decl.h:4566
ArrayRef< Capture > captures() const
Definition: Decl.h:4599
param_iterator param_begin()
Definition: Decl.h:4570
bool param_empty() const
Definition: Decl.h:4569
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6396
const Stmt * getBody() const
Definition: Expr.cpp:2574
const BlockDecl * getBlockDecl() const
Definition: Expr.h:6408
const FunctionProtoType * getFunctionType() const
getFunctionType - Return the underlying function type for this block.
Definition: Expr.cpp:2565
Pointer to a block type.
Definition: Type.h:3407
QualType getPointeeType() const
Definition: Type.h:3419
BreakStmt - This represents a break.
Definition: Stmt.h:2985
CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style cast in C++ (C++ [expr....
Definition: Expr.h:3843
SourceLocation getRParenLoc() const
Definition: Expr.h:3878
static CStyleCastExpr * Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind K, Expr *Op, const CXXCastPath *BasePath, FPOptionsOverride FPO, TypeSourceInfo *WrittenTy, SourceLocation L, SourceLocation R)
Definition: Expr.cpp:2160
SourceLocation getLParenLoc() const
Definition: Expr.h:3875
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1546
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2539
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition: DeclCXX.cpp:2791
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2882
arg_iterator arg_begin()
Definition: Expr.h:3126
arg_iterator arg_end()
Definition: Expr.h:3129
QualType withConst() const
Retrieves a version of this type with const applied.
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:3550
CastKind getCastKind() const
Definition: Expr.h:3594
Expr * getSubExpr()
Definition: Expr.h:3600
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
CompoundLiteralExpr - [C99 6.5.2.5].
Definition: Expr.h:3480
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1606
SourceLocation getBeginLoc() const
Definition: Stmt.h:1740
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4255
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3614
ContinueStmt - This represents a continue.
Definition: Stmt.h:2955
decl_iterator - Iterates through the declarations stored within this context.
Definition: DeclBase.h:2307
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
bool isFileContext() const
Definition: DeclBase.h:2161
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1988
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1766
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
ValueDecl * getDecl()
Definition: Expr.h:1333
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition: Expr.h:1463
SourceLocation getLocation() const
Definition: Expr.h:1341
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition: Stmt.h:1497
decl_iterator decl_end()
Definition: Stmt.h:1552
decl_iterator decl_begin()
Definition: Stmt.h:1551
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:442
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:600
bool isFunctionPointerType() const
Definition: DeclBase.cpp:1204
SourceLocation getLocation() const
Definition: DeclBase.h:446
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:438
bool hasAttr() const
Definition: DeclBase.h:584
Kind getKind() const
Definition: DeclBase.h:449
DeclContext * getDeclContext()
Definition: DeclBase.h:455
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
SourceLocation getTypeSpecStartLoc() const
Definition: Decl.cpp:1974
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:193
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1553
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition: Diagnostic.h:879
bool hasErrorOccurred() const
Definition: Diagnostic.h:849
Represents an enum.
Definition: Decl.h:3845
enumerator_range enumerators() const
Definition: Decl.h:3978
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:6001
This represents one expression.
Definition: Expr.h:110
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:437
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3122
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3110
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
QualType getType() const
Definition: Expr.h:142
Represents difference between two FPOptions values.
Definition: LangOptions.h:958
Represents a member of a struct/union/class.
Definition: Decl.h:3031
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3122
Expr * getBitWidth() const
Returns the expression that represents the bit width, if this field is a bit field.
Definition: Decl.h:3135
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Represents a function declaration or definition.
Definition: Decl.h:1933
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition: Decl.cpp:3228
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition: Decl.h:2247
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3081
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:2761
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition: Decl.cpp:3482
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition: Decl.cpp:3298
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition: Decl.h:2806
void setBody(Stmt *B)
Definition: Decl.cpp:3240
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5012
ArrayRef< QualType > param_types() const
Definition: Type.h:5421
unsigned getNumParams() const
Definition: Type.h:5265
QualType getParamType(unsigned i) const
Definition: Type.h:5267
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5389
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4318
QualType getReturnType() const
Definition: Type.h:4640
One of these records is kept for each identifier that is lexed.
StringRef getName() const
Return the actual identifier string.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3727
Describes an C or C++ initializer list.
Definition: Expr.h:5070
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:480
Represents a linkage specification.
Definition: DeclCXX.h:2938
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3239
This represents a decl that may have a name.
Definition: Decl.h:249
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:276
Visibility getVisibility() const
Determines the visibility of this entity.
Definition: Decl.h:420
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
std::string getNameAsString() const
Get a human-readable name for the declaration, even if it is one of the special kinds of names (C++ c...
Definition: Decl.h:292
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
ObjCArrayLiteral - used for objective-c array containers; as in: @["Hello", NSApp,...
Definition: ExprObjC.h:191
ObjCMethodDecl * getArrayWithObjectsMethod() const
Definition: ExprObjC.h:240
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: ExprObjC.h:215
unsigned getNumElements() const
getNumElements - Return number of elements of objective-c array literal.
Definition: ExprObjC.h:228
SourceLocation getEndLoc() const LLVM_READONLY
Definition: ExprObjC.h:216
Expr * getElement(unsigned Index)
getElement - Return the Element at the specified index.
Definition: ExprObjC.h:231
Represents Objective-C's @catch statement.
Definition: StmtObjC.h:77
Represents Objective-C's @finally statement.
Definition: StmtObjC.h:127
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: StmtObjC.h:143
const Stmt * getFinallyBody() const
Definition: StmtObjC.h:139
Represents Objective-C's @synchronized statement.
Definition: StmtObjC.h:303
Represents Objective-C's @throw statement.
Definition: StmtObjC.h:358
Represents Objective-C's @try ... @catch ... @finally statement.
Definition: StmtObjC.h:167
Represents Objective-C's @autoreleasepool Statement.
Definition: StmtObjC.h:394
ObjCBoolLiteralExpr - Objective-C Boolean Literal.
Definition: ExprObjC.h:87
SourceLocation getLocation() const
Definition: ExprObjC.h:106
ObjCBoxedExpr - used for generalized expression boxing.
Definition: ExprObjC.h:127
ObjCMethodDecl * getBoxingMethod() const
Definition: ExprObjC.h:146
Expr * getSubExpr()
Definition: ExprObjC.h:143
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: ExprObjC.h:158
SourceLocation getEndLoc() const LLVM_READONLY
Definition: ExprObjC.h:159
ObjCCategoryDecl - Represents a category declaration.
Definition: DeclObjC.h:2328
SourceLocation getIvarRBraceLoc() const
Definition: DeclObjC.h:2465
protocol_range protocols() const
Definition: DeclObjC.h:2402
ObjCInterfaceDecl * getClassInterface()
Definition: DeclObjC.h:2371
ObjCCategoryImplDecl - An object of this class encapsulates a category @implementation declaration.
Definition: DeclObjC.h:2544
ObjCCategoryDecl * getCategoryDecl() const
Definition: DeclObjC.cpp:2199
ObjCContainerDecl - Represents a container for method declarations.
Definition: DeclObjC.h:947
SourceRange getAtEndRange() const
Definition: DeclObjC.h:1102
instmeth_range instance_methods() const
Definition: DeclObjC.h:1032
ObjCMethodDecl * getClassMethod(Selector Sel, bool AllowHidden=false) const
Definition: DeclObjC.h:1070
instprop_range instance_properties() const
Definition: DeclObjC.h:981
ObjCMethodDecl * getInstanceMethod(Selector Sel, bool AllowHidden=false) const
Definition: DeclObjC.h:1065
classmeth_range class_methods() const
Definition: DeclObjC.h:1049
ObjCDictionaryLiteral - AST node to represent objective-c dictionary literals; as in:"name" : NSUserN...
Definition: ExprObjC.h:309
ObjCMethodDecl * getDictWithObjectsMethod() const
Definition: ExprObjC.h:377
unsigned getNumElements() const
getNumElements - Return number of elements of objective-c dictionary literal.
Definition: ExprObjC.h:360
ObjCDictionaryElement getKeyValueElement(unsigned Index) const
Definition: ExprObjC.h:362
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: ExprObjC.h:381
SourceLocation getEndLoc() const LLVM_READONLY
Definition: ExprObjC.h:382
ObjCEncodeExpr, used for @encode in Objective-C.
Definition: ExprObjC.h:410
QualType getEncodedType() const
Definition: ExprObjC.h:429
Represents Objective-C's collection statement.
Definition: StmtObjC.h:23
propimpl_range property_impls() const
Definition: DeclObjC.h:2512
const ObjCInterfaceDecl * getClassInterface() const
Definition: DeclObjC.h:2485
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2596
SourceLocation getIvarRBraceLoc() const
Definition: DeclObjC.h:2743
std::string getNameAsString() const
Get the name of the class associated with this interface.
Definition: DeclObjC.h:2728
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
ObjCIvarDecl * lookupInstanceVariable(IdentifierInfo *IVarName, ObjCInterfaceDecl *&ClassDeclared)
Definition: DeclObjC.cpp:637
bool isImplicitInterfaceDecl() const
isImplicitInterfaceDecl - check that this is an implicitly declared ObjCInterfaceDecl node.
Definition: DeclObjC.h:1892
ObjCIvarDecl * all_declared_ivar_begin()
all_declared_ivar_begin - return first ivar declared in this class, its extensions and its implementa...
Definition: DeclObjC.cpp:1672
ObjCCategoryDecl * FindCategoryDeclaration(const IdentifierInfo *CategoryId) const
FindCategoryDeclaration - Finds category declaration in the list of categories for this class and ret...
Definition: DeclObjC.cpp:1748
bool isThisDeclarationADefinition() const
Determine whether this particular declaration of this class is actually also a definition.
Definition: DeclObjC.h:1522
ObjCImplementationDecl * getImplementation() const
Definition: DeclObjC.cpp:1629
SourceLocation getEndOfDefinitionLoc() const
Definition: DeclObjC.h:1877
ObjCInterfaceDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this Objective-C class.
Definition: DeclObjC.h:1914
ObjCInterfaceDecl * getSuperClass() const
Definition: DeclObjC.cpp:352
const ObjCProtocolList & getReferencedProtocols() const
Definition: DeclObjC.h:1332
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:7353
ObjCInterfaceDecl * getDecl() const
Get the declaration of this interface.
Definition: Type.cpp:903
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1951
AccessControl getAccessControl() const
Definition: DeclObjC.h:1999
ObjCInterfaceDecl * getContainingInterface()
Return the class interface that this ivar is logically contained in; this is either the interface whe...
Definition: DeclObjC.cpp:1875
ObjCIvarDecl * getNextIvar()
Definition: DeclObjC.h:1986
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition: ExprObjC.h:549
void setBase(Expr *base)
Definition: ExprObjC.h:585
const Expr * getBase() const
Definition: ExprObjC.h:583
ObjCIvarDecl * getDecl()
Definition: ExprObjC.h:579
iterator end() const
Definition: DeclObjC.h:91
iterator begin() const
Definition: DeclObjC.h:90
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:945
void getSelectorLocs(SmallVectorImpl< SourceLocation > &SelLocs) const
Definition: ExprObjC.cpp:258
bool isImplicit() const
Indicates whether the message send was implicitly generated by the implementation.
Definition: ExprObjC.h:1230
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: ExprObjC.h:1451
SourceLocation getLeftLoc() const
Definition: ExprObjC.h:1416
SourceLocation getSuperLoc() const
Retrieve the location of the 'super' keyword for a class or instance message to 'super',...
Definition: ExprObjC.h:1301
Selector getSelector() const
Definition: ExprObjC.cpp:293
Expr * getInstanceReceiver()
Returns the object expression (receiver) for an instance message, or null for a message that is not a...
Definition: ExprObjC.h:1260
QualType getClassReceiver() const
Returns the type of a class message send, or NULL if the message is not a class message.
Definition: ExprObjC.h:1279
QualType getSuperType() const
Retrieve the type referred to by 'super'.
Definition: ExprObjC.h:1336
const ObjCMethodDecl * getMethodDecl() const
Definition: ExprObjC.h:1356
ReceiverKind getReceiverKind() const
Determine the kind of receiver that this message is being sent to.
Definition: ExprObjC.h:1234
TypeSourceInfo * getClassReceiverTypeInfo() const
Returns a type-source information of a class message send, or nullptr if the message is not a class m...
Definition: ExprObjC.h:1288
SourceLocation getEndLoc() const LLVM_READONLY
Definition: ExprObjC.h:1452
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: ExprObjC.h:1395
SourceLocation getRightLoc() const
Definition: ExprObjC.h:1417
unsigned getNumArgs() const
Return the number of actual arguments in this message, not counting the receiver.
Definition: ExprObjC.h:1382
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
CompoundStmt * getCompoundBody()
Definition: DeclObjC.h:530
bool isVariadic() const
Definition: DeclObjC.h:431
void setBody(Stmt *B)
Definition: DeclObjC.h:531
Stmt * getBody() const override
Retrieve the body of this method, if it has one.
Definition: DeclObjC.cpp:909
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclObjC.cpp:1047
bool isSynthesizedAccessorStub() const
Definition: DeclObjC.h:444
ImplicitParamDecl * getSelfDecl() const
Definition: DeclObjC.h:418
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclObjC.h:282
Selector getSelector() const
Definition: DeclObjC.h:327
bool isInstanceMethod() const
Definition: DeclObjC.h:426
QualType getReturnType() const
Definition: DeclObjC.h:329
ObjCImplementationControl getImplementationControl() const
Definition: DeclObjC.h:500
ObjCInterfaceDecl * getClassInterface()
Definition: DeclObjC.cpp:1211
ArrayRef< ParmVarDecl * > parameters() const
Definition: DeclObjC.h:373
Represents a pointer to an Objective C object.
Definition: Type.h:7409
Represents a class type in Objective C.
Definition: Type.h:7155
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:730
SourceLocation getAtLoc() const
Definition: DeclObjC.h:795
bool isReadOnly() const
isReadOnly - Return true iff the property has a setter.
Definition: DeclObjC.h:837
Selector getSetterName() const
Definition: DeclObjC.h:892
Selector getGetterName() const
Definition: DeclObjC.h:884
ObjCPropertyAttribute::Kind getPropertyAttributes() const
Definition: DeclObjC.h:814
ObjCPropertyImplDecl - Represents implementation declaration of a property in a class or category imp...
Definition: DeclObjC.h:2804
ObjCIvarDecl * getPropertyIvarDecl() const
Definition: DeclObjC.h:2878
ObjCPropertyDecl * getPropertyDecl() const
Definition: DeclObjC.h:2869
Kind getPropertyImplementation() const
Definition: DeclObjC.h:2874
ObjCMethodDecl * getSetterMethodDecl() const
Definition: DeclObjC.h:2903
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclObjC.h:2866
ObjCMethodDecl * getGetterMethodDecl() const
Definition: DeclObjC.h:2900
Represents an Objective-C protocol declaration.
Definition: DeclObjC.h:2083
bool isThisDeclarationADefinition() const
Determine whether this particular declaration is also the definition.
Definition: DeclObjC.h:2260
protocol_range protocols() const
Definition: DeclObjC.h:2160
ObjCProtocolDecl * getDefinition()
Retrieve the definition of this protocol, if any.
Definition: DeclObjC.h:2249
ObjCProtocolDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this Objective-C protocol.
Definition: DeclObjC.h:2296
ObjCProtocolExpr used for protocol expression in Objective-C.
Definition: ExprObjC.h:505
ObjCProtocolDecl * getProtocol() const
Definition: ExprObjC.h:522
ObjCSelectorExpr used for @selector in Objective-C.
Definition: ExprObjC.h:455
Selector getSelector() const
Definition: ExprObjC.h:469
ObjCStringLiteral, used for Objective-C string literals i.e.
Definition: ExprObjC.h:51
StringLiteral * getString()
Definition: ExprObjC.h:64
ParenExpr - This represents a parenthesized expression, e.g.
Definition: Expr.h:2187
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3197
QualType getPointeeType() const
Definition: Type.h:3207
Represents an unpacked "presumed" location which can be presented to the user.
const char * getFilename() const
Return the presumed filename of this location.
unsigned getLine() const
Return the presumed line number of this location.
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:6528
Expr * getSyntacticForm()
Return the syntactic form of this expression, i.e.
Definition: Expr.h:6570
Expr * getSemanticExpr(unsigned index)
Definition: Expr.h:6614
unsigned getNumSemanticExprs() const
Definition: Expr.h:6590
Expr * getResultExpr()
Return the result-bearing expression, or null if there is none.
Definition: Expr.h:6581
A (possibly-)qualified type.
Definition: Type.h:941
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:7844
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition: Type.h:7838
QualType IgnoreParens() const
Returns the specified type after dropping any outer-level parentheses.
Definition: Type.h:1322
QualType withConst() const
Definition: Type.h:1166
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1008
void getAsStringInternal(std::string &Str, const PrintingPolicy &Policy) const
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7833
bool isObjCGCWeak() const
true when Type is objc's weak.
Definition: Type.h:1434
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:7806
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1339
Represents a struct/union/class.
Definition: Decl.h:4146
field_range fields() const
Definition: Decl.h:4352
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4337
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition: Decl.cpp:5084
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5975
Rewriter - This is the main interface to the rewrite buffers.
Definition: Rewriter.h:32
Selector getSelector(unsigned NumArgs, const IdentifierInfo **IIV)
Can create any sort of selector.
Smart pointer class that efficiently represents Objective-C method names.
std::string getAsString() const
Derive the full selector name (e.g.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
This class handles loading and caching of source files into memory.
bool isBeforeInTranslationUnit(SourceLocation LHS, SourceLocation RHS) const
Determines the order of 2 source locations in the translation unit.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:350
void printPretty(raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation=0, StringRef NewlineSymbol="\n", const ASTContext *Context=nullptr) const
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1778
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind, bool Pascal, QualType Ty, const SourceLocation *Loc, unsigned NumConcatenated)
This is the "fully general" constructor that allows representation of strings formed from multiple co...
Definition: Expr.cpp:1246
unsigned getByteLength() const
Definition: Expr.h:1894
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3562
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3665
bool isStruct() const
Definition: Decl.h:3765
bool isUnion() const
Definition: Decl.h:3768
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1256
The top declaration context.
Definition: Decl.h:84
Represents a declaration of a type.
Definition: Decl.h:3368
Represents a typeof (or typeof) expression (a C23 feature and GCC extension) or a typeof_unqual expre...
Definition: Type.h:5707
Expr * getUnderlyingExpr() const
Definition: Type.h:5718
A container of type source information.
Definition: Type.h:7731
The base class of the type hierarchy.
Definition: Type.h:1829
bool isBlockPointerType() const
Definition: Type.h:8027
bool isArrayType() const
Definition: Type.h:8085
bool isFunctionPointerType() const
Definition: Type.h:8053
bool isPointerType() const
Definition: Type.h:8013
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8635
bool isEnumeralType() const
Definition: Type.h:8117
const ObjCObjectPointerType * getAsObjCInterfacePointerType() const
Definition: Type.cpp:1859
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2058
bool isObjCQualifiedIdType() const
Definition: Type.h:8176
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:705
bool isObjCQualifiedInterfaceType() const
Definition: Type.cpp:1827
bool isObjCObjectPointerType() const
Definition: Type.h:8155
bool isObjCQualifiedClassType() const
Definition: Type.h:8182
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2266
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8568
bool isRecordType() const
Definition: Type.h:8113
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3410
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2240
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:668
QualType getType() const
Definition: Decl.h:679
Represents a variable declaration or definition.
Definition: Decl.h:880
const Expr * getInit() const
Definition: Decl.h:1317
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1117
Defines the clang::TargetInfo interface.
@ BLOCK_HAS_CXX_OBJ
Definition: CGBlocks.h:51
@ BLOCK_HAS_COPY_DISPOSE
Definition: CGBlocks.h:50
@ BLOCK_FIELD_IS_BYREF
Definition: CGBlocks.h:92
@ BLOCK_FIELD_IS_WEAK
Definition: CGBlocks.h:94
@ BLOCK_BYREF_CALLER
Definition: CGBlocks.h:97
@ BLOCK_FIELD_IS_BLOCK
Definition: CGBlocks.h:90
@ BLOCK_BYREF_CURRENT_MAX
Definition: CGBlocks.h:99
@ BLOCK_FIELD_IS_OBJECT
Definition: CGBlocks.h:88
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const internal::VariadicDynCastAllOfMatcher< Decl, FieldDecl > fieldDecl
Matches field declarations.
const internal::VariadicDynCastAllOfMatcher< Stmt, CastExpr > castExpr
Matches any cast nodes of Clang's AST.
@ CF
Indicates that the tracked object is a CF object.
llvm::APInt APInt
Definition: Integral.h:29
bool Zero(InterpState &S, CodePtr OpPC)
Definition: Interp.h:2242
std::string toString(const til::SExpr *E)
RangeSelector name(std::string ID)
Given a node with a "name", (like NamedDecl, DeclRefExpr, CxxCtorInitializer, and TypeLoc) selects th...
The JSON file list parser is used to communicate input to InstallAPI.
bool isa(CodeGen::Address addr)
Definition: Address.h:328
@ Rewrite
We are substituting template parameters for (typically) other template parameters in order to rewrite...
@ ICIS_NoInit
No in-class initializer.
Definition: Specifiers.h:272
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition: Specifiers.h:151
@ SC_Extern
Definition: Specifiers.h:251
@ SC_Static
Definition: Specifiers.h:252
@ SC_None
Definition: Specifiers.h:250
LLVM_READONLY bool isAlphanumeric(unsigned char c)
Return true if this character is an ASCII letter or digit: [a-zA-Z0-9].
Definition: CharInfo.h:138
std::unique_ptr< ASTConsumer > CreateModernObjCRewriter(const std::string &InFile, std::unique_ptr< raw_ostream > OS, DiagnosticsEngine &Diags, const LangOptions &LOpts, bool SilenceRewriteMacroWarning, bool LineInfo)
CastKind
CastKind - The kind of operation required for a conversion.
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:135
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:139
const FunctionProtoType * T
U cast(CodeGen::Address addr)
Definition: Address.h:325
@ Class
The "class" keyword introduces the elaborated-type-specifier.
@ HiddenVisibility
Objects with "hidden" visibility are not seen by the dynamic linker.
Definition: Visibility.h:37
unsigned int uint32_t
int printf(__constant const char *st,...) __attribute__((format(printf
float __ovld __cnfn distance(float, float)
Returns the distance between p0 and p1.
Extra information about a function prototype.
Definition: Type.h:5097
An element in an Objective-C dictionary literal.
Definition: ExprObjC.h:262
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57
Iterator for iterating over Stmt * arrays that contain only T *.
Definition: Stmt.h:1316