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