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