Coverage Report

Created: 2020-09-19 12:23

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