Coverage Report

Created: 2020-09-19 12:23

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