Coverage Report

Created: 2022-07-16 07:03

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp
Line
Count
Source (jump to first uncovered line)
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:
177
      DisableReplaceStmtScope(RewriteModernObjC &R)
178
130
        : R(R), SavedValue(R.DisableReplaceStmt) {
179
130
        R.DisableReplaceStmt = true;
180
130
      }
181
130
      ~DisableReplaceStmtScope() {
182
130
        R.DisableReplaceStmt = SavedValue;
183
130
      }
184
    };
185
    void InitializeCommon(ASTContext &context);
186
187
  public:
188
    llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
189
190
    // Top Level Driver code.
191
584
    bool HandleTopLevelDecl(DeclGroupRef D) override {
192
998
      for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; 
++I414
) {
193
667
        if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
194
157
          if (!Class->isThisDeclarationADefinition()) {
195
11
            RewriteForwardClassDecl(D);
196
11
            break;
197
146
          } else {
198
            // Keep track of all interface declarations seen.
199
146
            ObjCInterfacesSeen.push_back(Class);
200
146
            break;
201
146
          }
202
157
        }
203
204
510
        if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
205
18
          if (!Proto->isThisDeclarationADefinition()) {
206
2
            RewriteForwardProtocolDecl(D);
207
2
            break;
208
2
          }
209
18
        }
210
211
508
        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
172
          if (FDecl->isThisDeclarationADefinition() &&
217
              // Not c functions defined inside an objc container.
218
172
              
!FDecl->isTopLevelDeclInObjCContainer()96
) {
219
94
            FunctionDefinitionsSeen.push_back(FDecl);
220
94
            break;
221
94
          }
222
172
        }
223
414
        HandleTopLevelSingleDecl(*I);
224
414
      }
225
584
      return true;
226
584
    }
227
228
1
    void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
229
2
      for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; 
++I1
) {
230
1
        if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(*I)) {
231
1
          if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
232
1
            RewriteBlockPointerDecl(TD);
233
0
          else if (TD->getUnderlyingType()->isFunctionPointerType())
234
0
            CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
235
0
          else
236
0
            RewriteObjCQualifiedInterfaceTypes(TD);
237
1
        }
238
1
      }
239
1
    }
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
247
78
    ~RewriteModernObjC() override {}
248
249
    void HandleTranslationUnit(ASTContext &C) override;
250
251
278
    void ReplaceStmt(Stmt *Old, Stmt *New) {
252
278
      ReplaceStmtWithRange(Old, New, Old->getSourceRange());
253
278
    }
254
255
408
    void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
256
408
      assert(Old != nullptr && New != nullptr && "Expected non-null Stmt's");
257
258
0
      Stmt *ReplacingStmt = ReplacedNodes[Old];
259
408
      if (ReplacingStmt)
260
0
        return; // We can't rewrite the same node twice.
261
262
408
      if (DisableReplaceStmt)
263
16
        return;
264
265
      // Measure the old text.
266
392
      int Size = Rewrite.getRangeSize(SrcRange);
267
392
      if (Size == -1) {
268
0
        Diags.Report(Context->getFullLoc(Old->getBeginLoc()), RewriteFailedDiag)
269
0
            << Old->getSourceRange();
270
0
        return;
271
0
      }
272
      // Get the new text.
273
392
      std::string SStr;
274
392
      llvm::raw_string_ostream S(SStr);
275
392
      New->printPretty(S, nullptr, PrintingPolicy(LangOpts));
276
392
      const std::string &Str = S.str();
277
278
      // If replacement succeeded or warning disabled return with no warning.
279
392
      if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
280
392
        ReplacedNodes[Old] = New;
281
392
        return;
282
392
      }
283
0
      if (SilenceRewriteMacroWarning)
284
0
        return;
285
0
      Diags.Report(Context->getFullLoc(Old->getBeginLoc()), RewriteFailedDiag)
286
0
          << Old->getSourceRange();
287
0
    }
288
289
    void InsertText(SourceLocation Loc, StringRef Str,
290
870
                    bool InsertAfter = true) {
291
      // If insertion succeeded or warning disabled return with no warning.
292
870
      if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
293
870
          
SilenceRewriteMacroWarning0
)
294
870
        return;
295
296
0
      Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
297
0
    }
298
299
    void ReplaceText(SourceLocation Start, unsigned OrigLength,
300
714
                     StringRef Str) {
301
      // If removal succeeded or warning disabled return with no warning.
302
714
      if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
303
714
          
SilenceRewriteMacroWarning0
)
304
714
        return;
305
306
0
      Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
307
0
    }
308
309
    // Syntactic Rewriting.
310
    void RewriteRecordBody(RecordDecl *RD);
311
    void RewriteInclude();
312
    void RewriteLineDirective(const Decl *D);
313
    void ConvertSourceLocationToLineDirective(SourceLocation Loc,
314
                                              std::string &LineString);
315
    void RewriteForwardClassDecl(DeclGroupRef D);
316
    void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG);
317
    void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
318
                                     const std::string &typedefString);
319
    void RewriteImplementations();
320
    void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
321
                                 ObjCImplementationDecl *IMD,
322
                                 ObjCCategoryImplDecl *CID);
323
    void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
324
    void RewriteImplementationDecl(Decl *Dcl);
325
    void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
326
                               ObjCMethodDecl *MDecl, std::string &ResultStr);
327
    void RewriteTypeIntoString(QualType T, std::string &ResultStr,
328
                               const FunctionType *&FPRetType);
329
    void RewriteByRefString(std::string &ResultStr, const std::string &Name,
330
                            ValueDecl *VD, bool def=false);
331
    void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
332
    void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
333
    void RewriteForwardProtocolDecl(DeclGroupRef D);
334
    void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG);
335
    void RewriteMethodDeclaration(ObjCMethodDecl *Method);
336
    void RewriteProperty(ObjCPropertyDecl *prop);
337
    void RewriteFunctionDecl(FunctionDecl *FD);
338
    void RewriteBlockPointerType(std::string& Str, QualType Type);
339
    void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
340
    void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
341
    void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
342
    void RewriteTypeOfDecl(VarDecl *VD);
343
    void RewriteObjCQualifiedInterfaceTypes(Expr *E);
344
345
    std::string getIvarAccessString(ObjCIvarDecl *D);
346
347
    // Expression Rewriting.
348
    Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
349
    Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
350
    Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
351
    Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
352
    Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
353
    Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
354
    Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
355
    Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
356
    Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
357
    Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
358
    Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
359
    Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
360
    Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
361
    Stmt *RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt  *S);
362
    Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
363
    Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
364
    Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
365
                                       SourceLocation OrigEnd);
366
    Stmt *RewriteBreakStmt(BreakStmt *S);
367
    Stmt *RewriteContinueStmt(ContinueStmt *S);
368
    void RewriteCastExpr(CStyleCastExpr *CE);
369
    void RewriteImplicitCastObjCExpr(CastExpr *IE);
370
371
    // Computes ivar bitfield group no.
372
    unsigned ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV);
373
    // Names field decl. for ivar bitfield group.
374
    void ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV, std::string &Result);
375
    // Names struct type for ivar bitfield group.
376
    void ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV, std::string &Result);
377
    // Names symbol for ivar bitfield group field offset.
378
    void ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV, std::string &Result);
379
    // Given an ivar bitfield, it builds (or finds) its group record type.
380
    QualType GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV);
381
    QualType SynthesizeBitfieldGroupStructType(
382
                                    ObjCIvarDecl *IV,
383
                                    SmallVectorImpl<ObjCIvarDecl *> &IVars);
384
385
    // Block rewriting.
386
    void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
387
388
    // Block specific rewrite rules.
389
    void RewriteBlockPointerDecl(NamedDecl *VD);
390
    void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl);
391
    Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
392
    Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
393
    void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
394
395
    void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
396
                                      std::string &Result);
397
398
    void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
399
    bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag,
400
                                 bool &IsNamedDefinition);
401
    void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
402
                                              std::string &Result);
403
404
    bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
405
406
    void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
407
                                  std::string &Result);
408
409
    void Initialize(ASTContext &context) override;
410
411
    // Misc. AST transformation routines. Sometimes they end up calling
412
    // rewriting routines on the new ASTs.
413
    CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
414
                                           ArrayRef<Expr *> Args,
415
                                           SourceLocation StartLoc=SourceLocation(),
416
                                           SourceLocation EndLoc=SourceLocation());
417
418
    Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
419
                                        QualType returnType,
420
                                        SmallVectorImpl<QualType> &ArgTypes,
421
                                        SmallVectorImpl<Expr*> &MsgExprs,
422
                                        ObjCMethodDecl *Method);
423
424
    Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
425
                           SourceLocation StartLoc=SourceLocation(),
426
                           SourceLocation EndLoc=SourceLocation());
427
428
    void SynthCountByEnumWithState(std::string &buf);
429
    void SynthMsgSendFunctionDecl();
430
    void SynthMsgSendSuperFunctionDecl();
431
    void SynthMsgSendStretFunctionDecl();
432
    void SynthMsgSendFpretFunctionDecl();
433
    void SynthMsgSendSuperStretFunctionDecl();
434
    void SynthGetClassFunctionDecl();
435
    void SynthGetMetaClassFunctionDecl();
436
    void SynthGetSuperClassFunctionDecl();
437
    void SynthSelGetUidFunctionDecl();
438
    void SynthSuperConstructorFunctionDecl();
439
440
    // Rewriting metadata
441
    template<typename MethodIterator>
442
    void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
443
                                    MethodIterator MethodEnd,
444
                                    bool IsInstanceMethod,
445
                                    StringRef prefix,
446
                                    StringRef ClassName,
447
                                    std::string &Result);
448
    void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
449
                                     std::string &Result);
450
    void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
451
                                          std::string &Result);
452
    void RewriteClassSetupInitHook(std::string &Result);
453
454
    void RewriteMetaDataIntoBuffer(std::string &Result);
455
    void WriteImageInfo(std::string &Result);
456
    void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
457
                                             std::string &Result);
458
    void RewriteCategorySetupInitHook(std::string &Result);
459
460
    // Rewriting ivar
461
    void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
462
                                              std::string &Result);
463
    Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
464
465
466
    std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
467
    std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
468
                                      StringRef funcName, std::string Tag);
469
    std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
470
                                      StringRef funcName, std::string Tag);
471
    std::string SynthesizeBlockImpl(BlockExpr *CE,
472
                                    std::string Tag, std::string Desc);
473
    std::string SynthesizeBlockDescriptor(std::string DescTag,
474
                                          std::string ImplTag,
475
                                          int i, StringRef funcName,
476
                                          unsigned hasCopy);
477
    Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
478
    void SynthesizeBlockLiterals(SourceLocation FunLocStart,
479
                                 StringRef FunName);
480
    FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
481
    Stmt *SynthBlockInitExpr(BlockExpr *Exp,
482
                      const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
483
484
    // Misc. helper routines.
485
    QualType getProtocolType();
486
    void WarnAboutReturnGotoStmts(Stmt *S);
487
    void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
488
    void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
489
    void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
490
491
    bool IsDeclStmtInForeachHeader(DeclStmt *DS);
492
    void CollectBlockDeclRefInfo(BlockExpr *Exp);
493
    void GetBlockDeclRefExprs(Stmt *S);
494
    void GetInnerBlockDeclRefExprs(Stmt *S,
495
                SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
496
                llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts);
497
498
    // We avoid calling Type::isBlockPointerType(), since it operates on the
499
    // canonical type. We only care if the top-level type is a closure pointer.
500
1.32k
    bool isTopLevelBlockPointerType(QualType T) {
501
1.32k
      return isa<BlockPointerType>(T);
502
1.32k
    }
503
504
    /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
505
    /// to a function pointer type and upon success, returns true; false
506
    /// otherwise.
507
709
    bool convertBlockPointerToFunctionPointer(QualType &T) {
508
709
      if (isTopLevelBlockPointerType(T)) {
509
22
        const auto *BPT = T->castAs<BlockPointerType>();
510
22
        T = Context->getPointerType(BPT->getPointeeType());
511
22
        return true;
512
22
      }
513
687
      return false;
514
709
    }
515
516
    bool convertObjCTypeToCStyleType(QualType &T);
517
518
    bool needToScanForQualifiers(QualType T);
519
    QualType getSuperStructType();
520
    QualType getConstantStringStructType();
521
    QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
522
523
529
    void convertToUnqualifiedObjCType(QualType &T) {
524
529
      if (T->isObjCQualifiedIdType()) {
525
15
        bool isConst = T.isConstQualified();
526
15
        T = isConst ? 
Context->getObjCIdType().withConst()2
527
15
                    : 
Context->getObjCIdType()13
;
528
15
      }
529
514
      else if (T->isObjCQualifiedClassType())
530
0
        T = Context->getObjCClassType();
531
514
      else if (T->isObjCObjectPointerType() &&
532
514
               
T->getPointeeType()->isObjCQualifiedInterfaceType()136
) {
533
18
        if (const ObjCObjectPointerType * OBJPT =
534
18
              T->getAsObjCInterfacePointerType()) {
535
18
          const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
536
18
          T = QualType(IFaceT, 0);
537
18
          T = Context->getPointerType(T);
538
18
        }
539
18
     }
540
529
    }
541
542
    // FIXME: This predicate seems like it would be useful to add to ASTContext.
543
36
    bool isObjCType(QualType T) {
544
36
      if (!LangOpts.ObjC)
545
0
        return false;
546
547
36
      QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
548
549
36
      if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
550
36
          
OCT == Context->getCanonicalType(Context->getObjCClassType())33
)
551
3
        return true;
552
553
33
      if (const PointerType *PT = OCT->getAs<PointerType>()) {
554
2
        if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
555
2
            PT->getPointeeType()->isObjCQualifiedIdType())
556
0
          return true;
557
2
      }
558
33
      return false;
559
33
    }
560
561
    bool PointerTypeTakesAnyBlockArguments(QualType QT);
562
    bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
563
    void GetExtentOfArgList(const char *Name, const char *&LParen,
564
                            const char *&RParen);
565
566
180
    void QuoteDoublequotes(std::string &From, std::string &To) {
567
2.41k
      for (unsigned i = 0; i < From.length(); 
i++2.23k
) {
568
2.23k
        if (From[i] == '"')
569
260
          To += "\\\"";
570
1.97k
        else
571
1.97k
          To += From[i];
572
2.23k
      }
573
180
    }
574
575
    QualType getSimpleFunctionType(QualType result,
576
                                   ArrayRef<QualType> args,
577
404
                                   bool variadic = false) {
578
404
      if (result == Context->getObjCInstanceType())
579
0
        result =  Context->getObjCIdType();
580
404
      FunctionProtoType::ExtProtoInfo fpi;
581
404
      fpi.Variadic = variadic;
582
404
      return Context->getFunctionType(result, args, fpi);
583
404
    }
584
585
    // Helper function: create a CStyleCastExpr with trivial type source info.
586
    CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
587
909
                                             CastKind Kind, Expr *E) {
588
909
      TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
589
909
      return CStyleCastExpr::Create(*Ctx, Ty, VK_PRValue, Kind, E, nullptr,
590
909
                                    FPOptionsOverride(), TInfo,
591
909
                                    SourceLocation(), SourceLocation());
592
909
    }
593
594
93
    bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
595
93
      IdentifierInfo* II = &Context->Idents.get("load");
596
93
      Selector LoadSel = Context->Selectors.getSelector(0, &II);
597
93
      return OD->getClassMethod(LoadSel) != nullptr;
598
93
    }
599
600
217
    StringLiteral *getStringLiteral(StringRef Str) {
601
217
      QualType StrType = Context->getConstantArrayType(
602
217
          Context->CharTy, llvm::APInt(32, Str.size() + 1), nullptr,
603
217
          ArrayType::Normal, 0);
604
217
      return StringLiteral::Create(*Context, Str, StringLiteral::Ordinary,
605
217
                                   /*Pascal=*/false, StrType, SourceLocation());
606
217
    }
607
  };
608
} // end anonymous namespace
609
610
void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
611
192
                                                   NamedDecl *D) {
612
192
  if (const FunctionProtoType *fproto
613
192
      = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
614
192
    for (const auto &I : fproto->param_types())
615
114
      if (isTopLevelBlockPointerType(I)) {
616
        // All the args are checked/rewritten. Don't call twice!
617
26
        RewriteBlockPointerDecl(D);
618
26
        break;
619
26
      }
620
192
  }
621
192
}
622
623
2
void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
624
2
  const PointerType *PT = funcType->getAs<PointerType>();
625
2
  if (PT && PointerTypeTakesAnyBlockArguments(funcType))
626
0
    RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
627
2
}
628
629
78
static bool IsHeaderFile(const std::string &Filename) {
630
78
  std::string::size_type DotPos = Filename.rfind('.');
631
632
78
  if (DotPos == std::string::npos) {
633
    // no file extension
634
0
    return false;
635
0
  }
636
637
78
  std::string Ext = Filename.substr(DotPos + 1);
638
  // C header: .h
639
  // C++ header: .hh or .H;
640
78
  return Ext == "h" || Ext == "hh" || Ext == "H";
641
78
}
642
643
RewriteModernObjC::RewriteModernObjC(std::string inFile,
644
                                     std::unique_ptr<raw_ostream> OS,
645
                                     DiagnosticsEngine &D,
646
                                     const LangOptions &LOpts,
647
                                     bool silenceMacroWarn, bool LineInfo)
648
    : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(std::move(OS)),
649
78
      SilenceRewriteMacroWarning(silenceMacroWarn), GenerateLineInfo(LineInfo) {
650
78
  IsHeader = IsHeaderFile(inFile);
651
78
  RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
652
78
               "rewriting sub-expression within a macro (may not be correct)");
653
  // FIXME. This should be an error. But if block is not called, it is OK. And it
654
  // may break including some headers.
655
78
  GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
656
78
    "rewriting block literal declared in global scope is not implemented");
657
658
78
  TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
659
78
               DiagnosticsEngine::Warning,
660
78
               "rewriter doesn't support user-specified control flow semantics "
661
78
               "for @try/@finally (code may not execute properly)");
662
78
}
663
664
std::unique_ptr<ASTConsumer> clang::CreateModernObjCRewriter(
665
    const std::string &InFile, std::unique_ptr<raw_ostream> OS,
666
    DiagnosticsEngine &Diags, const LangOptions &LOpts,
667
78
    bool SilenceRewriteMacroWarning, bool LineInfo) {
668
78
  return std::make_unique<RewriteModernObjC>(InFile, std::move(OS), Diags,
669
78
                                              LOpts, SilenceRewriteMacroWarning,
670
78
                                              LineInfo);
671
78
}
672
673
78
void RewriteModernObjC::InitializeCommon(ASTContext &context) {
674
78
  Context = &context;
675
78
  SM = &Context->getSourceManager();
676
78
  TUDecl = Context->getTranslationUnitDecl();
677
78
  MsgSendFunctionDecl = nullptr;
678
78
  MsgSendSuperFunctionDecl = nullptr;
679
78
  MsgSendStretFunctionDecl = nullptr;
680
78
  MsgSendSuperStretFunctionDecl = nullptr;
681
78
  MsgSendFpretFunctionDecl = nullptr;
682
78
  GetClassFunctionDecl = nullptr;
683
78
  GetMetaClassFunctionDecl = nullptr;
684
78
  GetSuperClassFunctionDecl = nullptr;
685
78
  SelGetUidFunctionDecl = nullptr;
686
78
  CFStringFunctionDecl = nullptr;
687
78
  ConstantStringClassReference = nullptr;
688
78
  NSStringRecord = nullptr;
689
78
  CurMethodDef = nullptr;
690
78
  CurFunctionDef = nullptr;
691
78
  GlobalVarDecl = nullptr;
692
78
  GlobalConstructionExp = nullptr;
693
78
  SuperStructDecl = nullptr;
694
78
  ProtocolTypeDecl = nullptr;
695
78
  ConstantStringDecl = nullptr;
696
78
  BcLabelCount = 0;
697
78
  SuperConstructorFunctionDecl = nullptr;
698
78
  NumObjCStringLiterals = 0;
699
78
  PropParentMap = nullptr;
700
78
  CurrentBody = nullptr;
701
78
  DisableReplaceStmt = false;
702
78
  objc_impl_method = false;
703
704
  // Get the ID and start/end of the main file.
705
78
  MainFileID = SM->getMainFileID();
706
78
  llvm::MemoryBufferRef MainBuf = SM->getBufferOrFake(MainFileID);
707
78
  MainFileStart = MainBuf.getBufferStart();
708
78
  MainFileEnd = MainBuf.getBufferEnd();
709
710
78
  Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
711
78
}
712
713
//===----------------------------------------------------------------------===//
714
// Top Level Driver Code
715
//===----------------------------------------------------------------------===//
716
717
541
void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
718
541
  if (Diags.hasErrorOccurred())
719
0
    return;
720
721
  // Two cases: either the decl could be in the main file, or it could be in a
722
  // #included file.  If the former, rewrite it now.  If the later, check to see
723
  // if we rewrote the #include/#import.
724
541
  SourceLocation Loc = D->getLocation();
725
541
  Loc = SM->getExpansionLoc(Loc);
726
727
  // If this is for a builtin, ignore it.
728
541
  if (Loc.isInvalid()) 
return0
;
729
730
  // Look for built-in declarations that we need to refer during the rewrite.
731
541
  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
732
192
    RewriteFunctionDecl(FD);
733
349
  } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
734
    // declared in <Foundation/NSString.h>
735
21
    if (FVD->getName() == "_NSConstantStringClassReference") {
736
0
      ConstantStringClassReference = FVD;
737
0
      return;
738
0
    }
739
328
  } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
740
14
    RewriteCategoryDecl(CD);
741
314
  } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
742
16
    if (PD->isThisDeclarationADefinition())
743
16
      RewriteProtocolDecl(PD);
744
298
  } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
745
    // Recurse into linkage specifications
746
25
    for (DeclContext::decl_iterator DI = LSD->decls_begin(),
747
25
                                 DIEnd = LSD->decls_end();
748
67
         DI != DIEnd; ) {
749
42
      if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
750
11
        if (!IFace->isThisDeclarationADefinition()) {
751
5
          SmallVector<Decl *, 8> DG;
752
5
          SourceLocation StartLoc = IFace->getBeginLoc();
753
21
          do {
754
21
            if (isa<ObjCInterfaceDecl>(*DI) &&
755
21
                
!cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition()20
&&
756
21
                
StartLoc == (*DI)->getBeginLoc()19
)
757
16
              DG.push_back(*DI);
758
5
            else
759
5
              break;
760
761
16
            ++DI;
762
16
          } while (DI != DIEnd);
763
0
          RewriteForwardClassDecl(DG);
764
5
          continue;
765
5
        }
766
6
        else {
767
          // Keep track of all interface declarations seen.
768
6
          ObjCInterfacesSeen.push_back(IFace);
769
6
          ++DI;
770
6
          continue;
771
6
        }
772
11
      }
773
774
31
      if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
775
0
        if (!Proto->isThisDeclarationADefinition()) {
776
0
          SmallVector<Decl *, 8> DG;
777
0
          SourceLocation StartLoc = Proto->getBeginLoc();
778
0
          do {
779
0
            if (isa<ObjCProtocolDecl>(*DI) &&
780
0
                !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
781
0
                StartLoc == (*DI)->getBeginLoc())
782
0
              DG.push_back(*DI);
783
0
            else
784
0
              break;
785
786
0
            ++DI;
787
0
          } while (DI != DIEnd);
788
0
          RewriteForwardProtocolDecl(DG);
789
0
          continue;
790
0
        }
791
0
      }
792
793
31
      HandleTopLevelSingleDecl(*DI);
794
31
      ++DI;
795
31
    }
796
25
  }
797
  // If we have a decl in the main file, see if we should rewrite it.
798
541
  if (SM->isWrittenInMainFile(Loc))
799
541
    return HandleDeclInMainFile(D);
800
541
}
801
802
//===----------------------------------------------------------------------===//
803
// Syntactic (non-AST) Rewriting Code
804
//===----------------------------------------------------------------------===//
805
806
78
void RewriteModernObjC::RewriteInclude() {
807
78
  SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
808
78
  StringRef MainBuf = SM->getBufferData(MainFileID);
809
78
  const char *MainBufStart = MainBuf.begin();
810
78
  const char *MainBufEnd = MainBuf.end();
811
78
  size_t ImportLen = strlen("import");
812
813
  // Loop over the whole file, looking for includes.
814
80.4k
  for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; 
++BufPtr80.3k
) {
815
80.3k
    if (*BufPtr == '#') {
816
182
      if (++BufPtr == MainBufEnd)
817
0
        return;
818
354
      
while (182
*BufPtr == ' ' ||
*BufPtr == '\t'182
)
819
172
        if (++BufPtr == MainBufEnd)
820
0
          return;
821
182
      if (!strncmp(BufPtr, "import", ImportLen)) {
822
        // replace import with include
823
0
        SourceLocation ImportLoc =
824
0
          LocStart.getLocWithOffset(BufPtr-MainBufStart);
825
0
        ReplaceText(ImportLoc, ImportLen, "include");
826
0
        BufPtr += ImportLen;
827
0
      }
828
182
    }
829
80.3k
  }
830
78
}
831
832
static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl,
833
438
                                  ObjCIvarDecl *IvarDecl, std::string &Result) {
834
438
  Result += "OBJC_IVAR_$_";
835
438
  Result += IDecl->getName();
836
438
  Result += "$";
837
438
  Result += IvarDecl->getName();
838
438
}
839
840
std::string
841
30
RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
842
30
  const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
843
844
  // Build name of symbol holding ivar offset.
845
30
  std::string IvarOffsetName;
846
30
  if (D->isBitField())
847
4
    ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
848
26
  else
849
26
    WriteInternalIvarName(ClassDecl, D, IvarOffsetName);
850
851
30
  std::string S = "(*(";
852
30
  QualType IvarT = D->getType();
853
30
  if (D->isBitField())
854
4
    IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
855
856
30
  if (!isa<TypedefType>(IvarT) && 
IvarT->isRecordType()23
) {
857
4
    RecordDecl *RD = IvarT->castAs<RecordType>()->getDecl();
858
4
    RD = RD->getDefinition();
859
4
    if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
860
      // decltype(((Foo_IMPL*)0)->bar) *
861
0
      auto *CDecl = cast<ObjCContainerDecl>(D->getDeclContext());
862
      // ivar in class extensions requires special treatment.
863
0
      if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
864
0
        CDecl = CatDecl->getClassInterface();
865
0
      std::string RecName = std::string(CDecl->getName());
866
0
      RecName += "_IMPL";
867
0
      RecordDecl *RD =
868
0
          RecordDecl::Create(*Context, TTK_Struct, TUDecl, SourceLocation(),
869
0
                             SourceLocation(), &Context->Idents.get(RecName));
870
0
      QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
871
0
      unsigned UnsignedIntSize =
872
0
      static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
873
0
      Expr *Zero = IntegerLiteral::Create(*Context,
874
0
                                          llvm::APInt(UnsignedIntSize, 0),
875
0
                                          Context->UnsignedIntTy, SourceLocation());
876
0
      Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
877
0
      ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
878
0
                                              Zero);
879
0
      FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
880
0
                                        SourceLocation(),
881
0
                                        &Context->Idents.get(D->getNameAsString()),
882
0
                                        IvarT, nullptr,
883
0
                                        /*BitWidth=*/nullptr, /*Mutable=*/true,
884
0
                                        ICIS_NoInit);
885
0
      MemberExpr *ME = MemberExpr::CreateImplicit(
886
0
          *Context, PE, true, FD, FD->getType(), VK_LValue, OK_Ordinary);
887
0
      IvarT = Context->getDecltypeType(ME, ME->getType());
888
0
    }
889
4
  }
890
30
  convertObjCTypeToCStyleType(IvarT);
891
30
  QualType castT = Context->getPointerType(IvarT);
892
30
  std::string TypeString(castT.getAsString(Context->getPrintingPolicy()));
893
30
  S += TypeString;
894
30
  S += ")";
895
896
  // ((char *)self + IVAR_OFFSET_SYMBOL_NAME)
897
30
  S += "((char *)self + ";
898
30
  S += IvarOffsetName;
899
30
  S += "))";
900
30
  if (D->isBitField()) {
901
4
    S += ".";
902
4
    S += D->getNameAsString();
903
4
  }
904
30
  ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D);
905
30
  return S;
906
30
}
907
908
/// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
909
/// been found in the class implementation. In this case, it must be synthesized.
910
static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
911
                                             ObjCPropertyDecl *PD,
912
104
                                             bool getter) {
913
104
  auto *OMD = IMP->getInstanceMethod(getter ? 
PD->getGetterName()56
914
104
                                            : 
PD->getSetterName()48
);
915
104
  return !OMD || OMD->isSynthesizedAccessorStub();
916
104
}
917
918
void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
919
                                          ObjCImplementationDecl *IMD,
920
31
                                          ObjCCategoryImplDecl *CID) {
921
31
  static bool objcGetPropertyDefined = false;
922
31
  static bool objcSetPropertyDefined = false;
923
31
  SourceLocation startGetterSetterLoc;
924
925
31
  if (PID->getBeginLoc().isValid()) {
926
23
    SourceLocation startLoc = PID->getBeginLoc();
927
23
    InsertText(startLoc, "// ");
928
23
    const char *startBuf = SM->getCharacterData(startLoc);
929
23
    assert((*startBuf == '@') && "bogus @synthesize location");
930
0
    const char *semiBuf = strchr(startBuf, ';');
931
23
    assert((*semiBuf == ';') && "@synthesize: can't find ';'");
932
0
    startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
933
23
  } else
934
8
    startGetterSetterLoc = IMD ? IMD->getEndLoc() : 
CID->getEndLoc()0
;
935
936
31
  if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
937
3
    return; // FIXME: is this correct?
938
939
  // Generate the 'getter' function.
940
28
  ObjCPropertyDecl *PD = PID->getPropertyDecl();
941
28
  ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
942
28
  assert(IMD && OID && "Synthesized ivars must be attached to @implementation");
943
944
0
  unsigned Attributes = PD->getPropertyAttributes();
945
28
  if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
946
26
    bool GenGetProperty =
947
26
        !(Attributes & ObjCPropertyAttribute::kind_nonatomic) &&
948
26
        (Attributes & (ObjCPropertyAttribute::kind_retain |
949
22
                       ObjCPropertyAttribute::kind_copy));
950
26
    std::string Getr;
951
26
    if (GenGetProperty && 
!objcGetPropertyDefined9
) {
952
5
      objcGetPropertyDefined = true;
953
      // FIXME. Is this attribute correct in all cases?
954
5
      Getr = "\nextern \"C\" __declspec(dllimport) "
955
5
            "id objc_getProperty(id, SEL, long, bool);\n";
956
5
    }
957
26
    RewriteObjCMethodDecl(OID->getContainingInterface(),
958
26
                          PID->getGetterMethodDecl(), Getr);
959
26
    Getr += "{ ";
960
    // Synthesize an explicit cast to gain access to the ivar.
961
    // See objc-act.c:objc_synthesize_new_getter() for details.
962
26
    if (GenGetProperty) {
963
      // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
964
9
      Getr += "typedef ";
965
9
      const FunctionType *FPRetType = nullptr;
966
9
      RewriteTypeIntoString(PID->getGetterMethodDecl()->getReturnType(), Getr,
967
9
                            FPRetType);
968
9
      Getr += " _TYPE";
969
9
      if (FPRetType) {
970
1
        Getr += ")"; // close the precedence "scope" for "*".
971
972
        // Now, emit the argument types (if any).
973
1
        if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
974
1
          Getr += "(";
975
1
          for (unsigned i = 0, e = FT->getNumParams(); i != e; 
++i0
) {
976
0
            if (i) Getr += ", ";
977
0
            std::string ParamStr =
978
0
                FT->getParamType(i).getAsString(Context->getPrintingPolicy());
979
0
            Getr += ParamStr;
980
0
          }
981
1
          if (FT->isVariadic()) {
982
0
            if (FT->getNumParams())
983
0
              Getr += ", ";
984
0
            Getr += "...";
985
0
          }
986
1
          Getr += ")";
987
1
        } else
988
0
          Getr += "()";
989
1
      }
990
9
      Getr += ";\n";
991
9
      Getr += "return (_TYPE)";
992
9
      Getr += "objc_getProperty(self, _cmd, ";
993
9
      RewriteIvarOffsetComputation(OID, Getr);
994
9
      Getr += ", 1)";
995
9
    }
996
17
    else
997
17
      Getr += "return " + getIvarAccessString(OID);
998
26
    Getr += "; }";
999
26
    InsertText(startGetterSetterLoc, Getr);
1000
26
  }
1001
1002
28
  if (PD->isReadOnly() ||
1003
28
      
!mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/)24
)
1004
6
    return;
1005
1006
  // Generate the 'setter' function.
1007
22
  std::string Setr;
1008
22
  bool GenSetProperty = Attributes & (ObjCPropertyAttribute::kind_retain |
1009
22
                                      ObjCPropertyAttribute::kind_copy);
1010
22
  if (GenSetProperty && 
!objcSetPropertyDefined9
) {
1011
6
    objcSetPropertyDefined = true;
1012
    // FIXME. Is this attribute correct in all cases?
1013
6
    Setr = "\nextern \"C\" __declspec(dllimport) "
1014
6
    "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
1015
6
  }
1016
1017
22
  RewriteObjCMethodDecl(OID->getContainingInterface(),
1018
22
                        PID->getSetterMethodDecl(), Setr);
1019
22
  Setr += "{ ";
1020
  // Synthesize an explicit cast to initialize the ivar.
1021
  // See objc-act.c:objc_synthesize_new_setter() for details.
1022
22
  if (GenSetProperty) {
1023
9
    Setr += "objc_setProperty (self, _cmd, ";
1024
9
    RewriteIvarOffsetComputation(OID, Setr);
1025
9
    Setr += ", (id)";
1026
9
    Setr += PD->getName();
1027
9
    Setr += ", ";
1028
9
    if (Attributes & ObjCPropertyAttribute::kind_nonatomic)
1029
2
      Setr += "0, ";
1030
7
    else
1031
7
      Setr += "1, ";
1032
9
    if (Attributes & ObjCPropertyAttribute::kind_copy)
1033
4
      Setr += "1)";
1034
5
    else
1035
5
      Setr += "0)";
1036
9
  }
1037
13
  else {
1038
13
    Setr += getIvarAccessString(OID) + " = ";
1039
13
    Setr += PD->getName();
1040
13
  }
1041
22
  Setr += "; }\n";
1042
22
  InsertText(startGetterSetterLoc, Setr);
1043
22
}
1044
1045
static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
1046
181
                                       std::string &typedefString) {
1047
181
  typedefString += "\n#ifndef _REWRITER_typedef_";
1048
181
  typedefString += ForwardDecl->getNameAsString();
1049
181
  typedefString += "\n";
1050
181
  typedefString += "#define _REWRITER_typedef_";
1051
181
  typedefString += ForwardDecl->getNameAsString();
1052
181
  typedefString += "\n";
1053
181
  typedefString += "typedef struct objc_object ";
1054
181
  typedefString += ForwardDecl->getNameAsString();
1055
  // typedef struct { } _objc_exc_Classname;
1056
181
  typedefString += ";\ntypedef struct {} _objc_exc_";
1057
181
  typedefString += ForwardDecl->getNameAsString();
1058
181
  typedefString += ";\n#endif\n";
1059
181
}
1060
1061
void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
1062
16
                                              const std::string &typedefString) {
1063
16
  SourceLocation startLoc = ClassDecl->getBeginLoc();
1064
16
  const char *startBuf = SM->getCharacterData(startLoc);
1065
16
  const char *semiPtr = strchr(startBuf, ';');
1066
  // Replace the @class with typedefs corresponding to the classes.
1067
16
  ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
1068
16
}
1069
1070
11
void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
1071
11
  std::string typedefString;
1072
26
  for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; 
++I15
) {
1073
15
    if (ObjCInterfaceDecl *ForwardDecl = dyn_cast<ObjCInterfaceDecl>(*I)) {
1074
13
      if (I == D.begin()) {
1075
        // Translate to typedef's that forward reference structs with the same name
1076
        // as the class. As a convenience, we include the original declaration
1077
        // as a comment.
1078
11
        typedefString += "// @class ";
1079
11
        typedefString += ForwardDecl->getNameAsString();
1080
11
        typedefString += ";";
1081
11
      }
1082
13
      RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1083
13
    }
1084
2
    else
1085
2
      HandleTopLevelSingleDecl(*I);
1086
15
  }
1087
11
  DeclGroupRef::iterator I = D.begin();
1088
11
  RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
1089
11
}
1090
1091
void RewriteModernObjC::RewriteForwardClassDecl(
1092
5
                                const SmallVectorImpl<Decl *> &D) {
1093
5
  std::string typedefString;
1094
21
  for (unsigned i = 0; i < D.size(); 
i++16
) {
1095
16
    ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
1096
16
    if (i == 0) {
1097
5
      typedefString += "// @class ";
1098
5
      typedefString += ForwardDecl->getNameAsString();
1099
5
      typedefString += ";";
1100
5
    }
1101
16
    RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1102
16
  }
1103
5
  RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
1104
5
}
1105
1106
210
void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
1107
  // When method is a synthesized one, such as a getter/setter there is
1108
  // nothing to rewrite.
1109
210
  if (Method->isImplicit())
1110
68
    return;
1111
142
  SourceLocation LocStart = Method->getBeginLoc();
1112
142
  SourceLocation LocEnd = Method->getEndLoc();
1113
1114
142
  if (SM->getExpansionLineNumber(LocEnd) >
1115
142
      SM->getExpansionLineNumber(LocStart)) {
1116
0
    InsertText(LocStart, "#if 0\n");
1117
0
    ReplaceText(LocEnd, 1, ";\n#endif\n");
1118
142
  } else {
1119
142
    InsertText(LocStart, "// ");
1120
142
  }
1121
142
}
1122
1123
37
void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
1124
37
  SourceLocation Loc = prop->getAtLoc();
1125
1126
37
  ReplaceText(Loc, 0, "// ");
1127
  // FIXME: handle properties that are declared across multiple lines.
1128
37
}
1129
1130
14
void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
1131
14
  SourceLocation LocStart = CatDecl->getBeginLoc();
1132
1133
  // FIXME: handle category headers that are declared across multiple lines.
1134
14
  if (CatDecl->getIvarRBraceLoc().isValid()) {
1135
8
    ReplaceText(LocStart, 1, "/** ");
1136
8
    ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1137
8
  }
1138
6
  else {
1139
6
    ReplaceText(LocStart, 0, "// ");
1140
6
  }
1141
1142
14
  for (auto *I : CatDecl->instance_properties())
1143
4
    RewriteProperty(I);
1144
1145
14
  for (auto *I : CatDecl->instance_methods())
1146
8
    RewriteMethodDeclaration(I);
1147
14
  for (auto *I : CatDecl->class_methods())
1148
0
    RewriteMethodDeclaration(I);
1149
1150
  // Lastly, comment out the @end.
1151
14
  ReplaceText(CatDecl->getAtEndRange().getBegin(),
1152
14
              strlen("@end"), "/* @end */\n");
1153
14
}
1154
1155
16
void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1156
16
  SourceLocation LocStart = PDecl->getBeginLoc();
1157
16
  assert(PDecl->isThisDeclarationADefinition());
1158
1159
  // FIXME: handle protocol headers that are declared across multiple lines.
1160
0
  ReplaceText(LocStart, 0, "// ");
1161
1162
16
  for (auto *I : PDecl->instance_methods())
1163
11
    RewriteMethodDeclaration(I);
1164
16
  for (auto *I : PDecl->class_methods())
1165
3
    RewriteMethodDeclaration(I);
1166
16
  for (auto *I : PDecl->instance_properties())
1167
2
    RewriteProperty(I);
1168
1169
  // Lastly, comment out the @end.
1170
16
  SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1171
16
  ReplaceText(LocEnd, strlen("@end"), "/* @end */\n");
1172
1173
  // Must comment out @optional/@required
1174
16
  const char *startBuf = SM->getCharacterData(LocStart);
1175
16
  const char *endBuf = SM->getCharacterData(LocEnd);
1176
933
  for (const char *p = startBuf; p < endBuf; 
p++917
) {
1177
917
    if (*p == '@' && 
!strncmp(p+1, "optional", strlen("optional"))23
) {
1178
4
      SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1179
4
      ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1180
1181
4
    }
1182
913
    else if (*p == '@' && 
!strncmp(p+1, "required", strlen("required"))19
) {
1183
1
      SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1184
1
      ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1185
1186
1
    }
1187
917
  }
1188
16
}
1189
1190
2
void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1191
2
  SourceLocation LocStart = (*D.begin())->getBeginLoc();
1192
2
  if (LocStart.isInvalid())
1193
0
    llvm_unreachable("Invalid SourceLocation");
1194
  // FIXME: handle forward protocol that are declared across multiple lines.
1195
2
  ReplaceText(LocStart, 0, "// ");
1196
2
}
1197
1198
void
1199
0
RewriteModernObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
1200
0
  SourceLocation LocStart = DG[0]->getBeginLoc();
1201
0
  if (LocStart.isInvalid())
1202
0
    llvm_unreachable("Invalid SourceLocation");
1203
  // FIXME: handle forward protocol that are declared across multiple lines.
1204
0
  ReplaceText(LocStart, 0, "// ");
1205
0
}
1206
1207
void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1208
122
                                        const FunctionType *&FPRetType) {
1209
122
  if (T->isObjCQualifiedIdType())
1210
0
    ResultStr += "id";
1211
122
  else if (T->isFunctionPointerType() ||
1212
122
           T->isBlockPointerType()) {
1213
    // needs special handling, since pointer-to-functions have special
1214
    // syntax (where a decaration models use).
1215
4
    QualType retType = T;
1216
4
    QualType PointeeTy;
1217
4
    if (const PointerType* PT = retType->getAs<PointerType>())
1218
0
      PointeeTy = PT->getPointeeType();
1219
4
    else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1220
4
      PointeeTy = BPT->getPointeeType();
1221
4
    if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1222
4
      ResultStr +=
1223
4
          FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
1224
4
      ResultStr += "(*";
1225
4
    }
1226
4
  } else
1227
118
    ResultStr += T.getAsString(Context->getPrintingPolicy());
1228
122
}
1229
1230
void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1231
                                        ObjCMethodDecl *OMD,
1232
113
                                        std::string &ResultStr) {
1233
  //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1234
113
  const FunctionType *FPRetType = nullptr;
1235
113
  ResultStr += "\nstatic ";
1236
113
  RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
1237
113
  ResultStr += " ";
1238
1239
  // Unique method name
1240
113
  std::string NameStr;
1241
1242
113
  if (OMD->isInstanceMethod())
1243
104
    NameStr += "_I_";
1244
9
  else
1245
9
    NameStr += "_C_";
1246
1247
113
  NameStr += IDecl->getNameAsString();
1248
113
  NameStr += "_";
1249
1250
113
  if (ObjCCategoryImplDecl *CID =
1251
113
      dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1252
0
    NameStr += CID->getNameAsString();
1253
0
    NameStr += "_";
1254
0
  }
1255
  // Append selector names, replacing ':' with '_'
1256
113
  {
1257
113
    std::string selString = OMD->getSelector().getAsString();
1258
113
    int len = selString.size();
1259
1.00k
    for (int i = 0; i < len; 
i++894
)
1260
894
      if (selString[i] == ':')
1261
48
        selString[i] = '_';
1262
113
    NameStr += selString;
1263
113
  }
1264
  // Remember this name for metadata emission
1265
113
  MethodInternalNames[OMD] = NameStr;
1266
113
  ResultStr += NameStr;
1267
1268
  // Rewrite arguments
1269
113
  ResultStr += "(";
1270
1271
  // invisible arguments
1272
113
  if (OMD->isInstanceMethod()) {
1273
104
    QualType selfTy = Context->getObjCInterfaceType(IDecl);
1274
104
    selfTy = Context->getPointerType(selfTy);
1275
104
    if (!LangOpts.MicrosoftExt) {
1276
0
      if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1277
0
        ResultStr += "struct ";
1278
0
    }
1279
    // When rewriting for Microsoft, explicitly omit the structure name.
1280
104
    ResultStr += IDecl->getNameAsString();
1281
104
    ResultStr += " *";
1282
104
  }
1283
9
  else
1284
9
    ResultStr += Context->getObjCClassType().getAsString(
1285
9
      Context->getPrintingPolicy());
1286
1287
113
  ResultStr += " self, ";
1288
113
  ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1289
113
  ResultStr += " _cmd";
1290
1291
  // Method arguments.
1292
113
  for (const auto *PDecl : OMD->parameters()) {
1293
48
    ResultStr += ", ";
1294
48
    if (PDecl->getType()->isObjCQualifiedIdType()) {
1295
0
      ResultStr += "id ";
1296
0
      ResultStr += PDecl->getNameAsString();
1297
48
    } else {
1298
48
      std::string Name = PDecl->getNameAsString();
1299
48
      QualType QT = PDecl->getType();
1300
      // Make sure we convert "t (^)(...)" to "t (*)(...)".
1301
48
      (void)convertBlockPointerToFunctionPointer(QT);
1302
48
      QT.getAsStringInternal(Name, Context->getPrintingPolicy());
1303
48
      ResultStr += Name;
1304
48
    }
1305
48
  }
1306
113
  if (OMD->isVariadic())
1307
0
    ResultStr += ", ...";
1308
113
  ResultStr += ") ";
1309
1310
113
  if (FPRetType) {
1311
3
    ResultStr += ")"; // close the precedence "scope" for "*".
1312
1313
    // Now, emit the argument types (if any).
1314
3
    if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1315
3
      ResultStr += "(";
1316
3
      for (unsigned i = 0, e = FT->getNumParams(); i != e; 
++i0
) {
1317
0
        if (i) ResultStr += ", ";
1318
0
        std::string ParamStr =
1319
0
            FT->getParamType(i).getAsString(Context->getPrintingPolicy());
1320
0
        ResultStr += ParamStr;
1321
0
      }
1322
3
      if (FT->isVariadic()) {
1323
0
        if (FT->getNumParams())
1324
0
          ResultStr += ", ";
1325
0
        ResultStr += "...";
1326
0
      }
1327
3
      ResultStr += ")";
1328
3
    } else {
1329
0
      ResultStr += "()";
1330
0
    }
1331
3
  }
1332
113
}
1333
1334
93
void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1335
93
  ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1336
93
  ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1337
93
  assert((IMD || CID) && "Unknown implementation type");
1338
1339
93
  if (IMD) {
1340
88
    if (IMD->getIvarRBraceLoc().isValid()) {
1341
3
      ReplaceText(IMD->getBeginLoc(), 1, "/** ");
1342
3
      ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
1343
3
    }
1344
85
    else {
1345
85
      InsertText(IMD->getBeginLoc(), "// ");
1346
85
    }
1347
88
  }
1348
5
  else
1349
5
    InsertText(CID->getBeginLoc(), "// ");
1350
1351
104
  for (auto *OMD : 
IMD93
?
IMD->instance_methods()88
:
CID->instance_methods()5
) {
1352
104
    if (!OMD->getBody())
1353
48
      continue;
1354
56
    std::string ResultStr;
1355
56
    RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1356
56
    SourceLocation LocStart = OMD->getBeginLoc();
1357
56
    SourceLocation LocEnd = OMD->getCompoundBody()->getBeginLoc();
1358
1359
56
    const char *startBuf = SM->getCharacterData(LocStart);
1360
56
    const char *endBuf = SM->getCharacterData(LocEnd);
1361
56
    ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1362
56
  }
1363
1364
93
  for (auto *OMD : IMD ? 
IMD->class_methods()88
:
CID->class_methods()5
) {
1365
9
    if (!OMD->getBody())
1366
0
      continue;
1367
9
    std::string ResultStr;
1368
9
    RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1369
9
    SourceLocation LocStart = OMD->getBeginLoc();
1370
9
    SourceLocation LocEnd = OMD->getCompoundBody()->getBeginLoc();
1371
1372
9
    const char *startBuf = SM->getCharacterData(LocStart);
1373
9
    const char *endBuf = SM->getCharacterData(LocEnd);
1374
9
    ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1375
9
  }
1376
93
  for (auto *I : IMD ? 
IMD->property_impls()88
:
CID->property_impls()5
)
1377
31
    RewritePropertyImplDecl(I, IMD, CID);
1378
1379
93
  InsertText(IMD ? 
IMD->getEndLoc()88
:
CID->getEndLoc()5
, "// ");
1380
93
}
1381
1382
183
void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
1383
  // Do not synthesize more than once.
1384
183
  if (ObjCSynthesizedStructs.count(ClassDecl))
1385
9
    return;
1386
  // Make sure super class's are written before current class is written.
1387
174
  ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1388
205
  while (SuperClass) {
1389
31
    RewriteInterfaceDecl(SuperClass);
1390
31
    SuperClass = SuperClass->getSuperClass();
1391
31
  }
1392
174
  std::string ResultStr;
1393
174
  if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
1394
    // we haven't seen a forward decl - generate a typedef.
1395
152
    RewriteOneForwardClassDecl(ClassDecl, ResultStr);
1396
152
    RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1397
1398
152
    RewriteObjCInternalStruct(ClassDecl, ResultStr);
1399
    // Mark this typedef as having been written into its c++ equivalent.
1400
152
    ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
1401
1402
152
    for (auto *I : ClassDecl->instance_properties())
1403
31
      RewriteProperty(I);
1404
152
    for (auto *I : ClassDecl->instance_methods())
1405
108
      RewriteMethodDeclaration(I);
1406
152
    for (auto *I : ClassDecl->class_methods())
1407
80
      RewriteMethodDeclaration(I);
1408
1409
    // Lastly, comment out the @end.
1410
152
    ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1411
152
                "/* @end */\n");
1412
152
  }
1413
174
}
1414
1415
13
Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1416
13
  SourceRange OldRange = PseudoOp->getSourceRange();
1417
1418
  // We just magically know some things about the structure of this
1419
  // expression.
1420
13
  ObjCMessageExpr *OldMsg =
1421
13
    cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1422
13
                            PseudoOp->getNumSemanticExprs() - 1));
1423
1424
  // Because the rewriter doesn't allow us to rewrite rewritten code,
1425
  // we need to suppress rewriting the sub-statements.
1426
13
  Expr *Base;
1427
13
  SmallVector<Expr*, 2> Args;
1428
13
  {
1429
13
    DisableReplaceStmtScope S(*this);
1430
1431
    // Rebuild the base expression if we have one.
1432
13
    Base = nullptr;
1433
13
    if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1434
13
      Base = OldMsg->getInstanceReceiver();
1435
13
      Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1436
13
      Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1437
13
    }
1438
1439
13
    unsigned numArgs = OldMsg->getNumArgs();
1440
29
    for (unsigned i = 0; i < numArgs; 
i++16
) {
1441
16
      Expr *Arg = OldMsg->getArg(i);
1442
16
      if (isa<OpaqueValueExpr>(Arg))
1443
13
        Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1444
16
      Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1445
16
      Args.push_back(Arg);
1446
16
    }
1447
13
  }
1448
1449
  // TODO: avoid this copy.
1450
13
  SmallVector<SourceLocation, 1> SelLocs;
1451
13
  OldMsg->getSelectorLocs(SelLocs);
1452
1453
13
  ObjCMessageExpr *NewMsg = nullptr;
1454
13
  switch (OldMsg->getReceiverKind()) {
1455
0
  case ObjCMessageExpr::Class:
1456
0
    NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1457
0
                                     OldMsg->getValueKind(),
1458
0
                                     OldMsg->getLeftLoc(),
1459
0
                                     OldMsg->getClassReceiverTypeInfo(),
1460
0
                                     OldMsg->getSelector(),
1461
0
                                     SelLocs,
1462
0
                                     OldMsg->getMethodDecl(),
1463
0
                                     Args,
1464
0
                                     OldMsg->getRightLoc(),
1465
0
                                     OldMsg->isImplicit());
1466
0
    break;
1467
1468
13
  case ObjCMessageExpr::Instance:
1469
13
    NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1470
13
                                     OldMsg->getValueKind(),
1471
13
                                     OldMsg->getLeftLoc(),
1472
13
                                     Base,
1473
13
                                     OldMsg->getSelector(),
1474
13
                                     SelLocs,
1475
13
                                     OldMsg->getMethodDecl(),
1476
13
                                     Args,
1477
13
                                     OldMsg->getRightLoc(),
1478
13
                                     OldMsg->isImplicit());
1479
13
    break;
1480
1481
0
  case ObjCMessageExpr::SuperClass:
1482
0
  case ObjCMessageExpr::SuperInstance:
1483
0
    NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1484
0
                                     OldMsg->getValueKind(),
1485
0
                                     OldMsg->getLeftLoc(),
1486
0
                                     OldMsg->getSuperLoc(),
1487
0
                 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1488
0
                                     OldMsg->getSuperType(),
1489
0
                                     OldMsg->getSelector(),
1490
0
                                     SelLocs,
1491
0
                                     OldMsg->getMethodDecl(),
1492
0
                                     Args,
1493
0
                                     OldMsg->getRightLoc(),
1494
0
                                     OldMsg->isImplicit());
1495
0
    break;
1496
13
  }
1497
1498
13
  Stmt *Replacement = SynthMessageExpr(NewMsg);
1499
13
  ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1500
13
  return Replacement;
1501
13
}
1502
1503
20
Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1504
20
  SourceRange OldRange = PseudoOp->getSourceRange();
1505
1506
  // We just magically know some things about the structure of this
1507
  // expression.
1508
20
  ObjCMessageExpr *OldMsg =
1509
20
    cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1510
1511
  // Because the rewriter doesn't allow us to rewrite rewritten code,
1512
  // we need to suppress rewriting the sub-statements.
1513
20
  Expr *Base = nullptr;
1514
20
  SmallVector<Expr*, 1> Args;
1515
20
  {
1516
20
    DisableReplaceStmtScope S(*this);
1517
    // Rebuild the base expression if we have one.
1518
20
    if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1519
20
      Base = OldMsg->getInstanceReceiver();
1520
20
      Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1521
20
      Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1522
20
    }
1523
20
    unsigned numArgs = OldMsg->getNumArgs();
1524
23
    for (unsigned i = 0; i < numArgs; 
i++3
) {
1525
3
      Expr *Arg = OldMsg->getArg(i);
1526
3
      if (isa<OpaqueValueExpr>(Arg))
1527
0
        Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1528
3
      Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1529
3
      Args.push_back(Arg);
1530
3
    }
1531
20
  }
1532
1533
  // Intentionally empty.
1534
20
  SmallVector<SourceLocation, 1> SelLocs;
1535
1536
20
  ObjCMessageExpr *NewMsg = nullptr;
1537
20
  switch (OldMsg->getReceiverKind()) {
1538
0
  case ObjCMessageExpr::Class:
1539
0
    NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1540
0
                                     OldMsg->getValueKind(),
1541
0
                                     OldMsg->getLeftLoc(),
1542
0
                                     OldMsg->getClassReceiverTypeInfo(),
1543
0
                                     OldMsg->getSelector(),
1544
0
                                     SelLocs,
1545
0
                                     OldMsg->getMethodDecl(),
1546
0
                                     Args,
1547
0
                                     OldMsg->getRightLoc(),
1548
0
                                     OldMsg->isImplicit());
1549
0
    break;
1550
1551
20
  case ObjCMessageExpr::Instance:
1552
20
    NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1553
20
                                     OldMsg->getValueKind(),
1554
20
                                     OldMsg->getLeftLoc(),
1555
20
                                     Base,
1556
20
                                     OldMsg->getSelector(),
1557
20
                                     SelLocs,
1558
20
                                     OldMsg->getMethodDecl(),
1559
20
                                     Args,
1560
20
                                     OldMsg->getRightLoc(),
1561
20
                                     OldMsg->isImplicit());
1562
20
    break;
1563
1564
0
  case ObjCMessageExpr::SuperClass:
1565
0
  case ObjCMessageExpr::SuperInstance:
1566
0
    NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1567
0
                                     OldMsg->getValueKind(),
1568
0
                                     OldMsg->getLeftLoc(),
1569
0
                                     OldMsg->getSuperLoc(),
1570
0
                 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1571
0
                                     OldMsg->getSuperType(),
1572
0
                                     OldMsg->getSelector(),
1573
0
                                     SelLocs,
1574
0
                                     OldMsg->getMethodDecl(),
1575
0
                                     Args,
1576
0
                                     OldMsg->getRightLoc(),
1577
0
                                     OldMsg->isImplicit());
1578
0
    break;
1579
20
  }
1580
1581
20
  Stmt *Replacement = SynthMessageExpr(NewMsg);
1582
20
  ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1583
20
  return Replacement;
1584
20
}
1585
1586
/// SynthCountByEnumWithState - To print:
1587
/// ((NSUInteger (*)
1588
///  (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
1589
///  (void *)objc_msgSend)((id)l_collection,
1590
///                        sel_registerName(
1591
///                          "countByEnumeratingWithState:objects:count:"),
1592
///                        &enumState,
1593
///                        (id *)__rw_items, (NSUInteger)16)
1594
///
1595
10
void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1596
10
  buf += "((_WIN_NSUInteger (*) (id, SEL, struct __objcFastEnumerationState *, "
1597
10
  "id *, _WIN_NSUInteger))(void *)objc_msgSend)";
1598
10
  buf += "\n\t\t";
1599
10
  buf += "((id)l_collection,\n\t\t";
1600
10
  buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1601
10
  buf += "\n\t\t";
1602
10
  buf += "&enumState, "
1603
10
         "(id *)__rw_items, (_WIN_NSUInteger)16)";
1604
10
}
1605
1606
/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1607
/// statement to exit to its outer synthesized loop.
1608
///
1609
5
Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1610
5
  if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1611
5
    return S;
1612
  // replace break with goto __break_label
1613
0
  std::string buf;
1614
1615
0
  SourceLocation startLoc = S->getBeginLoc();
1616
0
  buf = "goto __break_label_";
1617
0
  buf += utostr(ObjCBcLabelNo.back());
1618
0
  ReplaceText(startLoc, strlen("break"), buf);
1619
1620
0
  return nullptr;
1621
5
}
1622
1623
void RewriteModernObjC::ConvertSourceLocationToLineDirective(
1624
                                          SourceLocation Loc,
1625
117
                                          std::string &LineString) {
1626
117
  if (Loc.isFileID() && GenerateLineInfo) {
1627
1
    LineString += "\n#line ";
1628
1
    PresumedLoc PLoc = SM->getPresumedLoc(Loc);
1629
1
    LineString += utostr(PLoc.getLine());
1630
1
    LineString += " \"";
1631
1
    LineString += Lexer::Stringify(PLoc.getFilename());
1632
1
    LineString += "\"\n";
1633
1
  }
1634
117
}
1635
1636
/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1637
/// statement to continue with its inner synthesized loop.
1638
///
1639
0
Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1640
0
  if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1641
0
    return S;
1642
  // replace continue with goto __continue_label
1643
0
  std::string buf;
1644
1645
0
  SourceLocation startLoc = S->getBeginLoc();
1646
0
  buf = "goto __continue_label_";
1647
0
  buf += utostr(ObjCBcLabelNo.back());
1648
0
  ReplaceText(startLoc, strlen("continue"), buf);
1649
1650
0
  return nullptr;
1651
0
}
1652
1653
/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1654
///  It rewrites:
1655
/// for ( type elem in collection) { stmts; }
1656
1657
/// Into:
1658
/// {
1659
///   type elem;
1660
///   struct __objcFastEnumerationState enumState = { 0 };
1661
///   id __rw_items[16];
1662
///   id l_collection = (id)collection;
1663
///   NSUInteger limit = [l_collection countByEnumeratingWithState:&enumState
1664
///                                       objects:__rw_items count:16];
1665
/// if (limit) {
1666
///   unsigned long startMutations = *enumState.mutationsPtr;
1667
///   do {
1668
///        unsigned long counter = 0;
1669
///        do {
1670
///             if (startMutations != *enumState.mutationsPtr)
1671
///               objc_enumerationMutation(l_collection);
1672
///             elem = (type)enumState.itemsPtr[counter++];
1673
///             stmts;
1674
///             __continue_label: ;
1675
///        } while (counter < limit);
1676
///   } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1677
///                                  objects:__rw_items count:16]));
1678
///   elem = nil;
1679
///   __break_label: ;
1680
///  }
1681
///  else
1682
///       elem = nil;
1683
///  }
1684
///
1685
Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1686
5
                                                SourceLocation OrigEnd) {
1687
5
  assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1688
0
  assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1689
5
         "ObjCForCollectionStmt Statement stack mismatch");
1690
0
  assert(!ObjCBcLabelNo.empty() &&
1691
5
         "ObjCForCollectionStmt - Label No stack empty");
1692
1693
0
  SourceLocation startLoc = S->getBeginLoc();
1694
5
  const char *startBuf = SM->getCharacterData(startLoc);
1695
5
  StringRef elementName;
1696
5
  std::string elementTypeAsString;
1697
5
  std::string buf;
1698
  // line directive first.
1699
5
  SourceLocation ForEachLoc = S->getForLoc();
1700
5
  ConvertSourceLocationToLineDirective(ForEachLoc, buf);
1701
5
  buf += "{\n\t";
1702
5
  if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1703
    // type elem;
1704
5
    NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1705
5
    QualType ElementType = cast<ValueDecl>(D)->getType();
1706
5
    if (ElementType->isObjCQualifiedIdType() ||
1707
5
        ElementType->isObjCQualifiedInterfaceType())
1708
      // Simply use 'id' for all qualified types.
1709
0
      elementTypeAsString = "id";
1710
5
    else
1711
5
      elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1712
5
    buf += elementTypeAsString;
1713
5
    buf += " ";
1714
5
    elementName = D->getName();
1715
5
    buf += elementName;
1716
5
    buf += ";\n\t";
1717
5
  }
1718
0
  else {
1719
0
    DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1720
0
    elementName = DR->getDecl()->getName();
1721
0
    ValueDecl *VD = DR->getDecl();
1722
0
    if (VD->getType()->isObjCQualifiedIdType() ||
1723
0
        VD->getType()->isObjCQualifiedInterfaceType())
1724
      // Simply use 'id' for all qualified types.
1725
0
      elementTypeAsString = "id";
1726
0
    else
1727
0
      elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1728
0
  }
1729
1730
  // struct __objcFastEnumerationState enumState = { 0 };
1731
5
  buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1732
  // id __rw_items[16];
1733
5
  buf += "id __rw_items[16];\n\t";
1734
  // id l_collection = (id)
1735
5
  buf += "id l_collection = (id)";
1736
  // Find start location of 'collection' the hard way!
1737
5
  const char *startCollectionBuf = startBuf;
1738
5
  startCollectionBuf += 3;  // skip 'for'
1739
5
  startCollectionBuf = strchr(startCollectionBuf, '(');
1740
5
  startCollectionBuf++; // skip '('
1741
  // find 'in' and skip it.
1742
33
  while (*startCollectionBuf != ' ' ||
1743
33
         
*(startCollectionBuf+1) != 'i'10
||
*(startCollectionBuf+2) != 'n'5
||
1744
33
         
(5
*(startCollectionBuf+3) != ' '5
&&
1745
5
          
*(startCollectionBuf+3) != '['0
&&
*(startCollectionBuf+3) != '('0
))
1746
28
    startCollectionBuf++;
1747
5
  startCollectionBuf += 3;
1748
1749
  // Replace: "for (type element in" with string constructed thus far.
1750
5
  ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1751
  // Replace ')' in for '(' type elem in collection ')' with ';'
1752
5
  SourceLocation rightParenLoc = S->getRParenLoc();
1753
5
  const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1754
5
  SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1755
5
  buf = ";\n\t";
1756
1757
  // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1758
  //                                   objects:__rw_items count:16];
1759
  // which is synthesized into:
1760
  // NSUInteger limit =
1761
  // ((NSUInteger (*)
1762
  //  (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
1763
  //  (void *)objc_msgSend)((id)l_collection,
1764
  //                        sel_registerName(
1765
  //                          "countByEnumeratingWithState:objects:count:"),
1766
  //                        (struct __objcFastEnumerationState *)&state,
1767
  //                        (id *)__rw_items, (NSUInteger)16);
1768
5
  buf += "_WIN_NSUInteger limit =\n\t\t";
1769
5
  SynthCountByEnumWithState(buf);
1770
5
  buf += ";\n\t";
1771
  /// if (limit) {
1772
  ///   unsigned long startMutations = *enumState.mutationsPtr;
1773
  ///   do {
1774
  ///        unsigned long counter = 0;
1775
  ///        do {
1776
  ///             if (startMutations != *enumState.mutationsPtr)
1777
  ///               objc_enumerationMutation(l_collection);
1778
  ///             elem = (type)enumState.itemsPtr[counter++];
1779
5
  buf += "if (limit) {\n\t";
1780
5
  buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1781
5
  buf += "do {\n\t\t";
1782
5
  buf += "unsigned long counter = 0;\n\t\t";
1783
5
  buf += "do {\n\t\t\t";
1784
5
  buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1785
5
  buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1786
5
  buf += elementName;
1787
5
  buf += " = (";
1788
5
  buf += elementTypeAsString;
1789
5
  buf += ")enumState.itemsPtr[counter++];";
1790
  // Replace ')' in for '(' type elem in collection ')' with all of these.
1791
5
  ReplaceText(lparenLoc, 1, buf);
1792
1793
  ///            __continue_label: ;
1794
  ///        } while (counter < limit);
1795
  ///   } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1796
  ///                                  objects:__rw_items count:16]));
1797
  ///   elem = nil;
1798
  ///   __break_label: ;
1799
  ///  }
1800
  ///  else
1801
  ///       elem = nil;
1802
  ///  }
1803
  ///
1804
5
  buf = ";\n\t";
1805
5
  buf += "__continue_label_";
1806
5
  buf += utostr(ObjCBcLabelNo.back());
1807
5
  buf += ": ;";
1808
5
  buf += "\n\t\t";
1809
5
  buf += "} while (counter < limit);\n\t";
1810
5
  buf += "} while ((limit = ";
1811
5
  SynthCountByEnumWithState(buf);
1812
5
  buf += "));\n\t";
1813
5
  buf += elementName;
1814
5
  buf += " = ((";
1815
5
  buf += elementTypeAsString;
1816
5
  buf += ")0);\n\t";
1817
5
  buf += "__break_label_";
1818
5
  buf += utostr(ObjCBcLabelNo.back());
1819
5
  buf += ": ;\n\t";
1820
5
  buf += "}\n\t";
1821
5
  buf += "else\n\t\t";
1822
5
  buf += elementName;
1823
5
  buf += " = ((";
1824
5
  buf += elementTypeAsString;
1825
5
  buf += ")0);\n\t";
1826
5
  buf += "}\n";
1827
1828
  // Insert all these *after* the statement body.
1829
  // FIXME: If this should support Obj-C++, support CXXTryStmt
1830
5
  if (isa<CompoundStmt>(S->getBody())) {
1831
5
    SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1832
5
    InsertText(endBodyLoc, buf);
1833
5
  } else {
1834
    /* Need to treat single statements specially. For example:
1835
     *
1836
     *     for (A *a in b) if (stuff()) break;
1837
     *     for (A *a in b) xxxyy;
1838
     *
1839
     * The following code simply scans ahead to the semi to find the actual end.
1840
     */
1841
0
    const char *stmtBuf = SM->getCharacterData(OrigEnd);
1842
0
    const char *semiBuf = strchr(stmtBuf, ';');
1843
0
    assert(semiBuf && "Can't find ';'");
1844
0
    SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1845
0
    InsertText(endBodyLoc, buf);
1846
0
  }
1847
0
  Stmts.pop_back();
1848
5
  ObjCBcLabelNo.pop_back();
1849
5
  return nullptr;
1850
5
}
1851
1852
12
static void Write_RethrowObject(std::string &buf) {
1853
12
  buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1854
12
  buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1855
12
  buf += "\tid rethrow;\n";
1856
12
  buf += "\t} _fin_force_rethow(_rethrow);";
1857
12
}
1858
1859
/// RewriteObjCSynchronizedStmt -
1860
/// This routine rewrites @synchronized(expr) stmt;
1861
/// into:
1862
/// objc_sync_enter(expr);
1863
/// @try stmt @finally { objc_sync_exit(expr); }
1864
///
1865
4
Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1866
  // Get the start location and compute the semi location.
1867
4
  SourceLocation startLoc = S->getBeginLoc();
1868
4
  const char *startBuf = SM->getCharacterData(startLoc);
1869
1870
4
  assert((*startBuf == '@') && "bogus @synchronized location");
1871
1872
0
  std::string buf;
1873
4
  SourceLocation SynchLoc = S->getAtSynchronizedLoc();
1874
4
  ConvertSourceLocationToLineDirective(SynchLoc, buf);
1875
4
  buf += "{ id _rethrow = 0; id _sync_obj = (id)";
1876
1877
4
  const char *lparenBuf = startBuf;
1878
59
  while (*lparenBuf != '(') 
lparenBuf++55
;
1879
4
  ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
1880
1881
4
  buf = "; objc_sync_enter(_sync_obj);\n";
1882
4
  buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1883
4
  buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1884
4
  buf += "\n\tid sync_exit;";
1885
4
  buf += "\n\t} _sync_exit(_sync_obj);\n";
1886
1887
  // We can't use S->getSynchExpr()->getEndLoc() to find the end location, since
1888
  // the sync expression is typically a message expression that's already
1889
  // been rewritten! (which implies the SourceLocation's are invalid).
1890
4
  SourceLocation RParenExprLoc = S->getSynchBody()->getBeginLoc();
1891
4
  const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1892
12
  while (*RParenExprLocBuf != ')') 
RParenExprLocBuf--8
;
1893
4
  RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1894
1895
4
  SourceLocation LBranceLoc = S->getSynchBody()->getBeginLoc();
1896
4
  const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1897
4
  assert (*LBraceLocBuf == '{');
1898
0
  ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
1899
1900
4
  SourceLocation startRBraceLoc = S->getSynchBody()->getEndLoc();
1901
4
  assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1902
4
         "bogus @synchronized block");
1903
1904
0
  buf = "} catch (id e) {_rethrow = e;}\n";
1905
4
  Write_RethrowObject(buf);
1906
4
  buf += "}\n";
1907
4
  buf += "}\n";
1908
1909
4
  ReplaceText(startRBraceLoc, 1, buf);
1910
1911
4
  return nullptr;
1912
4
}
1913
1914
void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1915
33
{
1916
  // Perform a bottom up traversal of all children.
1917
33
  for (Stmt *SubStmt : S->children())
1918
25
    if (SubStmt)
1919
25
      WarnAboutReturnGotoStmts(SubStmt);
1920
1921
33
  if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1922
0
    Diags.Report(Context->getFullLoc(S->getBeginLoc()),
1923
0
                 TryFinallyContainsReturnDiag);
1924
0
  }
1925
33
}
1926
1927
1
Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt  *S) {
1928
1
  SourceLocation startLoc = S->getAtLoc();
1929
1
  ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
1930
1
  ReplaceText(S->getSubStmt()->getBeginLoc(), 1,
1931
1
              "{ __AtAutoreleasePool __autoreleasepool; ");
1932
1933
1
  return nullptr;
1934
1
}
1935
1936
14
Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
1937
14
  ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
1938
14
  bool noCatch = S->getNumCatchStmts() == 0;
1939
14
  std::string buf;
1940
14
  SourceLocation TryLocation = S->getAtTryLoc();
1941
14
  ConvertSourceLocationToLineDirective(TryLocation, buf);
1942
1943
14
  if (finalStmt) {
1944
8
    if (noCatch)
1945
7
      buf += "{ id volatile _rethrow = 0;\n";
1946
1
    else {
1947
1
      buf += "{ id volatile _rethrow = 0;\ntry {\n";
1948
1
    }
1949
8
  }
1950
  // Get the start location and compute the semi location.
1951
14
  SourceLocation startLoc = S->getBeginLoc();
1952
14
  const char *startBuf = SM->getCharacterData(startLoc);
1953
1954
14
  assert((*startBuf == '@') && "bogus @try location");
1955
14
  if (finalStmt)
1956
8
    ReplaceText(startLoc, 1, buf);
1957
6
  else
1958
    // @try -> try
1959
6
    ReplaceText(startLoc, 1, "");
1960
1961
14
  for (ObjCAtCatchStmt *Catch : S->catch_stmts()) {
1962
11
    VarDecl *catchDecl = Catch->getCatchParamDecl();
1963
1964
11
    startLoc = Catch->getBeginLoc();
1965
11
    bool AtRemoved = false;
1966
11
    if (catchDecl) {
1967
8
      QualType t = catchDecl->getType();
1968
8
      if (const ObjCObjectPointerType *Ptr =
1969
8
              t->getAs<ObjCObjectPointerType>()) {
1970
        // Should be a pointer to a class.
1971
8
        ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1972
8
        if (IDecl) {
1973
6
          std::string Result;
1974
6
          ConvertSourceLocationToLineDirective(Catch->getBeginLoc(), Result);
1975
1976
6
          startBuf = SM->getCharacterData(startLoc);
1977
6
          assert((*startBuf == '@') && "bogus @catch location");
1978
0
          SourceLocation rParenLoc = Catch->getRParenLoc();
1979
6
          const char *rParenBuf = SM->getCharacterData(rParenLoc);
1980
1981
          // _objc_exc_Foo *_e as argument to catch.
1982
6
          Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString();
1983
6
          Result += " *_"; Result += catchDecl->getNameAsString();
1984
6
          Result += ")";
1985
6
          ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1986
          // Foo *e = (Foo *)_e;
1987
6
          Result.clear();
1988
6
          Result = "{ ";
1989
6
          Result += IDecl->getNameAsString();
1990
6
          Result += " *"; Result += catchDecl->getNameAsString();
1991
6
          Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1992
6
          Result += "_"; Result += catchDecl->getNameAsString();
1993
1994
6
          Result += "; ";
1995
6
          SourceLocation lBraceLoc = Catch->getCatchBody()->getBeginLoc();
1996
6
          ReplaceText(lBraceLoc, 1, Result);
1997
6
          AtRemoved = true;
1998
6
        }
1999
8
      }
2000
8
    }
2001
11
    if (!AtRemoved)
2002
      // @catch -> catch
2003
5
      ReplaceText(startLoc, 1, "");
2004
2005
11
  }
2006
14
  if (finalStmt) {
2007
8
    buf.clear();
2008
8
    SourceLocation FinallyLoc = finalStmt->getBeginLoc();
2009
2010
8
    if (noCatch) {
2011
7
      ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2012
7
      buf += "catch (id e) {_rethrow = e;}\n";
2013
7
    }
2014
1
    else {
2015
1
      buf += "}\n";
2016
1
      ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2017
1
      buf += "catch (id e) {_rethrow = e;}\n";
2018
1
    }
2019
2020
8
    SourceLocation startFinalLoc = finalStmt->getBeginLoc();
2021
8
    ReplaceText(startFinalLoc, 8, buf);
2022
8
    Stmt *body = finalStmt->getFinallyBody();
2023
8
    SourceLocation startFinalBodyLoc = body->getBeginLoc();
2024
8
    buf.clear();
2025
8
    Write_RethrowObject(buf);
2026
8
    ReplaceText(startFinalBodyLoc, 1, buf);
2027
2028
8
    SourceLocation endFinalBodyLoc = body->getEndLoc();
2029
8
    ReplaceText(endFinalBodyLoc, 1, "}\n}");
2030
    // Now check for any return/continue/go statements within the @try.
2031
8
    WarnAboutReturnGotoStmts(S->getTryBody());
2032
8
  }
2033
2034
14
  return nullptr;
2035
14
}
2036
2037
// This can't be done with ReplaceStmt(S, ThrowExpr), since
2038
// the throw expression is typically a message expression that's already
2039
// been rewritten! (which implies the SourceLocation's are invalid).
2040
5
Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
2041
  // Get the start location and compute the semi location.
2042
5
  SourceLocation startLoc = S->getBeginLoc();
2043
5
  const char *startBuf = SM->getCharacterData(startLoc);
2044
2045
5
  assert((*startBuf == '@') && "bogus @throw location");
2046
2047
0
  std::string buf;
2048
  /* void objc_exception_throw(id) __attribute__((noreturn)); */
2049
5
  if (S->getThrowExpr())
2050
4
    buf = "objc_exception_throw(";
2051
1
  else
2052
1
    buf = "throw";
2053
2054
  // handle "@  throw" correctly.
2055
5
  const char *wBuf = strchr(startBuf, 'w');
2056
5
  assert((*wBuf == 'w') && "@throw: can't find 'w'");
2057
0
  ReplaceText(startLoc, wBuf-startBuf+1, buf);
2058
2059
5
  SourceLocation endLoc = S->getEndLoc();
2060
5
  const char *endBuf = SM->getCharacterData(endLoc);
2061
5
  const char *semiBuf = strchr(endBuf, ';');
2062
5
  assert((*semiBuf == ';') && "@throw: can't find ';'");
2063
0
  SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
2064
5
  if (S->getThrowExpr())
2065
4
    ReplaceText(semiLoc, 1, ");");
2066
5
  return nullptr;
2067
5
}
2068
2069
3
Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2070
  // Create a new string expression.
2071
3
  std::string StrEncoding;
2072
3
  Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
2073
3
  Expr *Replacement = getStringLiteral(StrEncoding);
2074
3
  ReplaceStmt(Exp, Replacement);
2075
2076
  // Replace this subexpr in the parent.
2077
  // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2078
3
  return Replacement;
2079
3
}
2080
2081
0
Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2082
0
  if (!SelGetUidFunctionDecl)
2083
0
    SynthSelGetUidFunctionDecl();
2084
0
  assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2085
  // Create a call to sel_registerName("selName").
2086
0
  SmallVector<Expr*, 8> SelExprs;
2087
0
  SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
2088
0
  CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2089
0
                                                  SelExprs);
2090
0
  ReplaceStmt(Exp, SelExp);
2091
  // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2092
0
  return SelExp;
2093
0
}
2094
2095
CallExpr *
2096
RewriteModernObjC::SynthesizeCallToFunctionDecl(FunctionDecl *FD,
2097
                                                ArrayRef<Expr *> Args,
2098
                                                SourceLocation StartLoc,
2099
215
                                                SourceLocation EndLoc) {
2100
  // Get the type, we will need to reference it in a couple spots.
2101
215
  QualType msgSendType = FD->getType();
2102
2103
  // Create a reference to the objc_msgSend() declaration.
2104
215
  DeclRefExpr *DRE = new (Context) DeclRefExpr(*Context, FD, false, msgSendType,
2105
215
                                               VK_LValue, SourceLocation());
2106
2107
  // Now, we cast the reference to a pointer to the objc_msgSend type.
2108
215
  QualType pToFunc = Context->getPointerType(msgSendType);
2109
215
  ImplicitCastExpr *ICE =
2110
215
      ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2111
215
                               DRE, nullptr, VK_PRValue, FPOptionsOverride());
2112
2113
215
  const auto *FT = msgSendType->castAs<FunctionType>();
2114
215
  CallExpr *Exp =
2115
215
      CallExpr::Create(*Context, ICE, Args, FT->getCallResultType(*Context),
2116
215
                       VK_PRValue, EndLoc, FPOptionsOverride());
2117
215
  return Exp;
2118
215
}
2119
2120
static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2121
6
                                const char *&startRef, const char *&endRef) {
2122
70
  while (startBuf < endBuf) {
2123
70
    if (*startBuf == '<')
2124
6
      startRef = startBuf; // mark the start.
2125
70
    if (*startBuf == '>') {
2126
6
      if (startRef && *startRef == '<') {
2127
6
        endRef = startBuf; // mark the end.
2128
6
        return true;
2129
6
      }
2130
0
      return false;
2131
6
    }
2132
64
    startBuf++;
2133
64
  }
2134
0
  return false;
2135
6
}
2136
2137
0
static void scanToNextArgument(const char *&argRef) {
2138
0
  int angle = 0;
2139
0
  while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2140
0
    if (*argRef == '<')
2141
0
      angle++;
2142
0
    else if (*argRef == '>')
2143
0
      angle--;
2144
0
    argRef++;
2145
0
  }
2146
0
  assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2147
0
}
2148
2149
568
bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2150
568
  if (T->isObjCQualifiedIdType())
2151
2
    return true;
2152
566
  if (const PointerType *PT = T->getAs<PointerType>()) {
2153
70
    if (PT->getPointeeType()->isObjCQualifiedIdType())
2154
0
      return true;
2155
70
  }
2156
566
  if (T->isObjCObjectPointerType()) {
2157
132
    T = T->getPointeeType();
2158
132
    return T->isObjCQualifiedInterfaceType();
2159
132
  }
2160
434
  if (T->isArrayType()) {
2161
0
    QualType ElemTy = Context->getBaseElementType(T);
2162
0
    return needToScanForQualifiers(ElemTy);
2163
0
  }
2164
434
  return false;
2165
434
}
2166
2167
30
void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2168
30
  QualType Type = E->getType();
2169
30
  if (needToScanForQualifiers(Type)) {
2170
1
    SourceLocation Loc, EndLoc;
2171
2172
1
    if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2173
1
      Loc = ECE->getLParenLoc();
2174
1
      EndLoc = ECE->getRParenLoc();
2175
1
    } else {
2176
0
      Loc = E->getBeginLoc();
2177
0
      EndLoc = E->getEndLoc();
2178
0
    }
2179
    // This will defend against trying to rewrite synthesized expressions.
2180
1
    if (Loc.isInvalid() || EndLoc.isInvalid())
2181
0
      return;
2182
2183
1
    const char *startBuf = SM->getCharacterData(Loc);
2184
1
    const char *endBuf = SM->getCharacterData(EndLoc);
2185
1
    const char *startRef = nullptr, *endRef = nullptr;
2186
1
    if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2187
      // Get the locations of the startRef, endRef.
2188
1
      SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2189
1
      SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2190
      // Comment out the protocol references.
2191
1
      InsertText(LessLoc, "/*");
2192
1
      InsertText(GreaterLoc, "*/");
2193
1
    }
2194
1
  }
2195
30
}
2196
2197
425
void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2198
425
  SourceLocation Loc;
2199
425
  QualType Type;
2200
425
  const FunctionProtoType *proto = nullptr;
2201
425
  if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2202
193
    Loc = VD->getLocation();
2203
193
    Type = VD->getType();
2204
193
  }
2205
232
  else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2206
163
    Loc = FD->getLocation();
2207
    // Check for ObjC 'id' and class types that have been adorned with protocol
2208
    // information (id<p>, C<p>*). The protocol references need to be rewritten!
2209
163
    const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2210
163
    assert(funcType && "missing function type");
2211
0
    proto = dyn_cast<FunctionProtoType>(funcType);
2212
163
    if (!proto)
2213
0
      return;
2214
163
    Type = proto->getReturnType();
2215
163
  }
2216
69
  else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2217
0
    Loc = FD->getLocation();
2218
0
    Type = FD->getType();
2219
0
  }
2220
69
  else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Dcl)) {
2221
69
    Loc = TD->getLocation();
2222
69
    Type = TD->getUnderlyingType();
2223
69
  }
2224
0
  else
2225
0
    return;
2226
2227
425
  if (needToScanForQualifiers(Type)) {
2228
    // Since types are unique, we need to scan the buffer.
2229
2230
5
    const char *endBuf = SM->getCharacterData(Loc);
2231
5
    const char *startBuf = endBuf;
2232
72
    while (*startBuf != ';' && *startBuf != '<' && 
startBuf != MainFileStart67
)
2233
67
      startBuf--; // scan backward (from the decl location) for return type.
2234
5
    const char *startRef = nullptr, *endRef = nullptr;
2235
5
    if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2236
      // Get the locations of the startRef, endRef.
2237
5
      SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2238
5
      SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2239
      // Comment out the protocol references.
2240
5
      InsertText(LessLoc, "/*");
2241
5
      InsertText(GreaterLoc, "*/");
2242
5
    }
2243
5
  }
2244
425
  if (!proto)
2245
262
      return; // most likely, was a variable
2246
  // Now check arguments.
2247
163
  const char *startBuf = SM->getCharacterData(Loc);
2248
163
  const char *startFuncBuf = startBuf;
2249
248
  for (unsigned i = 0; i < proto->getNumParams(); 
i++85
) {
2250
85
    if (needToScanForQualifiers(proto->getParamType(i))) {
2251
      // Since types are unique, we need to scan the buffer.
2252
2253
0
      const char *endBuf = startBuf;
2254
      // scan forward (from the decl location) for argument types.
2255
0
      scanToNextArgument(endBuf);
2256
0
      const char *startRef = nullptr, *endRef = nullptr;
2257
0
      if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2258
        // Get the locations of the startRef, endRef.
2259
0
        SourceLocation LessLoc =
2260
0
          Loc.getLocWithOffset(startRef-startFuncBuf);
2261
0
        SourceLocation GreaterLoc =
2262
0
          Loc.getLocWithOffset(endRef-startFuncBuf+1);
2263
        // Comment out the protocol references.
2264
0
        InsertText(LessLoc, "/*");
2265
0
        InsertText(GreaterLoc, "*/");
2266
0
      }
2267
0
      startBuf = ++endBuf;
2268
0
    }
2269
85
    else {
2270
      // If the function name is derived from a macro expansion, then the
2271
      // argument buffer will not follow the name. Need to speak with Chris.
2272
1.41k
      while (*startBuf && *startBuf != ')' && 
*startBuf != ','1.34k
)
2273
1.32k
        startBuf++; // scan forward (from the decl location) for argument types.
2274
85
      startBuf++;
2275
85
    }
2276
85
  }
2277
163
}
2278
2279
146
void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2280
146
  QualType QT = ND->getType();
2281
146
  const Type* TypePtr = QT->getAs<Type>();
2282
146
  if (!isa<TypeOfExprType>(TypePtr))
2283
143
    return;
2284
9
  
while (3
isa<TypeOfExprType>(TypePtr)) {
2285
6
    const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2286
6
    QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2287
6
    TypePtr = QT->getAs<Type>();
2288
6
  }
2289
  // FIXME. This will not work for multiple declarators; as in:
2290
  // __typeof__(a) b,c,d;
2291
3
  std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2292
3
  SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2293
3
  const char *startBuf = SM->getCharacterData(DeclLoc);
2294
3
  if (ND->getInit()) {
2295
2
    std::string Name(ND->getNameAsString());
2296
2
    TypeAsString += " " + Name + " = ";
2297
2
    Expr *E = ND->getInit();
2298
2
    SourceLocation startLoc;
2299
2
    if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2300
0
      startLoc = ECE->getLParenLoc();
2301
2
    else
2302
2
      startLoc = E->getBeginLoc();
2303
2
    startLoc = SM->getExpansionLoc(startLoc);
2304
2
    const char *endBuf = SM->getCharacterData(startLoc);
2305
2
    ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2306
2
  }
2307
1
  else {
2308
1
    SourceLocation X = ND->getEndLoc();
2309
1
    X = SM->getExpansionLoc(X);
2310
1
    const char *endBuf = SM->getCharacterData(X);
2311
1
    ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2312
1
  }
2313
3
}
2314
2315
// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2316
3
void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2317
3
  IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2318
3
  SmallVector<QualType, 16> ArgTys;
2319
3
  ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2320
3
  QualType getFuncType =
2321
3
    getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
2322
3
  SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2323
3
                                               SourceLocation(),
2324
3
                                               SourceLocation(),
2325
3
                                               SelGetUidIdent, getFuncType,
2326
3
                                               nullptr, SC_Extern);
2327
3
}
2328
2329
192
void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2330
  // declared in <objc/objc.h>
2331
192
  if (FD->getIdentifier() &&
2332
192
      FD->getName() == "sel_registerName") {
2333
29
    SelGetUidFunctionDecl = FD;
2334
29
    return;
2335
29
  }
2336
163
  RewriteObjCQualifiedInterfaceTypes(FD);
2337
163
}
2338
2339
9
void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2340
9
  std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2341
9
  const char *argPtr = TypeString.c_str();
2342
9
  if (!strchr(argPtr, '^')) {
2343
1
    Str += TypeString;
2344
1
    return;
2345
1
  }
2346
116
  
while (8
*argPtr) {
2347
108
    Str += (*argPtr == '^' ? 
'*'8
:
*argPtr100
);
2348
108
    argPtr++;
2349
108
  }
2350
8
}
2351
2352
// FIXME. Consolidate this routine with RewriteBlockPointerType.
2353
void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2354
2
                                                  ValueDecl *VD) {
2355
2
  QualType Type = VD->getType();
2356
2
  std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2357
2
  const char *argPtr = TypeString.c_str();
2358
2
  int paren = 0;
2359
29
  while (*argPtr) {
2360
27
    switch (*argPtr) {
2361
4
      case '(':
2362
4
        Str += *argPtr;
2363
4
        paren++;
2364
4
        break;
2365
4
      case ')':
2366
4
        Str += *argPtr;
2367
4
        paren--;
2368
4
        break;
2369
2
      case '^':
2370
2
        Str += '*';
2371
2
        if (paren == 1)
2372
2
          Str += VD->getNameAsString();
2373
2
        break;
2374
17
      default:
2375
17
        Str += *argPtr;
2376
17
        break;
2377
27
    }
2378
27
    argPtr++;
2379
27
  }
2380
2
}
2381
2382
5
void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2383
5
  SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2384
5
  const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2385
5
  const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2386
5
  if (!proto)
2387
0
    return;
2388
5
  QualType Type = proto->getReturnType();
2389
5
  std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2390
5
  FdStr += " ";
2391
5
  FdStr += FD->getName();
2392
5
  FdStr +=  "(";
2393
5
  unsigned numArgs = proto->getNumParams();
2394
8
  for (unsigned i = 0; i < numArgs; 
i++3
) {
2395
3
    QualType ArgType = proto->getParamType(i);
2396
3
  RewriteBlockPointerType(FdStr, ArgType);
2397
3
  if (i+1 < numArgs)
2398
0
    FdStr += ", ";
2399
3
  }
2400
5
  if (FD->isVariadic()) {
2401
2
    FdStr +=  (numArgs > 0) ? 
", ...);\n"1
:
"...);\n"1
;
2402
2
  }
2403
3
  else
2404
3
    FdStr +=  ");\n";
2405
5
  InsertText(FunLocStart, FdStr);
2406
5
}
2407
2408
// SynthSuperConstructorFunctionDecl - id __rw_objc_super(id obj, id super);
2409
1
void RewriteModernObjC::SynthSuperConstructorFunctionDecl() {
2410
1
  if (SuperConstructorFunctionDecl)
2411
0
    return;
2412
1
  IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2413
1
  SmallVector<QualType, 16> ArgTys;
2414
1
  QualType argT = Context->getObjCIdType();
2415
1
  assert(!argT.isNull() && "Can't find 'id' type");
2416
0
  ArgTys.push_back(argT);
2417
1
  ArgTys.push_back(argT);
2418
1
  QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2419
1
                                               ArgTys);
2420
1
  SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2421
1
                                                     SourceLocation(),
2422
1
                                                     SourceLocation(),
2423
1
                                                     msgSendIdent, msgSendType,
2424
1
                                                     nullptr, SC_Extern);
2425
1
}
2426
2427
// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2428
29
void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2429
29
  IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2430
29
  SmallVector<QualType, 16> ArgTys;
2431
29
  QualType argT = Context->getObjCIdType();
2432
29
  assert(!argT.isNull() && "Can't find 'id' type");
2433
0
  ArgTys.push_back(argT);
2434
29
  argT = Context->getObjCSelType();
2435
29
  assert(!argT.isNull() && "Can't find 'SEL' type");
2436
0
  ArgTys.push_back(argT);
2437
29
  QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2438
29
                                               ArgTys, /*variadic=*/true);
2439
29
  MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2440
29
                                             SourceLocation(),
2441
29
                                             SourceLocation(),
2442
29
                                             msgSendIdent, msgSendType, nullptr,
2443
29
                                             SC_Extern);
2444
29
}
2445
2446
// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
2447
25
void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2448
25
  IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2449
25
  SmallVector<QualType, 2> ArgTys;
2450
25
  ArgTys.push_back(Context->VoidTy);
2451
25
  QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2452
25
                                               ArgTys, /*variadic=*/true);
2453
25
  MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2454
25
                                                  SourceLocation(),
2455
25
                                                  SourceLocation(),
2456
25
                                                  msgSendIdent, msgSendType,
2457
25
                                                  nullptr, SC_Extern);
2458
25
}
2459
2460
// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2461
25
void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2462
25
  IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2463
25
  SmallVector<QualType, 16> ArgTys;
2464
25
  QualType argT = Context->getObjCIdType();
2465
25
  assert(!argT.isNull() && "Can't find 'id' type");
2466
0
  ArgTys.push_back(argT);
2467
25
  argT = Context->getObjCSelType();
2468
25
  assert(!argT.isNull() && "Can't find 'SEL' type");
2469
0
  ArgTys.push_back(argT);
2470
25
  QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2471
25
                                               ArgTys, /*variadic=*/true);
2472
25
  MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2473
25
                                                  SourceLocation(),
2474
25
                                                  SourceLocation(),
2475
25
                                                  msgSendIdent, msgSendType,
2476
25
                                                  nullptr, SC_Extern);
2477
25
}
2478
2479
// SynthMsgSendSuperStretFunctionDecl -
2480
// id objc_msgSendSuper_stret(void);
2481
25
void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2482
25
  IdentifierInfo *msgSendIdent =
2483
25
    &Context->Idents.get("objc_msgSendSuper_stret");
2484
25
  SmallVector<QualType, 2> ArgTys;
2485
25
  ArgTys.push_back(Context->VoidTy);
2486
25
  QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2487
25
                                               ArgTys, /*variadic=*/true);
2488
25
  MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2489
25
                                                       SourceLocation(),
2490
25
                                                       SourceLocation(),
2491
25
                                                       msgSendIdent,
2492
25
                                                       msgSendType, nullptr,
2493
25
                                                       SC_Extern);
2494
25
}
2495
2496
// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2497
25
void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2498
25
  IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2499
25
  SmallVector<QualType, 16> ArgTys;
2500
25
  QualType argT = Context->getObjCIdType();
2501
25
  assert(!argT.isNull() && "Can't find 'id' type");
2502
0
  ArgTys.push_back(argT);
2503
25
  argT = Context->getObjCSelType();
2504
25
  assert(!argT.isNull() && "Can't find 'SEL' type");
2505
0
  ArgTys.push_back(argT);
2506
25
  QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2507
25
                                               ArgTys, /*variadic=*/true);
2508
25
  MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2509
25
                                                  SourceLocation(),
2510
25
                                                  SourceLocation(),
2511
25
                                                  msgSendIdent, msgSendType,
2512
25
                                                  nullptr, SC_Extern);
2513
25
}
2514
2515
// SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
2516
29
void RewriteModernObjC::SynthGetClassFunctionDecl() {
2517
29
  IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2518
29
  SmallVector<QualType, 16> ArgTys;
2519
29
  ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2520
29
  QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2521
29
                                                ArgTys);
2522
29
  GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2523
29
                                              SourceLocation(),
2524
29
                                              SourceLocation(),
2525
29
                                              getClassIdent, getClassType,
2526
29
                                              nullptr, SC_Extern);
2527
29
}
2528
2529
// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2530
25
void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2531
25
  IdentifierInfo *getSuperClassIdent =
2532
25
    &Context->Idents.get("class_getSuperclass");
2533
25
  SmallVector<QualType, 16> ArgTys;
2534
25
  ArgTys.push_back(Context->getObjCClassType());
2535
25
  QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2536
25
                                                ArgTys);
2537
25
  GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2538
25
                                                   SourceLocation(),
2539
25
                                                   SourceLocation(),
2540
25
                                                   getSuperClassIdent,
2541
25
                                                   getClassType, nullptr,
2542
25
                                                   SC_Extern);
2543
25
}
2544
2545
// SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
2546
25
void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2547
25
  IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2548
25
  SmallVector<QualType, 16> ArgTys;
2549
25
  ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2550
25
  QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2551
25
                                                ArgTys);
2552
25
  GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2553
25
                                                  SourceLocation(),
2554
25
                                                  SourceLocation(),
2555
25
                                                  getClassIdent, getClassType,
2556
25
                                                  nullptr, SC_Extern);
2557
25
}
2558
2559
13
Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2560
13
  assert (Exp != nullptr && "Expected non-null ObjCStringLiteral");
2561
0
  QualType strType = getConstantStringStructType();
2562
2563
13
  std::string S = "__NSConstantStringImpl_";
2564
2565
13
  std::string tmpName = InFileName;
2566
13
  unsigned i;
2567
1.45k
  for (i=0; i < tmpName.length(); 
i++1.44k
) {
2568
1.44k
    char c = tmpName.at(i);
2569
    // replace any non-alphanumeric characters with '_'.
2570
1.44k
    if (!isAlphanumeric(c))
2571
194
      tmpName[i] = '_';
2572
1.44k
  }
2573
13
  S += tmpName;
2574
13
  S += "_";
2575
13
  S += utostr(NumObjCStringLiterals++);
2576
2577
13
  Preamble += "static __NSConstantStringImpl " + S;
2578
13
  Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2579
13
  Preamble += "0x000007c8,"; // utf8_str
2580
  // The pretty printer for StringLiteral handles escape characters properly.
2581
13
  std::string prettyBufS;
2582
13
  llvm::raw_string_ostream prettyBuf(prettyBufS);
2583
13
  Exp->getString()->printPretty(prettyBuf, nullptr, PrintingPolicy(LangOpts));
2584
13
  Preamble += prettyBuf.str();
2585
13
  Preamble += ",";
2586
13
  Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2587
2588
13
  VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2589
13
                                   SourceLocation(), &Context->Idents.get(S),
2590
13
                                   strType, nullptr, SC_Static);
2591
13
  DeclRefExpr *DRE = new (Context)
2592
13
      DeclRefExpr(*Context, NewVD, false, strType, VK_LValue, SourceLocation());
2593
13
  Expr *Unop = UnaryOperator::Create(
2594
13
      const_cast<ASTContext &>(*Context), DRE, UO_AddrOf,
2595
13
      Context->getPointerType(DRE->getType()), VK_PRValue, OK_Ordinary,
2596
13
      SourceLocation(), false, FPOptionsOverride());
2597
  // cast to NSConstantString *
2598
13
  CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2599
13
                                            CK_CPointerToObjCPointerCast, Unop);
2600
13
  ReplaceStmt(Exp, cast);
2601
  // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2602
13
  return cast;
2603
13
}
2604
2605
16
Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2606
16
  unsigned IntSize =
2607
16
    static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2608
2609
16
  Expr *FlagExp = IntegerLiteral::Create(*Context,
2610
16
                                         llvm::APInt(IntSize, Exp->getValue()),
2611
16
                                         Context->IntTy, Exp->getLocation());
2612
16
  CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2613
16
                                            CK_BitCast, FlagExp);
2614
16
  ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2615
16
                                          cast);
2616
16
  ReplaceStmt(Exp, PE);
2617
16
  return PE;
2618
16
}
2619
2620
36
Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
2621
  // synthesize declaration of helper functions needed in this routine.
2622
36
  if (!SelGetUidFunctionDecl)
2623
0
    SynthSelGetUidFunctionDecl();
2624
  // use objc_msgSend() for all.
2625
36
  if (!MsgSendFunctionDecl)
2626
4
    SynthMsgSendFunctionDecl();
2627
36
  if (!GetClassFunctionDecl)
2628
4
    SynthGetClassFunctionDecl();
2629
2630
36
  FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2631
36
  SourceLocation StartLoc = Exp->getBeginLoc();
2632
36
  SourceLocation EndLoc = Exp->getEndLoc();
2633
2634
  // Synthesize a call to objc_msgSend().
2635
36
  SmallVector<Expr*, 4> MsgExprs;
2636
36
  SmallVector<Expr*, 4> ClsExprs;
2637
2638
  // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2639
36
  ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2640
36
  ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
2641
2642
36
  IdentifierInfo *clsName = BoxingClass->getIdentifier();
2643
36
  ClsExprs.push_back(getStringLiteral(clsName->getName()));
2644
36
  CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
2645
36
                                               StartLoc, EndLoc);
2646
36
  MsgExprs.push_back(Cls);
2647
2648
  // Create a call to sel_registerName("<BoxingMethod>:"), etc.
2649
  // it will be the 2nd argument.
2650
36
  SmallVector<Expr*, 4> SelExprs;
2651
36
  SelExprs.push_back(
2652
36
      getStringLiteral(BoxingMethod->getSelector().getAsString()));
2653
36
  CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2654
36
                                                  SelExprs, StartLoc, EndLoc);
2655
36
  MsgExprs.push_back(SelExp);
2656
2657
  // User provided sub-expression is the 3rd, and last, argument.
2658
36
  Expr *subExpr  = Exp->getSubExpr();
2659
36
  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
2660
4
    QualType type = ICE->getType();
2661
4
    const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2662
4
    CastKind CK = CK_BitCast;
2663
4
    if (SubExpr->getType()->isIntegralType(*Context) && 
type->isBooleanType()2
)
2664
0
      CK = CK_IntegralToBoolean;
2665
4
    subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
2666
4
  }
2667
36
  MsgExprs.push_back(subExpr);
2668
2669
36
  SmallVector<QualType, 4> ArgTypes;
2670
36
  ArgTypes.push_back(Context->getObjCClassType());
2671
36
  ArgTypes.push_back(Context->getObjCSelType());
2672
36
  for (const auto PI : BoxingMethod->parameters())
2673
36
    ArgTypes.push_back(PI->getType());
2674
2675
36
  QualType returnType = Exp->getType();
2676
  // Get the type, we will need to reference it in a couple spots.
2677
36
  QualType msgSendType = MsgSendFlavor->getType();
2678
2679
  // Create a reference to the objc_msgSend() declaration.
2680
36
  DeclRefExpr *DRE = new (Context) DeclRefExpr(
2681
36
      *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
2682
2683
36
  CastExpr *cast = NoTypeInfoCStyleCastExpr(
2684
36
      Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE);
2685
2686
  // Now do the "normal" pointer to function cast.
2687
36
  QualType castType =
2688
36
    getSimpleFunctionType(returnType, ArgTypes, BoxingMethod->isVariadic());
2689
36
  castType = Context->getPointerType(castType);
2690
36
  cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2691
36
                                  cast);
2692
2693
  // Don't forget the parens to enforce the proper binding.
2694
36
  ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2695
2696
36
  auto *FT = msgSendType->castAs<FunctionType>();
2697
36
  CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
2698
36
                                  VK_PRValue, EndLoc, FPOptionsOverride());
2699
36
  ReplaceStmt(Exp, CE);
2700
36
  return CE;
2701
36
}
2702
2703
5
Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2704
  // synthesize declaration of helper functions needed in this routine.
2705
5
  if (!SelGetUidFunctionDecl)
2706
0
    SynthSelGetUidFunctionDecl();
2707
  // use objc_msgSend() for all.
2708
5
  if (!MsgSendFunctionDecl)
2709
0
    SynthMsgSendFunctionDecl();
2710
5
  if (!GetClassFunctionDecl)
2711
0
    SynthGetClassFunctionDecl();
2712
2713
5
  FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2714
5
  SourceLocation StartLoc = Exp->getBeginLoc();
2715
5
  SourceLocation EndLoc = Exp->getEndLoc();
2716
2717
  // Build the expression: __NSContainer_literal(int, ...).arr
2718
5
  QualType IntQT = Context->IntTy;
2719
5
  QualType NSArrayFType =
2720
5
    getSimpleFunctionType(Context->VoidTy, IntQT, true);
2721
5
  std::string NSArrayFName("__NSContainer_literal");
2722
5
  FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2723
5
  DeclRefExpr *NSArrayDRE = new (Context) DeclRefExpr(
2724
5
      *Context, NSArrayFD, false, NSArrayFType, VK_PRValue, SourceLocation());
2725
2726
5
  SmallVector<Expr*, 16> InitExprs;
2727
5
  unsigned NumElements = Exp->getNumElements();
2728
5
  unsigned UnsignedIntSize =
2729
5
    static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2730
5
  Expr *count = IntegerLiteral::Create(*Context,
2731
5
                                       llvm::APInt(UnsignedIntSize, NumElements),
2732
5
                                       Context->UnsignedIntTy, SourceLocation());
2733
5
  InitExprs.push_back(count);
2734
18
  for (unsigned i = 0; i < NumElements; 
i++13
)
2735
13
    InitExprs.push_back(Exp->getElement(i));
2736
5
  Expr *NSArrayCallExpr =
2737
5
      CallExpr::Create(*Context, NSArrayDRE, InitExprs, NSArrayFType, VK_LValue,
2738
5
                       SourceLocation(), FPOptionsOverride());
2739
2740
5
  FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
2741
5
                                    SourceLocation(),
2742
5
                                    &Context->Idents.get("arr"),
2743
5
                                    Context->getPointerType(Context->VoidPtrTy),
2744
5
                                    nullptr, /*BitWidth=*/nullptr,
2745
5
                                    /*Mutable=*/true, ICIS_NoInit);
2746
5
  MemberExpr *ArrayLiteralME =
2747
5
      MemberExpr::CreateImplicit(*Context, NSArrayCallExpr, false, ARRFD,
2748
5
                                 ARRFD->getType(), VK_LValue, OK_Ordinary);
2749
5
  QualType ConstIdT = Context->getObjCIdType().withConst();
2750
5
  CStyleCastExpr * ArrayLiteralObjects =
2751
5
    NoTypeInfoCStyleCastExpr(Context,
2752
5
                             Context->getPointerType(ConstIdT),
2753
5
                             CK_BitCast,
2754
5
                             ArrayLiteralME);
2755
2756
  // Synthesize a call to objc_msgSend().
2757
5
  SmallVector<Expr*, 32> MsgExprs;
2758
5
  SmallVector<Expr*, 4> ClsExprs;
2759
5
  QualType expType = Exp->getType();
2760
2761
  // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2762
5
  ObjCInterfaceDecl *Class =
2763
5
    expType->getPointeeType()->castAs<ObjCObjectType>()->getInterface();
2764
2765
5
  IdentifierInfo *clsName = Class->getIdentifier();
2766
5
  ClsExprs.push_back(getStringLiteral(clsName->getName()));
2767
5
  CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
2768
5
                                               StartLoc, EndLoc);
2769
5
  MsgExprs.push_back(Cls);
2770
2771
  // Create a call to sel_registerName("arrayWithObjects:count:").
2772
  // it will be the 2nd argument.
2773
5
  SmallVector<Expr*, 4> SelExprs;
2774
5
  ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
2775
5
  SelExprs.push_back(
2776
5
      getStringLiteral(ArrayMethod->getSelector().getAsString()));
2777
5
  CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2778
5
                                                  SelExprs, StartLoc, EndLoc);
2779
5
  MsgExprs.push_back(SelExp);
2780
2781
  // (const id [])objects
2782
5
  MsgExprs.push_back(ArrayLiteralObjects);
2783
2784
  // (NSUInteger)cnt
2785
5
  Expr *cnt = IntegerLiteral::Create(*Context,
2786
5
                                     llvm::APInt(UnsignedIntSize, NumElements),
2787
5
                                     Context->UnsignedIntTy, SourceLocation());
2788
5
  MsgExprs.push_back(cnt);
2789
2790
5
  SmallVector<QualType, 4> ArgTypes;
2791
5
  ArgTypes.push_back(Context->getObjCClassType());
2792
5
  ArgTypes.push_back(Context->getObjCSelType());
2793
5
  for (const auto *PI : ArrayMethod->parameters())
2794
10
    ArgTypes.push_back(PI->getType());
2795
2796
5
  QualType returnType = Exp->getType();
2797
  // Get the type, we will need to reference it in a couple spots.
2798
5
  QualType msgSendType = MsgSendFlavor->getType();
2799
2800
  // Create a reference to the objc_msgSend() declaration.
2801
5
  DeclRefExpr *DRE = new (Context) DeclRefExpr(
2802
5
      *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
2803
2804
5
  CastExpr *cast = NoTypeInfoCStyleCastExpr(
2805
5
      Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE);
2806
2807
  // Now do the "normal" pointer to function cast.
2808
5
  QualType castType =
2809
5
  getSimpleFunctionType(returnType, ArgTypes, ArrayMethod->isVariadic());
2810
5
  castType = Context->getPointerType(castType);
2811
5
  cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2812
5
                                  cast);
2813
2814
  // Don't forget the parens to enforce the proper binding.
2815
5
  ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2816
2817
5
  const FunctionType *FT = msgSendType->castAs<FunctionType>();
2818
5
  CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
2819
5
                                  VK_PRValue, EndLoc, FPOptionsOverride());
2820
5
  ReplaceStmt(Exp, CE);
2821
5
  return CE;
2822
5
}
2823
2824
2
Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2825
  // synthesize declaration of helper functions needed in this routine.
2826
2
  if (!SelGetUidFunctionDecl)
2827
0
    SynthSelGetUidFunctionDecl();
2828
  // use objc_msgSend() for all.
2829
2
  if (!MsgSendFunctionDecl)
2830
0
    SynthMsgSendFunctionDecl();
2831
2
  if (!GetClassFunctionDecl)
2832
0
    SynthGetClassFunctionDecl();
2833
2834
2
  FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2835
2
  SourceLocation StartLoc = Exp->getBeginLoc();
2836
2
  SourceLocation EndLoc = Exp->getEndLoc();
2837
2838
  // Build the expression: __NSContainer_literal(int, ...).arr
2839
2
  QualType IntQT = Context->IntTy;
2840
2
  QualType NSDictFType =
2841
2
    getSimpleFunctionType(Context->VoidTy, IntQT, true);
2842
2
  std::string NSDictFName("__NSContainer_literal");
2843
2
  FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2844
2
  DeclRefExpr *NSDictDRE = new (Context) DeclRefExpr(
2845
2
      *Context, NSDictFD, false, NSDictFType, VK_PRValue, SourceLocation());
2846
2847
2
  SmallVector<Expr*, 16> KeyExprs;
2848
2
  SmallVector<Expr*, 16> ValueExprs;
2849
2850
2
  unsigned NumElements = Exp->getNumElements();
2851
2
  unsigned UnsignedIntSize =
2852
2
    static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2853
2
  Expr *count = IntegerLiteral::Create(*Context,
2854
2
                                       llvm::APInt(UnsignedIntSize, NumElements),
2855
2
                                       Context->UnsignedIntTy, SourceLocation());
2856
2
  KeyExprs.push_back(count);
2857
2
  ValueExprs.push_back(count);
2858
8
  for (unsigned i = 0; i < NumElements; 
i++6
) {
2859
6
    ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2860
6
    KeyExprs.push_back(Element.Key);
2861
6
    ValueExprs.push_back(Element.Value);
2862
6
  }
2863
2864
  // (const id [])objects
2865
2
  Expr *NSValueCallExpr =
2866
2
      CallExpr::Create(*Context, NSDictDRE, ValueExprs, NSDictFType, VK_LValue,
2867
2
                       SourceLocation(), FPOptionsOverride());
2868
2869
2
  FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
2870
2
                                       SourceLocation(),
2871
2
                                       &Context->Idents.get("arr"),
2872
2
                                       Context->getPointerType(Context->VoidPtrTy),
2873
2
                                       nullptr, /*BitWidth=*/nullptr,
2874
2
                                       /*Mutable=*/true, ICIS_NoInit);
2875
2
  MemberExpr *DictLiteralValueME =
2876
2
      MemberExpr::CreateImplicit(*Context, NSValueCallExpr, false, ARRFD,
2877
2
                                 ARRFD->getType(), VK_LValue, OK_Ordinary);
2878
2
  QualType ConstIdT = Context->getObjCIdType().withConst();
2879
2
  CStyleCastExpr * DictValueObjects =
2880
2
    NoTypeInfoCStyleCastExpr(Context,
2881
2
                             Context->getPointerType(ConstIdT),
2882
2
                             CK_BitCast,
2883
2
                             DictLiteralValueME);
2884
  // (const id <NSCopying> [])keys
2885
2
  Expr *NSKeyCallExpr =
2886
2
      CallExpr::Create(*Context, NSDictDRE, KeyExprs, NSDictFType, VK_LValue,
2887
2
                       SourceLocation(), FPOptionsOverride());
2888
2889
2
  MemberExpr *DictLiteralKeyME =
2890
2
      MemberExpr::CreateImplicit(*Context, NSKeyCallExpr, false, ARRFD,
2891
2
                                 ARRFD->getType(), VK_LValue, OK_Ordinary);
2892
2893
2
  CStyleCastExpr * DictKeyObjects =
2894
2
    NoTypeInfoCStyleCastExpr(Context,
2895
2
                             Context->getPointerType(ConstIdT),
2896
2
                             CK_BitCast,
2897
2
                             DictLiteralKeyME);
2898
2899
  // Synthesize a call to objc_msgSend().
2900
2
  SmallVector<Expr*, 32> MsgExprs;
2901
2
  SmallVector<Expr*, 4> ClsExprs;
2902
2
  QualType expType = Exp->getType();
2903
2904
  // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2905
2
  ObjCInterfaceDecl *Class =
2906
2
  expType->getPointeeType()->castAs<ObjCObjectType>()->getInterface();
2907
2908
2
  IdentifierInfo *clsName = Class->getIdentifier();
2909
2
  ClsExprs.push_back(getStringLiteral(clsName->getName()));
2910
2
  CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
2911
2
                                               StartLoc, EndLoc);
2912
2
  MsgExprs.push_back(Cls);
2913
2914
  // Create a call to sel_registerName("arrayWithObjects:count:").
2915
  // it will be the 2nd argument.
2916
2
  SmallVector<Expr*, 4> SelExprs;
2917
2
  ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
2918
2
  SelExprs.push_back(getStringLiteral(DictMethod->getSelector().getAsString()));
2919
2
  CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2920
2
                                                  SelExprs, StartLoc, EndLoc);
2921
2
  MsgExprs.push_back(SelExp);
2922
2923
  // (const id [])objects
2924
2
  MsgExprs.push_back(DictValueObjects);
2925
2926
  // (const id <NSCopying> [])keys
2927
2
  MsgExprs.push_back(DictKeyObjects);
2928
2929
  // (NSUInteger)cnt
2930
2
  Expr *cnt = IntegerLiteral::Create(*Context,
2931
2
                                     llvm::APInt(UnsignedIntSize, NumElements),
2932
2
                                     Context->UnsignedIntTy, SourceLocation());
2933
2
  MsgExprs.push_back(cnt);
2934
2935
2
  SmallVector<QualType, 8> ArgTypes;
2936
2
  ArgTypes.push_back(Context->getObjCClassType());
2937
2
  ArgTypes.push_back(Context->getObjCSelType());
2938
6
  for (const auto *PI : DictMethod->parameters()) {
2939
6
    QualType T = PI->getType();
2940
6
    if (const PointerType* PT = T->getAs<PointerType>()) {
2941
4
      QualType PointeeTy = PT->getPointeeType();
2942
4
      convertToUnqualifiedObjCType(PointeeTy);
2943
4
      T = Context->getPointerType(PointeeTy);
2944
4
    }
2945
6
    ArgTypes.push_back(T);
2946
6
  }
2947
2948
2
  QualType returnType = Exp->getType();
2949
  // Get the type, we will need to reference it in a couple spots.
2950
2
  QualType msgSendType = MsgSendFlavor->getType();
2951
2952
  // Create a reference to the objc_msgSend() declaration.
2953
2
  DeclRefExpr *DRE = new (Context) DeclRefExpr(
2954
2
      *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
2955
2956
2
  CastExpr *cast = NoTypeInfoCStyleCastExpr(
2957
2
      Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE);
2958
2959
  // Now do the "normal" pointer to function cast.
2960
2
  QualType castType =
2961
2
  getSimpleFunctionType(returnType, ArgTypes, DictMethod->isVariadic());
2962
2
  castType = Context->getPointerType(castType);
2963
2
  cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2964
2
                                  cast);
2965
2966
  // Don't forget the parens to enforce the proper binding.
2967
2
  ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2968
2969
2
  const FunctionType *FT = msgSendType->castAs<FunctionType>();
2970
2
  CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
2971
2
                                  VK_PRValue, EndLoc, FPOptionsOverride());
2972
2
  ReplaceStmt(Exp, CE);
2973
2
  return CE;
2974
2
}
2975
2976
// struct __rw_objc_super {
2977
//   struct objc_object *object; struct objc_object *superClass;
2978
// };
2979
2
QualType RewriteModernObjC::getSuperStructType() {
2980
2
  if (!SuperStructDecl) {
2981
1
    SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2982
1
                                         SourceLocation(), SourceLocation(),
2983
1
                                         &Context->Idents.get("__rw_objc_super"));
2984
1
    QualType FieldTypes[2];
2985
2986
    // struct objc_object *object;
2987
1
    FieldTypes[0] = Context->getObjCIdType();
2988
    // struct objc_object *superClass;
2989
1
    FieldTypes[1] = Context->getObjCIdType();
2990
2991
    // Create fields
2992
3
    for (unsigned i = 0; i < 2; 
++i2
) {
2993
2
      SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2994
2
                                                 SourceLocation(),
2995
2
                                                 SourceLocation(), nullptr,
2996
2
                                                 FieldTypes[i], nullptr,
2997
2
                                                 /*BitWidth=*/nullptr,
2998
2
                                                 /*Mutable=*/false,
2999
2
                                                 ICIS_NoInit));
3000
2
    }
3001
3002
1
    SuperStructDecl->completeDefinition();
3003
1
  }
3004
2
  return Context->getTagDeclType(SuperStructDecl);
3005
2
}
3006
3007
13
QualType RewriteModernObjC::getConstantStringStructType() {
3008
13
  if (!ConstantStringDecl) {
3009
3
    ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3010
3
                                            SourceLocation(), SourceLocation(),
3011
3
                         &Context->Idents.get("__NSConstantStringImpl"));
3012
3
    QualType FieldTypes[4];
3013
3014
    // struct objc_object *receiver;
3015
3
    FieldTypes[0] = Context->getObjCIdType();
3016
    // int flags;
3017
3
    FieldTypes[1] = Context->IntTy;
3018
    // char *str;
3019
3
    FieldTypes[2] = Context->getPointerType(Context->CharTy);
3020
    // long length;
3021
3
    FieldTypes[3] = Context->LongTy;
3022
3023
    // Create fields
3024
15
    for (unsigned i = 0; i < 4; 
++i12
) {
3025
12
      ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3026
12
                                                    ConstantStringDecl,
3027
12
                                                    SourceLocation(),
3028
12
                                                    SourceLocation(), nullptr,
3029
12
                                                    FieldTypes[i], nullptr,
3030
12
                                                    /*BitWidth=*/nullptr,
3031
12
                                                    /*Mutable=*/true,
3032
12
                                                    ICIS_NoInit));
3033
12
    }
3034
3035
3
    ConstantStringDecl->completeDefinition();
3036
3
  }
3037
13
  return Context->getTagDeclType(ConstantStringDecl);
3038
13
}
3039
3040
/// getFunctionSourceLocation - returns start location of a function
3041
/// definition. Complication arises when function has declared as
3042
/// extern "C" or extern "C" {...}
3043
static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
3044
75
                                                 FunctionDecl *FD) {
3045
75
  if (FD->isExternC()  && 
!FD->isMain()16
) {
3046
16
    const DeclContext *DC = FD->getDeclContext();
3047
16
    if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3048
      // if it is extern "C" {...}, return function decl's own location.
3049
12
      if (!LSD->getRBraceLoc().isValid())
3050
4
        return LSD->getExternLoc();
3051
16
  }
3052
71
  if (FD->getStorageClass() != SC_None)
3053
5
    R.RewriteBlockLiteralFunctionDecl(FD);
3054
71
  return FD->getTypeSpecStartLoc();
3055
75
}
3056
3057
162
void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
3058
3059
162
  SourceLocation Location = D->getLocation();
3060
3061
162
  if (Location.isFileID() && GenerateLineInfo) {
3062
3
    std::string LineString("\n#line ");
3063
3
    PresumedLoc PLoc = SM->getPresumedLoc(Location);
3064
3
    LineString += utostr(PLoc.getLine());
3065
3
    LineString += " \"";
3066
3
    LineString += Lexer::Stringify(PLoc.getFilename());
3067
3
    if (isa<ObjCMethodDecl>(D))
3068
1
      LineString += "\"";
3069
2
    else LineString += "\"\n";
3070
3071
3
    Location = D->getBeginLoc();
3072
3
    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3073
2
      if (FD->isExternC()  && 
!FD->isMain()0
) {
3074
0
        const DeclContext *DC = FD->getDeclContext();
3075
0
        if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3076
          // if it is extern "C" {...}, return function decl's own location.
3077
0
          if (!LSD->getRBraceLoc().isValid())
3078
0
            Location = LSD->getExternLoc();
3079
0
      }
3080
2
    }
3081
3
    InsertText(Location, LineString);
3082
3
  }
3083
162
}
3084
3085
/// SynthMsgSendStretCallExpr - This routine translates message expression
3086
/// into a call to objc_msgSend_stret() entry point. Tricky part is that
3087
/// nil check on receiver must be performed before calling objc_msgSend_stret.
3088
/// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
3089
/// msgSendType - function type of objc_msgSend_stret(...)
3090
/// returnType - Result type of the method being synthesized.
3091
/// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
3092
/// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
3093
/// starting with receiver.
3094
/// Method - Method being rewritten.
3095
Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
3096
                                                 QualType returnType,
3097
                                                 SmallVectorImpl<QualType> &ArgTypes,
3098
                                                 SmallVectorImpl<Expr*> &MsgExprs,
3099
12
                                                 ObjCMethodDecl *Method) {
3100
  // Now do the "normal" pointer to function cast.
3101
12
  QualType FuncType = getSimpleFunctionType(
3102
12
      returnType, ArgTypes, Method ? Method->isVariadic() : 
false0
);
3103
12
  QualType castType = Context->getPointerType(FuncType);
3104
3105
  // build type for containing the objc_msgSend_stret object.
3106
12
  static unsigned stretCount=0;
3107
12
  std::string name = "__Stret"; name += utostr(stretCount);
3108
12
  std::string str =
3109
12
    "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
3110
12
  str += "namespace {\n";
3111
12
  str += "struct "; str += name;
3112
12
  str += " {\n\t";
3113
12
  str += name;
3114
12
  str += "(id receiver, SEL sel";
3115
22
  for (unsigned i = 2; i < ArgTypes.size(); 
i++10
) {
3116
10
    std::string ArgName = "arg"; ArgName += utostr(i);
3117
10
    ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
3118
10
    str += ", "; str += ArgName;
3119
10
  }
3120
  // could be vararg.
3121
19
  for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); 
i++7
) {
3122
7
    std::string ArgName = "arg"; ArgName += utostr(i);
3123
7
    MsgExprs[i]->getType().getAsStringInternal(ArgName,
3124
7
                                               Context->getPrintingPolicy());
3125
7
    str += ", "; str += ArgName;
3126
7
  }
3127
3128
12
  str += ") {\n";
3129
12
  str += "\t  unsigned size = sizeof(";
3130
12
  str += returnType.getAsString(Context->getPrintingPolicy()); str += ");\n";
3131
3132
12
  str += "\t  if (size == 1 || size == 2 || size == 4 || size == 8)\n";
3133
3134
12
  str += "\t    s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3135
12
  str += ")(void *)objc_msgSend)(receiver, sel";
3136
22
  for (unsigned i = 2; i < ArgTypes.size(); 
i++10
) {
3137
10
    str += ", arg"; str += utostr(i);
3138
10
  }
3139
  // could be vararg.
3140
19
  for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); 
i++7
) {
3141
7
    str += ", arg"; str += utostr(i);
3142
7
  }
3143
12
  str+= ");\n";
3144
3145
12
  str += "\t  else if (receiver == 0)\n";
3146
12
  str += "\t    memset((void*)&s, 0, sizeof(s));\n";
3147
12
  str += "\t  else\n";
3148
3149
12
  str += "\t    s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3150
12
  str += ")(void *)objc_msgSend_stret)(receiver, sel";
3151
22
  for (unsigned i = 2; i < ArgTypes.size(); 
i++10
) {
3152
10
    str += ", arg"; str += utostr(i);
3153
10
  }
3154
  // could be vararg.
3155
19
  for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); 
i++7
) {
3156
7
    str += ", arg"; str += utostr(i);
3157
7
  }
3158
12
  str += ");\n";
3159
3160
12
  str += "\t}\n";
3161
12
  str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
3162
12
  str += " s;\n";
3163
12
  str += "};\n};\n\n";
3164
12
  SourceLocation FunLocStart;
3165
12
  if (CurFunctionDef)
3166
11
    FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
3167
1
  else {
3168
1
    assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
3169
0
    FunLocStart = CurMethodDef->getBeginLoc();
3170
1
  }
3171
3172
0
  InsertText(FunLocStart, str);
3173
12
  ++stretCount;
3174
3175
  // AST for __Stretn(receiver, args).s;
3176
12
  IdentifierInfo *ID = &Context->Idents.get(name);
3177
12
  FunctionDecl *FD =
3178
12
      FunctionDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(),
3179
12
                           ID, FuncType, nullptr, SC_Extern, false, false);
3180
12
  DeclRefExpr *DRE = new (Context)
3181
12
      DeclRefExpr(*Context, FD, false, castType, VK_PRValue, SourceLocation());
3182
12
  CallExpr *STCE =
3183
12
      CallExpr::Create(*Context, DRE, MsgExprs, castType, VK_LValue,
3184
12
                       SourceLocation(), FPOptionsOverride());
3185
3186
12
  FieldDecl *FieldD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
3187
12
                                    SourceLocation(),
3188
12
                                    &Context->Idents.get("s"),
3189
12
                                    returnType, nullptr,
3190
12
                                    /*BitWidth=*/nullptr,
3191
12
                                    /*Mutable=*/true, ICIS_NoInit);
3192
12
  MemberExpr *ME = MemberExpr::CreateImplicit(
3193
12
      *Context, STCE, false, FieldD, FieldD->getType(), VK_LValue, OK_Ordinary);
3194
3195
12
  return ME;
3196
12
}
3197
3198
Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3199
                                    SourceLocation StartLoc,
3200
104
                                    SourceLocation EndLoc) {
3201
104
  if (!SelGetUidFunctionDecl)
3202
3
    SynthSelGetUidFunctionDecl();
3203
104
  if (!MsgSendFunctionDecl)
3204
25
    SynthMsgSendFunctionDecl();
3205
104
  if (!MsgSendSuperFunctionDecl)
3206
25
    SynthMsgSendSuperFunctionDecl();
3207
104
  if (!MsgSendStretFunctionDecl)
3208
25
    SynthMsgSendStretFunctionDecl();
3209
104
  if (!MsgSendSuperStretFunctionDecl)
3210
25
    SynthMsgSendSuperStretFunctionDecl();
3211
104
  if (!MsgSendFpretFunctionDecl)
3212
25
    SynthMsgSendFpretFunctionDecl();
3213
104
  if (!GetClassFunctionDecl)
3214
25
    SynthGetClassFunctionDecl();
3215
104
  if (!GetSuperClassFunctionDecl)
3216
25
    SynthGetSuperClassFunctionDecl();
3217
104
  if (!GetMetaClassFunctionDecl)
3218
25
    SynthGetMetaClassFunctionDecl();
3219
3220
  // default to objc_msgSend().
3221
104
  FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3222
  // May need to use objc_msgSend_stret() as well.
3223
104
  FunctionDecl *MsgSendStretFlavor = nullptr;
3224
104
  if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
3225
98
    QualType resultType = mDecl->getReturnType();
3226
98
    if (resultType->isRecordType())
3227
12
      MsgSendStretFlavor = MsgSendStretFunctionDecl;
3228
86
    else if (resultType->isRealFloatingType())
3229
0
      MsgSendFlavor = MsgSendFpretFunctionDecl;
3230
98
  }
3231
3232
  // Synthesize a call to objc_msgSend().
3233
104
  SmallVector<Expr*, 8> MsgExprs;
3234
104
  switch (Exp->getReceiverKind()) {
3235
0
  case ObjCMessageExpr::SuperClass: {
3236
0
    MsgSendFlavor = MsgSendSuperFunctionDecl;
3237
0
    if (MsgSendStretFlavor)
3238
0
      MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3239
0
    assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3240
3241
0
    ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3242
3243
0
    SmallVector<Expr*, 4> InitExprs;
3244
3245
    // set the receiver to self, the first argument to all methods.
3246
0
    InitExprs.push_back(NoTypeInfoCStyleCastExpr(
3247
0
        Context, Context->getObjCIdType(), CK_BitCast,
3248
0
        new (Context) DeclRefExpr(*Context, CurMethodDef->getSelfDecl(), false,
3249
0
                                  Context->getObjCIdType(), VK_PRValue,
3250
0
                                  SourceLocation()))); // set the 'receiver'.
3251
3252
    // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3253
0
    SmallVector<Expr*, 8> ClsExprs;
3254
0
    ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
3255
    // (Class)objc_getClass("CurrentClass")
3256
0
    CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3257
0
                                                 ClsExprs, StartLoc, EndLoc);
3258
0
    ClsExprs.clear();
3259
0
    ClsExprs.push_back(Cls);
3260
0
    Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
3261
0
                                       StartLoc, EndLoc);
3262
3263
    // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3264
    // To turn off a warning, type-cast to 'id'
3265
0
    InitExprs.push_back( // set 'super class', using class_getSuperclass().
3266
0
                        NoTypeInfoCStyleCastExpr(Context,
3267
0
                                                 Context->getObjCIdType(),
3268
0
                                                 CK_BitCast, Cls));
3269
    // struct __rw_objc_super
3270
0
    QualType superType = getSuperStructType();
3271
0
    Expr *SuperRep;
3272
3273
0
    if (LangOpts.MicrosoftExt) {
3274
0
      SynthSuperConstructorFunctionDecl();
3275
      // Simulate a constructor call...
3276
0
      DeclRefExpr *DRE = new (Context)
3277
0
          DeclRefExpr(*Context, SuperConstructorFunctionDecl, false, superType,
3278
0
                      VK_LValue, SourceLocation());
3279
0
      SuperRep =
3280
0
          CallExpr::Create(*Context, DRE, InitExprs, superType, VK_LValue,
3281
0
                           SourceLocation(), FPOptionsOverride());
3282
      // The code for super is a little tricky to prevent collision with
3283
      // the structure definition in the header. The rewriter has it's own
3284
      // internal definition (__rw_objc_super) that is uses. This is why
3285
      // we need the cast below. For example:
3286
      // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
3287
      //
3288
0
      SuperRep = UnaryOperator::Create(
3289
0
          const_cast<ASTContext &>(*Context), SuperRep, UO_AddrOf,
3290
0
          Context->getPointerType(SuperRep->getType()), VK_PRValue, OK_Ordinary,
3291
0
          SourceLocation(), false, FPOptionsOverride());
3292
0
      SuperRep = NoTypeInfoCStyleCastExpr(Context,
3293
0
                                          Context->getPointerType(superType),
3294
0
                                          CK_BitCast, SuperRep);
3295
0
    } else {
3296
      // (struct __rw_objc_super) { <exprs from above> }
3297
0
      InitListExpr *ILE =
3298
0
        new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
3299
0
                                   SourceLocation());
3300
0
      TypeSourceInfo *superTInfo
3301
0
        = Context->getTrivialTypeSourceInfo(superType);
3302
0
      SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3303
0
                                                   superType, VK_LValue,
3304
0
                                                   ILE, false);
3305
      // struct __rw_objc_super *
3306
0
      SuperRep = UnaryOperator::Create(
3307
0
          const_cast<ASTContext &>(*Context), SuperRep, UO_AddrOf,
3308
0
          Context->getPointerType(SuperRep->getType()), VK_PRValue, OK_Ordinary,
3309
0
          SourceLocation(), false, FPOptionsOverride());
3310
0
    }
3311
0
    MsgExprs.push_back(SuperRep);
3312
0
    break;
3313
0
  }
3314
3315
23
  case ObjCMessageExpr::Class: {
3316
23
    SmallVector<Expr*, 8> ClsExprs;
3317
23
    ObjCInterfaceDecl *Class
3318
23
      = Exp->getClassReceiver()->castAs<ObjCObjectType>()->getInterface();
3319
23
    IdentifierInfo *clsName = Class->getIdentifier();
3320
23
    ClsExprs.push_back(getStringLiteral(clsName->getName()));
3321
23
    CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
3322
23
                                                 StartLoc, EndLoc);
3323
23
    CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3324
23
                                                 Context->getObjCIdType(),
3325
23
                                                 CK_BitCast, Cls);
3326
23
    MsgExprs.push_back(ArgExpr);
3327
23
    break;
3328
0
  }
3329
3330
1
  case ObjCMessageExpr::SuperInstance:{
3331
1
    MsgSendFlavor = MsgSendSuperFunctionDecl;
3332
1
    if (MsgSendStretFlavor)
3333
0
      MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3334
1
    assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3335
0
    ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3336
1
    SmallVector<Expr*, 4> InitExprs;
3337
3338
1
    InitExprs.push_back(NoTypeInfoCStyleCastExpr(
3339
1
        Context, Context->getObjCIdType(), CK_BitCast,
3340
1
        new (Context) DeclRefExpr(*Context, CurMethodDef->getSelfDecl(), false,
3341
1
                                  Context->getObjCIdType(), VK_PRValue,
3342
1
                                  SourceLocation()))); // set the 'receiver'.
3343
3344
    // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3345
1
    SmallVector<Expr*, 8> ClsExprs;
3346
1
    ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
3347
    // (Class)objc_getClass("CurrentClass")
3348
1
    CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
3349
1
                                                 StartLoc, EndLoc);
3350
1
    ClsExprs.clear();
3351
1
    ClsExprs.push_back(Cls);
3352
1
    Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
3353
1
                                       StartLoc, EndLoc);
3354
3355
    // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3356
    // To turn off a warning, type-cast to 'id'
3357
1
    InitExprs.push_back(
3358
      // set 'super class', using class_getSuperclass().
3359
1
      NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3360
1
                               CK_BitCast, Cls));
3361
    // struct __rw_objc_super
3362
1
    QualType superType = getSuperStructType();
3363
1
    Expr *SuperRep;
3364
3365
1
    if (LangOpts.MicrosoftExt) {
3366
1
      SynthSuperConstructorFunctionDecl();
3367
      // Simulate a constructor call...
3368
1
      DeclRefExpr *DRE = new (Context)
3369
1
          DeclRefExpr(*Context, SuperConstructorFunctionDecl, false, superType,
3370
1
                      VK_LValue, SourceLocation());
3371
1
      SuperRep =
3372
1
          CallExpr::Create(*Context, DRE, InitExprs, superType, VK_LValue,
3373
1
                           SourceLocation(), FPOptionsOverride());
3374
      // The code for super is a little tricky to prevent collision with
3375
      // the structure definition in the header. The rewriter has it's own
3376
      // internal definition (__rw_objc_super) that is uses. This is why
3377
      // we need the cast below. For example:
3378
      // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
3379
      //
3380
1
      SuperRep = UnaryOperator::Create(
3381
1
          const_cast<ASTContext &>(*Context), SuperRep, UO_AddrOf,
3382
1
          Context->getPointerType(SuperRep->getType()), VK_PRValue, OK_Ordinary,
3383
1
          SourceLocation(), false, FPOptionsOverride());
3384
1
      SuperRep = NoTypeInfoCStyleCastExpr(Context,
3385
1
                               Context->getPointerType(superType),
3386
1
                               CK_BitCast, SuperRep);
3387
1
    } else {
3388
      // (struct __rw_objc_super) { <exprs from above> }
3389
0
      InitListExpr *ILE =
3390
0
        new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
3391
0
                                   SourceLocation());
3392
0
      TypeSourceInfo *superTInfo
3393
0
        = Context->getTrivialTypeSourceInfo(superType);
3394
0
      SuperRep = new (Context) CompoundLiteralExpr(
3395
0
          SourceLocation(), superTInfo, superType, VK_PRValue, ILE, false);
3396
0
    }
3397
1
    MsgExprs.push_back(SuperRep);
3398
1
    break;
3399
0
  }
3400
3401
80
  case ObjCMessageExpr::Instance: {
3402
    // Remove all type-casts because it may contain objc-style types; e.g.
3403
    // Foo<Proto> *.
3404
80
    Expr *recExpr = Exp->getInstanceReceiver();
3405
81
    while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3406
1
      recExpr = CE->getSubExpr();
3407
80
    CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3408
80
                    ? CK_BitCast : 
recExpr->getType()->isBlockPointerType()0
3409
0
                                     ? CK_BlockPointerToObjCPointerCast
3410
0
                                     : CK_CPointerToObjCPointerCast;
3411
3412
80
    recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3413
80
                                       CK, recExpr);
3414
80
    MsgExprs.push_back(recExpr);
3415
80
    break;
3416
0
  }
3417
104
  }
3418
3419
  // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3420
104
  SmallVector<Expr*, 8> SelExprs;
3421
104
  SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
3422
104
  CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3423
104
                                                  SelExprs, StartLoc, EndLoc);
3424
104
  MsgExprs.push_back(SelExp);
3425
3426
  // Now push any user supplied arguments.
3427
158
  for (unsigned i = 0; i < Exp->getNumArgs(); 
i++54
) {
3428
54
    Expr *userExpr = Exp->getArg(i);
3429
    // Make all implicit casts explicit...ICE comes in handy:-)
3430
54
    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3431
      // Reuse the ICE type, it is exactly what the doctor ordered.
3432
28
      QualType type = ICE->getType();
3433
28
      if (needToScanForQualifiers(type))
3434
0
        type = Context->getObjCIdType();
3435
      // Make sure we convert "type (^)(...)" to "type (*)(...)".
3436
28
      (void)convertBlockPointerToFunctionPointer(type);
3437
28
      const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3438
28
      CastKind CK;
3439
28
      if (SubExpr->getType()->isIntegralType(*Context) &&
3440
28
          
type->isBooleanType()13
) {
3441
0
        CK = CK_IntegralToBoolean;
3442
28
      } else if (type->isObjCObjectPointerType()) {
3443
13
        if (SubExpr->getType()->isBlockPointerType()) {
3444
0
          CK = CK_BlockPointerToObjCPointerCast;
3445
13
        } else if (SubExpr->getType()->isPointerType()) {
3446
0
          CK = CK_CPointerToObjCPointerCast;
3447
13
        } else {
3448
13
          CK = CK_BitCast;
3449
13
        }
3450
15
      } else {
3451
15
        CK = CK_BitCast;
3452
15
      }
3453
3454
28
      userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3455
28
    }
3456
    // Make id<P...> cast into an 'id' cast.
3457
26
    else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3458
3
      if (CE->getType()->isObjCQualifiedIdType()) {
3459
0
        while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3460
0
          userExpr = CE->getSubExpr();
3461
0
        CastKind CK;
3462
0
        if (userExpr->getType()->isIntegralType(*Context)) {
3463
0
          CK = CK_IntegralToPointer;
3464
0
        } else if (userExpr->getType()->isBlockPointerType()) {
3465
0
          CK = CK_BlockPointerToObjCPointerCast;
3466
0
        } else if (userExpr->getType()->isPointerType()) {
3467
0
          CK = CK_CPointerToObjCPointerCast;
3468
0
        } else {
3469
0
          CK = CK_BitCast;
3470
0
        }
3471
0
        userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3472
0
                                            CK, userExpr);
3473
0
      }
3474
3
    }
3475
54
    MsgExprs.push_back(userExpr);
3476
    // We've transferred the ownership to MsgExprs. For now, we *don't* null
3477
    // out the argument in the original expression (since we aren't deleting
3478
    // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3479
    //Exp->setArg(i, 0);
3480
54
  }
3481
  // Generate the funky cast.
3482
104
  CastExpr *cast;
3483
104
  SmallVector<QualType, 8> ArgTypes;
3484
104
  QualType returnType;
3485
3486
  // Push 'id' and 'SEL', the 2 implicit arguments.
3487
104
  if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3488
1
    ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3489
103
  else
3490
103
    ArgTypes.push_back(Context->getObjCIdType());
3491
104
  ArgTypes.push_back(Context->getObjCSelType());
3492
104
  if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3493
    // Push any user argument types.
3494
98
    for (const auto *PI : OMD->parameters()) {
3495
44
      QualType t = PI->getType()->isObjCQualifiedIdType()
3496
44
                     ? 
Context->getObjCIdType()0
3497
44
                     : PI->getType();
3498
      // Make sure we convert "t (^)(...)" to "t (*)(...)".
3499
44
      (void)convertBlockPointerToFunctionPointer(t);
3500
44
      ArgTypes.push_back(t);
3501
44
    }
3502
98
    returnType = Exp->getType();
3503
98
    convertToUnqualifiedObjCType(returnType);
3504
98
    (void)convertBlockPointerToFunctionPointer(returnType);
3505
98
  } else {
3506
6
    returnType = Context->getObjCIdType();
3507
6
  }
3508
  // Get the type, we will need to reference it in a couple spots.
3509
104
  QualType msgSendType = MsgSendFlavor->getType();
3510
3511
  // Create a reference to the objc_msgSend() declaration.
3512
104
  DeclRefExpr *DRE = new (Context) DeclRefExpr(
3513
104
      *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
3514
3515
  // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3516
  // If we don't do this cast, we get the following bizarre warning/note:
3517
  // xx.m:13: warning: function called through a non-compatible type
3518
  // xx.m:13: note: if this code is reached, the program will abort
3519
104
  cast = NoTypeInfoCStyleCastExpr(Context,
3520
104
                                  Context->getPointerType(Context->VoidTy),
3521
104
                                  CK_BitCast, DRE);
3522
3523
  // Now do the "normal" pointer to function cast.
3524
  // If we don't have a method decl, force a variadic cast.
3525
104
  const ObjCMethodDecl *MD = Exp->getMethodDecl();
3526
104
  QualType castType =
3527
104
    getSimpleFunctionType(returnType, ArgTypes, MD ? 
MD->isVariadic()98
:
true6
);
3528
104
  castType = Context->getPointerType(castType);
3529
104
  cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3530
104
                                  cast);
3531
3532
  // Don't forget the parens to enforce the proper binding.
3533
104
  ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3534
3535
104
  const FunctionType *FT = msgSendType->castAs<FunctionType>();
3536
104
  CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
3537
104
                                  VK_PRValue, EndLoc, FPOptionsOverride());
3538
104
  Stmt *ReplacingStmt = CE;
3539
104
  if (MsgSendStretFlavor) {
3540
    // We have the method which returns a struct/union. Must also generate
3541
    // call to objc_msgSend_stret and hang both varieties on a conditional
3542
    // expression which dictate which one to envoke depending on size of
3543
    // method's return type.
3544
3545
12
    Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3546
12
                                           returnType,
3547
12
                                           ArgTypes, MsgExprs,
3548
12
                                           Exp->getMethodDecl());
3549
12
    ReplacingStmt = STCE;
3550
12
  }
3551
  // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3552
104
  return ReplacingStmt;
3553
104
}
3554
3555
71
Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3556
71
  Stmt *ReplacingStmt =
3557
71
      SynthMessageExpr(Exp, Exp->getBeginLoc(), Exp->getEndLoc());
3558
3559
  // Now do the actual rewrite.
3560
71
  ReplaceStmt(Exp, ReplacingStmt);
3561
3562
  // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3563
71
  return ReplacingStmt;
3564
71
}
3565
3566
// typedef struct objc_object Protocol;
3567
4
QualType RewriteModernObjC::getProtocolType() {
3568
4
  if (!ProtocolTypeDecl) {
3569
1
    TypeSourceInfo *TInfo
3570
1
      = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3571
1
    ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3572
1
                                           SourceLocation(), SourceLocation(),
3573
1
                                           &Context->Idents.get("Protocol"),
3574
1
                                           TInfo);
3575
1
  }
3576
4
  return Context->getTypeDeclType(ProtocolTypeDecl);
3577
4
}
3578
3579
/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3580
/// a synthesized/forward data reference (to the protocol's metadata).
3581
/// The forward references (and metadata) are generated in
3582
/// RewriteModernObjC::HandleTranslationUnit().
3583
2
Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
3584
2
  std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3585
2
                      Exp->getProtocol()->getNameAsString();
3586
2
  IdentifierInfo *ID = &Context->Idents.get(Name);
3587
2
  VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3588
2
                                SourceLocation(), ID, getProtocolType(),
3589
2
                                nullptr, SC_Extern);
3590
2
  DeclRefExpr *DRE = new (Context) DeclRefExpr(
3591
2
      *Context, VD, false, getProtocolType(), VK_LValue, SourceLocation());
3592
2
  CastExpr *castExpr = NoTypeInfoCStyleCastExpr(
3593
2
      Context, Context->getPointerType(DRE->getType()), CK_BitCast, DRE);
3594
2
  ReplaceStmt(Exp, castExpr);
3595
2
  ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3596
  // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3597
2
  return castExpr;
3598
2
}
3599
3600
/// IsTagDefinedInsideClass - This routine checks that a named tagged type
3601
/// is defined inside an objective-c class. If so, it returns true.
3602
bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
3603
                                                TagDecl *Tag,
3604
39
                                                bool &IsNamedDefinition) {
3605
39
  if (!IDecl)
3606
0
    return false;
3607
39
  SourceLocation TagLocation;
3608
39
  if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3609
31
    RD = RD->getDefinition();
3610
31
    if (!RD || !RD->getDeclName().getAsIdentifierInfo())
3611
16
      return false;
3612
15
    IsNamedDefinition = true;
3613
15
    TagLocation = RD->getLocation();
3614
15
    return Context->getSourceManager().isBeforeInTranslationUnit(
3615
15
                                          IDecl->getLocation(), TagLocation);
3616
31
  }
3617
8
  if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3618
8
    if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3619
4
      return false;
3620
4
    IsNamedDefinition = true;
3621
4
    TagLocation = ED->getLocation();
3622
4
    return Context->getSourceManager().isBeforeInTranslationUnit(
3623
4
                                          IDecl->getLocation(), TagLocation);
3624
8
  }
3625
0
  return false;
3626
8
}
3627
3628
/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
3629
/// It handles elaborated types, as well as enum types in the process.
3630
bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3631
297
                                                 std::string &Result) {
3632
297
  if (isa<TypedefType>(Type)) {
3633
44
    Result += "\t";
3634
44
    return false;
3635
44
  }
3636
3637
253
  if (Type->isArrayType()) {
3638
2
    QualType ElemTy = Context->getBaseElementType(Type);
3639
2
    return RewriteObjCFieldDeclType(ElemTy, Result);
3640
2
  }
3641
251
  else if (Type->isRecordType()) {
3642
68
    RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
3643
68
    if (RD->isCompleteDefinition()) {
3644
68
      if (RD->isStruct())
3645
61
        Result += "\n\tstruct ";
3646
7
      else if (RD->isUnion())
3647
7
        Result += "\n\tunion ";
3648
0
      else
3649
0
        assert(false && "class not allowed as an ivar type");
3650
3651
0
      Result += RD->getName();
3652
68
      if (GlobalDefinedTags.count(RD)) {
3653
        // struct/union is defined globally, use it.
3654
27
        Result += " ";
3655
27
        return true;
3656
27
      }
3657
41
      Result += " {\n";
3658
41
      for (auto *FD : RD->fields())
3659
102
        RewriteObjCFieldDecl(FD, Result);
3660
41
      Result += "\t} ";
3661
41
      return true;
3662
68
    }
3663
68
  }
3664
183
  else if (Type->isEnumeralType()) {
3665
16
    EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
3666
16
    if (ED->isCompleteDefinition()) {
3667
16
      Result += "\n\tenum ";
3668
16
      Result += ED->getName();
3669
16
      if (GlobalDefinedTags.count(ED)) {
3670
        // Enum is globall defined, use it.
3671
9
        Result += " ";
3672
9
        return true;
3673
9
      }
3674
3675
7
      Result += " {\n";
3676
13
      for (const auto *EC : ED->enumerators()) {
3677
13
        Result += "\t"; Result += EC->getName(); Result += " = ";
3678
13
        Result += toString(EC->getInitVal(), 10);
3679
13
        Result += ",\n";
3680
13
      }
3681
7
      Result += "\t} ";
3682
7
      return true;
3683
16
    }
3684
16
  }
3685
3686
167
  Result += "\t";
3687
167
  convertObjCTypeToCStyleType(Type);
3688
167
  return false;
3689
253
}
3690
3691
3692
/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3693
/// It handles elaborated types, as well as enum types in the process.
3694
void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3695
269
                                             std::string &Result) {
3696
269
  QualType Type = fieldDecl->getType();
3697
269
  std::string Name = fieldDecl->getNameAsString();
3698
3699
269
  bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3700
269
  if (!EleboratedType)
3701
211
    Type.getAsStringInternal(Name, Context->getPrintingPolicy());
3702
269
  Result += Name;
3703
269
  if (fieldDecl->isBitField()) {
3704
64
    Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3705
64
  }
3706
205
  else if (EleboratedType && 
Type->isArrayType()58
) {
3707
1
    const ArrayType *AT = Context->getAsArrayType(Type);
3708
2
    do {
3709
2
      if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
3710
2
        Result += "[";
3711
2
        llvm::APInt Dim = CAT->getSize();
3712
2
        Result += utostr(Dim.getZExtValue());
3713
2
        Result += "]";
3714
2
      }
3715
2
      AT = Context->getAsArrayType(AT->getElementType());
3716
2
    } while (AT);
3717
1
  }
3718
3719
269
  Result += ";\n";
3720
269
}
3721
3722
/// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3723
/// named aggregate types into the input buffer.
3724
void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3725
213
                                             std::string &Result) {
3726
213
  QualType Type = fieldDecl->getType();
3727
213
  if (isa<TypedefType>(Type))
3728
42
    return;
3729
171
  if (Type->isArrayType())
3730
2
    Type = Context->getBaseElementType(Type);
3731
3732
171
  auto *IDecl = dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
3733
3734
171
  TagDecl *TD = nullptr;
3735
171
  if (Type->isRecordType()) {
3736
43
    TD = Type->castAs<RecordType>()->getDecl();
3737
43
  }
3738
128
  else if (Type->isEnumeralType()) {
3739
13
    TD = Type->castAs<EnumType>()->getDecl();
3740
13
  }
3741
3742
171
  if (TD) {
3743
56
    if (GlobalDefinedTags.count(TD))
3744
17
      return;
3745
3746
39
    bool IsNamedDefinition = false;
3747
39
    if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3748
14
      RewriteObjCFieldDeclType(Type, Result);
3749
14
      Result += ";";
3750
14
    }
3751
39
    if (IsNamedDefinition)
3752
19
      GlobalDefinedTags.insert(TD);
3753
39
  }
3754
171
}
3755
3756
171
unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) {
3757
171
  const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3758
171
  if (ObjCInterefaceHasBitfieldGroups.count(CDecl)) {
3759
160
    return IvarGroupNumber[IV];
3760
160
  }
3761
11
  unsigned GroupNo = 0;
3762
11
  SmallVector<const ObjCIvarDecl *, 8> IVars;
3763
11
  for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3764
90
       IVD; 
IVD = IVD->getNextIvar()79
)
3765
79
    IVars.push_back(IVD);
3766
3767
56
  for (unsigned i = 0, e = IVars.size(); i < e; 
i++45
)
3768
45
    if (IVars[i]->isBitField()) {
3769
12
      IvarGroupNumber[IVars[i++]] = ++GroupNo;
3770
46
      while (i < e && 
IVars[i]->isBitField()39
)
3771
34
        IvarGroupNumber[IVars[i++]] = GroupNo;
3772
12
      if (i < e)
3773
5
        --i;
3774
12
    }
3775
3776
11
  ObjCInterefaceHasBitfieldGroups.insert(CDecl);
3777
11
  return IvarGroupNumber[IV];
3778
171
}
3779
3780
QualType RewriteModernObjC::SynthesizeBitfieldGroupStructType(
3781
                              ObjCIvarDecl *IV,
3782
12
                              SmallVectorImpl<ObjCIvarDecl *> &IVars) {
3783
12
  std::string StructTagName;
3784
12
  ObjCIvarBitfieldGroupType(IV, StructTagName);
3785
12
  RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct,
3786
12
                                      Context->getTranslationUnitDecl(),
3787
12
                                      SourceLocation(), SourceLocation(),
3788
12
                                      &Context->Idents.get(StructTagName));
3789
58
  for (unsigned i=0, e = IVars.size(); i < e; 
i++46
) {
3790
46
    ObjCIvarDecl *Ivar = IVars[i];
3791
46
    RD->addDecl(FieldDecl::Create(*Context, RD, SourceLocation(), SourceLocation(),
3792
46
                                  &Context->Idents.get(Ivar->getName()),
3793
46
                                  Ivar->getType(),
3794
46
                                  nullptr, /*Expr *BW */Ivar->getBitWidth(),
3795
46
                                  false, ICIS_NoInit));
3796
46
  }
3797
12
  RD->completeDefinition();
3798
12
  return Context->getTagDeclType(RD);
3799
12
}
3800
3801
42
QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV) {
3802
42
  const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3803
42
  unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3804
42
  std::pair<const ObjCInterfaceDecl*, unsigned> tuple = std::make_pair(CDecl, GroupNo);
3805
42
  if (GroupRecordType.count(tuple))
3806
31
    return GroupRecordType[tuple];
3807
3808
11
  SmallVector<ObjCIvarDecl *, 8> IVars;
3809
11
  for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3810
90
       IVD; 
IVD = IVD->getNextIvar()79
) {
3811
79
    if (IVD->isBitField())
3812
46
      IVars.push_back(const_cast<ObjCIvarDecl *>(IVD));
3813
33
    else {
3814
33
      if (!IVars.empty()) {
3815
5
        unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3816
        // Generate the struct type for this group of bitfield ivars.
3817
5
        GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3818
5
          SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3819
5
        IVars.clear();
3820
5
      }
3821
33
    }
3822
79
  }
3823
11
  if (!IVars.empty()) {
3824
    // Do the last one.
3825
7
    unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3826
7
    GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3827
7
      SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3828
7
  }
3829
11
  QualType RetQT = GroupRecordType[tuple];
3830
11
  assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL");
3831
3832
0
  return RetQT;
3833
42
}
3834
3835
/// ObjCIvarBitfieldGroupDecl - Names field decl. for ivar bitfield group.
3836
/// Name would be: classname__GRBF_n where n is the group number for this ivar.
3837
void RewriteModernObjC::ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV,
3838
82
                                                  std::string &Result) {
3839
82
  const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3840
82
  Result += CDecl->getName();
3841
82
  Result += "__GRBF_";
3842
82
  unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3843
82
  Result += utostr(GroupNo);
3844
82
}
3845
3846
/// ObjCIvarBitfieldGroupType - Names struct type for ivar bitfield group.
3847
/// Name of the struct would be: classname__T_n where n is the group number for
3848
/// this ivar.
3849
void RewriteModernObjC::ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV,
3850
24
                                                  std::string &Result) {
3851
24
  const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3852
24
  Result += CDecl->getName();
3853
24
  Result += "__T_";
3854
24
  unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3855
24
  Result += utostr(GroupNo);
3856
24
}
3857
3858
/// ObjCIvarBitfieldGroupOffset - Names symbol for ivar bitfield group field offset.
3859
/// Name would be: OBJC_IVAR_$_classname__GRBF_n where n is the group number for
3860
/// this ivar.
3861
void RewriteModernObjC::ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV,
3862
44
                                                    std::string &Result) {
3863
44
  Result += "OBJC_IVAR_$_";
3864
44
  ObjCIvarBitfieldGroupDecl(IV, Result);
3865
44
}
3866
3867
46
#define SKIP_BITFIELDS(IX, ENDIX, VEC) { \
3868
204
      while ((IX < ENDIX) && 
VEC[IX]->isBitField()178
) \
3869
158
        ++IX; \
3870
46
      if (IX < ENDIX) \
3871
46
        
--IX20
; \
3872
46
}
3873
3874
/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3875
/// an objective-c class with ivars.
3876
void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3877
152
                                               std::string &Result) {
3878
152
  assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3879
0
  assert(CDecl->getName() != "" &&
3880
152
         "Name missing in SynthesizeObjCInternalStruct");
3881
0
  ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
3882
152
  SmallVector<ObjCIvarDecl *, 8> IVars;
3883
152
  for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3884
365
       IVD; 
IVD = IVD->getNextIvar()213
)
3885
213
    IVars.push_back(IVD);
3886
3887
152
  SourceLocation LocStart = CDecl->getBeginLoc();
3888
152
  SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
3889
3890
152
  const char *startBuf = SM->getCharacterData(LocStart);
3891
152
  const char *endBuf = SM->getCharacterData(LocEnd);
3892
3893
  // If no ivars and no root or if its root, directly or indirectly,
3894
  // have no ivars (thus not synthesized) then no need to synthesize this class.
3895
152
  if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
3896
152
      
(88
!RCDecl88
||
!ObjCSynthesizedStructs.count(RCDecl)15
)) {
3897
86
    endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3898
86
    ReplaceText(LocStart, endBuf-startBuf, Result);
3899
86
    return;
3900
86
  }
3901
3902
  // Insert named struct/union definitions inside class to
3903
  // outer scope. This follows semantics of locally defined
3904
  // struct/unions in objective-c classes.
3905
279
  
for (unsigned i = 0, e = IVars.size(); 66
i < e;
i++213
)
3906
213
    RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
3907
3908
  // Insert named structs which are syntheized to group ivar bitfields
3909
  // to outer scope as well.
3910
245
  for (unsigned i = 0, e = IVars.size(); i < e; 
i++179
)
3911
179
    if (IVars[i]->isBitField()) {
3912
12
      ObjCIvarDecl *IV = IVars[i];
3913
12
      QualType QT = GetGroupRecordTypeForObjCIvarBitfield(IV);
3914
12
      RewriteObjCFieldDeclType(QT, Result);
3915
12
      Result += ";";
3916
      // skip over ivar bitfields in this group.
3917
12
      SKIP_BITFIELDS(i , e, IVars);
3918
12
    }
3919
3920
66
  Result += "\nstruct ";
3921
66
  Result += CDecl->getNameAsString();
3922
66
  Result += "_IMPL {\n";
3923
3924
66
  if (RCDecl && 
ObjCSynthesizedStructs.count(RCDecl)14
) {
3925
9
    Result += "\tstruct "; Result += RCDecl->getNameAsString();
3926
9
    Result += "_IMPL "; Result += RCDecl->getNameAsString();
3927
9
    Result += "_IVARS;\n";
3928
9
  }
3929
3930
245
  for (unsigned i = 0, e = IVars.size(); i < e; 
i++179
) {
3931
179
    if (IVars[i]->isBitField()) {
3932
12
      ObjCIvarDecl *IV = IVars[i];
3933
12
      Result += "\tstruct ";
3934
12
      ObjCIvarBitfieldGroupType(IV, Result); Result += " ";
3935
12
      ObjCIvarBitfieldGroupDecl(IV, Result); Result += ";\n";
3936
      // skip over ivar bitfields in this group.
3937
12
      SKIP_BITFIELDS(i , e, IVars);
3938
12
    }
3939
167
    else
3940
167
      RewriteObjCFieldDecl(IVars[i], Result);
3941
179
  }
3942
3943
66
  Result += "};\n";
3944
66
  endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3945
66
  ReplaceText(LocStart, endBuf-startBuf, Result);
3946
  // Mark this struct as having been generated.
3947
66
  if (!ObjCSynthesizedStructs.insert(CDecl).second)
3948
0
    llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
3949
66
}
3950
3951
/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3952
/// have been referenced in an ivar access expression.
3953
void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3954
152
                                                  std::string &Result) {
3955
  // write out ivar offset symbols which have been referenced in an ivar
3956
  // access expression.
3957
152
  llvm::SmallSetVector<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3958
3959
152
  if (Ivars.empty())
3960
109
    return;
3961
3962
43
  llvm::DenseSet<std::pair<const ObjCInterfaceDecl*, unsigned> > GroupSymbolOutput;
3963
85
  for (ObjCIvarDecl *IvarDecl : Ivars) {
3964
85
    const ObjCInterfaceDecl *IDecl = IvarDecl->getContainingInterface();
3965
85
    unsigned GroupNo = 0;
3966
85
    if (IvarDecl->isBitField()) {
3967
11
      GroupNo = ObjCIvarBitfieldGroupNo(IvarDecl);
3968
11
      if (GroupSymbolOutput.count(std::make_pair(IDecl, GroupNo)))
3969
8
        continue;
3970
11
    }
3971
77
    Result += "\n";
3972
77
    if (LangOpts.MicrosoftExt)
3973
77
      Result += "__declspec(allocate(\".objc_ivar$B\")) ";
3974
77
    Result += "extern \"C\" ";
3975
77
    if (LangOpts.MicrosoftExt &&
3976
77
        IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
3977
77
        
IvarDecl->getAccessControl() != ObjCIvarDecl::Package50
)
3978
50
        Result += "__declspec(dllimport) ";
3979
3980
77
    Result += "unsigned long ";
3981
77
    if (IvarDecl->isBitField()) {
3982
3
      ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
3983
3
      GroupSymbolOutput.insert(std::make_pair(IDecl, GroupNo));
3984
3
    }
3985
74
    else
3986
74
      WriteInternalIvarName(CDecl, IvarDecl, Result);
3987
77
    Result += ";";
3988
77
  }
3989
43
}
3990
3991
//===----------------------------------------------------------------------===//
3992
// Meta Data Emission
3993
//===----------------------------------------------------------------------===//
3994
3995
/// RewriteImplementations - This routine rewrites all method implementations
3996
/// and emits meta-data.
3997
3998
52
void RewriteModernObjC::RewriteImplementations() {
3999
52
  int ClsDefCount = ClassImplementation.size();
4000
52
  int CatDefCount = CategoryImplementation.size();
4001
4002
  // Rewrite implemented methods
4003
140
  for (int i = 0; i < ClsDefCount; 
i++88
) {
4004
88
    ObjCImplementationDecl *OIMP = ClassImplementation[i];
4005
88
    ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
4006
88
    if (CDecl->isImplicitInterfaceDecl())
4007
0
      assert(false &&
4008
88
             "Legacy implicit interface rewriting not supported in moder abi");
4009
0
    RewriteImplementationDecl(OIMP);
4010
88
  }
4011
4012
57
  for (int i = 0; i < CatDefCount; 
i++5
) {
4013
5
    ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
4014
5
    ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
4015
5
    if (CDecl->isImplicitInterfaceDecl())
4016
0
      assert(false &&
4017
5
             "Legacy implicit interface rewriting not supported in moder abi");
4018
0
    RewriteImplementationDecl(CIMP);
4019
5
  }
4020
52
}
4021
4022
void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
4023
                                     const std::string &Name,
4024
291
                                     ValueDecl *VD, bool def) {
4025
291
  assert(BlockByRefDeclNo.count(VD) &&
4026
291
         "RewriteByRefString: ByRef decl missing");
4027
291
  if (def)
4028
83
    ResultStr += "struct ";
4029
291
  ResultStr += "__Block_byref_" + Name +
4030
291
    "_" + utostr(BlockByRefDeclNo[VD]) ;
4031
291
}
4032
4033
907
static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4034
907
  if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4035
436
    return (Var->isFunctionOrMethodVarDecl() && 
!Var->hasLocalStorage()176
);
4036
471
  return false;
4037
907
}
4038
4039
std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4040
                                                   StringRef funcName,
4041
80
                                                   std::string Tag) {
4042
80
  const FunctionType *AFT = CE->getFunctionType();
4043
80
  QualType RT = AFT->getReturnType();
4044
80
  std::string StructRef = "struct " + Tag;
4045
80
  SourceLocation BlockLoc = CE->getExprLoc();
4046
80
  std::string S;
4047
80
  ConvertSourceLocationToLineDirective(BlockLoc, S);
4048
4049
80
  S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
4050
80
         funcName.str() + "_block_func_" + utostr(i);
4051
4052
80
  BlockDecl *BD = CE->getBlockDecl();
4053
4054
80
  if (isa<FunctionNoProtoType>(AFT)) {
4055
    // No user-supplied arguments. Still need to pass in a pointer to the
4056
    // block (to reference imported block decl refs).
4057
0
    S += "(" + StructRef + " *__cself)";
4058
80
  } else if (BD->param_empty()) {
4059
70
    S += "(" + StructRef + " *__cself)";
4060
70
  } else {
4061
10
    const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4062
10
    assert(FT && "SynthesizeBlockFunc: No function proto");
4063
0
    S += '(';
4064
    // first add the implicit argument.
4065
10
    S += StructRef + " *__cself, ";
4066
10
    std::string ParamStr;
4067
10
    for (BlockDecl::param_iterator AI = BD->param_begin(),
4068
23
         E = BD->param_end(); AI != E; 
++AI13
) {
4069
13
      if (AI != BD->param_begin()) 
S += ", "3
;
4070
13
      ParamStr = (*AI)->getNameAsString();
4071
13
      QualType QT = (*AI)->getType();
4072
13
      (void)convertBlockPointerToFunctionPointer(QT);
4073
13
      QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
4074
13
      S += ParamStr;
4075
13
    }
4076
10
    if (FT->isVariadic()) {
4077
0
      if (!BD->param_empty()) S += ", ";
4078
0
      S += "...";
4079
0
    }
4080
10
    S += ')';
4081
10
  }
4082
0
  S += " {\n";
4083
4084
  // Create local declarations to avoid rewriting all closure decl ref exprs.
4085
  // First, emit a declaration for all "by ref" decls.
4086
80
  for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
4087
121
       E = BlockByRefDecls.end(); I != E; 
++I41
) {
4088
41
    S += "  ";
4089
41
    std::string Name = (*I)->getNameAsString();
4090
41
    std::string TypeString;
4091
41
    RewriteByRefString(TypeString, Name, (*I));
4092
41
    TypeString += " *";
4093
41
    Name = TypeString + Name;
4094
41
    S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4095
41
  }
4096
  // Next, emit a declaration for all "by copy" declarations.
4097
80
  for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
4098
116
       E = BlockByCopyDecls.end(); I != E; 
++I36
) {
4099
36
    S += "  ";
4100
    // Handle nested closure invocation. For example:
4101
    //
4102
    //   void (^myImportedClosure)(void);
4103
    //   myImportedClosure  = ^(void) { setGlobalInt(x + y); };
4104
    //
4105
    //   void (^anotherClosure)(void);
4106
    //   anotherClosure = ^(void) {
4107
    //     myImportedClosure(); // import and invoke the closure
4108
    //   };
4109
    //
4110
36
    if (isTopLevelBlockPointerType((*I)->getType())) {
4111
2
      RewriteBlockPointerTypeVariable(S, (*I));
4112
2
      S += " = (";
4113
2
      RewriteBlockPointerType(S, (*I)->getType());
4114
2
      S += ")";
4115
2
      S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4116
2
    }
4117
34
    else {
4118
34
      std::string Name = (*I)->getNameAsString();
4119
34
      QualType QT = (*I)->getType();
4120
34
      if (HasLocalVariableExternalStorage(*I))
4121
0
        QT = Context->getPointerType(QT);
4122
34
      QT.getAsStringInternal(Name, Context->getPrintingPolicy());
4123
34
      S += Name + " = __cself->" +
4124
34
                              (*I)->getNameAsString() + "; // bound by copy\n";
4125
34
    }
4126
36
  }
4127
80
  std::string RewrittenStr = RewrittenBlockExprs[CE];
4128
80
  const char *cstr = RewrittenStr.c_str();
4129
356
  while (*cstr++ != '{') 
;276
4130
80
  S += cstr;
4131
80
  S += "\n";
4132
80
  return S;
4133
80
}
4134
4135
std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4136
                                                   StringRef funcName,
4137
29
                                                   std::string Tag) {
4138
29
  std::string StructRef = "struct " + Tag;
4139
29
  std::string S = "static void __";
4140
4141
29
  S += funcName;
4142
29
  S += "_block_copy_" + utostr(i);
4143
29
  S += "(" + StructRef;
4144
29
  S += "*dst, " + StructRef;
4145
29
  S += "*src) {";
4146
44
  for (ValueDecl *VD : ImportedBlockDecls) {
4147
44
    S += "_Block_object_assign((void*)&dst->";
4148
44
    S += VD->getNameAsString();
4149
44
    S += ", (void*)src->";
4150
44
    S += VD->getNameAsString();
4151
44
    if (BlockByRefDeclsPtrSet.count(VD))
4152
28
      S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4153
16
    else if (VD->getType()->isBlockPointerType())
4154
2
      S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4155
14
    else
4156
14
      S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4157
44
  }
4158
29
  S += "}\n";
4159
4160
29
  S += "\nstatic void __";
4161
29
  S += funcName;
4162
29
  S += "_block_dispose_" + utostr(i);
4163
29
  S += "(" + StructRef;
4164
29
  S += "*src) {";
4165
44
  for (ValueDecl *VD : ImportedBlockDecls) {
4166
44
    S += "_Block_object_dispose((void*)src->";
4167
44
    S += VD->getNameAsString();
4168
44
    if (BlockByRefDeclsPtrSet.count(VD))
4169
28
      S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4170
16
    else if (VD->getType()->isBlockPointerType())
4171
2
      S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4172
14
    else
4173
14
      S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4174
44
  }
4175
29
  S += "}\n";
4176
29
  return S;
4177
29
}
4178
4179
std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4180
80
                                             std::string Desc) {
4181
80
  std::string S = "\nstruct " + Tag;
4182
80
  std::string Constructor = "  " + Tag;
4183
4184
80
  S += " {\n  struct __block_impl impl;\n";
4185
80
  S += "  struct " + Desc;
4186
80
  S += "* Desc;\n";
4187
4188
80
  Constructor += "(void *fp, "; // Invoke function pointer.
4189
80
  Constructor += "struct " + Desc; // Descriptor pointer.
4190
80
  Constructor += " *desc";
4191
4192
80
  if (BlockDeclRefs.size()) {
4193
    // Output all "by copy" declarations.
4194
43
    for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
4195
79
         E = BlockByCopyDecls.end(); I != E; 
++I36
) {
4196
36
      S += "  ";
4197
36
      std::string FieldName = (*I)->getNameAsString();
4198
36
      std::string ArgName = "_" + FieldName;
4199
      // Handle nested closure invocation. For example:
4200
      //
4201
      //   void (^myImportedBlock)(void);
4202
      //   myImportedBlock  = ^(void) { setGlobalInt(x + y); };
4203
      //
4204
      //   void (^anotherBlock)(void);
4205
      //   anotherBlock = ^(void) {
4206
      //     myImportedBlock(); // import and invoke the closure
4207
      //   };
4208
      //
4209
36
      if (isTopLevelBlockPointerType((*I)->getType())) {
4210
2
        S += "struct __block_impl *";
4211
2
        Constructor += ", void *" + ArgName;
4212
34
      } else {
4213
34
        QualType QT = (*I)->getType();
4214
34
        if (HasLocalVariableExternalStorage(*I))
4215
0
          QT = Context->getPointerType(QT);
4216
34
        QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4217
34
        QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4218
34
        Constructor += ", " + ArgName;
4219
34
      }
4220
36
      S += FieldName + ";\n";
4221
36
    }
4222
    // Output all "by ref" declarations.
4223
43
    for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
4224
84
         E = BlockByRefDecls.end(); I != E; 
++I41
) {
4225
41
      S += "  ";
4226
41
      std::string FieldName = (*I)->getNameAsString();
4227
41
      std::string ArgName = "_" + FieldName;
4228
41
      {
4229
41
        std::string TypeString;
4230
41
        RewriteByRefString(TypeString, FieldName, (*I));
4231
41
        TypeString += " *";
4232
41
        FieldName = TypeString + FieldName;
4233
41
        ArgName = TypeString + ArgName;
4234
41
        Constructor += ", " + ArgName;
4235
41
      }
4236
41
      S += FieldName + "; // by ref\n";
4237
41
    }
4238
    // Finish writing the constructor.
4239
43
    Constructor += ", int flags=0)";
4240
    // Initialize all "by copy" arguments.
4241
43
    bool firsTime = true;
4242
43
    for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
4243
79
         E = BlockByCopyDecls.end(); I != E; 
++I36
) {
4244
36
      std::string Name = (*I)->getNameAsString();
4245
36
        if (firsTime) {
4246
24
          Constructor += " : ";
4247
24
          firsTime = false;
4248
24
        }
4249
12
        else
4250
12
          Constructor += ", ";
4251
36
        if (isTopLevelBlockPointerType((*I)->getType()))
4252
2
          Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4253
34
        else
4254
34
          Constructor += Name + "(_" + Name + ")";
4255
36
    }
4256
    // Initialize all "by ref" arguments.
4257
43
    for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
4258
84
         E = BlockByRefDecls.end(); I != E; 
++I41
) {
4259
41
      std::string Name = (*I)->getNameAsString();
4260
41
      if (firsTime) {
4261
19
        Constructor += " : ";
4262
19
        firsTime = false;
4263
19
      }
4264
22
      else
4265
22
        Constructor += ", ";
4266
41
      Constructor += Name + "(_" + Name + "->__forwarding)";
4267
41
    }
4268
4269
43
    Constructor += " {\n";
4270
43
    if (GlobalVarDecl)
4271
0
      Constructor += "    impl.isa = &_NSConcreteGlobalBlock;\n";
4272
43
    else
4273
43
      Constructor += "    impl.isa = &_NSConcreteStackBlock;\n";
4274
43
    Constructor += "    impl.Flags = flags;\n    impl.FuncPtr = fp;\n";
4275
4276
43
    Constructor += "    Desc = desc;\n";
4277
43
  } else {
4278
    // Finish writing the constructor.
4279
37
    Constructor += ", int flags=0) {\n";
4280
37
    if (GlobalVarDecl)
4281
6
      Constructor += "    impl.isa = &_NSConcreteGlobalBlock;\n";
4282
31
    else
4283
31
      Constructor += "    impl.isa = &_NSConcreteStackBlock;\n";
4284
37
    Constructor += "    impl.Flags = flags;\n    impl.FuncPtr = fp;\n";
4285
37
    Constructor += "    Desc = desc;\n";
4286
37
  }
4287
80
  Constructor += "  ";
4288
80
  Constructor += "}\n";
4289
80
  S += Constructor;
4290
80
  S += "};\n";
4291
80
  return S;
4292
80
}
4293
4294
std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4295
                                                   std::string ImplTag, int i,
4296
                                                   StringRef FunName,
4297
80
                                                   unsigned hasCopy) {
4298
80
  std::string S = "\nstatic struct " + DescTag;
4299
4300
80
  S += " {\n  size_t reserved;\n";
4301
80
  S += "  size_t Block_size;\n";
4302
80
  if (hasCopy) {
4303
29
    S += "  void (*copy)(struct ";
4304
29
    S += ImplTag; S += "*, struct ";
4305
29
    S += ImplTag; S += "*);\n";
4306
4307
29
    S += "  void (*dispose)(struct ";
4308
29
    S += ImplTag; S += "*);\n";
4309
29
  }
4310
80
  S += "} ";
4311
4312
80
  S += DescTag + "_DATA = { 0, sizeof(struct ";
4313
80
  S += ImplTag + ")";
4314
80
  if (hasCopy) {
4315
29
    S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4316
29
    S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4317
29
  }
4318
80
  S += "};\n";
4319
80
  return S;
4320
80
}
4321
4322
void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4323
171
                                          StringRef FunName) {
4324
171
  bool RewriteSC = (GlobalVarDecl &&
4325
171
                    
!Blocks.empty()9
&&
4326
171
                    
GlobalVarDecl->getStorageClass() == SC_Static6
&&
4327
171
                    
GlobalVarDecl->getType().getCVRQualifiers()4
);
4328
171
  if (RewriteSC) {
4329
4
    std::string SC(" void __");
4330
4
    SC += GlobalVarDecl->getNameAsString();
4331
4
    SC += "() {}";
4332
4
    InsertText(FunLocStart, SC);
4333
4
  }
4334
4335
  // Insert closures that were part of the function.
4336
251
  for (unsigned i = 0, count=0; i < Blocks.size(); 
i++80
) {
4337
80
    CollectBlockDeclRefInfo(Blocks[i]);
4338
    // Need to copy-in the inner copied-in variables not actually used in this
4339
    // block.
4340
105
    for (int j = 0; j < InnerDeclRefsCount[i]; 
j++25
) {
4341
25
      DeclRefExpr *Exp = InnerDeclRefs[count++];
4342
25
      ValueDecl *VD = Exp->getDecl();
4343
25
      BlockDeclRefs.push_back(Exp);
4344
25
      if (!VD->hasAttr<BlocksAttr>()) {
4345
12
        if (!BlockByCopyDeclsPtrSet.count(VD)) {
4346
12
          BlockByCopyDeclsPtrSet.insert(VD);
4347
12
          BlockByCopyDecls.push_back(VD);
4348
12
        }
4349
12
        continue;
4350
12
      }
4351
4352
13
      if (!BlockByRefDeclsPtrSet.count(VD)) {
4353
13
        BlockByRefDeclsPtrSet.insert(VD);
4354
13
        BlockByRefDecls.push_back(VD);
4355
13
      }
4356
4357
      // imported objects in the inner blocks not used in the outer
4358
      // blocks must be copied/disposed in the outer block as well.
4359
13
      if (VD->getType()->isObjCObjectPointerType() ||
4360
13
          VD->getType()->isBlockPointerType())
4361
0
        ImportedBlockDecls.insert(VD);
4362
13
    }
4363
4364
80
    std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4365
80
    std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4366
4367
80
    std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4368
4369
80
    InsertText(FunLocStart, CI);
4370
4371
80
    std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4372
4373
80
    InsertText(FunLocStart, CF);
4374
4375
80
    if (ImportedBlockDecls.size()) {
4376
29
      std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4377
29
      InsertText(FunLocStart, HF);
4378
29
    }
4379
80
    std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4380
80
                                               ImportedBlockDecls.size() > 0);
4381
80
    InsertText(FunLocStart, BD);
4382
4383
80
    BlockDeclRefs.clear();
4384
80
    BlockByRefDecls.clear();
4385
80
    BlockByRefDeclsPtrSet.clear();
4386
80
    BlockByCopyDecls.clear();
4387
80
    BlockByCopyDeclsPtrSet.clear();
4388
80
    ImportedBlockDecls.clear();
4389
80
  }
4390
171
  if (RewriteSC) {
4391
    // Must insert any 'const/volatile/static here. Since it has been
4392
    // removed as result of rewriting of block literals.
4393
4
    std::string SC;
4394
4
    if (GlobalVarDecl->getStorageClass() == SC_Static)
4395
4
      SC = "static ";
4396
4
    if (GlobalVarDecl->getType().isConstQualified())
4397
4
      SC += "const ";
4398
4
    if (GlobalVarDecl->getType().isVolatileQualified())
4399
0
      SC += "volatile ";
4400
4
    if (GlobalVarDecl->getType().isRestrictQualified())
4401
0
      SC += "restrict ";
4402
4
    InsertText(FunLocStart, SC);
4403
4
  }
4404
171
  if (GlobalConstructionExp) {
4405
    // extra fancy dance for global literal expression.
4406
4407
    // Always the latest block expression on the block stack.
4408
6
    std::string Tag = "__";
4409
6
    Tag += FunName;
4410
6
    Tag += "_block_impl_";
4411
6
    Tag += utostr(Blocks.size()-1);
4412
6
    std::string globalBuf = "static ";
4413
6
    globalBuf += Tag; globalBuf += " ";
4414
6
    std::string SStr;
4415
4416
6
    llvm::raw_string_ostream constructorExprBuf(SStr);
4417
6
    GlobalConstructionExp->printPretty(constructorExprBuf, nullptr,
4418
6
                                       PrintingPolicy(LangOpts));
4419
6
    globalBuf += constructorExprBuf.str();
4420
6
    globalBuf += ";\n";
4421
6
    InsertText(FunLocStart, globalBuf);
4422
6
    GlobalConstructionExp = nullptr;
4423
6
  }
4424
4425
171
  Blocks.clear();
4426
171
  InnerDeclRefsCount.clear();
4427
171
  InnerDeclRefs.clear();
4428
171
  RewrittenBlockExprs.clear();
4429
171
}
4430
4431
99
void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4432
99
  SourceLocation FunLocStart =
4433
99
    (!Blocks.empty()) ? 
getFunctionSourceLocation(*this, FD)31
4434
99
                      : 
FD->getTypeSpecStartLoc()68
;
4435
99
  StringRef FuncName = FD->getName();
4436
4437
99
  SynthesizeBlockLiterals(FunLocStart, FuncName);
4438
99
}
4439
4440
static void BuildUniqueMethodName(std::string &Name,
4441
84
                                  ObjCMethodDecl *MD) {
4442
84
  ObjCInterfaceDecl *IFace = MD->getClassInterface();
4443
84
  Name = std::string(IFace->getName());
4444
84
  Name += "__" + MD->getSelector().getAsString();
4445
  // Convert colons to underscores.
4446
84
  std::string::size_type loc = 0;
4447
114
  while ((loc = Name.find(':', loc)) != std::string::npos)
4448
30
    Name.replace(loc, 1, "_");
4449
84
}
4450
4451
63
void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4452
  // fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4453
  // SourceLocation FunLocStart = MD->getBeginLoc();
4454
63
  SourceLocation FunLocStart = MD->getBeginLoc();
4455
63
  std::string FuncName;
4456
63
  BuildUniqueMethodName(FuncName, MD);
4457
63
  SynthesizeBlockLiterals(FunLocStart, FuncName);
4458
63
}
4459
4460
1.91k
void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4461
1.91k
  for (Stmt *SubStmt : S->children())
4462
1.75k
    if (SubStmt) {
4463
1.75k
      if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt))
4464
0
        GetBlockDeclRefExprs(CBE->getBody());
4465
1.75k
      else
4466
1.75k
        GetBlockDeclRefExprs(SubStmt);
4467
1.75k
    }
4468
  // Handle specific things.
4469
1.91k
  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4470
448
    if (DRE->refersToEnclosingVariableOrCapture() ||
4471
448
        
HasLocalVariableExternalStorage(DRE->getDecl())336
)
4472
      // FIXME: Handle enums.
4473
112
      BlockDeclRefs.push_back(DRE);
4474
1.91k
}
4475
4476
void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4477
                SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
4478
720
                llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts) {
4479
720
  for (Stmt *SubStmt : S->children())
4480
640
    if (SubStmt) {
4481
640
      if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt)) {
4482
21
        InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4483
21
        GetInnerBlockDeclRefExprs(CBE->getBody(),
4484
21
                                  InnerBlockDeclRefs,
4485
21
                                  InnerContexts);
4486
21
      }
4487
619
      else
4488
619
        GetInnerBlockDeclRefExprs(SubStmt, InnerBlockDeclRefs, InnerContexts);
4489
640
    }
4490
  // Handle specific things.
4491
720
  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4492
154
    if (DRE->refersToEnclosingVariableOrCapture() ||
4493
154
        
HasLocalVariableExternalStorage(DRE->getDecl())61
) {
4494
93
      if (!InnerContexts.count(DRE->getDecl()->getDeclContext()))
4495
88
        InnerBlockDeclRefs.push_back(DRE);
4496
93
      if (VarDecl *Var = cast<VarDecl>(DRE->getDecl()))
4497
93
        if (Var->isFunctionOrMethodVarDecl())
4498
70
          ImportedLocalExternalDecls.insert(Var);
4499
93
    }
4500
154
  }
4501
720
}
4502
4503
/// convertObjCTypeToCStyleType - This routine converts such objc types
4504
/// as qualified objects, and blocks to their closest c/c++ types that
4505
/// it can. It returns true if input type was modified.
4506
419
bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4507
419
  QualType oldT = T;
4508
419
  convertBlockPointerToFunctionPointer(T);
4509
419
  if (T->isFunctionPointerType()) {
4510
14
    QualType PointeeTy;
4511
14
    if (const PointerType* PT = T->getAs<PointerType>()) {
4512
14
      PointeeTy = PT->getPointeeType();
4513
14
      if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4514
14
        T = convertFunctionTypeOfBlocks(FT);
4515
14
        T = Context->getPointerType(T);
4516
14
      }
4517
14
    }
4518
14
  }
4519
4520
419
  convertToUnqualifiedObjCType(T);
4521
419
  return T != oldT;
4522
419
}
4523
4524
/// convertFunctionTypeOfBlocks - This routine converts a function type
4525
/// whose result type may be a block pointer or whose argument type(s)
4526
/// might be block pointers to an equivalent function type replacing
4527
/// all block pointers to function pointers.
4528
94
QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4529
94
  const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4530
  // FTP will be null for closures that don't take arguments.
4531
  // Generate a funky cast.
4532
94
  SmallVector<QualType, 8> ArgTypes;
4533
94
  QualType Res = FT->getReturnType();
4534
94
  bool modified = convertObjCTypeToCStyleType(Res);
4535
4536
94
  if (FTP) {
4537
94
    for (auto &I : FTP->param_types()) {
4538
31
      QualType t = I;
4539
      // Make sure we convert "t (^)(...)" to "t (*)(...)".
4540
31
      if (convertObjCTypeToCStyleType(t))
4541
16
        modified = true;
4542
31
      ArgTypes.push_back(t);
4543
31
    }
4544
94
  }
4545
94
  QualType FuncType;
4546
94
  if (modified)
4547
12
    FuncType = getSimpleFunctionType(Res, ArgTypes);
4548
82
  else FuncType = QualType(FT, 0);
4549
94
  return FuncType;
4550
94
}
4551
4552
14
Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4553
  // Navigate to relevant type information.
4554
14
  const BlockPointerType *CPT = nullptr;
4555
4556
14
  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4557
0
    CPT = DRE->getType()->getAs<BlockPointerType>();
4558
14
  } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4559
0
    CPT = MExpr->getType()->getAs<BlockPointerType>();
4560
0
  }
4561
14
  else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4562
0
    return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4563
0
  }
4564
14
  else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4565
14
    CPT = IEXPR->getType()->getAs<BlockPointerType>();
4566
0
  else if (const ConditionalOperator *CEXPR =
4567
0
            dyn_cast<ConditionalOperator>(BlockExp)) {
4568
0
    Expr *LHSExp = CEXPR->getLHS();
4569
0
    Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4570
0
    Expr *RHSExp = CEXPR->getRHS();
4571
0
    Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4572
0
    Expr *CONDExp = CEXPR->getCond();
4573
0
    ConditionalOperator *CondExpr = new (Context) ConditionalOperator(
4574
0
        CONDExp, SourceLocation(), cast<Expr>(LHSStmt), SourceLocation(),
4575
0
        cast<Expr>(RHSStmt), Exp->getType(), VK_PRValue, OK_Ordinary);
4576
0
    return CondExpr;
4577
0
  } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4578
0
    CPT = IRE->getType()->getAs<BlockPointerType>();
4579
0
  } else if (const PseudoObjectExpr *POE
4580
0
               = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4581
0
    CPT = POE->getType()->castAs<BlockPointerType>();
4582
0
  } else {
4583
0
    assert(false && "RewriteBlockClass: Bad type");
4584
0
  }
4585
14
  assert(CPT && "RewriteBlockClass: Bad type");
4586
0
  const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4587
14
  assert(FT && "RewriteBlockClass: Bad type");
4588
0
  const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4589
  // FTP will be null for closures that don't take arguments.
4590
4591
14
  RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4592
14
                                      SourceLocation(), SourceLocation(),
4593
14
                                      &Context->Idents.get("__block_impl"));
4594
14
  QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4595
4596
  // Generate a funky cast.
4597
14
  SmallVector<QualType, 8> ArgTypes;
4598
4599
  // Push the block argument type.
4600
14
  ArgTypes.push_back(PtrBlock);
4601
14
  if (FTP) {
4602
14
    for (auto &I : FTP->param_types()) {
4603
8
      QualType t = I;
4604
      // Make sure we convert "t (^)(...)" to "t (*)(...)".
4605
8
      if (!convertBlockPointerToFunctionPointer(t))
4606
8
        convertToUnqualifiedObjCType(t);
4607
8
      ArgTypes.push_back(t);
4608
8
    }
4609
14
  }
4610
  // Now do the pointer to function cast.
4611
14
  QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
4612
4613
14
  PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4614
4615
14
  CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4616
14
                                               CK_BitCast,
4617
14
                                               const_cast<Expr*>(BlockExp));
4618
  // Don't forget the parens to enforce the proper binding.
4619
14
  ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4620
14
                                          BlkCast);
4621
  //PE->dump();
4622
4623
14
  FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
4624
14
                                    SourceLocation(),
4625
14
                                    &Context->Idents.get("FuncPtr"),
4626
14
                                    Context->VoidPtrTy, nullptr,
4627
14
                                    /*BitWidth=*/nullptr, /*Mutable=*/true,
4628
14
                                    ICIS_NoInit);
4629
14
  MemberExpr *ME = MemberExpr::CreateImplicit(
4630
14
      *Context, PE, true, FD, FD->getType(), VK_LValue, OK_Ordinary);
4631
4632
14
  CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4633
14
                                                CK_BitCast, ME);
4634
14
  PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4635
4636
14
  SmallVector<Expr*, 8> BlkExprs;
4637
  // Add the implicit argument.
4638
14
  BlkExprs.push_back(BlkCast);
4639
  // Add the user arguments.
4640
14
  for (CallExpr::arg_iterator I = Exp->arg_begin(),
4641
22
       E = Exp->arg_end(); I != E; 
++I8
) {
4642
8
    BlkExprs.push_back(*I);
4643
8
  }
4644
14
  CallExpr *CE =
4645
14
      CallExpr::Create(*Context, PE, BlkExprs, Exp->getType(), VK_PRValue,
4646
14
                       SourceLocation(), FPOptionsOverride());
4647
14
  return CE;
4648
14
}
4649
4650
// We need to return the rewritten expression to handle cases where the
4651
// DeclRefExpr is embedded in another expression being rewritten.
4652
// For example:
4653
//
4654
// int main() {
4655
//    __block Foo *f;
4656
//    __block int i;
4657
//
4658
//    void (^myblock)() = ^() {
4659
//        [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
4660
//        i = 77;
4661
//    };
4662
//}
4663
36
Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
4664
  // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4665
  // for each DeclRefExp where BYREFVAR is name of the variable.
4666
36
  ValueDecl *VD = DeclRefExp->getDecl();
4667
36
  bool isArrow = DeclRefExp->refersToEnclosingVariableOrCapture() ||
4668
36
                 
HasLocalVariableExternalStorage(DeclRefExp->getDecl())8
;
4669
4670
36
  FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
4671
36
                                    SourceLocation(),
4672
36
                                    &Context->Idents.get("__forwarding"),
4673
36
                                    Context->VoidPtrTy, nullptr,
4674
36
                                    /*BitWidth=*/nullptr, /*Mutable=*/true,
4675
36
                                    ICIS_NoInit);
4676
36
  MemberExpr *ME = MemberExpr::CreateImplicit(
4677
36
      *Context, DeclRefExp, isArrow, FD, FD->getType(), VK_LValue, OK_Ordinary);
4678
4679
36
  StringRef Name = VD->getName();
4680
36
  FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(),
4681
36
                         &Context->Idents.get(Name),
4682
36
                         Context->VoidPtrTy, nullptr,
4683
36
                         /*BitWidth=*/nullptr, /*Mutable=*/true,
4684
36
                         ICIS_NoInit);
4685
36
  ME = MemberExpr::CreateImplicit(*Context, ME, true, FD, DeclRefExp->getType(),
4686
36
                                  VK_LValue, OK_Ordinary);
4687
4688
  // Need parens to enforce precedence.
4689
36
  ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4690
36
                                          DeclRefExp->getExprLoc(),
4691
36
                                          ME);
4692
36
  ReplaceStmt(DeclRefExp, PE);
4693
36
  return PE;
4694
36
}
4695
4696
// Rewrites the imported local variable V with external storage
4697
// (static, extern, etc.) as *V
4698
//
4699
0
Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4700
0
  ValueDecl *VD = DRE->getDecl();
4701
0
  if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4702
0
    if (!ImportedLocalExternalDecls.count(Var))
4703
0
      return DRE;
4704
0
  Expr *Exp = UnaryOperator::Create(
4705
0
      const_cast<ASTContext &>(*Context), DRE, UO_Deref, DRE->getType(),
4706
0
      VK_LValue, OK_Ordinary, DRE->getLocation(), false, FPOptionsOverride());
4707
  // Need parens to enforce precedence.
4708
0
  ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4709
0
                                          Exp);
4710
0
  ReplaceStmt(DRE, PE);
4711
0
  return PE;
4712
0
}
4713
4714
30
void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4715
30
  SourceLocation LocStart = CE->getLParenLoc();
4716
30
  SourceLocation LocEnd = CE->getRParenLoc();
4717
4718
  // Need to avoid trying to rewrite synthesized casts.
4719
30
  if (LocStart.isInvalid())
4720
0
    return;
4721
  // Need to avoid trying to rewrite casts contained in macros.
4722
30
  if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4723
0
    return;
4724
4725
30
  const char *startBuf = SM->getCharacterData(LocStart);
4726
30
  const char *endBuf = SM->getCharacterData(LocEnd);
4727
30
  QualType QT = CE->getType();
4728
30
  const Type* TypePtr = QT->getAs<Type>();
4729
30
  if (isa<TypeOfExprType>(TypePtr)) {
4730
4
    const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4731
4
    QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4732
4
    std::string TypeAsString = "(";
4733
4
    RewriteBlockPointerType(TypeAsString, QT);
4734
4
    TypeAsString += ")";
4735
4
    ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4736
4
    return;
4737
4
  }
4738
  // advance the location to startArgList.
4739
26
  const char *argPtr = startBuf;
4740
4741
221
  while (*argPtr++ && (argPtr < endBuf)) {
4742
195
    switch (*argPtr) {
4743
0
    case '^':
4744
      // Replace the '^' with '*'.
4745
0
      LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4746
0
      ReplaceText(LocStart, 1, "*");
4747
0
      break;
4748
195
    }
4749
195
  }
4750
26
}
4751
4752
604
void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4753
604
  CastKind CastKind = IC->getCastKind();
4754
604
  if (CastKind != CK_BlockPointerToObjCPointerCast &&
4755
604
      
CastKind != CK_AnyPointerToBlockPointerCast599
)
4756
595
    return;
4757
4758
9
  QualType QT = IC->getType();
4759
9
  (void)convertBlockPointerToFunctionPointer(QT);
4760
9
  std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4761
9
  std::string Str = "(";
4762
9
  Str += TypeString;
4763
9
  Str += ")";
4764
9
  InsertText(IC->getSubExpr()->getBeginLoc(), Str);
4765
9
}
4766
4767
26
void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4768
26
  SourceLocation DeclLoc = FD->getLocation();
4769
26
  unsigned parenCount = 0;
4770
4771
  // We have 1 or more arguments that have closure pointers.
4772
26
  const char *startBuf = SM->getCharacterData(DeclLoc);
4773
26
  const char *startArgList = strchr(startBuf, '(');
4774
4775
26
  assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4776
4777
0
  parenCount++;
4778
  // advance the location to startArgList.
4779
26
  DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4780
26
  assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4781
4782
0
  const char *argPtr = startArgList;
4783
4784
488
  while (*argPtr++ && parenCount) {
4785
462
    switch (*argPtr) {
4786
26
    case '^':
4787
      // Replace the '^' with '*'.
4788
26
      DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4789
26
      ReplaceText(DeclLoc, 1, "*");
4790
26
      break;
4791
52
    case '(':
4792
52
      parenCount++;
4793
52
      break;
4794
78
    case ')':
4795
78
      parenCount--;
4796
78
      break;
4797
462
    }
4798
462
  }
4799
26
}
4800
4801
50
bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4802
50
  const FunctionProtoType *FTP;
4803
50
  const PointerType *PT = QT->getAs<PointerType>();
4804
50
  if (PT) {
4805
2
    FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4806
48
  } else {
4807
48
    const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4808
48
    assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4809
0
    FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4810
48
  }
4811
50
  if (FTP) {
4812
50
    for (const auto &I : FTP->param_types())
4813
29
      if (isTopLevelBlockPointerType(I))
4814
3
        return true;
4815
50
  }
4816
47
  return false;
4817
50
}
4818
4819
45
bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4820
45
  const FunctionProtoType *FTP;
4821
45
  const PointerType *PT = QT->getAs<PointerType>();
4822
45
  if (PT) {
4823
0
    FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4824
45
  } else {
4825
45
    const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4826
45
    assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4827
0
    FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4828
45
  }
4829
45
  if (FTP) {
4830
45
    for (const auto &I : FTP->param_types()) {
4831
15
      if (I->isObjCQualifiedIdType())
4832
5
        return true;
4833
10
      if (I->isObjCObjectPointerType() &&
4834
10
          
I->getPointeeType()->isObjCQualifiedInterfaceType()6
)
4835
1
        return true;
4836
10
    }
4837
4838
45
  }
4839
39
  return false;
4840
45
}
4841
4842
void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4843
9
                                     const char *&RParen) {
4844
9
  const char *argPtr = strchr(Name, '(');
4845
9
  assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4846
4847
0
  LParen = argPtr; // output the start.
4848
9
  argPtr++; // skip past the left paren.
4849
9
  unsigned parenCount = 1;
4850
4851
884
  while (*argPtr && parenCount) {
4852
875
    switch (*argPtr) {
4853
10
    case '(': parenCount++; break;
4854
19
    case ')': parenCount--; break;
4855
846
    default: break;
4856
875
    }
4857
875
    if (parenCount) 
argPtr++866
;
4858
875
  }
4859
9
  assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4860
0
  RParen = argPtr; // output the end
4861
9
}
4862
4863
74
void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4864
74
  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4865
26
    RewriteBlockPointerFunctionArgs(FD);
4866
26
    return;
4867
26
  }
4868
  // Handle Variables and Typedefs.
4869
48
  SourceLocation DeclLoc = ND->getLocation();
4870
48
  QualType DeclT;
4871
48
  if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4872
28
    DeclT = VD->getType();
4873
20
  else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4874
19
    DeclT = TDD->getUnderlyingType();
4875
1
  else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4876
1
    DeclT = FD->getType();
4877
0
  else
4878
0
    llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4879
4880
48
  const char *startBuf = SM->getCharacterData(DeclLoc);
4881
48
  const char *endBuf = startBuf;
4882
  // scan backward (from the decl location) for the end of the previous decl.
4883
98
  while (*startBuf != '^' && 
*startBuf != ';'50
&&
startBuf != MainFileStart50
)
4884
50
    startBuf--;
4885
48
  SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4886
48
  std::string buf;
4887
48
  unsigned OrigLength=0;
4888
  // *startBuf != '^' if we are dealing with a pointer to function that
4889
  // may take block argument types (which will be handled below).
4890
48
  if (*startBuf == '^') {
4891
    // Replace the '^' with '*', computing a negative offset.
4892
48
    buf = '*';
4893
48
    startBuf++;
4894
48
    OrigLength++;
4895
48
  }
4896
432
  while (*startBuf != ')') {
4897
384
    buf += *startBuf;
4898
384
    startBuf++;
4899
384
    OrigLength++;
4900
384
  }
4901
48
  buf += ')';
4902
48
  OrigLength++;
4903
4904
48
  if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4905
48
      
PointerTypeTakesAnyObjCQualifiedType(DeclT)45
) {
4906
    // Replace the '^' with '*' for arguments.
4907
    // Replace id<P> with id/*<>*/
4908
9
    DeclLoc = ND->getLocation();
4909
9
    startBuf = SM->getCharacterData(DeclLoc);
4910
9
    const char *argListBegin, *argListEnd;
4911
9
    GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4912
453
    while (argListBegin < argListEnd) {
4913
444
      if (*argListBegin == '^')
4914
5
        buf += '*';
4915
439
      else if (*argListBegin ==  '<') {
4916
17
        buf += "/*";
4917
17
        buf += *argListBegin++;
4918
17
        OrigLength++;
4919
431
        while (*argListBegin != '>') {
4920
414
          buf += *argListBegin++;
4921
414
          OrigLength++;
4922
414
        }
4923
17
        buf += *argListBegin;
4924
17
        buf += "*/";
4925
17
      }
4926
422
      else
4927
422
        buf += *argListBegin;
4928
444
      argListBegin++;
4929
444
      OrigLength++;
4930
444
    }
4931
9
    buf += ')';
4932
9
    OrigLength++;
4933
9
  }
4934
48
  ReplaceText(Start, OrigLength, buf);
4935
48
}
4936
4937
/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4938
/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4939
///                    struct Block_byref_id_object *src) {
4940
///  _Block_object_assign (&_dest->object, _src->object,
4941
///                        BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4942
///                        [|BLOCK_FIELD_IS_WEAK]) // object
4943
///  _Block_object_assign(&_dest->object, _src->object,
4944
///                       BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4945
///                       [|BLOCK_FIELD_IS_WEAK]) // block
4946
/// }
4947
/// And:
4948
/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4949
///  _Block_object_dispose(_src->object,
4950
///                        BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4951
///                        [|BLOCK_FIELD_IS_WEAK]) // object
4952
///  _Block_object_dispose(_src->object,
4953
///                         BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4954
///                         [|BLOCK_FIELD_IS_WEAK]) // block
4955
/// }
4956
4957
std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4958
6
                                                          int flag) {
4959
6
  std::string S;
4960
6
  if (CopyDestroyCache.count(flag))
4961
2
    return S;
4962
4
  CopyDestroyCache.insert(flag);
4963
4
  S = "static void __Block_byref_id_object_copy_";
4964
4
  S += utostr(flag);
4965
4
  S += "(void *dst, void *src) {\n";
4966
4967
  // offset into the object pointer is computed as:
4968
  // void * + void* + int + int + void* + void *
4969
4
  unsigned IntSize =
4970
4
  static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4971
4
  unsigned VoidPtrSize =
4972
4
  static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4973
4974
4
  unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4975
4
  S += " _Block_object_assign((char*)dst + ";
4976
4
  S += utostr(offset);
4977
4
  S += ", *(void * *) ((char*)src + ";
4978
4
  S += utostr(offset);
4979
4
  S += "), ";
4980
4
  S += utostr(flag);
4981
4
  S += ");\n}\n";
4982
4983
4
  S += "static void __Block_byref_id_object_dispose_";
4984
4
  S += utostr(flag);
4985
4
  S += "(void *src) {\n";
4986
4
  S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4987
4
  S += utostr(offset);
4988
4
  S += "), ";
4989
4
  S += utostr(flag);
4990
4
  S += ");\n}\n";
4991
4
  return S;
4992
6
}
4993
4994
/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4995
/// the declaration into:
4996
/// struct __Block_byref_ND {
4997
/// void *__isa;                  // NULL for everything except __weak pointers
4998
/// struct __Block_byref_ND *__forwarding;
4999
/// int32_t __flags;
5000
/// int32_t __size;
5001
/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5002
/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
5003
/// typex ND;
5004
/// };
5005
///
5006
/// It then replaces declaration of ND variable with:
5007
/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5008
///                               __size=sizeof(struct __Block_byref_ND),
5009
///                               ND=initializer-if-any};
5010
///
5011
///
5012
void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
5013
42
                                        bool lastDecl) {
5014
42
  int flag = 0;
5015
42
  int isa = 0;
5016
42
  SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
5017
42
  if (DeclLoc.isInvalid())
5018
    // If type location is missing, it is because of missing type (a warning).
5019
    // Use variable's location which is good for this case.
5020
0
    DeclLoc = ND->getLocation();
5021
42
  const char *startBuf = SM->getCharacterData(DeclLoc);
5022
42
  SourceLocation X = ND->getEndLoc();
5023
42
  X = SM->getExpansionLoc(X);
5024
42
  const char *endBuf = SM->getCharacterData(X);
5025
42
  std::string Name(ND->getNameAsString());
5026
42
  std::string ByrefType;
5027
42
  RewriteByRefString(ByrefType, Name, ND, true);
5028
42
  ByrefType += " {\n";
5029
42
  ByrefType += "  void *__isa;\n";
5030
42
  RewriteByRefString(ByrefType, Name, ND);
5031
42
  ByrefType += " *__forwarding;\n";
5032
42
  ByrefType += " int __flags;\n";
5033
42
  ByrefType += " int __size;\n";
5034
  // Add void *__Block_byref_id_object_copy;
5035
  // void *__Block_byref_id_object_dispose; if needed.
5036
42
  QualType Ty = ND->getType();
5037
42
  bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
5038
42
  if (HasCopyAndDispose) {
5039
6
    ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5040
6
    ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5041
6
  }
5042
5043
42
  QualType T = Ty;
5044
42
  (void)convertBlockPointerToFunctionPointer(T);
5045
42
  T.getAsStringInternal(Name, Context->getPrintingPolicy());
5046
5047
42
  ByrefType += " " + Name + ";\n";
5048
42
  ByrefType += "};\n";
5049
  // Insert this type in global scope. It is needed by helper function.
5050
42
  SourceLocation FunLocStart;
5051
42
  if (CurFunctionDef)
5052
33
     FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
5053
9
  else {
5054
9
    assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5055
0
    FunLocStart = CurMethodDef->getBeginLoc();
5056
9
  }
5057
0
  InsertText(FunLocStart, ByrefType);
5058
5059
42
  if (Ty.isObjCGCWeak()) {
5060
0
    flag |= BLOCK_FIELD_IS_WEAK;
5061
0
    isa = 1;
5062
0
  }
5063
42
  if (HasCopyAndDispose) {
5064
6
    flag = BLOCK_BYREF_CALLER;
5065
6
    QualType Ty = ND->getType();
5066
    // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5067
6
    if (Ty->isBlockPointerType())
5068
4
      flag |= BLOCK_FIELD_IS_BLOCK;
5069
2
    else
5070
2
      flag |= BLOCK_FIELD_IS_OBJECT;
5071
6
    std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5072
6
    if (!HF.empty())
5073
4
      Preamble += HF;
5074
6
  }
5075
5076
  // struct __Block_byref_ND ND =
5077
  // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5078
  //  initializer-if-any};
5079
42
  bool hasInit = (ND->getInit() != nullptr);
5080
  // FIXME. rewriter does not support __block c++ objects which
5081
  // require construction.
5082
42
  if (hasInit)
5083
26
    if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
5084
1
      CXXConstructorDecl *CXXDecl = CExp->getConstructor();
5085
1
      if (CXXDecl && CXXDecl->isDefaultConstructor())
5086
1
        hasInit = false;
5087
1
    }
5088
5089
42
  unsigned flags = 0;
5090
42
  if (HasCopyAndDispose)
5091
6
    flags |= BLOCK_HAS_COPY_DISPOSE;
5092
42
  Name = ND->getNameAsString();
5093
42
  ByrefType.clear();
5094
42
  RewriteByRefString(ByrefType, Name, ND);
5095
42
  std::string ForwardingCastType("(");
5096
42
  ForwardingCastType += ByrefType + " *)";
5097
42
  ByrefType += " " + Name + " = {(void*)";
5098
42
  ByrefType += utostr(isa);
5099
42
  ByrefType += "," +  ForwardingCastType + "&" + Name + ", ";
5100
42
  ByrefType += utostr(flags);
5101
42
  ByrefType += ", ";
5102
42
  ByrefType += "sizeof(";
5103
42
  RewriteByRefString(ByrefType, Name, ND);
5104
42
  ByrefType += ")";
5105
42
  if (HasCopyAndDispose) {
5106
6
    ByrefType += ", __Block_byref_id_object_copy_";
5107
6
    ByrefType += utostr(flag);
5108
6
    ByrefType += ", __Block_byref_id_object_dispose_";
5109
6
    ByrefType += utostr(flag);
5110
6
  }
5111
5112
42
  if (!firstDecl) {
5113
    // In multiple __block declarations, and for all but 1st declaration,
5114
    // find location of the separat