Coverage Report

Created: 2022-05-17 06:19

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/CodeGen/CodeGenFunction.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
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
// This coordinates the per-function state used while generating code.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "CodeGenFunction.h"
14
#include "CGBlocks.h"
15
#include "CGCUDARuntime.h"
16
#include "CGCXXABI.h"
17
#include "CGCleanup.h"
18
#include "CGDebugInfo.h"
19
#include "CGOpenMPRuntime.h"
20
#include "CodeGenModule.h"
21
#include "CodeGenPGO.h"
22
#include "TargetInfo.h"
23
#include "clang/AST/ASTContext.h"
24
#include "clang/AST/ASTLambda.h"
25
#include "clang/AST/Attr.h"
26
#include "clang/AST/Decl.h"
27
#include "clang/AST/DeclCXX.h"
28
#include "clang/AST/Expr.h"
29
#include "clang/AST/StmtCXX.h"
30
#include "clang/AST/StmtObjC.h"
31
#include "clang/Basic/Builtins.h"
32
#include "clang/Basic/CodeGenOptions.h"
33
#include "clang/Basic/TargetInfo.h"
34
#include "clang/CodeGen/CGFunctionInfo.h"
35
#include "clang/Frontend/FrontendDiagnostic.h"
36
#include "llvm/ADT/ArrayRef.h"
37
#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
38
#include "llvm/IR/DataLayout.h"
39
#include "llvm/IR/Dominators.h"
40
#include "llvm/IR/FPEnv.h"
41
#include "llvm/IR/IntrinsicInst.h"
42
#include "llvm/IR/Intrinsics.h"
43
#include "llvm/IR/MDBuilder.h"
44
#include "llvm/IR/Operator.h"
45
#include "llvm/Support/CRC.h"
46
#include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
47
#include "llvm/Transforms/Utils/PromoteMemToReg.h"
48
49
using namespace clang;
50
using namespace CodeGen;
51
52
/// shouldEmitLifetimeMarkers - Decide whether we need emit the life-time
53
/// markers.
54
static bool shouldEmitLifetimeMarkers(const CodeGenOptions &CGOpts,
55
316k
                                      const LangOptions &LangOpts) {
56
316k
  if (CGOpts.DisableLifetimeMarkers)
57
7
    return false;
58
59
  // Sanitizers may use markers.
60
316k
  if (CGOpts.SanitizeAddressUseAfterScope ||
61
316k
      
LangOpts.Sanitize.has(SanitizerKind::HWAddress)315k
||
62
316k
      
LangOpts.Sanitize.has(SanitizerKind::Memory)315k
)
63
935
    return true;
64
65
  // For now, only in optimized builds.
66
315k
  return CGOpts.OptimizationLevel != 0;
67
316k
}
68
69
CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext)
70
    : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()),
71
      Builder(cgm, cgm.getModule().getContext(), llvm::ConstantFolder(),
72
              CGBuilderInserterTy(this)),
73
      SanOpts(CGM.getLangOpts().Sanitize), CurFPFeatures(CGM.getLangOpts()),
74
      DebugInfo(CGM.getModuleDebugInfo()), PGO(cgm),
75
      ShouldEmitLifetimeMarkers(
76
316k
          shouldEmitLifetimeMarkers(CGM.getCodeGenOpts(), CGM.getLangOpts())) {
77
316k
  if (!suppressNewContext)
78
289k
    CGM.getCXXABI().getMangleContext().startNewFunction();
79
316k
  EHStack.setCGF(this);
80
81
316k
  SetFastMathFlags(CurFPFeatures);
82
316k
}
83
84
316k
CodeGenFunction::~CodeGenFunction() {
85
316k
  assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup");
86
87
316k
  if (getLangOpts().OpenMP && 
CurFn70.3k
)
88
70.3k
    CGM.getOpenMPRuntime().functionFinished(*this);
89
90
  // If we have an OpenMPIRBuilder we want to finalize functions (incl.
91
  // outlining etc) at some point. Doing it once the function codegen is done
92
  // seems to be a reasonable spot. We do it here, as opposed to the deletion
93
  // time of the CodeGenModule, because we have to ensure the IR has not yet
94
  // been "emitted" to the outside, thus, modifications are still sensible.
95
316k
  if (CGM.getLangOpts().OpenMPIRBuilder && 
CurFn456
)
96
456
    CGM.getOpenMPRuntime().getOMPBuilder().finalize(CurFn);
97
316k
}
98
99
// Map the LangOption for exception behavior into
100
// the corresponding enum in the IR.
101
llvm::fp::ExceptionBehavior
102
317k
clang::ToConstrainedExceptMD(LangOptions::FPExceptionModeKind Kind) {
103
104
317k
  switch (Kind) {
105
313k
  case LangOptions::FPE_Ignore:  return llvm::fp::ebIgnore;
106
748
  case LangOptions::FPE_MayTrap: return llvm::fp::ebMayTrap;
107
2.82k
  case LangOptions::FPE_Strict:  return llvm::fp::ebStrict;
108
317k
  }
109
0
  llvm_unreachable("Unsupported FP Exception Behavior");
110
0
}
111
112
318k
void CodeGenFunction::SetFastMathFlags(FPOptions FPFeatures) {
113
318k
  llvm::FastMathFlags FMF;
114
318k
  FMF.setAllowReassoc(FPFeatures.getAllowFPReassociate());
115
318k
  FMF.setNoNaNs(FPFeatures.getNoHonorNaNs());
116
318k
  FMF.setNoInfs(FPFeatures.getNoHonorInfs());
117
318k
  FMF.setNoSignedZeros(FPFeatures.getNoSignedZero());
118
318k
  FMF.setAllowReciprocal(FPFeatures.getAllowReciprocal());
119
318k
  FMF.setApproxFunc(FPFeatures.getAllowApproxFunc());
120
318k
  FMF.setAllowContract(FPFeatures.allowFPContractAcrossStatement());
121
318k
  Builder.setFastMathFlags(FMF);
122
318k
}
123
124
CodeGenFunction::CGFPOptionsRAII::CGFPOptionsRAII(CodeGenFunction &CGF,
125
                                                  const Expr *E)
126
193k
    : CGF(CGF) {
127
193k
  ConstructorHelper(E->getFPFeaturesInEffect(CGF.getLangOpts()));
128
193k
}
129
130
CodeGenFunction::CGFPOptionsRAII::CGFPOptionsRAII(CodeGenFunction &CGF,
131
                                                  FPOptions FPFeatures)
132
32.5k
    : CGF(CGF) {
133
32.5k
  ConstructorHelper(FPFeatures);
134
32.5k
}
135
136
226k
void CodeGenFunction::CGFPOptionsRAII::ConstructorHelper(FPOptions FPFeatures) {
137
226k
  OldFPFeatures = CGF.CurFPFeatures;
138
226k
  CGF.CurFPFeatures = FPFeatures;
139
140
226k
  OldExcept = CGF.Builder.getDefaultConstrainedExcept();
141
226k
  OldRounding = CGF.Builder.getDefaultConstrainedRounding();
142
143
226k
  if (OldFPFeatures == FPFeatures)
144
223k
    return;
145
146
2.38k
  FMFGuard.emplace(CGF.Builder);
147
148
2.38k
  llvm::RoundingMode NewRoundingBehavior =
149
2.38k
      static_cast<llvm::RoundingMode>(FPFeatures.getRoundingMode());
150
2.38k
  CGF.Builder.setDefaultConstrainedRounding(NewRoundingBehavior);
151
2.38k
  auto NewExceptionBehavior =
152
2.38k
      ToConstrainedExceptMD(static_cast<LangOptions::FPExceptionModeKind>(
153
2.38k
          FPFeatures.getFPExceptionMode()));
154
2.38k
  CGF.Builder.setDefaultConstrainedExcept(NewExceptionBehavior);
155
156
2.38k
  CGF.SetFastMathFlags(FPFeatures);
157
158
2.38k
  assert((CGF.CurFuncDecl == nullptr || CGF.Builder.getIsFPConstrained() ||
159
2.38k
          isa<CXXConstructorDecl>(CGF.CurFuncDecl) ||
160
2.38k
          isa<CXXDestructorDecl>(CGF.CurFuncDecl) ||
161
2.38k
          (NewExceptionBehavior == llvm::fp::ebIgnore &&
162
2.38k
           NewRoundingBehavior == llvm::RoundingMode::NearestTiesToEven)) &&
163
2.38k
         "FPConstrained should be enabled on entire function");
164
165
9.54k
  auto mergeFnAttrValue = [&](StringRef Name, bool Value) {
166
9.54k
    auto OldValue =
167
9.54k
        CGF.CurFn->getFnAttribute(Name).getValueAsBool();
168
9.54k
    auto NewValue = OldValue & Value;
169
9.54k
    if (OldValue != NewValue)
170
85
      CGF.CurFn->addFnAttr(Name, llvm::toStringRef(NewValue));
171
9.54k
  };
172
2.38k
  mergeFnAttrValue("no-infs-fp-math", FPFeatures.getNoHonorInfs());
173
2.38k
  mergeFnAttrValue("no-nans-fp-math", FPFeatures.getNoHonorNaNs());
174
2.38k
  mergeFnAttrValue("no-signed-zeros-fp-math", FPFeatures.getNoSignedZero());
175
2.38k
  mergeFnAttrValue("unsafe-fp-math", FPFeatures.getAllowFPReassociate() &&
176
2.38k
                                         
FPFeatures.getAllowReciprocal()220
&&
177
2.38k
                                         
FPFeatures.getAllowApproxFunc()172
&&
178
2.38k
                                         
FPFeatures.getNoSignedZero()172
);
179
2.38k
}
180
181
226k
CodeGenFunction::CGFPOptionsRAII::~CGFPOptionsRAII() {
182
226k
  CGF.CurFPFeatures = OldFPFeatures;
183
226k
  CGF.Builder.setDefaultConstrainedExcept(OldExcept);
184
226k
  CGF.Builder.setDefaultConstrainedRounding(OldRounding);
185
226k
}
186
187
41.2k
LValue CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) {
188
41.2k
  LValueBaseInfo BaseInfo;
189
41.2k
  TBAAAccessInfo TBAAInfo;
190
41.2k
  CharUnits Alignment = CGM.getNaturalTypeAlignment(T, &BaseInfo, &TBAAInfo);
191
41.2k
  Address Addr(V, ConvertTypeForMem(T), Alignment);
192
41.2k
  return LValue::MakeAddr(Addr, T, getContext(), BaseInfo, TBAAInfo);
193
41.2k
}
194
195
/// Given a value of type T* that may not be to a complete object,
196
/// construct an l-value with the natural pointee alignment of T.
197
LValue
198
62.8k
CodeGenFunction::MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T) {
199
62.8k
  LValueBaseInfo BaseInfo;
200
62.8k
  TBAAAccessInfo TBAAInfo;
201
62.8k
  CharUnits Align = CGM.getNaturalTypeAlignment(T, &BaseInfo, &TBAAInfo,
202
62.8k
                                                /* forPointeeType= */ true);
203
62.8k
  Address Addr(V, ConvertTypeForMem(T), Align);
204
62.8k
  return MakeAddrLValue(Addr, T, BaseInfo, TBAAInfo);
205
62.8k
}
206
207
208
1.64M
llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
209
1.64M
  return CGM.getTypes().ConvertTypeForMem(T);
210
1.64M
}
211
212
3.38M
llvm::Type *CodeGenFunction::ConvertType(QualType T) {
213
3.38M
  return CGM.getTypes().ConvertType(T);
214
3.38M
}
215
216
6.15M
TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) {
217
6.15M
  type = type.getCanonicalType();
218
6.15M
  while (true) {
219
6.15M
    switch (type->getTypeClass()) {
220
0
#define TYPE(name, parent)
221
0
#define ABSTRACT_TYPE(name, parent)
222
0
#define NON_CANONICAL_TYPE(name, parent) case Type::name:
223
0
#define DEPENDENT_TYPE(name, parent) case Type::name:
224
0
#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
225
0
#include "clang/AST/TypeNodes.inc"
226
0
      llvm_unreachable("non-canonical or dependent type in IR-generation");
227
228
0
    case Type::Auto:
229
0
    case Type::DeducedTemplateSpecialization:
230
0
      llvm_unreachable("undeduced type in IR-generation");
231
232
    // Various scalar types.
233
3.12M
    case Type::Builtin:
234
5.00M
    case Type::Pointer:
235
5.01M
    case Type::BlockPointer:
236
5.20M
    case Type::LValueReference:
237
5.25M
    case Type::RValueReference:
238
5.25M
    case Type::MemberPointer:
239
5.76M
    case Type::Vector:
240
5.76M
    case Type::ExtVector:
241
5.76M
    case Type::ConstantMatrix:
242
5.76M
    case Type::FunctionProto:
243
5.76M
    case Type::FunctionNoProto:
244
5.77M
    case Type::Enum:
245
5.90M
    case Type::ObjCObjectPointer:
246
5.90M
    case Type::Pipe:
247
5.91M
    case Type::BitInt:
248
5.91M
      return TEK_Scalar;
249
250
    // Complexes.
251
7.39k
    case Type::Complex:
252
7.39k
      return TEK_Complex;
253
254
    // Arrays, records, and Objective-C objects.
255
5.48k
    case Type::ConstantArray:
256
5.48k
    case Type::IncompleteArray:
257
5.51k
    case Type::VariableArray:
258
232k
    case Type::Record:
259
232k
    case Type::ObjCObject:
260
232k
    case Type::ObjCInterface:
261
232k
      return TEK_Aggregate;
262
263
    // We operate on atomic values according to their underlying type.
264
180
    case Type::Atomic:
265
180
      type = cast<AtomicType>(type)->getValueType();
266
180
      continue;
267
6.15M
    }
268
0
    llvm_unreachable("unknown type kind!");
269
0
  }
270
6.15M
}
271
272
314k
llvm::DebugLoc CodeGenFunction::EmitReturnBlock() {
273
  // For cleanliness, we try to avoid emitting the return block for
274
  // simple cases.
275
314k
  llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
276
277
314k
  if (CurBB) {
278
159k
    assert(!CurBB->getTerminator() && "Unexpected terminated block.");
279
280
    // We have a valid insert point, reuse it if it is empty or there are no
281
    // explicit jumps to the return block.
282
159k
    if (CurBB->empty() || 
ReturnBlock.getBlock()->use_empty()132k
) {
283
159k
      ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
284
159k
      delete ReturnBlock.getBlock();
285
159k
      ReturnBlock = JumpDest();
286
159k
    } else
287
36
      EmitBlock(ReturnBlock.getBlock());
288
159k
    return llvm::DebugLoc();
289
159k
  }
290
291
  // Otherwise, if the return block is the target of a single direct
292
  // branch then we can just put the code in that block instead. This
293
  // cleans up functions which started with a unified return block.
294
155k
  if (ReturnBlock.getBlock()->hasOneUse()) {
295
151k
    llvm::BranchInst *BI =
296
151k
      dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin());
297
151k
    if (BI && 
BI->isUnconditional()151k
&&
298
151k
        
BI->getSuccessor(0) == ReturnBlock.getBlock()151k
) {
299
      // Record/return the DebugLoc of the simple 'return' expression to be used
300
      // later by the actual 'ret' instruction.
301
151k
      llvm::DebugLoc Loc = BI->getDebugLoc();
302
151k
      Builder.SetInsertPoint(BI->getParent());
303
151k
      BI->eraseFromParent();
304
151k
      delete ReturnBlock.getBlock();
305
151k
      ReturnBlock = JumpDest();
306
151k
      return Loc;
307
151k
    }
308
151k
  }
309
310
  // FIXME: We are at an unreachable point, there is no reason to emit the block
311
  // unless it has uses. However, we still need a place to put the debug
312
  // region.end for now.
313
314
3.40k
  EmitBlock(ReturnBlock.getBlock());
315
3.40k
  return llvm::DebugLoc();
316
155k
}
317
318
1.25M
static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
319
1.25M
  if (!BB) 
return1.25M
;
320
8.70k
  if (!BB->use_empty())
321
8.69k
    return CGF.CurFn->getBasicBlockList().push_back(BB);
322
8
  delete BB;
323
8
}
324
325
314k
void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
326
314k
  assert(BreakContinueStack.empty() &&
327
314k
         "mismatched push/pop in break/continue stack!");
328
329
314k
  bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
330
314k
    && 
NumSimpleReturnExprs == NumReturnExprs15.0k
331
314k
    && 
ReturnBlock.getBlock()->use_empty()13.7k
;
332
  // Usually the return expression is evaluated before the cleanup
333
  // code.  If the function contains only a simple return statement,
334
  // such as a constant, the location before the cleanup code becomes
335
  // the last useful breakpoint in the function, because the simple
336
  // return expression will be evaluated after the cleanup code. To be
337
  // safe, set the debug location for cleanup code to the location of
338
  // the return statement.  Otherwise the cleanup code should be at the
339
  // end of the function's lexical scope.
340
  //
341
  // If there are multiple branches to the return block, the branch
342
  // instructions will get the location of the return statements and
343
  // all will be fine.
344
314k
  if (CGDebugInfo *DI = getDebugInfo()) {
345
101k
    if (OnlySimpleReturnStmts)
346
627
      DI->EmitLocation(Builder, LastStopPoint);
347
100k
    else
348
100k
      DI->EmitLocation(Builder, EndLoc);
349
101k
  }
350
351
  // Pop any cleanups that might have been associated with the
352
  // parameters.  Do this in whatever block we're currently in; it's
353
  // important to do this before we enter the return block or return
354
  // edges will be *really* confused.
355
314k
  bool HasCleanups = EHStack.stable_begin() != PrologueCleanupDepth;
356
314k
  bool HasOnlyLifetimeMarkers =
357
314k
      HasCleanups && 
EHStack.containsOnlyLifetimeMarkers(PrologueCleanupDepth)6.96k
;
358
314k
  bool EmitRetDbgLoc = !HasCleanups || 
HasOnlyLifetimeMarkers6.96k
;
359
314k
  if (HasCleanups) {
360
    // Make sure the line table doesn't jump back into the body for
361
    // the ret after it's been at EndLoc.
362
6.96k
    Optional<ApplyDebugLocation> AL;
363
6.96k
    if (CGDebugInfo *DI = getDebugInfo()) {
364
1.73k
      if (OnlySimpleReturnStmts)
365
627
        DI->EmitLocation(Builder, EndLoc);
366
1.11k
      else
367
        // We may not have a valid end location. Try to apply it anyway, and
368
        // fall back to an artificial location if needed.
369
1.11k
        AL = ApplyDebugLocation::CreateDefaultArtificial(*this, EndLoc);
370
1.73k
    }
371
372
6.96k
    PopCleanupBlocks(PrologueCleanupDepth);
373
6.96k
  }
374
375
  // Emit function epilog (to return).
376
314k
  llvm::DebugLoc Loc = EmitReturnBlock();
377
378
314k
  if (ShouldInstrumentFunction()) {
379
11
    if (CGM.getCodeGenOpts().InstrumentFunctions)
380
7
      CurFn->addFnAttr("instrument-function-exit", "__cyg_profile_func_exit");
381
11
    if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
382
2
      CurFn->addFnAttr("instrument-function-exit-inlined",
383
2
                       "__cyg_profile_func_exit");
384
11
  }
385
386
  // Emit debug descriptor for function end.
387
314k
  if (CGDebugInfo *DI = getDebugInfo())
388
101k
    DI->EmitFunctionEnd(Builder, CurFn);
389
390
  // Reset the debug location to that of the simple 'return' expression, if any
391
  // rather than that of the end of the function's scope '}'.
392
314k
  ApplyDebugLocation AL(*this, Loc);
393
314k
  EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc);
394
314k
  EmitEndEHSpec(CurCodeDecl);
395
396
314k
  assert(EHStack.empty() &&
397
314k
         "did not remove all scopes from cleanup stack!");
398
399
  // If someone did an indirect goto, emit the indirect goto block at the end of
400
  // the function.
401
314k
  if (IndirectBranch) {
402
39
    EmitBlock(IndirectBranch->getParent());
403
39
    Builder.ClearInsertionPoint();
404
39
  }
405
406
  // If some of our locals escaped, insert a call to llvm.localescape in the
407
  // entry block.
408
314k
  if (!EscapedLocals.empty()) {
409
    // Invert the map from local to index into a simple vector. There should be
410
    // no holes.
411
38
    SmallVector<llvm::Value *, 4> EscapeArgs;
412
38
    EscapeArgs.resize(EscapedLocals.size());
413
38
    for (auto &Pair : EscapedLocals)
414
46
      EscapeArgs[Pair.second] = Pair.first;
415
38
    llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration(
416
38
        &CGM.getModule(), llvm::Intrinsic::localescape);
417
38
    CGBuilderTy(*this, AllocaInsertPt).CreateCall(FrameEscapeFn, EscapeArgs);
418
38
  }
419
420
  // Remove the AllocaInsertPt instruction, which is just a convenience for us.
421
314k
  llvm::Instruction *Ptr = AllocaInsertPt;
422
314k
  AllocaInsertPt = nullptr;
423
314k
  Ptr->eraseFromParent();
424
425
  // PostAllocaInsertPt, if created, was lazily created when it was required,
426
  // remove it now since it was just created for our own convenience.
427
314k
  if (PostAllocaInsertPt) {
428
1.51k
    llvm::Instruction *PostPtr = PostAllocaInsertPt;
429
1.51k
    PostAllocaInsertPt = nullptr;
430
1.51k
    PostPtr->eraseFromParent();
431
1.51k
  }
432
433
  // If someone took the address of a label but never did an indirect goto, we
434
  // made a zero entry PHI node, which is illegal, zap it now.
435
314k
  if (IndirectBranch) {
436
39
    llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
437
39
    if (PN->getNumIncomingValues() == 0) {
438
19
      PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
439
19
      PN->eraseFromParent();
440
19
    }
441
39
  }
442
443
314k
  EmitIfUsed(*this, EHResumeBlock);
444
314k
  EmitIfUsed(*this, TerminateLandingPad);
445
314k
  EmitIfUsed(*this, TerminateHandler);
446
314k
  EmitIfUsed(*this, UnreachableBlock);
447
448
314k
  for (const auto &FuncletAndParent : TerminateFunclets)
449
17
    EmitIfUsed(*this, FuncletAndParent.second);
450
451
314k
  if (CGM.getCodeGenOpts().EmitDeclMetadata)
452
22.9k
    EmitDeclMetadata();
453
454
314k
  for (const auto &R : DeferredReplacements) {
455
107
    if (llvm::Value *Old = R.first) {
456
106
      Old->replaceAllUsesWith(R.second);
457
106
      cast<llvm::Instruction>(Old)->eraseFromParent();
458
106
    }
459
107
  }
460
314k
  DeferredReplacements.clear();
461
462
  // Eliminate CleanupDestSlot alloca by replacing it with SSA values and
463
  // PHIs if the current function is a coroutine. We don't do it for all
464
  // functions as it may result in slight increase in numbers of instructions
465
  // if compiled with no optimizations. We do it for coroutine as the lifetime
466
  // of CleanupDestSlot alloca make correct coroutine frame building very
467
  // difficult.
468
314k
  if (NormalCleanupDest.isValid() && 
isCoroutine()383
) {
469
112
    llvm::DominatorTree DT(*CurFn);
470
112
    llvm::PromoteMemToReg(
471
112
        cast<llvm::AllocaInst>(NormalCleanupDest.getPointer()), DT);
472
112
    NormalCleanupDest = Address::invalid();
473
112
  }
474
475
  // Scan function arguments for vector width.
476
314k
  for (llvm::Argument &A : CurFn->args())
477
525k
    if (auto *VT = dyn_cast<llvm::VectorType>(A.getType()))
478
130k
      LargestVectorWidth =
479
130k
          std::max((uint64_t)LargestVectorWidth,
480
130k
                   VT->getPrimitiveSizeInBits().getKnownMinSize());
481
482
  // Update vector width based on return type.
483
314k
  if (auto *VT = dyn_cast<llvm::VectorType>(CurFn->getReturnType()))
484
58.5k
    LargestVectorWidth =
485
58.5k
        std::max((uint64_t)LargestVectorWidth,
486
58.5k
                 VT->getPrimitiveSizeInBits().getKnownMinSize());
487
488
314k
  if (CurFnInfo->getMaxVectorWidth() > LargestVectorWidth)
489
4
    LargestVectorWidth = CurFnInfo->getMaxVectorWidth();
490
491
  // Add the required-vector-width attribute. This contains the max width from:
492
  // 1. min-vector-width attribute used in the source program.
493
  // 2. Any builtins used that have a vector width specified.
494
  // 3. Values passed in and out of inline assembly.
495
  // 4. Width of vector arguments and return types for this function.
496
  // 5. Width of vector aguments and return types for functions called by this
497
  //    function.
498
314k
  CurFn->addFnAttr("min-legal-vector-width", llvm::utostr(LargestVectorWidth));
499
500
  // Add vscale_range attribute if appropriate.
501
314k
  Optional<std::pair<unsigned, unsigned>> VScaleRange =
502
314k
      getContext().getTargetInfo().getVScaleRange(getLangOpts());
503
314k
  if (VScaleRange) {
504
30.1k
    CurFn->addFnAttr(llvm::Attribute::getWithVScaleRangeArgs(
505
30.1k
        getLLVMContext(), VScaleRange.getValue().first,
506
30.1k
        VScaleRange.getValue().second));
507
30.1k
  }
508
509
  // If we generated an unreachable return block, delete it now.
510
314k
  if (ReturnBlock.isValid() && 
ReturnBlock.getBlock()->use_empty()3.43k
) {
511
1.63k
    Builder.ClearInsertionPoint();
512
1.63k
    ReturnBlock.getBlock()->eraseFromParent();
513
1.63k
  }
514
314k
  if (ReturnValue.isValid()) {
515
154k
    auto *RetAlloca = dyn_cast<llvm::AllocaInst>(ReturnValue.getPointer());
516
154k
    if (RetAlloca && 
RetAlloca->use_empty()150k
) {
517
135k
      RetAlloca->eraseFromParent();
518
135k
      ReturnValue = Address::invalid();
519
135k
    }
520
154k
  }
521
314k
}
522
523
/// ShouldInstrumentFunction - Return true if the current function should be
524
/// instrumented with __cyg_profile_func_* calls
525
629k
bool CodeGenFunction::ShouldInstrumentFunction() {
526
629k
  if (!CGM.getCodeGenOpts().InstrumentFunctions &&
527
629k
      
!CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining629k
&&
528
629k
      
!CGM.getCodeGenOpts().InstrumentFunctionEntryBare629k
)
529
629k
    return false;
530
40
  if (!CurFuncDecl || 
CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()36
)
531
18
    return false;
532
22
  return true;
533
40
}
534
535
314k
bool CodeGenFunction::ShouldSkipSanitizerInstrumentation() {
536
314k
  if (!CurFuncDecl)
537
15.5k
    return false;
538
299k
  return CurFuncDecl->hasAttr<DisableSanitizerInstrumentationAttr>();
539
314k
}
540
541
/// ShouldXRayInstrument - Return true if the current function should be
542
/// instrumented with XRay nop sleds.
543
629k
bool CodeGenFunction::ShouldXRayInstrumentFunction() const {
544
629k
  return CGM.getCodeGenOpts().XRayInstrumentFunctions;
545
629k
}
546
547
/// AlwaysEmitXRayCustomEvents - Return true if we should emit IR for calls to
548
/// the __xray_customevent(...) builtin calls, when doing XRay instrumentation.
549
2
bool CodeGenFunction::AlwaysEmitXRayCustomEvents() const {
550
2
  return CGM.getCodeGenOpts().XRayInstrumentFunctions &&
551
2
         (CGM.getCodeGenOpts().XRayAlwaysEmitCustomEvents ||
552
2
          CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask ==
553
1
              XRayInstrKind::Custom);
554
2
}
555
556
2
bool CodeGenFunction::AlwaysEmitXRayTypedEvents() const {
557
2
  return CGM.getCodeGenOpts().XRayInstrumentFunctions &&
558
2
         (CGM.getCodeGenOpts().XRayAlwaysEmitTypedEvents ||
559
2
          CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask ==
560
1
              XRayInstrKind::Typed);
561
2
}
562
563
llvm::Constant *
564
CodeGenFunction::EncodeAddrForUseInPrologue(llvm::Function *F,
565
111
                                            llvm::Constant *Addr) {
566
  // Addresses stored in prologue data can't require run-time fixups and must
567
  // be PC-relative. Run-time fixups are undesirable because they necessitate
568
  // writable text segments, which are unsafe. And absolute addresses are
569
  // undesirable because they break PIE mode.
570
571
  // Add a layer of indirection through a private global. Taking its address
572
  // won't result in a run-time fixup, even if Addr has linkonce_odr linkage.
573
111
  auto *GV = new llvm::GlobalVariable(CGM.getModule(), Addr->getType(),
574
111
                                      /*isConstant=*/true,
575
111
                                      llvm::GlobalValue::PrivateLinkage, Addr);
576
577
  // Create a PC-relative address.
578
111
  auto *GOTAsInt = llvm::ConstantExpr::getPtrToInt(GV, IntPtrTy);
579
111
  auto *FuncAsInt = llvm::ConstantExpr::getPtrToInt(F, IntPtrTy);
580
111
  auto *PCRelAsInt = llvm::ConstantExpr::getSub(GOTAsInt, FuncAsInt);
581
111
  return (IntPtrTy == Int32Ty)
582
111
             ? 
PCRelAsInt70
583
111
             : 
llvm::ConstantExpr::getTrunc(PCRelAsInt, Int32Ty)41
;
584
111
}
585
586
llvm::Value *
587
CodeGenFunction::DecodeAddrUsedInPrologue(llvm::Value *F,
588
8
                                          llvm::Value *EncodedAddr) {
589
  // Reconstruct the address of the global.
590
8
  auto *PCRelAsInt = Builder.CreateSExt(EncodedAddr, IntPtrTy);
591
8
  auto *FuncAsInt = Builder.CreatePtrToInt(F, IntPtrTy, "func_addr.int");
592
8
  auto *GOTAsInt = Builder.CreateAdd(PCRelAsInt, FuncAsInt, "global_addr.int");
593
8
  auto *GOTAddr = Builder.CreateIntToPtr(GOTAsInt, Int8PtrPtrTy, "global_addr");
594
595
  // Load the original pointer through the global.
596
8
  return Builder.CreateLoad(Address(GOTAddr, Int8PtrTy, getPointerAlign()),
597
8
                            "decoded_addr");
598
8
}
599
600
void CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD,
601
                                               llvm::Function *Fn)
602
1.48k
{
603
1.48k
  if (!FD->hasAttr<OpenCLKernelAttr>())
604
1.09k
    return;
605
606
381
  llvm::LLVMContext &Context = getLLVMContext();
607
608
381
  CGM.GenOpenCLArgMetadata(Fn, FD, this);
609
610
381
  if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) {
611
2
    QualType HintQTy = A->getTypeHint();
612
2
    const ExtVectorType *HintEltQTy = HintQTy->getAs<ExtVectorType>();
613
2
    bool IsSignedInteger =
614
2
        HintQTy->isSignedIntegerType() ||
615
2
        
(1
HintEltQTy1
&&
HintEltQTy->getElementType()->isSignedIntegerType()1
);
616
2
    llvm::Metadata *AttrMDArgs[] = {
617
2
        llvm::ConstantAsMetadata::get(llvm::UndefValue::get(
618
2
            CGM.getTypes().ConvertType(A->getTypeHint()))),
619
2
        llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
620
2
            llvm::IntegerType::get(Context, 32),
621
2
            llvm::APInt(32, (uint64_t)(IsSignedInteger ? 
11
:
01
))))};
622
2
    Fn->setMetadata("vec_type_hint", llvm::MDNode::get(Context, AttrMDArgs));
623
2
  }
624
625
381
  if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) {
626
1
    llvm::Metadata *AttrMDArgs[] = {
627
1
        llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
628
1
        llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
629
1
        llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
630
1
    Fn->setMetadata("work_group_size_hint", llvm::MDNode::get(Context, AttrMDArgs));
631
1
  }
632
633
381
  if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) {
634
7
    llvm::Metadata *AttrMDArgs[] = {
635
7
        llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
636
7
        llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
637
7
        llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
638
7
    Fn->setMetadata("reqd_work_group_size", llvm::MDNode::get(Context, AttrMDArgs));
639
7
  }
640
641
381
  if (const OpenCLIntelReqdSubGroupSizeAttr *A =
642
381
          FD->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
643
1
    llvm::Metadata *AttrMDArgs[] = {
644
1
        llvm::ConstantAsMetadata::get(Builder.getInt32(A->getSubGroupSize()))};
645
1
    Fn->setMetadata("intel_reqd_sub_group_size",
646
1
                    llvm::MDNode::get(Context, AttrMDArgs));
647
1
  }
648
381
}
649
650
/// Determine whether the function F ends with a return stmt.
651
159k
static bool endsWithReturn(const Decl* F) {
652
159k
  const Stmt *Body = nullptr;
653
159k
  if (auto *FD = dyn_cast_or_null<FunctionDecl>(F))
654
118k
    Body = FD->getBody();
655
41.2k
  else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F))
656
1.25k
    Body = OMD->getBody();
657
658
159k
  if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
659
119k
    auto LastStmt = CS->body_rbegin();
660
119k
    if (LastStmt != CS->body_rend())
661
74.0k
      return isa<ReturnStmt>(*LastStmt);
662
119k
  }
663
85.8k
  return false;
664
159k
}
665
666
336
void CodeGenFunction::markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn) {
667
336
  if (SanOpts.has(SanitizerKind::Thread)) {
668
4
    Fn->addFnAttr("sanitize_thread_no_checking_at_run_time");
669
4
    Fn->removeFnAttr(llvm::Attribute::SanitizeThread);
670
4
  }
671
336
}
672
673
/// Check if the return value of this function requires sanitization.
674
471k
bool CodeGenFunction::requiresReturnValueCheck() const {
675
471k
  return requiresReturnValueNullabilityCheck() ||
676
471k
         
(471k
SanOpts.has(SanitizerKind::ReturnsNonnullAttribute)471k
&&
CurCodeDecl111
&&
677
471k
          
CurCodeDecl->getAttr<ReturnsNonNullAttr>()111
);
678
471k
}
679
680
35
static bool matchesStlAllocatorFn(const Decl *D, const ASTContext &Ctx) {
681
35
  auto *MD = dyn_cast_or_null<CXXMethodDecl>(D);
682
35
  if (!MD || 
!MD->getDeclName().getAsIdentifierInfo()3
||
683
35
      
!MD->getDeclName().getAsIdentifierInfo()->isStr("allocate")3
||
684
35
      
(2
MD->getNumParams() != 12
&&
MD->getNumParams() != 21
))
685
33
    return false;
686
687
2
  if (MD->parameters()[0]->getType().getCanonicalType() != Ctx.getSizeType())
688
0
    return false;
689
690
2
  if (MD->getNumParams() == 2) {
691
1
    auto *PT = MD->parameters()[1]->getType()->getAs<PointerType>();
692
1
    if (!PT || !PT->isVoidPointerType() ||
693
1
        !PT->getPointeeType().isConstQualified())
694
0
      return false;
695
1
  }
696
697
2
  return true;
698
2
}
699
700
/// Return the UBSan prologue signature for \p FD if one is available.
701
static llvm::Constant *getPrologueSignature(CodeGenModule &CGM,
702
204
                                            const FunctionDecl *FD) {
703
204
  if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
704
99
    if (!MD->isStatic())
705
93
      return nullptr;
706
111
  return CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM);
707
204
}
708
709
void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
710
                                    llvm::Function *Fn,
711
                                    const CGFunctionInfo &FnInfo,
712
                                    const FunctionArgList &Args,
713
                                    SourceLocation Loc,
714
314k
                                    SourceLocation StartLoc) {
715
314k
  assert(!CurFn &&
716
314k
         "Do not use a CodeGenFunction object for more than one function");
717
718
0
  const Decl *D = GD.getDecl();
719
720
314k
  DidCallStackSave = false;
721
314k
  CurCodeDecl = D;
722
314k
  const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
723
314k
  if (FD && 
FD->usesSEHTry()270k
)
724
109
    CurSEHParent = FD;
725
314k
  CurFuncDecl = (D ? 
D->getNonClosureContext()305k
:
nullptr9.00k
);
726
314k
  FnRetTy = RetTy;
727
314k
  CurFn = Fn;
728
314k
  CurFnInfo = &FnInfo;
729
314k
  assert(CurFn->isDeclaration() && "Function already has body?");
730
731
  // If this function is ignored for any of the enabled sanitizers,
732
  // disable the sanitizer for the function.
733
314k
  do {
734
314k
#define SANITIZER(NAME, ID)                                                    \
735
840k
  if (
SanOpts.empty()529k
) \
736
840k
    
break310k
; \
737
840k
  
if (218k
SanOpts.has(SanitizerKind::ID)218k
) \
738
218k
    
if (7.25k
CGM.isInNoSanitizeList(SanitizerKind::ID, Fn, Loc)7.25k
) \
739
7.25k
      
SanOpts.set(SanitizerKind::ID, false)55
;
740
741
314k
#include "clang/Basic/Sanitizers.def"
742
218k
#undef SANITIZER
743
218k
  } while (
false3.89k
);
744
745
314k
  if (D) {
746
305k
    const bool SanitizeBounds = SanOpts.hasOneOf(SanitizerKind::Bounds);
747
305k
    bool NoSanitizeCoverage = false;
748
749
305k
    for (auto Attr : D->specific_attrs<NoSanitizeAttr>()) {
750
      // Apply the no_sanitize* attributes to SanOpts.
751
1.09k
      SanitizerMask mask = Attr->getMask();
752
1.09k
      SanOpts.Mask &= ~mask;
753
1.09k
      if (mask & SanitizerKind::Address)
754
65
        SanOpts.set(SanitizerKind::KernelAddress, false);
755
1.09k
      if (mask & SanitizerKind::KernelAddress)
756
5
        SanOpts.set(SanitizerKind::Address, false);
757
1.09k
      if (mask & SanitizerKind::HWAddress)
758
5
        SanOpts.set(SanitizerKind::KernelHWAddress, false);
759
1.09k
      if (mask & SanitizerKind::KernelHWAddress)
760
5
        SanOpts.set(SanitizerKind::HWAddress, false);
761
762
      // SanitizeCoverage is not handled by SanOpts.
763
1.09k
      if (Attr->hasCoverage())
764
24
        NoSanitizeCoverage = true;
765
1.09k
    }
766
767
305k
    if (SanitizeBounds && 
!SanOpts.hasOneOf(SanitizerKind::Bounds)120
)
768
6
      Fn->addFnAttr(llvm::Attribute::NoSanitizeBounds);
769
770
305k
    if (NoSanitizeCoverage && 
CGM.getCodeGenOpts().hasSanitizeCoverage()24
)
771
24
      Fn->addFnAttr(llvm::Attribute::NoSanitizeCoverage);
772
305k
  }
773
774
314k
  if (ShouldSkipSanitizerInstrumentation()) {
775
11
    CurFn->addFnAttr(llvm::Attribute::DisableSanitizerInstrumentation);
776
314k
  } else {
777
    // Apply sanitizer attributes to the function.
778
314k
    if (SanOpts.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress))
779
507
      Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
780
314k
    if (SanOpts.hasOneOf(SanitizerKind::HWAddress |
781
314k
                         SanitizerKind::KernelHWAddress))
782
36
      Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress);
783
314k
    if (SanOpts.has(SanitizerKind::MemtagStack))
784
20
      Fn->addFnAttr(llvm::Attribute::SanitizeMemTag);
785
314k
    if (SanOpts.has(SanitizerKind::Thread))
786
66
      Fn->addFnAttr(llvm::Attribute::SanitizeThread);
787
314k
    if (SanOpts.hasOneOf(SanitizerKind::Memory | SanitizerKind::KernelMemory))
788
383
      Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
789
314k
  }
790
314k
  if (SanOpts.has(SanitizerKind::SafeStack))
791
20
    Fn->addFnAttr(llvm::Attribute::SafeStack);
792
314k
  if (SanOpts.has(SanitizerKind::ShadowCallStack))
793
3
    Fn->addFnAttr(llvm::Attribute::ShadowCallStack);
794
795
  // Apply fuzzing attribute to the function.
796
314k
  if (SanOpts.hasOneOf(SanitizerKind::Fuzzer | SanitizerKind::FuzzerNoLink))
797
2
    Fn->addFnAttr(llvm::Attribute::OptForFuzzing);
798
799
  // Ignore TSan memory acesses from within ObjC/ObjC++ dealloc, initialize,
800
  // .cxx_destruct, __destroy_helper_block_ and all of their calees at run time.
801
314k
  if (SanOpts.has(SanitizerKind::Thread)) {
802
67
    if (const auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) {
803
3
      IdentifierInfo *II = OMD->getSelector().getIdentifierInfoForSlot(0);
804
3
      if (OMD->getMethodFamily() == OMF_dealloc ||
805
3
          
OMD->getMethodFamily() == OMF_initialize2
||
806
3
          
(1
OMD->getSelector().isUnarySelector()1
&&
II->isStr(".cxx_destruct")1
)) {
807
3
        markAsIgnoreThreadCheckingAtRuntime(Fn);
808
3
      }
809
3
    }
810
67
  }
811
812
  // Ignore unrelated casts in STL allocate() since the allocator must cast
813
  // from void* to T* before object initialization completes. Don't match on the
814
  // namespace because not all allocators are in std::
815
314k
  if (D && 
SanOpts.has(SanitizerKind::CFIUnrelatedCast)305k
) {
816
35
    if (matchesStlAllocatorFn(D, getContext()))
817
2
      SanOpts.Mask &= ~SanitizerKind::CFIUnrelatedCast;
818
35
  }
819
820
  // Ignore null checks in coroutine functions since the coroutines passes
821
  // are not aware of how to move the extra UBSan instructions across the split
822
  // coroutine boundaries.
823
314k
  if (D && 
SanOpts.has(SanitizerKind::Null)305k
)
824
248
    if (FD && FD->getBody() &&
825
248
        FD->getBody()->getStmtClass() == Stmt::CoroutineBodyStmtClass)
826
1
      SanOpts.Mask &= ~SanitizerKind::Null;
827
828
  // Apply xray attributes to the function (as a string, for now)
829
314k
  bool AlwaysXRayAttr = false;
830
314k
  if (const auto *XRayAttr = D ? D->getAttr<XRayInstrumentAttr>() : nullptr) {
831
86
    if (CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
832
86
            XRayInstrKind::FunctionEntry) ||
833
86
        CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
834
82
            XRayInstrKind::FunctionExit)) {
835
82
      if (XRayAttr->alwaysXRayInstrument() && 
ShouldXRayInstrumentFunction()45
) {
836
38
        Fn->addFnAttr("function-instrument", "xray-always");
837
38
        AlwaysXRayAttr = true;
838
38
      }
839
82
      if (XRayAttr->neverXRayInstrument())
840
37
        Fn->addFnAttr("function-instrument", "xray-never");
841
82
      if (const auto *LogArgs = D->getAttr<XRayLogArgsAttr>())
842
1
        if (ShouldXRayInstrumentFunction())
843
1
          Fn->addFnAttr("xray-log-args",
844
1
                        llvm::utostr(LogArgs->getArgumentCount()));
845
82
    }
846
314k
  } else {
847
314k
    if (ShouldXRayInstrumentFunction() && 
!CGM.imbueXRayAttrs(Fn, Loc)31
)
848
19
      Fn->addFnAttr(
849
19
          "xray-instruction-threshold",
850
19
          llvm::itostr(CGM.getCodeGenOpts().XRayInstructionThreshold));
851
314k
  }
852
853
314k
  if (ShouldXRayInstrumentFunction()) {
854
103
    if (CGM.getCodeGenOpts().XRayIgnoreLoops)
855
1
      Fn->addFnAttr("xray-ignore-loops");
856
857
103
    if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
858
103
            XRayInstrKind::FunctionExit))
859
6
      Fn->addFnAttr("xray-skip-exit");
860
861
103
    if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
862
103
            XRayInstrKind::FunctionEntry))
863
6
      Fn->addFnAttr("xray-skip-entry");
864
865
103
    auto FuncGroups = CGM.getCodeGenOpts().XRayTotalFunctionGroups;
866
103
    if (FuncGroups > 1) {
867
15
      auto FuncName = llvm::makeArrayRef<uint8_t>(
868
15
          CurFn->getName().bytes_begin(), CurFn->getName().bytes_end());
869
15
      auto Group = crc32(FuncName) % FuncGroups;
870
15
      if (Group != CGM.getCodeGenOpts().XRaySelectedFunctionGroup &&
871
15
          
!AlwaysXRayAttr10
)
872
8
        Fn->addFnAttr("function-instrument", "xray-never");
873
15
    }
874
103
  }
875
876
314k
  if (CGM.getCodeGenOpts().getProfileInstr() != CodeGenOptions::ProfileNone)
877
477
    if (CGM.isProfileInstrExcluded(Fn, Loc))
878
4
      Fn->addFnAttr(llvm::Attribute::NoProfile);
879
880
314k
  unsigned Count, Offset;
881
314k
  if (const auto *Attr =
882
314k
          D ? D->getAttr<PatchableFunctionEntryAttr>() : nullptr) {
883
21
    Count = Attr->getCount();
884
21
    Offset = Attr->getOffset();
885
314k
  } else {
886
314k
    Count = CGM.getCodeGenOpts().PatchableFunctionEntryCount;
887
314k
    Offset = CGM.getCodeGenOpts().PatchableFunctionEntryOffset;
888
314k
  }
889
314k
  if (Count && 
Offset <= Count16
) {
890
16
    Fn->addFnAttr("patchable-function-entry", std::to_string(Count - Offset));
891
16
    if (Offset)
892
6
      Fn->addFnAttr("patchable-function-prefix", std::to_string(Offset));
893
16
  }
894
  // Instruct that functions for COFF/CodeView targets should start with a
895
  // patchable instruction, but only on x86/x64. Don't forward this to ARM/ARM64
896
  // backends as they don't need it -- instructions on these architectures are
897
  // always atomically patchable at runtime.
898
314k
  if (CGM.getCodeGenOpts().HotPatch &&
899
314k
      
getContext().getTargetInfo().getTriple().isX86()11
)
900
9
    Fn->addFnAttr("patchable-function", "prologue-short-redirect");
901
902
  // Add no-jump-tables value.
903
314k
  if (CGM.getCodeGenOpts().NoUseJumpTables)
904
1
    Fn->addFnAttr("no-jump-tables", "true");
905
906
  // Add no-inline-line-tables value.
907
314k
  if (CGM.getCodeGenOpts().NoInlineLineTables)
908
4
    Fn->addFnAttr("no-inline-line-tables");
909
910
  // Add profile-sample-accurate value.
911
314k
  if (CGM.getCodeGenOpts().ProfileSampleAccurate)
912
2
    Fn->addFnAttr("profile-sample-accurate");
913
914
314k
  if (!CGM.getCodeGenOpts().SampleProfileFile.empty())
915
20
    Fn->addFnAttr("use-sample-profile");
916
917
314k
  if (D && 
D->hasAttr<CFICanonicalJumpTableAttr>()305k
)
918
2
    Fn->addFnAttr("cfi-canonical-jump-table");
919
920
314k
  if (D && 
D->hasAttr<NoProfileFunctionAttr>()305k
)
921
4
    Fn->addFnAttr(llvm::Attribute::NoProfile);
922
923
314k
  if (FD && 
getLangOpts().OpenCL270k
) {
924
    // Add metadata for a kernel function.
925
1.48k
    EmitOpenCLKernelMetadata(FD, Fn);
926
1.48k
  }
927
928
  // If we are checking function types, emit a function type signature as
929
  // prologue data.
930
314k
  if (FD && 
getLangOpts().CPlusPlus270k
&&
SanOpts.has(SanitizerKind::Function)186k
) {
931
204
    if (llvm::Constant *PrologueSig = getPrologueSignature(CGM, FD)) {
932
      // Remove any (C++17) exception specifications, to allow calling e.g. a
933
      // noexcept function through a non-noexcept pointer.
934
111
      auto ProtoTy = getContext().getFunctionTypeWithExceptionSpec(
935
111
          FD->getType(), EST_None);
936
111
      llvm::Constant *FTRTTIConst =
937
111
          CGM.GetAddrOfRTTIDescriptor(ProtoTy, /*ForEH=*/true);
938
111
      llvm::Constant *FTRTTIConstEncoded =
939
111
          EncodeAddrForUseInPrologue(Fn, FTRTTIConst);
940
111
      llvm::Constant *PrologueStructElems[] = {PrologueSig, FTRTTIConstEncoded};
941
111
      llvm::Constant *PrologueStructConst =
942
111
          llvm::ConstantStruct::getAnon(PrologueStructElems, /*Packed=*/true);
943
111
      Fn->setPrologueData(PrologueStructConst);
944
111
    }
945
204
  }
946
947
  // If we're checking nullability, we need to know whether we can check the
948
  // return value. Initialize the flag to 'true' and refine it in EmitParmDecl.
949
314k
  if (SanOpts.has(SanitizerKind::NullabilityReturn)) {
950
60
    auto Nullability = FnRetTy->getNullability(getContext());
951
60
    if (Nullability && 
*Nullability == NullabilityKind::NonNull17
) {
952
15
      if (!(SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) &&
953
15
            
CurCodeDecl1
&&
CurCodeDecl->getAttr<ReturnsNonNullAttr>()1
))
954
14
        RetValNullabilityPrecondition =
955
14
            llvm::ConstantInt::getTrue(getLLVMContext());
956
15
    }
957
60
  }
958
959
  // If we're in C++ mode and the function name is "main", it is guaranteed
960
  // to be norecurse by the standard (3.6.1.3 "The function main shall not be
961
  // used within a program").
962
  //
963
  // OpenCL C 2.0 v2.2-11 s6.9.i:
964
  //     Recursion is not supported.
965
  //
966
  // SYCL v1.2.1 s3.10:
967
  //     kernels cannot include RTTI information, exception classes,
968
  //     recursive code, virtual functions or make use of C++ libraries that
969
  //     are not compiled for the device.
970
314k
  if (FD && 
(270k
(270k
getLangOpts().CPlusPlus270k
&&
FD->isMain()186k
) ||
971
270k
             
getLangOpts().OpenCL266k
||
getLangOpts().SYCLIsDevice265k
||
972
270k
             
(265k
getLangOpts().CUDA265k
&&
FD->hasAttr<CUDAGlobalAttr>()604
)))
973
5.70k
    Fn->addFnAttr(llvm::Attribute::NoRecurse);
974
975
314k
  llvm::RoundingMode RM = getLangOpts().getFPRoundingMode();
976
314k
  llvm::fp::ExceptionBehavior FPExceptionBehavior =
977
314k
      ToConstrainedExceptMD(getLangOpts().getFPExceptionMode());
978
314k
  Builder.setDefaultConstrainedRounding(RM);
979
314k
  Builder.setDefaultConstrainedExcept(FPExceptionBehavior);
980
314k
  if ((FD && 
(270k
FD->UsesFPIntrin()270k
||
FD->hasAttr<StrictFPAttr>()269k
)) ||
981
314k
      
(313k
!FD313k
&&
(44.1k
FPExceptionBehavior != llvm::fp::ebIgnore44.1k
||
982
44.1k
               
RM != llvm::RoundingMode::NearestTiesToEven44.1k
))) {
983
1.72k
    Builder.setIsFPConstrained(true);
984
1.72k
    Fn->addFnAttr(llvm::Attribute::StrictFP);
985
1.72k
  }
986
987
  // If a custom alignment is used, force realigning to this alignment on
988
  // any main function which certainly will need it.
989
314k
  if (FD && 
(270k
(270k
FD->isMain()270k
||
FD->isMSVCRTEntryPoint()265k
) &&
990
270k
             
CGM.getCodeGenOpts().StackAlignment5.67k
))
991
1
    Fn->addFnAttr("stackrealign");
992
993
  // "main" doesn't need to zero out call-used registers.
994
314k
  if (FD && 
FD->isMain()270k
)
995
5.64k
    Fn->removeFnAttr("zero-call-used-regs");
996
997
314k
  llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
998
999
  // Create a marker to make it easy to insert allocas into the entryblock
1000
  // later.  Don't create this with the builder, because we don't want it
1001
  // folded.
1002
314k
  llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
1003
314k
  AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "allocapt", EntryBB);
1004
1005
314k
  ReturnBlock = getJumpDestInCurrentScope("return");
1006
1007
314k
  Builder.SetInsertPoint(EntryBB);
1008
1009
  // If we're checking the return value, allocate space for a pointer to a
1010
  // precise source location of the checked return statement.
1011
314k
  if (requiresReturnValueCheck()) {
1012
19
    ReturnLocation = CreateDefaultAlignTempAlloca(Int8PtrTy, "return.sloc.ptr");
1013
19
    Builder.CreateStore(llvm::ConstantPointerNull::get(Int8PtrTy),
1014
19
                        ReturnLocation);
1015
19
  }
1016
1017
  // Emit subprogram debug descriptor.
1018
314k
  if (CGDebugInfo *DI = getDebugInfo()) {
1019
    // Reconstruct the type from the argument list so that implicit parameters,
1020
    // such as 'this' and 'vtt', show up in the debug info. Preserve the calling
1021
    // convention.
1022
101k
    DI->emitFunctionStart(GD, Loc, StartLoc,
1023
101k
                          DI->getFunctionType(FD, RetTy, Args), CurFn,
1024
101k
                          CurFuncIsThunk);
1025
101k
  }
1026
1027
314k
  if (ShouldInstrumentFunction()) {
1028
11
    if (CGM.getCodeGenOpts().InstrumentFunctions)
1029
7
      CurFn->addFnAttr("instrument-function-entry", "__cyg_profile_func_enter");
1030
11
    if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
1031
2
      CurFn->addFnAttr("instrument-function-entry-inlined",
1032
2
                       "__cyg_profile_func_enter");
1033
11
    if (CGM.getCodeGenOpts().InstrumentFunctionEntryBare)
1034
2
      CurFn->addFnAttr("instrument-function-entry-inlined",
1035
2
                       "__cyg_profile_func_enter_bare");
1036
11
  }
1037
1038
  // Since emitting the mcount call here impacts optimizations such as function
1039
  // inlining, we just add an attribute to insert a mcount call in backend.
1040
  // The attribute "counting-function" is set to mcount function name which is
1041
  // architecture dependent.
1042
314k
  if (CGM.getCodeGenOpts().InstrumentForProfiling) {
1043
    // Calls to fentry/mcount should not be generated if function has
1044
    // the no_instrument_function attribute.
1045
147
    if (!CurFuncDecl || !CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()) {
1046
117
      if (CGM.getCodeGenOpts().CallFEntry)
1047
4
        Fn->addFnAttr("fentry-call", "true");
1048
113
      else {
1049
113
        Fn->addFnAttr("instrument-function-entry-inlined",
1050
113
                      getTarget().getMCountName());
1051
113
      }
1052
117
      if (CGM.getCodeGenOpts().MNopMCount) {
1053
2
        if (!CGM.getCodeGenOpts().CallFEntry)
1054
1
          CGM.getDiags().Report(diag::err_opt_not_valid_without_opt)
1055
1
            << "-mnop-mcount" << "-mfentry";
1056
2
        Fn->addFnAttr("mnop-mcount");
1057
2
      }
1058
1059
117
      if (CGM.getCodeGenOpts().RecordMCount) {
1060
2
        if (!CGM.getCodeGenOpts().CallFEntry)
1061
1
          CGM.getDiags().Report(diag::err_opt_not_valid_without_opt)
1062
1
            << "-mrecord-mcount" << "-mfentry";
1063
2
        Fn->addFnAttr("mrecord-mcount");
1064
2
      }
1065
117
    }
1066
147
  }
1067
1068
314k
  if (CGM.getCodeGenOpts().PackedStack) {
1069
2
    if (getContext().getTargetInfo().getTriple().getArch() !=
1070
2
        llvm::Triple::systemz)
1071
1
      CGM.getDiags().Report(diag::err_opt_not_valid_on_target)
1072
1
        << "-mpacked-stack";
1073
2
    Fn->addFnAttr("packed-stack");
1074
2
  }
1075
1076
314k
  if (CGM.getCodeGenOpts().WarnStackSize != UINT_MAX &&
1077
314k
      
!CGM.getDiags().isIgnored(diag::warn_fe_backend_frame_larger_than, Loc)37
)
1078
32
    Fn->addFnAttr("warn-stack-size",
1079
32
                  std::to_string(CGM.getCodeGenOpts().WarnStackSize));
1080
1081
314k
  if (RetTy->isVoidType()) {
1082
    // Void type; nothing to return.
1083
159k
    ReturnValue = Address::invalid();
1084
1085
    // Count the implicit return.
1086
159k
    if (!endsWithReturn(D))
1087
156k
      ++NumReturnExprs;
1088
159k
  } else 
if (154k
CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect154k
) {
1089
    // Indirect return; emit returned value directly into sret slot.
1090
    // This reduces code size, and affects correctness in C++.
1091
4.14k
    auto AI = CurFn->arg_begin();
1092
4.14k
    if (CurFnInfo->getReturnInfo().isSRetAfterThis())
1093
54
      ++AI;
1094
4.14k
    ReturnValue = Address(&*AI, ConvertType(RetTy),
1095
4.14k
                          CurFnInfo->getReturnInfo().getIndirectAlign());
1096
4.14k
    if (!CurFnInfo->getReturnInfo().getIndirectByVal()) {
1097
2.49k
      ReturnValuePointer =
1098
2.49k
          CreateDefaultAlignTempAlloca(Int8PtrTy, "result.ptr");
1099
2.49k
      Builder.CreateStore(Builder.CreatePointerBitCastOrAddrSpaceCast(
1100
2.49k
                              ReturnValue.getPointer(), Int8PtrTy),
1101
2.49k
                          ReturnValuePointer);
1102
2.49k
    }
1103
150k
  } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
1104
150k
             
!hasScalarEvaluationKind(CurFnInfo->getReturnType())5
) {
1105
    // Load the sret pointer from the argument struct and return into that.
1106
5
    unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
1107
5
    llvm::Function::arg_iterator EI = CurFn->arg_end();
1108
5
    --EI;
1109
5
    llvm::Value *Addr = Builder.CreateStructGEP(
1110
5
        CurFnInfo->getArgStruct(), &*EI, Idx);
1111
5
    llvm::Type *Ty =
1112
5
        cast<llvm::GetElementPtrInst>(Addr)->getResultElementType();
1113
5
    ReturnValuePointer = Address(Addr, Ty, getPointerAlign());
1114
5
    Addr = Builder.CreateAlignedLoad(Ty, Addr, getPointerAlign(), "agg.result");
1115
5
    ReturnValue =
1116
5
        Address(Addr, ConvertType(RetTy), CGM.getNaturalTypeAlignment(RetTy));
1117
150k
  } else {
1118
150k
    ReturnValue = CreateIRTemp(RetTy, "retval");
1119
1120
    // Tell the epilog emitter to autorelease the result.  We do this
1121
    // now so that various specialized functions can suppress it
1122
    // during their IR-generation.
1123
150k
    if (getLangOpts().ObjCAutoRefCount &&
1124
150k
        
!CurFnInfo->isReturnsRetained()423
&&
1125
150k
        
RetTy->isObjCRetainableType()388
)
1126
159
      AutoreleaseResult = true;
1127
150k
  }
1128
1129
314k
  EmitStartEHSpec(CurCodeDecl);
1130
1131
314k
  PrologueCleanupDepth = EHStack.stable_begin();
1132
1133
  // Emit OpenMP specific initialization of the device functions.
1134
314k
  if (getLangOpts().OpenMP && 
CurCodeDecl70.3k
)
1135
63.9k
    CGM.getOpenMPRuntime().emitFunctionProlog(*this, CurCodeDecl);
1136
1137
314k
  EmitFunctionProlog(*CurFnInfo, CurFn, Args);
1138
1139
314k
  if (isa_and_nonnull<CXXMethodDecl>(D) &&
1140
314k
      
cast<CXXMethodDecl>(D)->isInstance()108k
) {
1141
102k
    CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
1142
102k
    const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
1143
102k
    if (MD->getParent()->isLambda() &&
1144
102k
        
MD->getOverloadedOperator() == OO_Call1.75k
) {
1145
      // We're in a lambda; figure out the captures.
1146
1.63k
      MD->getParent()->getCaptureFields(LambdaCaptureFields,
1147
1.63k
                                        LambdaThisCaptureField);
1148
1.63k
      if (LambdaThisCaptureField) {
1149
        // If the lambda captures the object referred to by '*this' - either by
1150
        // value or by reference, make sure CXXThisValue points to the correct
1151
        // object.
1152
1153
        // Get the lvalue for the field (which is a copy of the enclosing object
1154
        // or contains the address of the enclosing object).
1155
79
        LValue ThisFieldLValue = EmitLValueForLambdaField(LambdaThisCaptureField);
1156
79
        if (!LambdaThisCaptureField->getType()->isPointerType()) {
1157
          // If the enclosing object was captured by value, just use its address.
1158
2
          CXXThisValue = ThisFieldLValue.getAddress(*this).getPointer();
1159
77
        } else {
1160
          // Load the lvalue pointed to by the field, since '*this' was captured
1161
          // by reference.
1162
77
          CXXThisValue =
1163
77
              EmitLoadOfLValue(ThisFieldLValue, SourceLocation()).getScalarVal();
1164
77
        }
1165
79
      }
1166
2.68k
      for (auto *FD : MD->getParent()->fields()) {
1167
2.68k
        if (FD->hasCapturedVLAType()) {
1168
24
          auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD),
1169
24
                                           SourceLocation()).getScalarVal();
1170
24
          auto VAT = FD->getCapturedVLAType();
1171
24
          VLASizeMap[VAT->getSizeExpr()] = ExprArg;
1172
24
        }
1173
2.68k
      }
1174
100k
    } else {
1175
      // Not in a lambda; just use 'this' from the method.
1176
      // FIXME: Should we generate a new load for each use of 'this'?  The
1177
      // fast register allocator would be happier...
1178
100k
      CXXThisValue = CXXABIThisValue;
1179
100k
    }
1180
1181
    // Check the 'this' pointer once per function, if it's available.
1182
102k
    if (CXXABIThisValue) {
1183
102k
      SanitizerSet SkippedChecks;
1184
102k
      SkippedChecks.set(SanitizerKind::ObjectSize, true);
1185
102k
      QualType ThisTy = MD->getThisType();
1186
1187
      // If this is the call operator of a lambda with no capture-default, it
1188
      // may have a static invoker function, which may call this operator with
1189
      // a null 'this' pointer.
1190
102k
      if (isLambdaCallOperator(MD) &&
1191
102k
          
MD->getParent()->getLambdaCaptureDefault() == LCD_None1.63k
)
1192
354
        SkippedChecks.set(SanitizerKind::Null, true);
1193
1194
102k
      EmitTypeCheck(
1195
102k
          isa<CXXConstructorDecl>(MD) ? 
TCK_ConstructorCall39.7k
:
TCK_MemberCall62.5k
,
1196
102k
          Loc, CXXABIThisValue, ThisTy, CXXABIThisAlignment, SkippedChecks);
1197
102k
    }
1198
102k
  }
1199
1200
  // If any of the arguments have a variably modified type, make sure to
1201
  // emit the type size, but only if the function is not naked. Naked functions
1202
  // have no prolog to run this evaluation.
1203
314k
  if (!FD || 
!FD->hasAttr<NakedAttr>()270k
) {
1204
526k
    for (const VarDecl *VD : Args) {
1205
      // Dig out the type as written from ParmVarDecls; it's unclear whether
1206
      // the standard (C99 6.9.1p10) requires this, but we're following the
1207
      // precedent set by gcc.
1208
526k
      QualType Ty;
1209
526k
      if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
1210
335k
        Ty = PVD->getOriginalType();
1211
191k
      else
1212
191k
        Ty = VD->getType();
1213
1214
526k
      if (Ty->isVariablyModifiedType())
1215
137
        EmitVariablyModifiedType(Ty);
1216
526k
    }
1217
314k
  }
1218
  // Emit a location at the end of the prologue.
1219
314k
  if (CGDebugInfo *DI = getDebugInfo())
1220
101k
    DI->EmitLocation(Builder, StartLoc);
1221
  // TODO: Do we need to handle this in two places like we do with
1222
  // target-features/target-cpu?
1223
314k
  if (CurFuncDecl)
1224
299k
    if (const auto *VecWidth = CurFuncDecl->getAttr<MinVectorWidthAttr>())
1225
9.49k
      LargestVectorWidth = VecWidth->getVectorWidth();
1226
314k
}
1227
1228
213k
void CodeGenFunction::EmitFunctionBody(const Stmt *Body) {
1229
213k
  incrementProfileCounter(Body);
1230
213k
  if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
1231
213k
    EmitCompoundStmtWithoutScope(*S);
1232
116
  else
1233
116
    EmitStmt(Body);
1234
1235
  // This is checked after emitting the function body so we know if there
1236
  // are any permitted infinite loops.
1237
213k
  if (checkIfFunctionMustProgress())
1238
128k
    CurFn->addFnAttr(llvm::Attribute::MustProgress);
1239
213k
}
1240
1241
/// When instrumenting to collect profile data, the counts for some blocks
1242
/// such as switch cases need to not include the fall-through counts, so
1243
/// emit a branch around the instrumentation code. When not instrumenting,
1244
/// this just calls EmitBlock().
1245
void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB,
1246
1.92k
                                               const Stmt *S) {
1247
1.92k
  llvm::BasicBlock *SkipCountBB = nullptr;
1248
1.92k
  if (HaveInsertPoint() && 
CGM.getCodeGenOpts().hasProfileClangInstr()829
) {
1249
    // When instrumenting for profiling, the fallthrough to certain
1250
    // statements needs to skip over the instrumentation code so that we
1251
    // get an accurate count.
1252
23
    SkipCountBB = createBasicBlock("skipcount");
1253
23
    EmitBranch(SkipCountBB);
1254
23
  }
1255
1.92k
  EmitBlock(BB);
1256
1.92k
  uint64_t CurrentCount = getCurrentProfileCount();
1257
1.92k
  incrementProfileCounter(S);
1258
1.92k
  setCurrentProfileCount(getCurrentProfileCount() + CurrentCount);
1259
1.92k
  if (SkipCountBB)
1260
23
    EmitBlock(SkipCountBB);
1261
1.92k
}
1262
1263
/// Tries to mark the given function nounwind based on the
1264
/// non-existence of any throwing calls within it.  We believe this is
1265
/// lightweight enough to do at -O0.
1266
202k
static void TryMarkNoThrow(llvm::Function *F) {
1267
  // LLVM treats 'nounwind' on a function as part of the type, so we
1268
  // can't do this on functions that can be overwritten.
1269
202k
  if (F->isInterposable()) 
return36
;
1270
1271
202k
  for (llvm::BasicBlock &BB : *F)
1272
320k
    for (llvm::Instruction &I : BB)
1273
2.87M
      if (I.mayThrow())
1274
72.5k
        return;
1275
1276
130k
  F->setDoesNotThrow();
1277
130k
}
1278
1279
QualType CodeGenFunction::BuildFunctionArgList(GlobalDecl GD,
1280
402k
                                               FunctionArgList &Args) {
1281
402k
  const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
1282
402k
  QualType ResTy = FD->getReturnType();
1283
1284
402k
  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
1285
402k
  if (MD && 
MD->isInstance()115k
) {
1286
102k
    if (CGM.getCXXABI().HasThisReturn(GD))
1287
1.66k
      ResTy = MD->getThisType();
1288
100k
    else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
1289
216
      ResTy = CGM.getContext().VoidPtrTy;
1290
102k
    CGM.getCXXABI().buildThisParam(*this, Args);
1291
102k
  }
1292
1293
  // The base version of an inheriting constructor whose constructed base is a
1294
  // virtual base is not passed any arguments (because it doesn't actually call
1295
  // the inherited constructor).
1296
402k
  bool PassedParams = true;
1297
402k
  if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
1298
39.7k
    if (auto Inherited = CD->getInheritedConstructor())
1299
226
      PassedParams =
1300
226
          getTypes().inheritingCtorHasParams(Inherited, GD.getCtorType());
1301
1302
402k
  if (PassedParams) {
1303
494k
    for (auto *Param : FD->parameters()) {
1304
494k
      Args.push_back(Param);
1305
494k
      if (!Param->hasAttr<PassObjectSizeAttr>())
1306
494k
        continue;
1307
1308
88
      auto *Implicit = ImplicitParamDecl::Create(
1309
88
          getContext(), Param->getDeclContext(), Param->getLocation(),
1310
88
          /*Id=*/nullptr, getContext().getSizeType(), ImplicitParamDecl::Other);
1311
88
      SizeArguments[Param] = Implicit;
1312
88
      Args.push_back(Implicit);
1313
88
    }
1314
402k
  }
1315
1316
402k
  if (MD && 
(115k
isa<CXXConstructorDecl>(MD)115k
||
isa<CXXDestructorDecl>(MD)76.1k
))
1317
55.9k
    CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args);
1318
1319
402k
  return ResTy;
1320
402k
}
1321
1322
void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
1323
270k
                                   const CGFunctionInfo &FnInfo) {
1324
270k
  assert(Fn && "generating code for null Function");
1325
0
  const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
1326
270k
  CurGD = GD;
1327
1328
270k
  FunctionArgList Args;
1329
270k
  QualType ResTy = BuildFunctionArgList(GD, Args);
1330
1331
270k
  if (FD->isInlineBuiltinDeclaration()) {
1332
    // When generating code for a builtin with an inline declaration, use a
1333
    // mangled name to hold the actual body, while keeping an external
1334
    // definition in case the function pointer is referenced somewhere.
1335
15
    std::string FDInlineName = (Fn->getName() + ".inline").str();
1336
15
    llvm::Module *M = Fn->getParent();
1337
15
    llvm::Function *Clone = M->getFunction(FDInlineName);
1338
15
    if (!Clone) {
1339
3
      Clone = llvm::Function::Create(Fn->getFunctionType(),
1340
3
                                     llvm::GlobalValue::InternalLinkage,
1341
3
                                     Fn->getAddressSpace(), FDInlineName, M);
1342
3
      Clone->addFnAttr(llvm::Attribute::AlwaysInline);
1343
3
    }
1344
15
    Fn->setLinkage(llvm::GlobalValue::ExternalLinkage);
1345
15
    Fn = Clone;
1346
270k
  } else {
1347
    // Detect the unusual situation where an inline version is shadowed by a
1348
    // non-inline version. In that case we should pick the external one
1349
    // everywhere. That's GCC behavior too. Unfortunately, I cannot find a way
1350
    // to detect that situation before we reach codegen, so do some late
1351
    // replacement.
1352
277k
    for (const FunctionDecl *PD = FD->getPreviousDecl(); PD;
1353
270k
         
PD = PD->getPreviousDecl()6.71k
) {
1354
6.71k
      if (LLVM_UNLIKELY(PD->isInlineBuiltinDeclaration())) {
1355
2
        std::string FDInlineName = (Fn->getName() + ".inline").str();
1356
2
        llvm::Module *M = Fn->getParent();
1357
2
        if (llvm::Function *Clone = M->getFunction(FDInlineName)) {
1358
1
          Clone->replaceAllUsesWith(Fn);
1359
1
          Clone->eraseFromParent();
1360
1
        }
1361
2
        break;
1362
2
      }
1363
6.71k
    }
1364
270k
  }
1365
1366
  // Check if we should generate debug info for this function.
1367
270k
  if (FD->hasAttr<NoDebugAttr>()) {
1368
    // Clear non-distinct debug info that was possibly attached to the function
1369
    // due to an earlier declaration without the nodebug attribute
1370
15.1k
    Fn->setSubprogram(nullptr);
1371
    // Disable debug info indefinitely for this function
1372
15.1k
    DebugInfo = nullptr;
1373
15.1k
  }
1374
1375
  // The function might not have a body if we're generating thunks for a
1376
  // function declaration.
1377
270k
  SourceRange BodyRange;
1378
270k
  if (Stmt *Body = FD->getBody())
1379
270k
    BodyRange = Body->getSourceRange();
1380
130
  else
1381
130
    BodyRange = FD->getLocation();
1382
270k
  CurEHLocation = BodyRange.getEnd();
1383
1384
  // Use the location of the start of the function to determine where
1385
  // the function definition is located. By default use the location
1386
  // of the declaration as the location for the subprogram. A function
1387
  // may lack a declaration in the source code if it is created by code
1388
  // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
1389
270k
  SourceLocation Loc = FD->getLocation();
1390
1391
  // If this is a function specialization then use the pattern body
1392
  // as the location for the function.
1393
270k
  if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern())
1394
96.5k
    if (SpecDecl->hasBody(SpecDecl))
1395
95.7k
      Loc = SpecDecl->getLocation();
1396
1397
270k
  Stmt *Body = FD->getBody();
1398
1399
270k
  if (Body) {
1400
    // Coroutines always emit lifetime markers.
1401
270k
    if (isa<CoroutineBodyStmt>(Body))
1402
112
      ShouldEmitLifetimeMarkers = true;
1403
1404
    // Initialize helper which will detect jumps which can cause invalid
1405
    // lifetime markers.
1406
270k
    if (ShouldEmitLifetimeMarkers)
1407
39.9k
      Bypasses.Init(Body);
1408
270k
  }
1409
1410
  // Emit the standard function prologue.
1411
270k
  StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin());
1412
1413
  // Save parameters for coroutine function.
1414
270k
  if (Body && 
isa_and_nonnull<CoroutineBodyStmt>(Body)270k
)
1415
112
    llvm::append_range(FnArgs, FD->parameters());
1416
1417
  // Generate the body of the function.
1418
270k
  PGO.assignRegionCounters(GD, CurFn);
1419
270k
  if (isa<CXXDestructorDecl>(FD))
1420
16.1k
    EmitDestructorBody(Args);
1421
254k
  else if (isa<CXXConstructorDecl>(FD))
1422
39.7k
    EmitConstructorBody(Args);
1423
214k
  else if (getLangOpts().CUDA &&
1424
214k
           
!getLangOpts().CUDAIsDevice533
&&
1425
214k
           
FD->hasAttr<CUDAGlobalAttr>()238
)
1426
69
    CGM.getCUDARuntime().emitDeviceStub(*this, Args);
1427
214k
  else if (isa<CXXMethodDecl>(FD) &&
1428
214k
           
cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()52.5k
) {
1429
    // The lambda static invoker function is special, because it forwards or
1430
    // clones the body of the function call operator (but is actually static).
1431
60
    EmitLambdaStaticInvokeBody(cast<CXXMethodDecl>(FD));
1432
214k
  } else if (FD->isDefaulted() && 
isa<CXXMethodDecl>(FD)750
&&
1433
214k
             
(746
cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator()746
||
1434
746
              
cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator()214
)) {
1435
    // Implicit copy-assignment gets the same special treatment as implicit
1436
    // copy-constructors.
1437
728
    emitImplicitAssignmentOperatorBody(Args);
1438
213k
  } else if (Body) {
1439
213k
    EmitFunctionBody(Body);
1440
213k
  } else
1441
0
    llvm_unreachable("no definition for emitted function");
1442
1443
  // C++11 [stmt.return]p2:
1444
  //   Flowing off the end of a function [...] results in undefined behavior in
1445
  //   a value-returning function.
1446
  // C11 6.9.1p12:
1447
  //   If the '}' that terminates a function is reached, and the value of the
1448
  //   function call is used by the caller, the behavior is undefined.
1449
270k
  if (getLangOpts().CPlusPlus && 
!FD->hasImplicitReturnZero()186k
&&
!SawAsmBlock182k
&&
1450
270k
      
!FD->getReturnType()->isVoidType()182k
&&
Builder.GetInsertBlock()77.3k
) {
1451
185
    bool ShouldEmitUnreachable =
1452
185
        CGM.getCodeGenOpts().StrictReturn ||
1453
185
        
!CGM.MayDropFunctionReturn(FD->getASTContext(), FD->getReturnType())21
;
1454
185
    if (SanOpts.has(SanitizerKind::Return)) {
1455
1
      SanitizerScope SanScope(this);
1456
1
      llvm::Value *IsFalse = Builder.getFalse();
1457
1
      EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return),
1458
1
                SanitizerHandler::MissingReturn,
1459
1
                EmitCheckSourceLocation(FD->getLocation()), None);
1460
184
    } else if (ShouldEmitUnreachable) {
1461
166
      if (CGM.getCodeGenOpts().OptimizationLevel == 0)
1462
142
        EmitTrapCall(llvm::Intrinsic::trap);
1463
166
    }
1464
185
    if (SanOpts.has(SanitizerKind::Return) || 
ShouldEmitUnreachable184
) {
1465
167
      Builder.CreateUnreachable();
1466
167
      Builder.ClearInsertionPoint();
1467
167
    }
1468
185
  }
1469
1470
  // Emit the standard function epilogue.
1471
270k
  FinishFunction(BodyRange.getEnd());
1472
1473
  // If we haven't marked the function nothrow through other means, do
1474
  // a quick pass now to see if we can.
1475
270k
  if (!CurFn->doesNotThrow())
1476
202k
    TryMarkNoThrow(CurFn);
1477
270k
}
1478
1479
/// ContainsLabel - Return true if the statement contains a label in it.  If
1480
/// this statement is not executed normally, it not containing a label means
1481
/// that we can just remove the code.
1482
67.9k
bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
1483
  // Null statement, not a label!
1484
67.9k
  if (!S) 
return false108
;
1485
1486
  // If this is a label, we have to emit the code, consider something like:
1487
  // if (0) {  ...  foo:  bar(); }  goto foo;
1488
  //
1489
  // TODO: If anyone cared, we could track __label__'s, since we know that you
1490
  // can't jump to one from outside their declared region.
1491
67.8k
  if (isa<LabelStmt>(S))
1492
9
    return true;
1493
1494
  // If this is a case/default statement, and we haven't seen a switch, we have
1495
  // to emit the code.
1496
67.7k
  if (isa<SwitchCase>(S) && 
!IgnoreCaseStmts12
)
1497
0
    return true;
1498
1499
  // If this is a switch statement, we want to ignore cases below it.
1500
67.7k
  if (isa<SwitchStmt>(S))
1501
10
    IgnoreCaseStmts = true;
1502
1503
  // Scan subexpressions for verboten labels.
1504
67.7k
  for (const Stmt *SubStmt : S->children())
1505
50.4k
    if (ContainsLabel(SubStmt, IgnoreCaseStmts))
1506
16
      return true;
1507
1508
67.7k
  return false;
1509
67.7k
}
1510
1511
/// containsBreak - Return true if the statement contains a break out of it.
1512
/// If the statement (recursively) contains a switch or loop with a break
1513
/// inside of it, this is fine.
1514
88
bool CodeGenFunction::containsBreak(const Stmt *S) {
1515
  // Null statement, not a label!
1516
88
  if (!S) 
return false0
;
1517
1518
  // If this is a switch or loop that defines its own break scope, then we can
1519
  // include it and anything inside of it.
1520
88
  if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
1521
88
      
isa<ForStmt>(S)85
)
1522
3
    return false;
1523
1524
85
  if (isa<BreakStmt>(S))
1525
1
    return true;
1526
1527
  // Scan subexpressions for verboten breaks.
1528
84
  for (const Stmt *SubStmt : S->children())
1529
54
    if (containsBreak(SubStmt))
1530
1
      return true;
1531
1532
83
  return false;
1533
84
}
1534
1535
210
bool CodeGenFunction::mightAddDeclToScope(const Stmt *S) {
1536
210
  if (!S) 
return false0
;
1537
1538
  // Some statement kinds add a scope and thus never add a decl to the current
1539
  // scope. Note, this list is longer than the list of statements that might
1540
  // have an unscoped decl nested within them, but this way is conservatively
1541
  // correct even if more statement kinds are added.
1542
210
  if (isa<IfStmt>(S) || 
isa<SwitchStmt>(S)208
||
isa<WhileStmt>(S)208
||
1543
210
      
isa<DoStmt>(S)208
||
isa<ForStmt>(S)205
||
isa<CompoundStmt>(S)205
||
1544
210
      
isa<CXXForRangeStmt>(S)195
||
isa<CXXTryStmt>(S)195
||
1545
210
      
isa<ObjCForCollectionStmt>(S)195
||
isa<ObjCAtTryStmt>(S)195
)
1546
15
    return false;
1547
1548
195
  if (isa<DeclStmt>(S))
1549
7
    return true;
1550
1551
188
  for (const Stmt *SubStmt : S->children())
1552
145
    if (mightAddDeclToScope(SubStmt))
1553
2
      return true;
1554
1555
186
  return false;
1556
188
}
1557
1558
/// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1559
/// to a constant, or if it does but contains a label, return false.  If it
1560
/// constant folds return true and set the boolean result in Result.
1561
bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
1562
                                                   bool &ResultBool,
1563
161k
                                                   bool AllowLabels) {
1564
161k
  llvm::APSInt ResultInt;
1565
161k
  if (!ConstantFoldsToSimpleInteger(Cond, ResultInt, AllowLabels))
1566
145k
    return false;
1567
1568
15.2k
  ResultBool = ResultInt.getBoolValue();
1569
15.2k
  return true;
1570
161k
}
1571
1572
/// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1573
/// to a constant, or if it does but contains a label, return false.  If it
1574
/// constant folds return true and set the folded value.
1575
bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
1576
                                                   llvm::APSInt &ResultInt,
1577
161k
                                                   bool AllowLabels) {
1578
  // FIXME: Rename and handle conversion of other evaluatable things
1579
  // to bool.
1580
161k
  Expr::EvalResult Result;
1581
161k
  if (!Cond->EvaluateAsInt(Result, getContext()))
1582
146k
    return false;  // Not foldable, not integer or not fully evaluatable.
1583
1584
15.3k
  llvm::APSInt Int = Result.Val.getInt();
1585
15.3k
  if (!AllowLabels && 
CodeGenFunction::ContainsLabel(Cond)15.2k
)
1586
0
    return false;  // Contains a label.
1587
1588
15.3k
  ResultInt = Int;
1589
15.3k
  return true;
1590
15.3k
}
1591
1592
/// Determine whether the given condition is an instrumentable condition
1593
/// (i.e. no "&&" or "||").
1594
672
bool CodeGenFunction::isInstrumentedCondition(const Expr *C) {
1595
  // Bypass simplistic logical-NOT operator before determining whether the
1596
  // condition contains any other logical operator.
1597
672
  if (const UnaryOperator *UnOp = dyn_cast<UnaryOperator>(C->IgnoreParens()))
1598
9
    if (UnOp->getOpcode() == UO_LNot)
1599
8
      C = UnOp->getSubExpr();
1600
1601
672
  const BinaryOperator *BOp = dyn_cast<BinaryOperator>(C->IgnoreParens());
1602
672
  return (!BOp || 
!BOp->isLogicalOp()256
);
1603
672
}
1604
1605
/// EmitBranchToCounterBlock - Emit a conditional branch to a new block that
1606
/// increments a profile counter based on the semantics of the given logical
1607
/// operator opcode.  This is used to instrument branch condition coverage for
1608
/// logical operators.
1609
void CodeGenFunction::EmitBranchToCounterBlock(
1610
    const Expr *Cond, BinaryOperator::Opcode LOp, llvm::BasicBlock *TrueBlock,
1611
    llvm::BasicBlock *FalseBlock, uint64_t TrueCount /* = 0 */,
1612
7.39k
    Stmt::Likelihood LH /* =None */, const Expr *CntrIdx /* = nullptr */) {
1613
  // If not instrumenting, just emit a branch.
1614
7.39k
  bool InstrumentRegions = CGM.getCodeGenOpts().hasProfileClangInstr();
1615
7.39k
  if (!InstrumentRegions || 
!isInstrumentedCondition(Cond)78
)
1616
7.33k
    return EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount, LH);
1617
1618
62
  llvm::BasicBlock *ThenBlock = nullptr;
1619
62
  llvm::BasicBlock *ElseBlock = nullptr;
1620
62
  llvm::BasicBlock *NextBlock = nullptr;
1621
1622
  // Create the block we'll use to increment the appropriate counter.
1623
62
  llvm::BasicBlock *CounterIncrBlock = createBasicBlock("lop.rhscnt");
1624
1625
  // Set block pointers according to Logical-AND (BO_LAnd) semantics. This
1626
  // means we need to evaluate the condition and increment the counter on TRUE:
1627
  //
1628
  // if (Cond)
1629
  //   goto CounterIncrBlock;
1630
  // else
1631
  //   goto FalseBlock;
1632
  //
1633
  // CounterIncrBlock:
1634
  //   Counter++;
1635
  //   goto TrueBlock;
1636
1637
62
  if (LOp == BO_LAnd) {
1638
35
    ThenBlock = CounterIncrBlock;
1639
35
    ElseBlock = FalseBlock;
1640
35
    NextBlock = TrueBlock;
1641
35
  }
1642
1643
  // Set block pointers according to Logical-OR (BO_LOr) semantics. This means
1644
  // we need to evaluate the condition and increment the counter on FALSE:
1645
  //
1646
  // if (Cond)
1647
  //   goto TrueBlock;
1648
  // else
1649
  //   goto CounterIncrBlock;
1650
  //
1651
  // CounterIncrBlock:
1652
  //   Counter++;
1653
  //   goto FalseBlock;
1654
1655
27
  else if (LOp == BO_LOr) {
1656
27
    ThenBlock = TrueBlock;
1657
27
    ElseBlock = CounterIncrBlock;
1658
27
    NextBlock = FalseBlock;
1659
27
  } else {
1660
0
    llvm_unreachable("Expected Opcode must be that of a Logical Operator");
1661
0
  }
1662
1663
  // Emit Branch based on condition.
1664
62
  EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, TrueCount, LH);
1665
1666
  // Emit the block containing the counter increment(s).
1667
62
  EmitBlock(CounterIncrBlock);
1668
1669
  // Increment corresponding counter; if index not provided, use Cond as index.
1670
62
  incrementProfileCounter(CntrIdx ? 
CntrIdx2
:
Cond60
);
1671
1672
  // Go to the next block.
1673
62
  EmitBranch(NextBlock);
1674
62
}
1675
1676
/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
1677
/// statement) to the specified blocks.  Based on the condition, this might try
1678
/// to simplify the codegen of the conditional based on the branch.
1679
/// \param LH The value of the likelihood attribute on the True branch.
1680
void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
1681
                                           llvm::BasicBlock *TrueBlock,
1682
                                           llvm::BasicBlock *FalseBlock,
1683
                                           uint64_t TrueCount,
1684
160k
                                           Stmt::Likelihood LH) {
1685
160k
  Cond = Cond->IgnoreParens();
1686
1687
160k
  if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
1688
1689
    // Handle X && Y in a condition.
1690
71.7k
    if (CondBOp->getOpcode() == BO_LAnd) {
1691
      // If we have "1 && X", simplify the code.  "0 && X" would have constant
1692
      // folded if the case was simple enough.
1693
6.97k
      bool ConstantBool = false;
1694
6.97k
      if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
1695
6.97k
          
ConstantBool62
) {
1696
        // br(1 && X) -> br(X).
1697
62
        incrementProfileCounter(CondBOp);
1698
62
        return EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LAnd, TrueBlock,
1699
62
                                        FalseBlock, TrueCount, LH);
1700
62
      }
1701
1702
      // If we have "X && 1", simplify the code to use an uncond branch.
1703
      // "X && 0" would have been constant folded to 0.
1704
6.91k
      if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
1705
6.91k
          
ConstantBool29
) {
1706
        // br(X && 1) -> br(X).
1707
29
        return EmitBranchToCounterBlock(CondBOp->getLHS(), BO_LAnd, TrueBlock,
1708
29
                                        FalseBlock, TrueCount, LH, CondBOp);
1709
29
      }
1710
1711
      // Emit the LHS as a conditional.  If the LHS conditional is false, we
1712
      // want to jump to the FalseBlock.
1713
6.88k
      llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
1714
      // The counter tells us how often we evaluate RHS, and all of TrueCount
1715
      // can be propagated to that branch.
1716
6.88k
      uint64_t RHSCount = getProfileCount(CondBOp->getRHS());
1717
1718
6.88k
      ConditionalEvaluation eval(*this);
1719
6.88k
      {
1720
6.88k
        ApplyDebugLocation DL(*this, Cond);
1721
        // Propagate the likelihood attribute like __builtin_expect
1722
        // __builtin_expect(X && Y, 1) -> X and Y are likely
1723
        // __builtin_expect(X && Y, 0) -> only Y is unlikely
1724
6.88k
        EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount,
1725
6.88k
                             LH == Stmt::LH_Unlikely ? 
Stmt::LH_None1
:
LH6.88k
);
1726
6.88k
        EmitBlock(LHSTrue);
1727
6.88k
      }
1728
1729
6.88k
      incrementProfileCounter(CondBOp);
1730
6.88k
      setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
1731
1732
      // Any temporaries created here are conditional.
1733
6.88k
      eval.begin(*this);
1734
6.88k
      EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LAnd, TrueBlock,
1735
6.88k
                               FalseBlock, TrueCount, LH);
1736
6.88k
      eval.end(*this);
1737
1738
6.88k
      return;
1739
6.91k
    }
1740
1741
64.7k
    if (CondBOp->getOpcode() == BO_LOr) {
1742
      // If we have "0 || X", simplify the code.  "1 || X" would have constant
1743
      // folded if the case was simple enough.
1744
420
      bool ConstantBool = false;
1745
420
      if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
1746
420
          
!ConstantBool7
) {
1747
        // br(0 || X) -> br(X).
1748
7
        incrementProfileCounter(CondBOp);
1749
7
        return EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LOr, TrueBlock,
1750
7
                                        FalseBlock, TrueCount, LH);
1751
7
      }
1752
1753
      // If we have "X || 0", simplify the code to use an uncond branch.
1754
      // "X || 1" would have been constant folded to 1.
1755
413
      if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
1756
413
          
!ConstantBool1
) {
1757
        // br(X || 0) -> br(X).
1758
1
        return EmitBranchToCounterBlock(CondBOp->getLHS(), BO_LOr, TrueBlock,
1759
1
                                        FalseBlock, TrueCount, LH, CondBOp);
1760
1
      }
1761
1762
      // Emit the LHS as a conditional.  If the LHS conditional is true, we
1763
      // want to jump to the TrueBlock.
1764
412
      llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
1765
      // We have the count for entry to the RHS and for the whole expression
1766
      // being true, so we can divy up True count between the short circuit and
1767
      // the RHS.
1768
412
      uint64_t LHSCount =
1769
412
          getCurrentProfileCount() - getProfileCount(CondBOp->getRHS());
1770
412
      uint64_t RHSCount = TrueCount - LHSCount;
1771
1772
412
      ConditionalEvaluation eval(*this);
1773
412
      {
1774
        // Propagate the likelihood attribute like __builtin_expect
1775
        // __builtin_expect(X || Y, 1) -> only Y is likely
1776
        // __builtin_expect(X || Y, 0) -> both X and Y are unlikely
1777
412
        ApplyDebugLocation DL(*this, Cond);
1778
412
        EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount,
1779
412
                             LH == Stmt::LH_Likely ? 
Stmt::LH_None1
:
LH411
);
1780
412
        EmitBlock(LHSFalse);
1781
412
      }
1782
1783
412
      incrementProfileCounter(CondBOp);
1784
412
      setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
1785
1786
      // Any temporaries created here are conditional.
1787
412
      eval.begin(*this);
1788
412
      EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LOr, TrueBlock, FalseBlock,
1789
412
                               RHSCount, LH);
1790
1791
412
      eval.end(*this);
1792
1793
412
      return;
1794
413
    }
1795
64.7k
  }
1796
1797
153k
  if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
1798
    // br(!x, t, f) -> br(x, f, t)
1799
1.30k
    if (CondUOp->getOpcode() == UO_LNot) {
1800
      // Negate the count.
1801
1.30k
      uint64_t FalseCount = getCurrentProfileCount() - TrueCount;
1802
      // The values of the enum are chosen to make this negation possible.
1803
1.30k
      LH = static_cast<Stmt::Likelihood>(-LH);
1804
      // Negate the condition and swap the destination blocks.
1805
1.30k
      return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock,
1806
1.30k
                                  FalseCount, LH);
1807
1.30k
    }
1808
1.30k
  }
1809
1810
151k
  if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
1811
    // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
1812
2
    llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
1813
2
    llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
1814
1815
    // The ConditionalOperator itself has no likelihood information for its
1816
    // true and false branches. This matches the behavior of __builtin_expect.
1817
2
    ConditionalEvaluation cond(*this);
1818
2
    EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock,
1819
2
                         getProfileCount(CondOp), Stmt::LH_None);
1820
1821
    // When computing PGO branch weights, we only know the overall count for
1822
    // the true block. This code is essentially doing tail duplication of the
1823
    // naive code-gen, introducing new edges for which counts are not
1824
    // available. Divide the counts proportionally between the LHS and RHS of
1825
    // the conditional operator.
1826
2
    uint64_t LHSScaledTrueCount = 0;
1827
2
    if (TrueCount) {
1828
0
      double LHSRatio =
1829
0
          getProfileCount(CondOp) / (double)getCurrentProfileCount();
1830
0
      LHSScaledTrueCount = TrueCount * LHSRatio;
1831
0
    }
1832
1833
2
    cond.begin(*this);
1834
2
    EmitBlock(LHSBlock);
1835
2
    incrementProfileCounter(CondOp);
1836
2
    {
1837
2
      ApplyDebugLocation DL(*this, Cond);
1838
2
      EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock,
1839
2
                           LHSScaledTrueCount, LH);
1840
2
    }
1841
2
    cond.end(*this);
1842
1843
2
    cond.begin(*this);
1844
2
    EmitBlock(RHSBlock);
1845
2
    EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock,
1846
2
                         TrueCount - LHSScaledTrueCount, LH);
1847
2
    cond.end(*this);
1848
1849
2
    return;
1850
2
  }
1851
1852
151k
  if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
1853
    // Conditional operator handling can give us a throw expression as a
1854
    // condition for a case like:
1855
    //   br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
1856
    // Fold this to:
1857
    //   br(c, throw x, br(y, t, f))
1858
0
    EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
1859
0
    return;
1860
0
  }
1861
1862
  // Emit the code with the fully general case.
1863
151k
  llvm::Value *CondV;
1864
151k
  {
1865
151k
    ApplyDebugLocation DL(*this, Cond);
1866
151k
    CondV = EvaluateExprAsBool(Cond);
1867
151k
  }
1868
1869
151k
  llvm::MDNode *Weights = nullptr;
1870
151k
  llvm::MDNode *Unpredictable = nullptr;
1871
1872
  // If the branch has a condition wrapped by __builtin_unpredictable,
1873
  // create metadata that specifies that the branch is unpredictable.
1874
  // Don't bother if not optimizing because that metadata would not be used.
1875
151k
  auto *Call = dyn_cast<CallExpr>(Cond->IgnoreImpCasts());
1876
151k
  if (Call && 
CGM.getCodeGenOpts().OptimizationLevel != 05.97k
) {
1877
116
    auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
1878
116
    if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
1879
3
      llvm::MDBuilder MDHelper(getLLVMContext());
1880
3
      Unpredictable = MDHelper.createUnpredictable();
1881
3
    }
1882
116
  }
1883
1884
  // If there is a Likelihood knowledge for the cond, lower it.
1885
  // Note that if not optimizing this won't emit anything.
1886
151k
  llvm::Value *NewCondV = emitCondLikelihoodViaExpectIntrinsic(CondV, LH);
1887
151k
  if (CondV != NewCondV)
1888
40
    CondV = NewCondV;
1889
151k
  else {
1890
    // Otherwise, lower profile counts. Note that we do this even at -O0.
1891
151k
    uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount);
1892
151k
    Weights = createProfileWeights(TrueCount, CurrentCount - TrueCount);
1893
151k
  }
1894
1895
151k
  Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable);
1896
151k
}
1897
1898
/// ErrorUnsupported - Print out an error that codegen doesn't support the
1899
/// specified stmt yet.
1900
1
void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
1901
1
  CGM.ErrorUnsupported(S, Type);
1902
1
}
1903
1904
/// emitNonZeroVLAInit - Emit the "zero" initialization of a
1905
/// variable-length array whose elements have a non-zero bit-pattern.
1906
///
1907
/// \param baseType the inner-most element type of the array
1908
/// \param src - a char* pointing to the bit-pattern for a single
1909
/// base element of the array
1910
/// \param sizeInChars - the total size of the VLA, in chars
1911
static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
1912
                               Address dest, Address src,
1913
0
                               llvm::Value *sizeInChars) {
1914
0
  CGBuilderTy &Builder = CGF.Builder;
1915
1916
0
  CharUnits baseSize = CGF.getContext().getTypeSizeInChars(baseType);
1917
0
  llvm::Value *baseSizeInChars
1918
0
    = llvm::ConstantInt::get(CGF.IntPtrTy, baseSize.getQuantity());
1919
1920
0
  Address begin =
1921
0
    Builder.CreateElementBitCast(dest, CGF.Int8Ty, "vla.begin");
1922
0
  llvm::Value *end = Builder.CreateInBoundsGEP(
1923
0
      begin.getElementType(), begin.getPointer(), sizeInChars, "vla.end");
1924
1925
0
  llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
1926
0
  llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
1927
0
  llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
1928
1929
  // Make a loop over the VLA.  C99 guarantees that the VLA element
1930
  // count must be nonzero.
1931
0
  CGF.EmitBlock(loopBB);
1932
1933
0
  llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2, "vla.cur");
1934
0
  cur->addIncoming(begin.getPointer(), originBB);
1935
1936
0
  CharUnits curAlign =
1937
0
    dest.getAlignment().alignmentOfArrayElement(baseSize);
1938
1939
  // memcpy the individual element bit-pattern.
1940
0
  Builder.CreateMemCpy(Address(cur, CGF.Int8Ty, curAlign), src, baseSizeInChars,
1941
0
                       /*volatile*/ false);
1942
1943
  // Go to the next element.
1944
0
  llvm::Value *next =
1945
0
    Builder.CreateInBoundsGEP(CGF.Int8Ty, cur, baseSizeInChars, "vla.next");
1946
1947
  // Leave if that's the end of the VLA.
1948
0
  llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
1949
0
  Builder.CreateCondBr(done, contBB, loopBB);
1950
0
  cur->addIncoming(next, loopBB);
1951
1952
0
  CGF.EmitBlock(contBB);
1953
0
}
1954
1955
void
1956
6.96k
CodeGenFunction::EmitNullInitialization(Address DestPtr, QualType Ty) {
1957
  // Ignore empty classes in C++.
1958
6.96k
  if (getLangOpts().CPlusPlus) {
1959
6.81k
    if (const RecordType *RT = Ty->getAs<RecordType>()) {
1960
6.46k
      if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
1961
5.71k
        return;
1962
6.46k
    }
1963
6.81k
  }
1964
1965
  // Cast the dest ptr to the appropriate i8 pointer type.
1966
1.25k
  if (DestPtr.getElementType() != Int8Ty)
1967
1.25k
    DestPtr = Builder.CreateElementBitCast(DestPtr, Int8Ty);
1968
1969
  // Get size and alignment info for this aggregate.
1970
1.25k
  CharUnits size = getContext().getTypeSizeInChars(Ty);
1971
1972
1.25k
  llvm::Value *SizeVal;
1973
1.25k
  const VariableArrayType *vla;
1974
1975
  // Don't bother emitting a zero-byte memset.
1976
1.25k
  if (size.isZero()) {
1977
    // But note that getTypeInfo returns 0 for a VLA.
1978
11
    if (const VariableArrayType *vlaType =
1979
11
          dyn_cast_or_null<VariableArrayType>(
1980
11
                                          getContext().getAsArrayType(Ty))) {
1981
8
      auto VlaSize = getVLASize(vlaType);
1982
8
      SizeVal = VlaSize.NumElts;
1983
8
      CharUnits eltSize = getContext().getTypeSizeInChars(VlaSize.Type);
1984
8
      if (!eltSize.isOne())
1985
8
        SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
1986
8
      vla = vlaType;
1987
8
    } else {
1988
3
      return;
1989
3
    }
1990
1.24k
  } else {
1991
1.24k
    SizeVal = CGM.getSize(size);
1992
1.24k
    vla = nullptr;
1993
1.24k
  }
1994
1995
  // If the type contains a pointer to data member we can't memset it to zero.
1996
  // Instead, create a null constant and copy it to the destination.
1997
  // TODO: there are other patterns besides zero that we can usefully memset,
1998
  // like -1, which happens to be the pattern used by member-pointers.
1999
1.25k
  if (!CGM.getTypes().isZeroInitializable(Ty)) {
2000
    // For a VLA, emit a single element, then splat that over the VLA.
2001
9
    if (vla) 
Ty = getContext().getBaseElementType(vla)0
;
2002
2003
9
    llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
2004
2005
9
    llvm::GlobalVariable *NullVariable =
2006
9
      new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
2007
9
                               /*isConstant=*/true,
2008
9
                               llvm::GlobalVariable::PrivateLinkage,
2009
9
                               NullConstant, Twine());
2010
9
    CharUnits NullAlign = DestPtr.getAlignment();
2011
9
    NullVariable->setAlignment(NullAlign.getAsAlign());
2012
9
    Address SrcPtr(Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy()),
2013
9
                   Builder.getInt8Ty(), NullAlign);
2014
2015
9
    if (vla) 
return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal)0
;
2016
2017
    // Get and call the appropriate llvm.memcpy overload.
2018
9
    Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, false);
2019
9
    return;
2020
9
  }
2021
2022
  // Otherwise, just memset the whole thing to zero.  This is legal
2023
  // because in LLVM, all default initializers (other than the ones we just
2024
  // handled above) are guaranteed to have a bit pattern of all zeros.
2025
1.24k
  Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, false);
2026
1.24k
}
2027
2028
61
llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
2029
  // Make sure that there is a block for the indirect goto.
2030
61
  if (!IndirectBranch)
2031
38
    GetIndirectGotoBlock();
2032
2033
61
  llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
2034
2035
  // Make sure the indirect branch includes all of the address-taken blocks.
2036
61
  IndirectBranch->addDestination(BB);
2037
61
  return llvm::BlockAddress::get(CurFn, BB);
2038
61
}
2039
2040
60
llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
2041
  // If we already made the indirect branch for indirect goto, return its block.
2042
60
  if (IndirectBranch) 
return IndirectBranch->getParent()21
;
2043
2044
39
  CGBuilderTy TmpBuilder(*this, createBasicBlock("indirectgoto"));
2045
2046
  // Create the PHI node that indirect gotos will add entries to.
2047
39
  llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
2048
39
                                              "indirect.goto.dest");
2049
2050
  // Create the indirect branch instruction.
2051
39
  IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
2052
39
  return IndirectBranch->getParent();
2053
60
}
2054
2055
/// Computes the length of an array in elements, as well as the base
2056
/// element type and a properly-typed first element pointer.
2057
llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
2058
                                              QualType &baseType,
2059
4.81k
                                              Address &addr) {
2060
4.81k
  const ArrayType *arrayType = origArrayType;
2061
2062
  // If it's a VLA, we have to load the stored size.  Note that
2063
  // this is the size of the VLA in bytes, not its size in elements.
2064
4.81k
  llvm::Value *numVLAElements = nullptr;
2065
4.81k
  if (isa<VariableArrayType>(arrayType)) {
2066
630
    numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).NumElts;
2067
2068
    // Walk into all VLAs.  This doesn't require changes to addr,
2069
    // which has type T* where T is the first non-VLA element type.
2070
667
    do {
2071
667
      QualType elementType = arrayType->getElementType();
2072
667
      arrayType = getContext().getAsArrayType(elementType);
2073
2074
      // If we only have VLA components, 'addr' requires no adjustment.
2075
667
      if (!arrayType) {
2076
626
        baseType = elementType;
2077
626
        return numVLAElements;
2078
626
      }
2079
667
    } while (
isa<VariableArrayType>(arrayType)41
);
2080
2081
    // We get out here only if we find a constant array type
2082
    // inside the VLA.
2083
630
  }
2084
2085
  // We have some number of constant-length arrays, so addr should
2086
  // have LLVM type [M x [N x [...]]]*.  Build a GEP that walks
2087
  // down to the first element of addr.
2088
4.19k
  SmallVector<llvm::Value*, 8> gepIndices;
2089
2090
  // GEP down to the array type.
2091
4.19k
  llvm::ConstantInt *zero = Builder.getInt32(0);
2092
4.19k
  gepIndices.push_back(zero);
2093
2094
4.19k
  uint64_t countFromCLAs = 1;
2095
4.19k
  QualType eltType;
2096
2097
4.19k
  llvm::ArrayType *llvmArrayType =
2098
4.19k
    dyn_cast<llvm::ArrayType>(addr.getElementType());
2099
8.15k
  while (llvmArrayType) {
2100
3.96k
    assert(isa<ConstantArrayType>(arrayType));
2101
0
    assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
2102
3.96k
             == llvmArrayType->getNumElements());
2103
2104
0
    gepIndices.push_back(zero);
2105
3.96k
    countFromCLAs *= llvmArrayType->getNumElements();
2106
3.96k
    eltType = arrayType->getElementType();
2107
2108
3.96k
    llvmArrayType =
2109
3.96k
      dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
2110
3.96k
    arrayType = getContext().getAsArrayType(arrayType->getElementType());
2111
3.96k
    assert((!llvmArrayType || arrayType) &&
2112
3.96k
           "LLVM and Clang types are out-of-synch");
2113
3.96k
  }
2114
2115
4.19k
  if (arrayType) {
2116
    // From this point onwards, the Clang array type has been emitted
2117
    // as some other type (probably a packed struct). Compute the array
2118
    // size, and just emit the 'begin' expression as a bitcast.
2119
694
    while (arrayType) {
2120
368
      countFromCLAs *=
2121
368
          cast<ConstantArrayType>(arrayType)->getSize().getZExtValue();
2122
368
      eltType = arrayType->getElementType();
2123
368
      arrayType = getContext().getAsArrayType(eltType);
2124
368
    }
2125
2126
326
    llvm::Type *baseType = ConvertType(eltType);
2127
326
    addr = Builder.CreateElementBitCast(addr, baseType, "array.begin");
2128
3.86k
  } else {
2129
    // Create the actual GEP.
2130
3.86k
    addr = Address(Builder.CreateInBoundsGEP(
2131
3.86k
        addr.getElementType(), addr.getPointer(), gepIndices, "array.begin"),
2132
3.86k
        ConvertTypeForMem(eltType),
2133
3.86k
        addr.getAlignment());
2134
3.86k
  }
2135
2136
4.19k
  baseType = eltType;
2137
2138
4.19k
  llvm::Value *numElements
2139
4.19k
    = llvm::ConstantInt::get(SizeTy, countFromCLAs);
2140
2141
  // If we had any VLA dimensions, factor them in.
2142
4.19k
  if (numVLAElements)
2143
4
    numElements = Builder.CreateNUWMul(numVLAElements, numElements);
2144
2145
4.19k
  return numElements;
2146
4.81k
}
2147
2148
2.16k
CodeGenFunction::VlaSizePair CodeGenFunction::getVLASize(QualType type) {
2149
2.16k
  const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
2150
2.16k
  assert(vla && "type was not a variable array type!");
2151
0
  return getVLASize(vla);
2152
2.16k
}
2153
2154
CodeGenFunction::VlaSizePair
2155
5.82k
CodeGenFunction::getVLASize(const VariableArrayType *type) {
2156
  // The number of elements so far; always size_t.
2157
5.82k
  llvm::Value *numElements = nullptr;
2158
2159
5.82k
  QualType elementType;
2160
7.37k
  do {
2161
7.37k
    elementType = type->getElementType();
2162
7.37k
    llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
2163
7.37k
    assert(vlaSize && "no size for VLA!");
2164
0
    assert(vlaSize->getType() == SizeTy);
2165
2166
7.37k
    if (!numElements) {
2167
5.82k
      numElements = vlaSize;
2168
5.82k
    } else {
2169
      // It's undefined behavior if this wraps around, so mark it that way.
2170
      // FIXME: Teach -fsanitize=undefined to trap this.
2171
1.54k
      numElements = Builder.CreateNUWMul(numElements, vlaSize);
2172
1.54k
    }
2173
7.37k
  } while ((type = getContext().getAsVariableArrayType(elementType)));
2174
2175
0
  return { numElements, elementType };
2176
5.82k
}
2177
2178
CodeGenFunction::VlaSizePair
2179
3.20k
CodeGenFunction::getVLAElements1D(QualType type) {
2180
3.20k
  const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
2181
3.20k
  assert(vla && "type was not a variable array type!");
2182
0
  return getVLAElements1D(vla);
2183
3.20k
}
2184
2185
CodeGenFunction::VlaSizePair
2186
3.20k
CodeGenFunction::getVLAElements1D(const VariableArrayType *Vla) {
2187
3.20k
  llvm::Value *VlaSize = VLASizeMap[Vla->getSizeExpr()];
2188
3.20k
  assert(VlaSize && "no size for VLA!");
2189
0
  assert(VlaSize->getType() == SizeTy);
2190
0
  return { VlaSize, Vla->getElementType() };
2191
3.20k
}
2192
2193
2.86k
void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
2194
2.86k
  assert(type->isVariablyModifiedType() &&
2195
2.86k
         "Must pass variably modified type to EmitVLASizes!");
2196
2197
0
  EnsureInsertPoint();
2198
2199
  // We're going to walk down into the type and look for VLA
2200
  // expressions.
2201
4.07k
  do {
2202
4.07k
    assert(type->isVariablyModifiedType());
2203
2204
0
    const Type *ty = type.getTypePtr();
2205
4.07k
    switch (ty->getTypeClass()) {
2206
2207
0
#define TYPE(Class, Base)
2208
0
#define ABSTRACT_TYPE(Class, Base)
2209
0
#define NON_CANONICAL_TYPE(Class, Base)
2210
0
#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2211
0
#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
2212
0
#include "clang/AST/TypeNodes.inc"
2213
0
      llvm_unreachable("unexpected dependent type!");
2214
2215
    // These types are never variably-modified.
2216
0
    case Type::Builtin:
2217
0
    case Type::Complex:
2218
0
    case Type::Vector:
2219
0
    case Type::ExtVector:
2220
0
    case Type::ConstantMatrix:
2221
0
    case Type::Record:
2222
0
    case Type::Enum:
2223
0
    case Type::Elaborated:
2224
0
    case Type::Using:
2225
0
    case Type::TemplateSpecialization:
2226
0
    case Type::ObjCTypeParam:
2227
0
    case Type::ObjCObject:
2228
0
    case Type::ObjCInterface:
2229
0
    case Type::ObjCObjectPointer:
2230
0
    case Type::BitInt:
2231
0
      llvm_unreachable("type class is never variably-modified!");
2232
2233
0
    case Type::Adjusted:
2234
0
      type = cast<AdjustedType>(ty)->getAdjustedType();
2235
0
      break;
2236
2237
70
    case Type::Decayed:
2238
70
      type = cast<DecayedType>(ty)->getPointeeType();
2239
70
      break;
2240
2241
91
    case Type::Pointer:
2242
91
      type = cast<PointerType>(ty)->getPointeeType();
2243
91
      break;
2244
2245
0
    case Type::BlockPointer:
2246
0
      type = cast<BlockPointerType>(ty)->getPointeeType();
2247
0
      break;
2248
2249
3
    case Type::LValueReference:
2250
3
    case Type::RValueReference:
2251
3
      type = cast<ReferenceType>(ty)->getPointeeType();
2252
3
      break;
2253
2254
0
    case Type::MemberPointer:
2255
0
      type = cast<MemberPointerType>(ty)->getPointeeType();
2256
0
      break;
2257
2258
2
    case Type::ConstantArray:
2259
12
    case Type::IncompleteArray:
2260
      // Losing element qualification here is fine.
2261
12
      type = cast<ArrayType>(ty)->getElementType();
2262
12
      break;
2263
2264
3.81k
    case Type::VariableArray: {
2265
      // Losing element qualification here is fine.
2266
3.81k
      const VariableArrayType *vat = cast<VariableArrayType>(ty);
2267
2268
      // Unknown size indication requires no size computation.
2269
      // Otherwise, evaluate and record it.
2270
3.81k
      if (const Expr *sizeExpr = vat->getSizeExpr()) {
2271
        // It's possible that we might have emitted this already,
2272
        // e.g. with a typedef and a pointer to it.
2273
3.81k
        llvm::Value *&entry = VLASizeMap[sizeExpr];
2274
3.81k
        if (!entry) {
2275
3.45k
          llvm::Value *size = EmitScalarExpr(sizeExpr);
2276
2277
          // C11 6.7.6.2p5:
2278
          //   If the size is an expression that is not an integer constant
2279
          //   expression [...] each time it is evaluated it shall have a value
2280
          //   greater than zero.
2281
3.45k
          if (SanOpts.has(SanitizerKind::VLABound)) {
2282
4
            SanitizerScope SanScope(this);
2283
4
            llvm::Value *Zero = llvm::Constant::getNullValue(size->getType());
2284
4
            clang::QualType SEType = sizeExpr->getType();
2285
4
            llvm::Value *CheckCondition =
2286
4
                SEType->isSignedIntegerType()
2287
4
                    ? 
Builder.CreateICmpSGT(size, Zero)2
2288
4
                    : 
Builder.CreateICmpUGT(size, Zero)2
;
2289
4
            llvm::Constant *StaticArgs[] = {
2290
4
                EmitCheckSourceLocation(sizeExpr->getBeginLoc()),
2291
4
                EmitCheckTypeDescriptor(SEType)};
2292
4
            EmitCheck(std::make_pair(CheckCondition, SanitizerKind::VLABound),
2293
4
                      SanitizerHandler::VLABoundNotPositive, StaticArgs, size);
2294
4
          }
2295
2296
          // Always zexting here would be wrong if it weren't
2297
          // undefined behavior to have a negative bound.
2298
          // FIXME: What about when size's type is larger than size_t?
2299
3.45k
          entry = Builder.CreateIntCast(size, SizeTy, /*signed*/ false);
2300
3.45k
        }
2301
3.81k
      }
2302
3.81k
      type = vat->getElementType();
2303
3.81k
      break;
2304
2
    }
2305
2306
1
    case Type::FunctionProto:
2307
1
    case Type::FunctionNoProto:
2308
1
      type = cast<FunctionType>(ty)->getReturnType();
2309
1
      break;
2310
2311
43
    case Type::Paren:
2312
45
    case Type::TypeOf:
2313
45
    case Type::UnaryTransform:
2314
45
    case Type::Attributed:
2315
45
    case Type::BTFTagAttributed:
2316
45
    case Type::SubstTemplateTypeParm:
2317
45
    case Type::MacroQualified:
2318
      // Keep walking after single level desugaring.
2319
45
      type = type.getSingleStepDesugaredType(getContext());
2320
45
      break;
2321
2322
28
    case Type::Typedef:
2323
28
    case Type::Decltype:
2324
28
    case Type::Auto:
2325
28
    case Type::DeducedTemplateSpecialization:
2326
      // Stop walking: nothing to do.
2327
28
      return;
2328
2329
14
    case Type::TypeOfExpr:
2330
      // Stop walking: emit typeof expression.
2331
14
      EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
2332
14
      return;
2333
2334
1
    case Type::Atomic:
2335
1
      type = cast<AtomicType>(ty)->getValueType();
2336
1
      break;
2337
2338
0
    case Type::Pipe:
2339
0
      type = cast<PipeType>(ty)->getElementType();
2340
0
      break;
2341
4.07k
    }
2342
4.07k
  } while (
type->isVariablyModifiedType()4.03k
);
2343
2.86k
}
2344
2345
1.33k
Address CodeGenFunction::EmitVAListRef(const Expr* E) {
2346
1.33k
  if (getContext().getBuiltinVaListType()->isArrayType())
2347
548
    return EmitPointerWithAlignment(E);
2348
783
  return EmitLValue(E).getAddress(*this);
2349
1.33k
}
2350
2351
40
Address CodeGenFunction::EmitMSVAListRef(const Expr *E) {
2352
40
  return EmitLValue(E).getAddress(*this);
2353
40
}
2354
2355
void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
2356
6.34k
                                              const APValue &Init) {
2357
6.34k
  assert(Init.hasValue() && "Invalid DeclRefExpr initializer!");
2358
6.34k
  if (CGDebugInfo *Dbg = getDebugInfo())
2359
3.76k
    if (CGM.getCodeGenOpts().hasReducedDebugInfo())
2360
3.76k
      Dbg->EmitGlobalVariable(E->getDecl(), Init);
2361
6.34k
}
2362
2363
CodeGenFunction::PeepholeProtection
2364
1.69k
CodeGenFunction::protectFromPeepholes(RValue rvalue) {
2365
  // At the moment, the only aggressive peephole we do in IR gen
2366
  // is trunc(zext) folding, but if we add more, we can easily
2367
  // extend this protection.
2368
2369
1.69k
  if (!rvalue.isScalar()) 
return PeepholeProtection()77
;
2370
1.61k
  llvm::Value *value = rvalue.getScalarVal();
2371
1.61k
  if (!isa<llvm::ZExtInst>(value)) 
return PeepholeProtection()1.53k
;
2372
2373
  // Just make an extra bitcast.
2374
77
  assert(HaveInsertPoint());
2375
0
  llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
2376
77
                                                  Builder.GetInsertBlock());
2377
2378
77
  PeepholeProtection protection;
2379
77
  protection.Inst = inst;
2380
77
  return protection;
2381
1.61k
}
2382
2383
1.69k
void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
2384
1.69k
  if (!protection.Inst) 
return1.61k
;
2385
2386
  // In theory, we could try to duplicate the peepholes now, but whatever.
2387
77
  protection.Inst->eraseFromParent();
2388
77
}
2389
2390
void CodeGenFunction::emitAlignmentAssumption(llvm::Value *PtrValue,
2391
                                              QualType Ty, SourceLocation Loc,
2392
                                              SourceLocation AssumptionLoc,
2393
                                              llvm::Value *Alignment,
2394
439
                                              llvm::Value *OffsetValue) {
2395
439
  if (Alignment->getType() != IntPtrTy)
2396
200
    Alignment =
2397
200
        Builder.CreateIntCast(Alignment, IntPtrTy, false, "casted.align");
2398
439
  if (OffsetValue && 
OffsetValue->getType() != IntPtrTy16
)
2399
5
    OffsetValue =
2400
5
        Builder.CreateIntCast(OffsetValue, IntPtrTy, true, "casted.offset");
2401
439
  llvm::Value *TheCheck = nullptr;
2402
439
  if (SanOpts.has(SanitizerKind::Alignment)) {
2403
33
    llvm::Value *PtrIntValue =
2404
33
        Builder.CreatePtrToInt(PtrValue, IntPtrTy, "ptrint");
2405
2406
33
    if (OffsetValue) {
2407
9
      bool IsOffsetZero = false;
2408
9
      if (const auto *CI = dyn_cast<llvm::ConstantInt>(OffsetValue))
2409
6
        IsOffsetZero = CI->isZero();
2410
2411
9
      if (!IsOffsetZero)
2412
9
        PtrIntValue = Builder.CreateSub(PtrIntValue, OffsetValue, "offsetptr");
2413
9
    }
2414
2415
33
    llvm::Value *Zero = llvm::ConstantInt::get(IntPtrTy, 0);
2416
33
    llvm::Value *Mask =
2417
33
        Builder.CreateSub(Alignment, llvm::ConstantInt::get(IntPtrTy, 1));
2418
33
    llvm::Value *MaskedPtr = Builder.CreateAnd(PtrIntValue, Mask, "maskedptr");
2419
33
    TheCheck = Builder.CreateICmpEQ(MaskedPtr, Zero, "maskcond");
2420
33
  }
2421
439
  llvm::Instruction *Assumption = Builder.CreateAlignmentAssumption(
2422
439
      CGM.getDataLayout(), PtrValue, Alignment, OffsetValue);
2423
2424
439
  if (!SanOpts.has(SanitizerKind::Alignment))
2425
406
    return;
2426
33
  emitAlignmentAssumptionCheck(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
2427
33
                               OffsetValue, TheCheck, Assumption);
2428
33
}
2429
2430
void CodeGenFunction::emitAlignmentAssumption(llvm::Value *PtrValue,
2431
                                              const Expr *E,
2432
                                              SourceLocation AssumptionLoc,
2433
                                              llvm::Value *Alignment,
2434
408
                                              llvm::Value *OffsetValue) {
2435
408
  if (auto *CE = dyn_cast<CastExpr>(E))
2436
168
    E = CE->getSubExprAsWritten();
2437
408
  QualType Ty = E->getType();
2438
408
  SourceLocation Loc = E->getExprLoc();
2439
2440
408
  emitAlignmentAssumption(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
2441
408
                          OffsetValue);
2442
408
}
2443
2444
llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Function *AnnotationFn,
2445
                                                 llvm::Value *AnnotatedVal,
2446
                                                 StringRef AnnotationStr,
2447
                                                 SourceLocation Location,
2448
28
                                                 const AnnotateAttr *Attr) {
2449
28
  SmallVector<llvm::Value *, 5> Args = {
2450
28
      AnnotatedVal,
2451
28
      Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy),
2452
28
      Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy),
2453
28
      CGM.EmitAnnotationLineNo(Location),
2454
28
  };
2455
28
  if (Attr)
2456
21
    Args.push_back(CGM.EmitAnnotationArgs(Attr));
2457
28
  return Builder.CreateCall(AnnotationFn, Args);
2458
28
}
2459
2460
8
void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
2461
8
  assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
2462
  // FIXME We create a new bitcast for every annotation because that's what
2463
  // llvm-gcc was doing.
2464
0
  for (const auto *I : D->specific_attrs<AnnotateAttr>())
2465
12
    EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation),
2466
12
                       Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()),
2467
12
                       I->getAnnotation(), D->getLocation(), I);
2468
8
}
2469
2470
Address CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
2471
5
                                              Address Addr) {
2472
5
  assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
2473
0
  llvm::Value *V = Addr.getPointer();
2474
5
  llvm::Type *VTy = V->getType();
2475
5
  auto *PTy = dyn_cast<llvm::PointerType>(VTy);
2476
5
  unsigned AS = PTy ? PTy->getAddressSpace() : 
00
;
2477
5
  llvm::PointerType *IntrinTy =
2478
5
      llvm::PointerType::getWithSamePointeeType(CGM.Int8PtrTy, AS);
2479
5
  llvm::Function *F =
2480
5
      CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation, IntrinTy);
2481
2482
9
  for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
2483
    // FIXME Always emit the cast inst so we can differentiate between
2484
    // annotation on the first field of a struct and annotation on the struct
2485
    // itself.
2486
9
    if (VTy != IntrinTy)
2487
9
      V = Builder.CreateBitCast(V, IntrinTy);
2488
9
    V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation(), I);
2489
9
    V = Builder.CreateBitCast(V, VTy);
2490
9
  }
2491
2492
5
  return Address(V, Addr.getElementType(), Addr.getAlignment());
2493
5
}
2494
2495
69.1k
CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { }
2496
2497
CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF)
2498
58.6k
    : CGF(CGF) {
2499
58.6k
  assert(!CGF->IsSanitizerScope);
2500
0
  CGF->IsSanitizerScope = true;
2501
58.6k
}
2502
2503
58.6k
CodeGenFunction::SanitizerScope::~SanitizerScope() {
2504
58.6k
  CGF->IsSanitizerScope = false;
2505
58.6k
}
2506
2507
void CodeGenFunction::InsertHelper(llvm::Instruction *I,
2508
                                   const llvm::Twine &Name,
2509
                                   llvm::BasicBlock *BB,
2510
5.78M
                                   llvm::BasicBlock::iterator InsertPt) const {
2511
5.78M
  LoopStack.InsertHelper(I);
2512
5.78M
  if (IsSanitizerScope)
2513
15.5k
    CGM.getSanitizerMetadata()->disableSanitizerForInstruction(I);
2514
5.78M
}
2515
2516
void CGBuilderInserter::InsertHelper(
2517
    llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB,
2518
5.78M
    llvm::BasicBlock::iterator InsertPt) const {
2519
5.78M
  llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt);
2520
5.78M
  if (CGF)
2521
5.78M
    CGF->InsertHelper(I, Name, BB, InsertPt);
2522
5.78M
}
2523
2524
// Emits an error if we don't have a valid set of target features for the
2525
// called function.
2526
void CodeGenFunction::checkTargetFeatures(const CallExpr *E,
2527
56.3k
                                          const FunctionDecl *TargetDecl) {
2528
56.3k
  return checkTargetFeatures(E->getBeginLoc(), TargetDecl);
2529
56.3k
}
2530
2531
// Emits an error if we don't have a valid set of target features for the
2532
// called function.
2533
void CodeGenFunction::checkTargetFeatures(SourceLocation Loc,
2534
71.2k
                                          const FunctionDecl *TargetDecl) {
2535
  // Early exit if this is an indirect call.
2536
71.2k
  if (!TargetDecl)
2537
0
    return;
2538
2539
  // Get the current enclosing function if it exists. If it doesn't
2540
  // we can't check the target features anyhow.
2541
71.2k
  const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl);
2542
71.2k
  if (!FD)
2543
0
    return;
2544
2545
  // Grab the required features for the call. For a builtin this is listed in
2546
  // the td file with the default cpu, for an always_inline function this is any
2547
  // listed cpu and any listed features.
2548
71.2k
  unsigned BuiltinID = TargetDecl->getBuiltinID();
2549
71.2k
  std::string MissingFeature;
2550
71.2k
  llvm::StringMap<bool> CallerFeatureMap;
2551
71.2k
  CGM.getContext().getFunctionFeatureMap(CallerFeatureMap, FD);
2552
71.2k
  if (BuiltinID) {
2553
56.3k
    StringRef FeatureList(
2554
56.3k
        CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID));
2555
    // Return if the builtin doesn't have any required features.
2556
56.3k
    if (FeatureList.empty())
2557
41.1k
      return;
2558
15.2k
    assert(!FeatureList.contains(' ') && "Space in feature list");
2559
0
    TargetFeatures TF(CallerFeatureMap);
2560
15.2k
    if (!TF.hasRequiredFeatures(FeatureList))
2561
466
      CGM.getDiags().Report(Loc, diag::err_builtin_needs_feature)
2562
466
          << TargetDecl->getDeclName() << FeatureList;
2563
15.2k
  } else 
if (14.8k
!TargetDecl->isMultiVersion()14.8k
&&
2564
14.8k
             TargetDecl->hasAttr<TargetAttr>()) {
2565
    // Get the required features for the callee.
2566
2567
14.8k
    const TargetAttr *TD = TargetDecl->getAttr<TargetAttr>();
2568
14.8k
    ParsedTargetAttr ParsedAttr =
2569
14.8k
        CGM.getContext().filterFunctionTargetAttrs(TD);
2570
2571
14.8k
    SmallVector<StringRef, 1> ReqFeatures;
2572
14.8k
    llvm::StringMap<bool> CalleeFeatureMap;
2573
14.8k
    CGM.getContext().getFunctionFeatureMap(CalleeFeatureMap, TargetDecl);
2574
2575
16.4k
    for (const auto &F : ParsedAttr.Features) {
2576
16.4k
      if (F[0] == '+' && CalleeFeatureMap.lookup(F.substr(1)))
2577
16.4k
        ReqFeatures.push_back(StringRef(F).substr(1));
2578
16.4k
    }
2579
2580
232k
    for (const auto &F : CalleeFeatureMap) {
2581
      // Only positive features are "required".
2582
232k
      if (F.getValue())
2583
232k
        ReqFeatures.push_back(F.getKey());
2584
232k
    }
2585
248k
    if (
!llvm::all_of(ReqFeatures, [&](StringRef Feature) 14.8k
{
2586
248k
      if (!CallerFeatureMap.lookup(Feature)) {
2587
19
        MissingFeature = Feature.str();
2588
19
        return false;
2589
19
      }
2590
248k
      return true;
2591
248k
    }))
2592
19
      CGM.getDiags().Report(Loc, diag::err_function_needs_feature)
2593
19
          << FD->getDeclName() << TargetDecl->getDeclName() << MissingFeature;
2594
14.8k
  }
2595
71.2k
}
2596
2597
87
void CodeGenFunction::EmitSanitizerStatReport(llvm::SanitizerStatKind SSK) {
2598
87
  if (!CGM.getCodeGenOpts().SanitizeStats)
2599
77
    return;
2600
2601
10
  llvm::IRBuilder<> IRB(Builder.GetInsertBlock(), Builder.GetInsertPoint());
2602
10
  IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation());
2603
10
  CGM.getSanStats().create(IRB, SSK);
2604
10
}
2605
2606
llvm::Value *
2607
336
CodeGenFunction::FormResolverCondition(const MultiVersionResolverOption &RO) {
2608
336
  llvm::Value *Condition = nullptr;
2609
2610
336
  if (!RO.Conditions.Architecture.empty())
2611
100
    Condition = EmitX86CpuIs(RO.Conditions.Architecture);
2612
2613
336
  if (!RO.Conditions.Features.empty()) {
2614
140
    llvm::Value *FeatureCond = EmitX86CpuSupports(RO.Conditions.Features);
2615
140
    Condition =
2616
140
        Condition ? 
Builder.CreateAnd(Condition, FeatureCond)2
:
FeatureCond138
;
2617
140
  }
2618
336
  return Condition;
2619
336
}
2620
2621
static void CreateMultiVersionResolverReturn(CodeGenModule &CGM,
2622
                                             llvm::Function *Resolver,
2623
                                             CGBuilderTy &Builder,
2624
                                             llvm::Function *FuncToReturn,
2625
336
                                             bool SupportsIFunc) {
2626
336
  if (SupportsIFunc) {
2627
169
    Builder.CreateRet(FuncToReturn);
2628
169
    return;
2629
169
  }
2630
2631
167
  llvm::SmallVector<llvm::Value *, 10> Args(
2632
167
      llvm::make_pointer_range(Resolver->args()));
2633
2634
167
  llvm::CallInst *Result = Builder.CreateCall(FuncToReturn, Args);
2635
167
  Result->setTailCallKind(llvm::CallInst::TCK_MustTail);
2636
2637
167
  if (Resolver->getReturnType()->isVoidTy())
2638
43
    Builder.CreateRetVoid();
2639
124
  else
2640
124
    Builder.CreateRet(Result);
2641
167
}
2642
2643
void CodeGenFunction::EmitMultiVersionResolver(
2644
120
    llvm::Function *Resolver, ArrayRef<MultiVersionResolverOption> Options) {
2645
120
  assert(getContext().getTargetInfo().getTriple().isX86() &&
2646
120
         "Only implemented for x86 targets");
2647
2648
0
  bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc();
2649
2650
  // Main function's basic block.
2651
120
  llvm::BasicBlock *CurBlock = createBasicBlock("resolver_entry", Resolver);
2652
120
  Builder.SetInsertPoint(CurBlock);
2653
120
  EmitX86CpuInit();
2654
2655
336
  for (const MultiVersionResolverOption &RO : Options) {
2656
336
    Builder.SetInsertPoint(CurBlock);
2657
336
    llvm::Value *Condition = FormResolverCondition(RO);
2658
2659
    // The 'default' or 'generic' case.
2660
336
    if (!Condition) {
2661
98
      assert(&RO == Options.end() - 1 &&
2662
98
             "Default or Generic case must be last");
2663
0
      CreateMultiVersionResolverReturn(CGM, Resolver, Builder, RO.Function,
2664
98
                                       SupportsIFunc);
2665
98
      return;
2666
98
    }
2667
2668
238
    llvm::BasicBlock *RetBlock = createBasicBlock("resolver_return", Resolver);
2669
238
    CGBuilderTy RetBuilder(*this, RetBlock);
2670
238
    CreateMultiVersionResolverReturn(CGM, Resolver, RetBuilder, RO.Function,
2671
238
                                     SupportsIFunc);
2672
238
    CurBlock = createBasicBlock("resolver_else", Resolver);
2673
238
    Builder.CreateCondBr(Condition, RetBlock, CurBlock);
2674
238
  }
2675
2676
  // If no generic/default, emit an unreachable.
2677
22
  Builder.SetInsertPoint(CurBlock);
2678
22
  llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
2679
22
  TrapCall->setDoesNotReturn();
2680
22
  TrapCall->setDoesNotThrow();
2681
22
  Builder.CreateUnreachable();
2682
22
  Builder.ClearInsertionPoint();
2683
22
}
2684
2685
// Loc - where the diagnostic will point, where in the source code this
2686
//  alignment has failed.
2687
// SecondaryLoc - if present (will be present if sufficiently different from
2688
//  Loc), the diagnostic will additionally point a "Note:" to this location.
2689
//  It should be the location where the __attribute__((assume_aligned))
2690
//  was written e.g.
2691
void CodeGenFunction::emitAlignmentAssumptionCheck(
2692
    llvm::Value *Ptr, QualType Ty, SourceLocation Loc,
2693
    SourceLocation SecondaryLoc, llvm::Value *Alignment,
2694
    llvm::Value *OffsetValue, llvm::Value *TheCheck,
2695
33
    llvm::Instruction *Assumption) {
2696
33
  assert(Assumption && isa<llvm::CallInst>(Assumption) &&
2697
33
         cast<llvm::CallInst>(Assumption)->getCalledOperand() ==
2698
33
             llvm::Intrinsic::getDeclaration(
2699
33
                 Builder.GetInsertBlock()->getParent()->getParent(),
2700
33
                 llvm::Intrinsic::assume) &&
2701
33
         "Assumption should be a call to llvm.assume().");
2702
0
  assert(&(Builder.GetInsertBlock()->back()) == Assumption &&
2703
33
         "Assumption should be the last instruction of the basic block, "
2704
33
         "since the basic block is still being generated.");
2705
2706
33
  if (!SanOpts.has(SanitizerKind::Alignment))
2707
0
    return;
2708
2709
  // Don't check pointers to volatile data. The behavior here is implementation-
2710
  // defined.
2711
33
  if (Ty->getPointeeType().isVolatileQualified())
2712
1
    return;
2713
2714
  // We need to temorairly remove the assumption so we can insert the
2715
  // sanitizer check before it, else the check will be dropped by optimizations.
2716
32
  Assumption->removeFromParent();
2717
2718
32
  {
2719
32
    SanitizerScope SanScope(this);
2720
2721
32
    if (!OffsetValue)
2722
23
      OffsetValue = Builder.getInt1(false); // no offset.
2723
2724
32
    llvm::Constant *StaticData[] = {EmitCheckSourceLocation(Loc),
2725
32
                                    EmitCheckSourceLocation(SecondaryLoc),
2726
32
                                    EmitCheckTypeDescriptor(Ty)};
2727
32
    llvm::Value *DynamicData[] = {EmitCheckValue(Ptr),
2728
32
                                  EmitCheckValue(Alignment),
2729
32
                                  EmitCheckValue(OffsetValue)};
2730
32
    EmitCheck({std::make_pair(TheCheck, SanitizerKind::Alignment)},
2731
32
              SanitizerHandler::AlignmentAssumption, StaticData, DynamicData);
2732
32
  }
2733
2734
  // We are now in the (new, empty) "cont" basic block.
2735
  // Reintroduce the assumption.
2736
32
  Builder.Insert(Assumption);
2737
  // FIXME: Assumption still has it's original basic block as it's Parent.
2738
32
}
2739
2740
69.5k
llvm::DebugLoc CodeGenFunction::SourceLocToDebugLoc(SourceLocation Location) {
2741
69.5k
  if (CGDebugInfo *DI = getDebugInfo())
2742
30.9k
    return DI->SourceLocToDebugLoc(Location);
2743
2744
38.6k
  return llvm::DebugLoc();
2745
69.5k
}
2746
2747
llvm::Value *
2748
CodeGenFunction::emitCondLikelihoodViaExpectIntrinsic(llvm::Value *Cond,
2749
152k
                                                      Stmt::Likelihood LH) {
2750
152k
  switch (LH) {
2751
151k
  case Stmt::LH_None:
2752
151k
    return Cond;
2753
17
  case Stmt::LH_Likely:
2754
58
  case Stmt::LH_Unlikely:
2755
    // Don't generate llvm.expect on -O0 as the backend won't use it for
2756
    // anything.
2757
58
    if (CGM.getCodeGenOpts().OptimizationLevel == 0)
2758
0
      return Cond;
2759
58
    llvm::Type *CondTy = Cond->getType();
2760
58
    assert(CondTy->isIntegerTy(1) && "expecting condition to be a boolean");
2761
0
    llvm::Function *FnExpect =
2762
58
        CGM.getIntrinsic(llvm::Intrinsic::expect, CondTy);
2763
58
    llvm::Value *ExpectedValueOfCond =
2764
58
        llvm::ConstantInt::getBool(CondTy, LH == Stmt::LH_Likely);
2765
58
    return Builder.CreateCall(FnExpect, {Cond, ExpectedValueOfCond},
2766
58
                              Cond->getName() + ".expval");
2767
152k
  }
2768
0
  llvm_unreachable("Unknown Likelihood");
2769
0
}
2770
2771
llvm::Value *CodeGenFunction::emitBoolVecConversion(llvm::Value *SrcVec,
2772
                                                    unsigned NumElementsDst,
2773
11
                                                    const llvm::Twine &Name) {
2774
11
  auto *SrcTy = cast<llvm::FixedVectorType>(SrcVec->getType());
2775
11
  unsigned NumElementsSrc = SrcTy->getNumElements();
2776
11
  if (NumElementsSrc == NumElementsDst)
2777
0
    return SrcVec;
2778
2779
11
  std::vector<int> ShuffleMask(NumElementsDst, -1);
2780
11
  for (unsigned MaskIdx = 0;
2781
55
       MaskIdx < std::min<>(NumElementsDst, NumElementsSrc); 
++MaskIdx44
)
2782
44
    ShuffleMask[MaskIdx] = MaskIdx;
2783
2784
11
  return Builder.CreateShuffleVector(SrcVec, ShuffleMask, Name);
2785
11
}