File: Outlining.cpp

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (643 lines) | stat: -rw-r--r-- 23,458 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
//===--- Outlining.cpp - Outlining value operations -----------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
//  This file implements IR generation for outlined value operations in Swift.
//
//===----------------------------------------------------------------------===//

#include "Outlining.h"

#include "Explosion.h"
#include "GenOpaque.h"
#include "GenProto.h"
#include "GenericRequirement.h"
#include "IRGenFunction.h"
#include "IRGenMangler.h"
#include "IRGenModule.h"
#include "LoadableTypeInfo.h"
#include "LocalTypeDataKind.h"
#include "MetadataRequest.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/IRGenOptions.h"
#include "swift/IRGen/GenericRequirement.h"
#include "swift/SIL/SILModule.h"

using namespace swift;
using namespace irgen;

static GenericEnvironment *digOutGenericEnvironment(CanType loweredType) {
  // Find a non-local, non-opaque archetype in the type and pull out
  // its generic environment.
  // TODO: we ought to be able to usefully minimize this

  GenericEnvironment *env = nullptr;
  loweredType.findIf([&env](CanType t) -> bool {
    if (auto arch = dyn_cast<ArchetypeType>(t)) {
      if (!isa<PrimaryArchetypeType>(arch) && !isa<PackArchetypeType>(arch))
        return false;
      env = arch->getGenericEnvironment();
      return true;
    }
    return false;
  });

  return env;
}

OutliningMetadataCollector::OutliningMetadataCollector(
    SILType T, IRGenFunction &IGF, LayoutIsNeeded_t needsLayout,
    DeinitIsNeeded_t needsDeinitTypes)
    : T(T), IGF(IGF), needsLayout(needsLayout), needsDeinit(needsDeinitTypes) {}

void OutliningMetadataCollector::collectTypeMetadata(SILType ty) {
  assert(state != OutliningMetadataCollector::State::Kind::Collected);
  // If the type has no archetypes, we can emit it from scratch in the callee.
  if (!ty.hasArchetype()) {
    return;
  }

  // Substitute opaque types if allowed.
  ty = IGF.IGM.substOpaqueTypesWithUnderlyingTypes(ty, CanGenericSignature());

  collectTypeMetadataForLayout(ty);
  collectTypeMetadataForDeinit(ty);
}

void OutliningMetadataCollector::collectTypeMetadataForLayout(SILType ty) {
  if (!needsLayout)
    return;

  auto astType = ty.getASTType();
  auto &ti = IGF.IGM.getTypeInfoForLowered(astType);

  // We don't need the metadata for fixed size types or types that are not ABI
  // accessible. Outlining will call the value witness of the enclosing type of
  // non ABI accessible field/element types.
  if (isa<FixedTypeInfo>(ti) || !ti.isABIAccessible()) {
    return;
  }

  // If the type is a legal formal type, add it as a formal type.
  // FIXME: does this force us to emit a more expensive metadata than we need
  // to?
  if (astType->isLegalFormalType()) {
    return state.getCollecting().addFormalTypeMetadata(astType);
  }

  state.getCollecting().addRepresentationTypeMetadata(ty);
}

void OutliningMetadataCollector::collectTypeMetadataForDeinit(SILType ty) {
  if (!needsDeinit)
    return;

  auto *nominal = ty.getASTType()->getAnyNominal();
  if (!nominal)
    return;
  if (!nominal->getValueTypeDestructor())
    return;
  assert(ty.isMoveOnly());

  state.getCollecting().addValueTypeWithDeinit(ty);
}

void OutliningMetadataCollector::materializeFormalTypeMetadata(
    CanType ty, State::Collected::Elements &into) {
  // If the type has no archetypes, we can emit it from scratch in the callee.
  assert(ty->hasArchetype());

  auto key = LocalTypeDataKey(ty, LocalTypeDataKind::forFormalTypeMetadata());
  if (into.Values.count(key))
    return;

  auto metadata = IGF.emitTypeMetadataRef(ty);
  into.Values.insert({key, metadata});

  assert(into.Values.count(key));
}

void OutliningMetadataCollector::materializeRepresentationTypeMetadata(
    SILType ty, State::Collected::Elements &into) {
  auto key = LocalTypeDataKey(
      ty.getASTType(), LocalTypeDataKind::forRepresentationTypeMetadata());
  if (into.Values.count(key))
    return;

  auto metadata = IGF.emitTypeMetadataRefForLayout(ty);
  into.Values.insert({key, metadata});
}

void OutliningMetadataCollector::materialize() {
  if (state == State::Kind::Collected)
    return;

  auto collection = std::move(state.getCollecting());
  switch (collection) {
  case State::CollectionKind::Elements: {
    auto &elements = collection.getElements();
    auto &collected = state.setCollectedElements();
    for (auto &element : elements.elements) {
      switch (element) {
      case State::ElementKind::MetadataForFormal: {
        auto ty = element.getFormalType();
        materializeFormalTypeMetadata(ty, /*into=*/collected);
        break;
      }
      case State::ElementKind::MetadataForRepresentation: {
        auto ty = element.getRepresentationType();
        materializeRepresentationTypeMetadata(ty, /*into=*/collected);
        break;
      }
      }
    }
    return;
  }
  case State::CollectionKind::Environment: {
    auto pair = getTypeAndGenericSignatureForManglingOutlineFunction(T);
    auto sig = pair.second;
    auto subs = digOutGenericEnvironment(T.getASTType())
                    ->getForwardingSubstitutionMap();
    auto &collected = state.setCollectedEnvironment(subs);

    GenericTypeRequirements requirements(IGF.IGM, sig);
    for (auto requirement : requirements.getRequirements()) {
      auto *value = emitGenericRequirementFromSubstitutions(
          IGF, requirement, MetadataState::Complete, subs);
      collected.Requirements.insert({requirement, value});
    }
    return;
  }
  }
}

void OutliningMetadataCollector::addPolymorphicArguments(
    SmallVectorImpl<llvm::Value *> &args) const {
  assert(hasFinished());
  if (state == State::Kind::Empty)
    return;
  auto &collected = state.getCollected();
  switch (collected) {
  case State::CollectionKind::Elements: {
    for (auto &pair : collected.getElements().Values) {
      auto metadata = pair.second;
      assert(metadata->getType() == IGF.IGM.TypeMetadataPtrTy);
      args.push_back(metadata);
    }
    return;
  }
  case State::CollectionKind::Environment: {
    for (auto &pair : collected.getEnvironment().Requirements) {
      auto *value = pair.second;
      args.push_back(value);
    }
    return;
  }
  }
}

void OutliningMetadataCollector::addPolymorphicParameterTypes(
    SmallVectorImpl<llvm::Type *> &paramTys) const {
  assert(hasFinished());
  if (state == State::Kind::Empty)
    return;
  auto &collected = state.getCollected();
  switch (collected) {
  case State::CollectionKind::Elements: {
    for (auto &pair : collected.getElements().Values) {
      auto *metadata = pair.second;
      paramTys.push_back(metadata->getType());
    }
    return;
  }
  case State::CollectionKind::Environment: {
    for (auto &pair : collected.getEnvironment().Requirements) {
      auto *value = pair.second;
      paramTys.push_back(value->getType());
    }
    return;
  }
  }
}

void OutliningMetadataCollector::bindPolymorphicParameters(
    IRGenFunction &IGF, Explosion &params) const {
  assert(hasFinished());
  if (state == State::Kind::Empty)
    return;
  auto &collected = state.getCollected();
  switch (collected) {
  case State::CollectionKind::Elements: {
    // Note that our parameter IGF intentionally shadows the IGF that this
    // collector was built with.
    for (auto &pair : collected.getElements().Values) {
      llvm::Value *arg = params.claimNext();

      auto key = pair.first;
      assert(key.Kind.isAnyTypeMetadata());
      setTypeMetadataName(IGF.IGM, arg, key.Type);
      IGF.setUnscopedLocalTypeData(key, MetadataResponse::forComplete(arg));
    }
    return;
  }
  case State::CollectionKind::Environment: {
    auto &environment = collected.getEnvironment();
    for (auto &pair : environment.Requirements) {
      bindGenericRequirement(IGF, pair.first, params.claimNext(),
                             MetadataState::Complete, environment.Subs);
    }
    return;
  }
  }
}

std::pair<CanType, CanGenericSignature>
irgen::getTypeAndGenericSignatureForManglingOutlineFunction(SILType type) {
  auto loweredType = type.getASTType();
  if (!loweredType->hasArchetype()) return {loweredType, nullptr};

  GenericEnvironment *env = digOutGenericEnvironment(loweredType);

  assert(env && "has archetype but no archetype?!");
  return {loweredType->mapTypeOutOfContext()->getCanonicalType(),
          env->getGenericSignature().getCanonicalSignature()};
}

bool TypeInfo::withWitnessableMetadataCollector(
    IRGenFunction &IGF, SILType T, LayoutIsNeeded_t mayNeedLayout,
    DeinitIsNeeded_t needsDeinit,
    llvm::function_ref<void(OutliningMetadataCollector &)> invocation) const {
  bool needsCollector = false;
  LayoutIsNeeded_t needsLayout = LayoutIsNotNeeded;
  if (!T.hasLocalArchetype() &&
      !IGF.outliningCanCallValueWitnesses()) {
    needsCollector = true;
    if (T.hasArchetype()) {
      needsLayout = LayoutIsNeeded;
    }
  } else if (!T.hasArchetype()) {
    needsCollector = true;
    // The implementation will call vwt in this case.
    needsLayout = LayoutIsNotNeeded;
  }

  if (needsCollector) {
    OutliningMetadataCollector collector(T, IGF, needsLayout, needsDeinit);
    if (needsDeinit || needsLayout) {
      // Only collect if anything would be collected.
      collectMetadataForOutlining(collector, T);
    }
    collector.materialize();
    invocation(collector);
    return true;
  }

  return false;
}

void TypeInfo::callOutlinedCopy(IRGenFunction &IGF, Address dest, Address src,
                                SILType T, IsInitialization_t isInit,
                                IsTake_t isTake) const {
  if (withWitnessableMetadataCollector(
          IGF, T, LayoutIsNeeded, DeinitIsNotNeeded, [&](auto collector) {
            collector.emitCallToOutlinedCopy(dest, src, T, *this, isInit,
                                             isTake);
          })) {
    return;
  }

  if (isInit == IsInitialization && isTake == IsTake) {
    return emitInitializeWithTakeCall(IGF, T, dest, src);
  } else if (isInit == IsInitialization && isTake == IsNotTake) {
    return emitInitializeWithCopyCall(IGF, T, dest, src);
  } else if (isInit == IsNotInitialization && isTake == IsTake) {
    return emitAssignWithTakeCall(IGF, T, dest, src);
  } else if (isInit == IsNotInitialization && isTake == IsNotTake) {
    return emitAssignWithCopyCall(IGF, T, dest, src);
  }
  llvm_unreachable("unknown case");
}

void OutliningMetadataCollector::emitCallToOutlinedCopy(
    Address dest, Address src, SILType T, const TypeInfo &ti,
    IsInitialization_t isInit, IsTake_t isTake) const {
  assert(hasFinished());
  assert(!needsDeinit);
  llvm::SmallVector<llvm::Value *, 4> args;
  args.push_back(IGF.Builder.CreateElementBitCast(src, ti.getStorageType())
                            .getAddress());
  args.push_back(IGF.Builder.CreateElementBitCast(dest, ti.getStorageType())
                            .getAddress());
  addPolymorphicArguments(args);

  llvm::Constant *outlinedFn;
  if (isInit && isTake) {
    outlinedFn =
      IGF.IGM.getOrCreateOutlinedInitializeWithTakeFunction(T, ti, *this);
  } else if (isInit) {
    outlinedFn =
      IGF.IGM.getOrCreateOutlinedInitializeWithCopyFunction(T, ti, *this);
  } else if (isTake) {
    outlinedFn =
      IGF.IGM.getOrCreateOutlinedAssignWithTakeFunction(T, ti, *this);
  } else {
    outlinedFn =
      IGF.IGM.getOrCreateOutlinedAssignWithCopyFunction(T, ti, *this);
  }

  llvm::CallInst *call = IGF.Builder.CreateCall(
      cast<llvm::Function>(outlinedFn)->getFunctionType(), outlinedFn, args);
  call->setCallingConv(IGF.IGM.DefaultCC);
}

static bool needsSpecialOwnershipHandling(SILType t) {
  auto astType = t.getASTType();
  auto ref = dyn_cast<ReferenceStorageType>(astType);
  if (!ref) {
    return false;
  }
  return ref->getOwnership() != ReferenceOwnership::Strong;
}

static bool canUseValueWitnessForValueOp(IRGenModule &IGM, SILType T) {
  if (!IGM.getSILModule().isTypeMetadataForLayoutAccessible(T))
    return false;

  // No value witness tables in embedded Swift.
  if (IGM.Context.LangOpts.hasFeature(Feature::Embedded))
    return false;

  // It is not a good code size trade-off to instantiate a metatype for
  // existentials, and also does not back-deploy gracefully in the case of
  // constrained protocols.
  if (T.getASTType()->isExistentialType())
    return false;

  if (needsSpecialOwnershipHandling(T))
    return false;
  if (T.getASTType()->hasDynamicSelfType())
    return false;
  return true;
}

llvm::Constant *IRGenModule::getOrCreateOutlinedInitializeWithTakeFunction(
                              SILType T, const TypeInfo &ti,
                              const OutliningMetadataCollector &collector) {
  auto manglingBits = getTypeAndGenericSignatureForManglingOutlineFunction(T);
  auto funcName =
    IRGenMangler().mangleOutlinedInitializeWithTakeFunction(manglingBits.first,
        manglingBits.second, collector.IGF.isPerformanceConstraint);

  return getOrCreateOutlinedCopyAddrHelperFunction(
      T, ti, collector, funcName,
      [this](IRGenFunction &IGF, Address dest, Address src, SILType T,
         const TypeInfo &ti) {
        if (!IGF.outliningCanCallValueWitnesses() ||
            T.hasArchetype() || !canUseValueWitnessForValueOp(*this, T)) {
          ti.initializeWithTake(IGF, dest, src, T, true);
        } else {
          emitInitializeWithTakeCall(IGF, T, dest, src);
        }
      });
}

llvm::Constant *IRGenModule::getOrCreateOutlinedInitializeWithCopyFunction(
                              SILType T, const TypeInfo &ti,
                              const OutliningMetadataCollector &collector) {
  auto manglingBits = getTypeAndGenericSignatureForManglingOutlineFunction(T);
  auto funcName =
    IRGenMangler().mangleOutlinedInitializeWithCopyFunction(manglingBits.first,
        manglingBits.second, collector.IGF.isPerformanceConstraint);

  return getOrCreateOutlinedCopyAddrHelperFunction(
      T, ti, collector, funcName,
      [this](IRGenFunction &IGF, Address dest, Address src, SILType T,
         const TypeInfo &ti) {
        if (!IGF.outliningCanCallValueWitnesses() ||
            T.hasArchetype() || !canUseValueWitnessForValueOp(*this, T)) {
          ti.initializeWithCopy(IGF, dest, src, T, true);
        } else {
          emitInitializeWithCopyCall(IGF, T, dest, src);
        }
      });
}

llvm::Constant *IRGenModule::getOrCreateOutlinedAssignWithTakeFunction(
                              SILType T, const TypeInfo &ti,
                              const OutliningMetadataCollector &collector) {
  auto manglingBits = getTypeAndGenericSignatureForManglingOutlineFunction(T);
  auto funcName =
    IRGenMangler().mangleOutlinedAssignWithTakeFunction(manglingBits.first,
        manglingBits.second, collector.IGF.isPerformanceConstraint);

  return getOrCreateOutlinedCopyAddrHelperFunction(
      T, ti, collector, funcName,
      [this](IRGenFunction &IGF, Address dest, Address src, SILType T,
         const TypeInfo &ti) {
        if (!IGF.outliningCanCallValueWitnesses() ||
            T.hasArchetype() || !canUseValueWitnessForValueOp(*this, T)) {
          ti.assignWithTake(IGF, dest, src, T, true);
        } else {
          emitAssignWithTakeCall(IGF, T, dest, src);
        }
      });
}

llvm::Constant *IRGenModule::getOrCreateOutlinedAssignWithCopyFunction(
                              SILType T, const TypeInfo &ti,
                              const OutliningMetadataCollector &collector) {
  auto manglingBits = getTypeAndGenericSignatureForManglingOutlineFunction(T);
  auto funcName =
    IRGenMangler().mangleOutlinedAssignWithCopyFunction(manglingBits.first,
        manglingBits.second, collector.IGF.isPerformanceConstraint);

  return getOrCreateOutlinedCopyAddrHelperFunction(
      T, ti, collector, funcName,
      [this](IRGenFunction &IGF, Address dest, Address src, SILType T,
             const TypeInfo &ti) {
        if (!IGF.outliningCanCallValueWitnesses() ||
            T.hasArchetype() || !canUseValueWitnessForValueOp(*this, T)) {
          ti.assignWithCopy(IGF, dest, src, T, true);
        } else {
          emitAssignWithCopyCall(IGF, T, dest, src);
        }
      });
}

llvm::Constant *IRGenModule::getOrCreateOutlinedCopyAddrHelperFunction(
                              SILType T, const TypeInfo &ti,
                              const OutliningMetadataCollector &collector,
                              StringRef funcName,
                              CopyAddrHelperGenerator generator) {
  assert(collector.hasFinished());
  auto ptrTy = ti.getStorageType()->getPointerTo();

  llvm::SmallVector<llvm::Type *, 4> paramTys;
  paramTys.push_back(ptrTy);
  paramTys.push_back(ptrTy);
  collector.addPolymorphicParameterTypes(paramTys);

  return getOrCreateHelperFunction(funcName, ptrTy, paramTys,
      [&](IRGenFunction &IGF) {
        auto params = IGF.collectParameters();
        Address src = ti.getAddressForPointer(params.claimNext());
        Address dest = ti.getAddressForPointer(params.claimNext());
        collector.bindPolymorphicParameters(IGF, params);
        generator(IGF, dest, src, T, ti);
        IGF.Builder.CreateRet(dest.getAddress());
      },
      true /*setIsNoInline*/,
      false /*forPrologue*/,
      collector.IGF.isPerformanceConstraint);
}

void TypeInfo::callOutlinedDestroy(IRGenFunction &IGF,
                                   Address addr, SILType T) const {
  // Short-cut destruction of trivial values.
  if (IGF.IGM.getTypeLowering(T).isTrivial())
    return;

  if (withWitnessableMetadataCollector(
          IGF, T, LayoutIsNeeded, DeinitIsNeeded, [&](auto collector) {
            collector.emitCallToOutlinedDestroy(addr, T, *this);
          })) {
    return;
  }

  return emitDestroyCall(IGF, T, addr);
}

void OutliningMetadataCollector::emitCallToOutlinedDestroy(
    Address addr, SILType T, const TypeInfo &ti) const {
  assert(hasFinished());
  assert(needsDeinit);
  llvm::SmallVector<llvm::Value *, 4> args;
  args.push_back(IGF.Builder.CreateElementBitCast(addr, ti.getStorageType())
                            .getAddress());
  addPolymorphicArguments(args);

  auto outlinedFn =
    IGF.IGM.getOrCreateOutlinedDestroyFunction(T, ti, *this);

  llvm::CallInst *call = IGF.Builder.CreateCall(
      cast<llvm::Function>(outlinedFn)->getFunctionType(), outlinedFn, args);
  call->setCallingConv(IGF.IGM.DefaultCC);
}

llvm::Constant *IRGenModule::getOrCreateOutlinedDestroyFunction(
                              SILType T, const TypeInfo &ti,
                              const OutliningMetadataCollector &collector) {
  IRGenMangler mangler;
  auto manglingBits = getTypeAndGenericSignatureForManglingOutlineFunction(T);
  auto funcName = mangler.mangleOutlinedDestroyFunction(manglingBits.first,
                     manglingBits.second, collector.IGF.isPerformanceConstraint);

  auto ptrTy = ti.getStorageType()->getPointerTo();
  llvm::SmallVector<llvm::Type *, 4> paramTys;
  paramTys.push_back(ptrTy);
  collector.addPolymorphicParameterTypes(paramTys);

  return getOrCreateHelperFunction(funcName, ptrTy, paramTys,
      [&](IRGenFunction &IGF) {
        Explosion params = IGF.collectParameters();
        Address addr = ti.getAddressForPointer(params.claimNext());
        collector.bindPolymorphicParameters(IGF, params);
        if (!IGF.outliningCanCallValueWitnesses() ||
            T.hasArchetype() || !canUseValueWitnessForValueOp(*this, T)) {
          ti.destroy(IGF, addr, T, true);
        } else {
          emitDestroyCall(IGF, T, addr);
        }

        IGF.Builder.CreateRet(addr.getAddress());
      },
      true /*setIsNoInline*/,
      false /*forPrologue*/,
      collector.IGF.isPerformanceConstraint);
}

llvm::Constant *IRGenModule::getOrCreateRetainFunction(const TypeInfo &ti,
                                                       SILType t,
                                                       llvm::Type *llvmType,
                                                       Atomicity atomicity) {
  auto *loadableTI = cast<LoadableTypeInfo>(&ti);
  IRGenMangler mangler;
  auto manglingBits =
    getTypeAndGenericSignatureForManglingOutlineFunction(t);
  auto funcName = mangler.mangleOutlinedRetainFunction(manglingBits.first,
                                                       manglingBits.second);
  llvm::Type *argTys[] = {llvmType};
  return getOrCreateHelperFunction(
      funcName, llvmType, argTys,
      [&](IRGenFunction &IGF) {
        auto it = IGF.CurFn->arg_begin();
        Address addr(&*it++, loadableTI->getStorageType(),
                     loadableTI->getFixedAlignment());
        Explosion loaded;
        loadableTI->loadAsTake(IGF, addr, loaded);
        Explosion out;
        loadableTI->copy(IGF, loaded, out, atomicity);
        (void)out.claimAll();
        IGF.Builder.CreateRet(addr.getAddress());
      },
      true /*setIsNoInline*/);
}

void TypeInfo::callOutlinedRelease(IRGenFunction &IGF, Address addr, SILType T,
                                   Atomicity atomicity) const {
  OutliningMetadataCollector collector(T, IGF, LayoutIsNotNeeded,
                                       DeinitIsNeeded);
  collectMetadataForOutlining(collector, T);
  collector.materialize();
  collector.emitCallToOutlinedRelease(addr, T, *this, atomicity);
}

void OutliningMetadataCollector::emitCallToOutlinedRelease(
    Address addr, SILType T, const TypeInfo &ti, Atomicity atomicity) const {
  assert(hasFinished());
  assert(!needsLayout);
  assert(needsDeinit);
  llvm::SmallVector<llvm::Value *, 4> args;
  args.push_back(addr.getAddress());
  addPolymorphicArguments(args);
  auto *outlinedF = cast<llvm::Function>(IGF.IGM.getOrCreateReleaseFunction(
      ti, T, addr.getAddress()->getType(), atomicity, *this));
  llvm::CallInst *call =
      IGF.Builder.CreateCall(outlinedF->getFunctionType(), outlinedF, args);
  call->setCallingConv(IGF.IGM.DefaultCC);
}

llvm::Constant *IRGenModule::getOrCreateReleaseFunction(
    const TypeInfo &ti, SILType t, llvm::Type *ptrTy, Atomicity atomicity,
    const OutliningMetadataCollector &collector) {
  auto *loadableTI = cast<LoadableTypeInfo>(&ti);
  IRGenMangler mangler;
  auto manglingBits =
    getTypeAndGenericSignatureForManglingOutlineFunction(t);
  auto funcName = mangler.mangleOutlinedReleaseFunction(manglingBits.first,
                                                        manglingBits.second);
  llvm::SmallVector<llvm::Type *, 4> argTys;
  argTys.push_back(ptrTy);
  collector.addPolymorphicParameterTypes(argTys);
  return getOrCreateHelperFunction(
      funcName, ptrTy, argTys,
      [&](IRGenFunction &IGF) {
        Explosion params = IGF.collectParameters();
        Address addr(params.claimNext(), loadableTI->getStorageType(),
                     loadableTI->getFixedAlignment());
        collector.bindPolymorphicParameters(IGF, params);
        Explosion loaded;
        loadableTI->loadAsTake(IGF, addr, loaded);
        loadableTI->consume(IGF, loaded, atomicity, t);
        IGF.Builder.CreateRet(addr.getAddress());
      },
      true /*setIsNoInline*/);
}