blob: 659ec0fc5c82cea579b60d3f49b36b5b45c34421 [file] [log] [blame]
Daniel Dunbar9c426522008-07-29 23:18:29 +00001//===-- CodeGenFunction.h - Per-Function state for LLVM CodeGen -*- C++ -*-===//
Chris Lattnerbed31442007-05-28 01:07:47 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerbed31442007-05-28 01:07:47 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stumpfc496822009-02-08 23:14:22 +000010// This is the internal per-function state used for llvm translation.
Chris Lattnerbed31442007-05-28 01:07:47 +000011//
12//===----------------------------------------------------------------------===//
13
Benjamin Kramer2f5db8b2014-08-13 16:25:19 +000014#ifndef LLVM_CLANG_LIB_CODEGEN_CODEGENFUNCTION_H
15#define LLVM_CLANG_LIB_CODEGEN_CODEGENFUNCTION_H
Chris Lattnerbed31442007-05-28 01:07:47 +000016
Daniel Dunbarcb463852008-11-01 01:53:16 +000017#include "CGBuilder.h"
Eric Christophera9d34972011-10-19 00:43:52 +000018#include "CGDebugInfo.h"
Alexander Musman515ad8c2014-05-22 08:54:05 +000019#include "CGLoopInfo.h"
Daniel Dunbar97db84c2008-08-23 03:46:30 +000020#include "CGValue.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "CodeGenModule.h"
Justin Bogneref512b92014-01-06 22:27:43 +000022#include "CodeGenPGO.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000023#include "EHScopeStack.h"
Vitaly Buka64c80b42016-10-26 05:42:30 +000024#include "VarBypassDetector.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/AST/CharUnits.h"
26#include "clang/AST/ExprCXX.h"
27#include "clang/AST/ExprObjC.h"
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +000028#include "clang/AST/ExprOpenMP.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000029#include "clang/AST/Type.h"
30#include "clang/Basic/ABI.h"
Ben Langmuir3b4c30b2013-05-09 19:17:11 +000031#include "clang/Basic/CapturedStmt.h"
Alexander Musmandf7a8e22015-01-22 08:49:35 +000032#include "clang/Basic/OpenMPKinds.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000033#include "clang/Basic/TargetInfo.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000034#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000035#include "llvm/ADT/ArrayRef.h"
36#include "llvm/ADT/DenseMap.h"
37#include "llvm/ADT/SmallVector.h"
Chandler Carruth61743af2014-03-04 11:18:19 +000038#include "llvm/IR/ValueHandle.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000039#include "llvm/Support/Debug.h"
Peter Collingbournedc134532016-01-16 00:31:22 +000040#include "llvm/Transforms/Utils/SanitizerStats.h"
Daniel Dunbar97db84c2008-08-23 03:46:30 +000041
Chris Lattnerbed31442007-05-28 01:07:47 +000042namespace llvm {
Rafael Espindola42ae7452014-05-09 00:57:59 +000043class BasicBlock;
44class LLVMContext;
45class MDNode;
46class Module;
47class SwitchInst;
48class Twine;
49class Value;
50class CallSite;
Chris Lattner23b7eb62007-06-15 23:05:46 +000051}
52
Chris Lattnerbed31442007-05-28 01:07:47 +000053namespace clang {
Rafael Espindola42ae7452014-05-09 00:57:59 +000054class ASTContext;
55class BlockDecl;
56class CXXDestructorDecl;
57class CXXForRangeStmt;
58class CXXTryStmt;
59class Decl;
60class LabelDecl;
61class EnumConstantDecl;
62class FunctionDecl;
63class FunctionProtoType;
64class LabelStmt;
65class ObjCContainerDecl;
66class ObjCInterfaceDecl;
67class ObjCIvarDecl;
68class ObjCMethodDecl;
69class ObjCImplementationDecl;
70class ObjCPropertyImplDecl;
71class TargetInfo;
Rafael Espindola42ae7452014-05-09 00:57:59 +000072class VarDecl;
73class ObjCForCollectionStmt;
74class ObjCAtTryStmt;
75class ObjCAtThrowStmt;
76class ObjCAtSynchronizedStmt;
77class ObjCAutoreleasePoolStmt;
Devang Patel3e11cce2007-10-23 02:10:49 +000078
Chris Lattnerbed31442007-05-28 01:07:47 +000079namespace CodeGen {
Rafael Espindola42ae7452014-05-09 00:57:59 +000080class CodeGenTypes;
John McCallb92ab1a2016-10-26 23:46:34 +000081class CGCallee;
Rafael Espindola42ae7452014-05-09 00:57:59 +000082class CGFunctionInfo;
83class CGRecordLayout;
84class CGBlockInfo;
85class CGCXXABI;
John McCall7f416cc2015-09-08 08:05:57 +000086class BlockByrefHelpers;
87class BlockByrefInfo;
Rafael Espindola42ae7452014-05-09 00:57:59 +000088class BlockFlags;
89class BlockFieldFlags;
Alexey Bataev7292c292016-04-25 12:22:29 +000090class RegionCodeGenTy;
John McCall12f23522016-04-04 18:33:08 +000091class TargetCodeGenInfo;
Alexey Bataev24b5bae2016-04-28 09:23:51 +000092struct OMPTaskDataTy;
Gor Nishanov97e3b6d2016-10-03 22:44:48 +000093struct CGCoroData;
Mike Stumpfc496822009-02-08 23:14:22 +000094
John McCall47fb9502013-03-07 21:37:08 +000095/// The kind of evaluation to perform on values of a particular
96/// type. Basically, is the code in CGExprScalar, CGExprComplex, or
97/// CGExprAgg?
98///
99/// TODO: should vectors maybe be split out into their own thing?
100enum TypeEvaluationKind {
101 TEK_Scalar,
102 TEK_Complex,
103 TEK_Aggregate
104};
105
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +0000106#define LIST_SANITIZER_CHECKS \
107 SANITIZER_CHECK(AddOverflow, add_overflow, 0) \
108 SANITIZER_CHECK(BuiltinUnreachable, builtin_unreachable, 0) \
109 SANITIZER_CHECK(CFICheckFail, cfi_check_fail, 0) \
110 SANITIZER_CHECK(DivremOverflow, divrem_overflow, 0) \
111 SANITIZER_CHECK(DynamicTypeCacheMiss, dynamic_type_cache_miss, 0) \
112 SANITIZER_CHECK(FloatCastOverflow, float_cast_overflow, 0) \
113 SANITIZER_CHECK(FunctionTypeMismatch, function_type_mismatch, 0) \
114 SANITIZER_CHECK(LoadInvalidValue, load_invalid_value, 0) \
115 SANITIZER_CHECK(MissingReturn, missing_return, 0) \
116 SANITIZER_CHECK(MulOverflow, mul_overflow, 0) \
117 SANITIZER_CHECK(NegateOverflow, negate_overflow, 0) \
118 SANITIZER_CHECK(NonnullArg, nonnull_arg, 0) \
119 SANITIZER_CHECK(NonnullReturn, nonnull_return, 0) \
120 SANITIZER_CHECK(OutOfBounds, out_of_bounds, 0) \
121 SANITIZER_CHECK(ShiftOutOfBounds, shift_out_of_bounds, 0) \
122 SANITIZER_CHECK(SubOverflow, sub_overflow, 0) \
Filipe Cabecinhasfe5e5af2017-01-06 14:40:12 +0000123 SANITIZER_CHECK(TypeMismatch, type_mismatch, 1) \
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +0000124 SANITIZER_CHECK(VLABoundNotPositive, vla_bound_not_positive, 0)
125
126enum SanitizerHandler {
127#define SANITIZER_CHECK(Enum, Name, Version) Enum,
128 LIST_SANITIZER_CHECKS
129#undef SANITIZER_CHECK
130};
131
Chris Lattnerbed31442007-05-28 01:07:47 +0000132/// CodeGenFunction - This class organizes the per-function state that is used
133/// while generating LLVM code.
John McCalle3dc1702011-02-15 09:22:45 +0000134class CodeGenFunction : public CodeGenTypeCache {
Aaron Ballmanabc18922015-02-15 22:54:08 +0000135 CodeGenFunction(const CodeGenFunction &) = delete;
136 void operator=(const CodeGenFunction &) = delete;
John McCall5d865c322010-08-31 07:33:07 +0000137
138 friend class CGCXXABI;
Chris Lattnerbda69f82007-08-26 23:13:56 +0000139public:
John McCallad5d61e2010-07-23 21:56:41 +0000140 /// A jump destination is an abstract label, branching to which may
141 /// require a jump out through normal cleanups.
John McCallbd309292010-07-06 01:34:17 +0000142 struct JumpDest {
Craig Topper8a13c412014-05-21 05:09:00 +0000143 JumpDest() : Block(nullptr), ScopeDepth(), Index(0) {}
John McCallad5d61e2010-07-23 21:56:41 +0000144 JumpDest(llvm::BasicBlock *Block,
145 EHScopeStack::stable_iterator Depth,
146 unsigned Index)
147 : Block(Block), ScopeDepth(Depth), Index(Index) {}
148
Craig Topper8a13c412014-05-21 05:09:00 +0000149 bool isValid() const { return Block != nullptr; }
John McCallad5d61e2010-07-23 21:56:41 +0000150 llvm::BasicBlock *getBlock() const { return Block; }
151 EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; }
152 unsigned getDestIndex() const { return Index; }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000153
Nadav Rotem1da30942013-03-23 06:43:35 +0000154 // This should be used cautiously.
155 void setScopeDepth(EHScopeStack::stable_iterator depth) {
156 ScopeDepth = depth;
157 }
158
John McCallad5d61e2010-07-23 21:56:41 +0000159 private:
John McCallbd309292010-07-06 01:34:17 +0000160 llvm::BasicBlock *Block;
161 EHScopeStack::stable_iterator ScopeDepth;
John McCallad5d61e2010-07-23 21:56:41 +0000162 unsigned Index;
163 };
164
Chris Lattnerbed31442007-05-28 01:07:47 +0000165 CodeGenModule &CGM; // Per-module state.
Daniel Dunbar1b444192009-11-13 05:51:54 +0000166 const TargetInfo &Target;
Mike Stumpfc496822009-02-08 23:14:22 +0000167
Chris Lattner96d72562007-08-21 16:57:55 +0000168 typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy;
Alexander Musman515ad8c2014-05-22 08:54:05 +0000169 LoopInfoStack LoopStack;
Daniel Dunbarcb463852008-11-01 01:53:16 +0000170 CGBuilderTy Builder;
Mike Stumpfc496822009-02-08 23:14:22 +0000171
Vitaly Buka64c80b42016-10-26 05:42:30 +0000172 // Stores variables for which we can't generate correct lifetime markers
173 // because of jumps.
174 VarBypassDetector Bypasses;
175
Alexander Musman515ad8c2014-05-22 08:54:05 +0000176 /// \brief CGBuilder insert helper. This function is called after an
177 /// instruction is created using Builder.
178 void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name,
179 llvm::BasicBlock *BB,
180 llvm::BasicBlock::iterator InsertPt) const;
181
John McCalldec348f72013-05-03 07:33:41 +0000182 /// CurFuncDecl - Holds the Decl for the current outermost
183 /// non-closure context.
Chris Lattner5696e7b2008-06-17 18:05:57 +0000184 const Decl *CurFuncDecl;
Chris Lattner28ec0cf2009-04-23 05:30:27 +0000185 /// CurCodeDecl - This is the inner-most code context, which includes blocks.
186 const Decl *CurCodeDecl;
Daniel Dunbard931a872009-02-02 22:03:45 +0000187 const CGFunctionInfo *CurFnInfo;
Chris Lattner4bd55962008-03-30 23:03:07 +0000188 QualType FnRetTy;
Chris Lattnerac248202007-05-30 00:13:02 +0000189 llvm::Function *CurFn;
190
Gor Nishanov97e3b6d2016-10-03 22:44:48 +0000191 // Holds coroutine data if the current function is a coroutine. We use a
192 // wrapper to manage its lifetime, so that we don't have to define CGCoroData
193 // in this header.
194 struct CGCoroInfo {
195 std::unique_ptr<CGCoroData> Data;
196 CGCoroInfo();
197 ~CGCoroInfo();
198 };
199 CGCoroInfo CurCoro;
200
Mike Stumpbee78dd2009-12-04 23:26:17 +0000201 /// CurGD - The GlobalDecl for the current function being compiled.
202 GlobalDecl CurGD;
Mike Stumpbee78dd2009-12-04 23:26:17 +0000203
John McCall31168b02011-06-15 23:02:42 +0000204 /// PrologueCleanupDepth - The cleanup depth enclosing all the
205 /// cleanups associated with the parameters.
206 EHScopeStack::stable_iterator PrologueCleanupDepth;
207
Daniel Dunbar54bb1932008-09-09 21:00:17 +0000208 /// ReturnBlock - Unified return block.
John McCallbd309292010-07-06 01:34:17 +0000209 JumpDest ReturnBlock;
210
John McCall7f416cc2015-09-08 08:05:57 +0000211 /// ReturnValue - The temporary alloca to hold the return
212 /// value. This is invalid iff the function has no return value.
213 Address ReturnValue;
Mike Stumpfc496822009-02-08 23:14:22 +0000214
Akira Hatanakafdcd18b2017-01-25 22:55:13 +0000215 /// Return true if a label was seen in the current scope.
216 bool hasLabelBeenSeenInCurrentScope() const {
217 if (CurLexicalScope)
218 return CurLexicalScope->hasLabels();
219 return !LabelMap.empty();
220 }
221
Chris Lattner03df1222007-06-02 04:53:11 +0000222 /// AllocaInsertPoint - This is an instruction in the entry block before which
223 /// we prefer to insert allocas.
Chris Lattner2739d2b2009-03-31 22:17:44 +0000224 llvm::AssertingVH<llvm::Instruction> AllocaInsertPt;
Daniel Dunbar88402ce2008-08-04 16:51:22 +0000225
Ben Langmuir3b4c30b2013-05-09 19:17:11 +0000226 /// \brief API for captured statement code generation.
227 class CGCapturedStmtInfo {
228 public:
Alexey Bataevf841bd92014-12-16 07:00:22 +0000229 explicit CGCapturedStmtInfo(CapturedRegionKind K = CR_Default)
230 : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {}
Ben Langmuir3b4c30b2013-05-09 19:17:11 +0000231 explicit CGCapturedStmtInfo(const CapturedStmt &S,
232 CapturedRegionKind K = CR_Default)
Craig Topper8a13c412014-05-21 05:09:00 +0000233 : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {
Ben Langmuir3b4c30b2013-05-09 19:17:11 +0000234
235 RecordDecl::field_iterator Field =
236 S.getCapturedRecordDecl()->field_begin();
237 for (CapturedStmt::const_capture_iterator I = S.capture_begin(),
238 E = S.capture_end();
239 I != E; ++I, ++Field) {
240 if (I->capturesThis())
241 CXXThisFieldDecl = *Field;
Alexey Bataev330de032014-10-29 12:21:55 +0000242 else if (I->capturesVariable())
Ben Langmuir3b4c30b2013-05-09 19:17:11 +0000243 CaptureFields[I->getCapturedVar()] = *Field;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000244 else if (I->capturesVariableByCopy())
245 CaptureFields[I->getCapturedVar()] = *Field;
Ben Langmuir3b4c30b2013-05-09 19:17:11 +0000246 }
247 }
248
249 virtual ~CGCapturedStmtInfo();
250
251 CapturedRegionKind getKind() const { return Kind; }
252
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000253 virtual void setContextValue(llvm::Value *V) { ThisValue = V; }
Ben Langmuir3b4c30b2013-05-09 19:17:11 +0000254 // \brief Retrieve the value of the context parameter.
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000255 virtual llvm::Value *getContextValue() const { return ThisValue; }
Ben Langmuir3b4c30b2013-05-09 19:17:11 +0000256
257 /// \brief Lookup the captured field decl for a variable.
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000258 virtual const FieldDecl *lookup(const VarDecl *VD) const {
Ben Langmuir3b4c30b2013-05-09 19:17:11 +0000259 return CaptureFields.lookup(VD);
260 }
261
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000262 bool isCXXThisExprCaptured() const { return getThisFieldDecl() != nullptr; }
263 virtual FieldDecl *getThisFieldDecl() const { return CXXThisFieldDecl; }
Ben Langmuir3b4c30b2013-05-09 19:17:11 +0000264
Alexey Bataev18095712014-10-10 12:19:54 +0000265 static bool classof(const CGCapturedStmtInfo *) {
266 return true;
267 }
268
Ben Langmuir3b4c30b2013-05-09 19:17:11 +0000269 /// \brief Emit the captured statement body.
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000270 virtual void EmitBody(CodeGenFunction &CGF, const Stmt *S) {
Justin Bogner66242d62015-04-23 23:06:47 +0000271 CGF.incrementProfileCounter(S);
Ben Langmuir3b4c30b2013-05-09 19:17:11 +0000272 CGF.EmitStmt(S);
273 }
274
275 /// \brief Get the name of the capture helper.
276 virtual StringRef getHelperName() const { return "__captured_stmt"; }
277
278 private:
279 /// \brief The kind of captured statement being generated.
280 CapturedRegionKind Kind;
281
282 /// \brief Keep the map between VarDecl and FieldDecl.
283 llvm::SmallDenseMap<const VarDecl *, FieldDecl *> CaptureFields;
284
285 /// \brief The base address of the captured record, passed in as the first
286 /// argument of the parallel region function.
287 llvm::Value *ThisValue;
288
289 /// \brief Captured 'this' type.
290 FieldDecl *CXXThisFieldDecl;
291 };
292 CGCapturedStmtInfo *CapturedStmtInfo;
293
Alexey Bataevd157d472015-06-24 03:35:38 +0000294 /// \brief RAII for correct setting/restoring of CapturedStmtInfo.
295 class CGCapturedStmtRAII {
296 private:
297 CodeGenFunction &CGF;
298 CGCapturedStmtInfo *PrevCapturedStmtInfo;
299 public:
300 CGCapturedStmtRAII(CodeGenFunction &CGF,
301 CGCapturedStmtInfo *NewCapturedStmtInfo)
302 : CGF(CGF), PrevCapturedStmtInfo(CGF.CapturedStmtInfo) {
303 CGF.CapturedStmtInfo = NewCapturedStmtInfo;
304 }
305 ~CGCapturedStmtRAII() { CGF.CapturedStmtInfo = PrevCapturedStmtInfo; }
306 };
307
Vedant Kumared00ea02017-03-06 05:28:22 +0000308 /// An abstract representation of regular/ObjC call/message targets.
309 class AbstractCallee {
310 /// The function declaration of the callee.
311 const Decl *CalleeDecl;
312
313 public:
314 AbstractCallee() : CalleeDecl(nullptr) {}
315 AbstractCallee(const FunctionDecl *FD) : CalleeDecl(FD) {}
316 AbstractCallee(const ObjCMethodDecl *OMD) : CalleeDecl(OMD) {}
317 bool hasFunctionDecl() const {
318 return dyn_cast_or_null<FunctionDecl>(CalleeDecl);
319 }
320 const Decl *getDecl() const { return CalleeDecl; }
321 unsigned getNumParams() const {
322 if (const auto *FD = dyn_cast<FunctionDecl>(CalleeDecl))
323 return FD->getNumParams();
324 return cast<ObjCMethodDecl>(CalleeDecl)->param_size();
325 }
326 const ParmVarDecl *getParamDecl(unsigned I) const {
327 if (const auto *FD = dyn_cast<FunctionDecl>(CalleeDecl))
328 return FD->getParamDecl(I);
329 return *(cast<ObjCMethodDecl>(CalleeDecl)->param_begin() + I);
330 }
331 };
332
Alexey Samsonova0416102014-11-11 01:26:14 +0000333 /// \brief Sanitizers enabled for this function.
334 SanitizerSet SanOpts;
Will Dietzf54319c2013-01-18 11:30:38 +0000335
Alexey Samsonov24cad992014-07-17 18:46:27 +0000336 /// \brief True if CodeGen currently emits code implementing sanitizer checks.
337 bool IsSanitizerScope;
338
339 /// \brief RAII object to set/unset CodeGenFunction::IsSanitizerScope.
340 class SanitizerScope {
341 CodeGenFunction *CGF;
342 public:
343 SanitizerScope(CodeGenFunction *CGF);
344 ~SanitizerScope();
345 };
346
Reid Kleckner19819442014-07-25 21:39:46 +0000347 /// In C++, whether we are code generating a thunk. This controls whether we
348 /// should emit cleanups.
349 bool CurFuncIsThunk;
350
John McCall31168b02011-06-15 23:02:42 +0000351 /// In ARC, whether we should autorelease the return value.
352 bool AutoreleaseResult;
353
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000354 /// Whether we processed a Microsoft-style asm block during CodeGen. These can
355 /// potentially set the return value.
356 bool SawAsmBlock;
357
David Majnemer25eb1652016-03-01 19:42:53 +0000358 const FunctionDecl *CurSEHParent = nullptr;
359
Reid Klecknerebaf28d2015-04-14 20:59:00 +0000360 /// True if the current function is an outlined SEH helper. This can be a
361 /// finally block or filter expression.
362 bool IsOutlinedSEHHelper;
363
John McCallad7c5c12011-02-08 08:22:06 +0000364 const CodeGen::CGBlockInfo *BlockInfo;
365 llvm::Value *BlockPointer;
366
Eli Friedman9fbeba02012-02-11 02:57:39 +0000367 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
368 FieldDecl *LambdaThisCaptureField;
369
Douglas Gregor9154b5d2010-05-17 15:52:46 +0000370 /// \brief A mapping from NRVO variables to the flags used to indicate
371 /// when the NRVO has been applied to this variable.
372 llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000373
John McCallbd309292010-07-06 01:34:17 +0000374 EHScopeStack EHStack;
Richard Smith736a9472013-06-12 20:42:33 +0000375 llvm::SmallVector<char, 256> LifetimeExtendedCleanupStack;
Nico Weber5779f842015-02-12 23:16:11 +0000376 llvm::SmallVector<const JumpDest *, 2> SEHTryEpilogueStack;
Richard Smith736a9472013-06-12 20:42:33 +0000377
David Majnemer4e52d6f2015-12-12 05:39:21 +0000378 llvm::Instruction *CurrentFuncletPad = nullptr;
379
Tim Shen421119f2016-07-01 21:08:47 +0000380 class CallLifetimeEnd final : public EHScopeStack::Cleanup {
381 llvm::Value *Addr;
382 llvm::Value *Size;
383
384 public:
385 CallLifetimeEnd(Address addr, llvm::Value *size)
386 : Addr(addr.getPointer()), Size(size) {}
387
388 void Emit(CodeGenFunction &CGF, Flags flags) override {
389 CGF.EmitLifetimeEnd(Size, Addr);
390 }
391 };
392
Richard Smith736a9472013-06-12 20:42:33 +0000393 /// Header for data within LifetimeExtendedCleanupStack.
394 struct LifetimeExtendedCleanupHeader {
395 /// The size of the following cleanup object.
Justin Bognerbdff2192015-07-01 00:59:27 +0000396 unsigned Size;
Richard Smith736a9472013-06-12 20:42:33 +0000397 /// The kind of cleanup to push: a value from the CleanupKind enumeration.
Justin Bognerbdff2192015-07-01 00:59:27 +0000398 CleanupKind Kind;
Richard Smith736a9472013-06-12 20:42:33 +0000399
Justin Bognerbdff2192015-07-01 00:59:27 +0000400 size_t getSize() const { return Size; }
401 CleanupKind getKind() const { return Kind; }
Richard Smith736a9472013-06-12 20:42:33 +0000402 };
John McCallbd309292010-07-06 01:34:17 +0000403
John McCallad5d61e2010-07-23 21:56:41 +0000404 /// i32s containing the indexes of the cleanup destinations.
405 llvm::AllocaInst *NormalCleanupDest;
John McCallad5d61e2010-07-23 21:56:41 +0000406
407 unsigned NextCleanupDestIndex;
408
John McCall08ef4662011-11-10 08:15:53 +0000409 /// FirstBlockInfo - The head of a singly-linked-list of block layouts.
410 CGBlockInfo *FirstBlockInfo;
411
John McCall8e4c74b2011-08-11 02:22:43 +0000412 /// EHResumeBlock - Unified block containing a call to llvm.eh.resume.
413 llvm::BasicBlock *EHResumeBlock;
414
Bill Wendlingf0724e82011-09-19 20:31:14 +0000415 /// The exception slot. All landing pads write the current exception pointer
416 /// into this alloca.
John McCallbd309292010-07-06 01:34:17 +0000417 llvm::Value *ExceptionSlot;
418
Bill Wendlingf0724e82011-09-19 20:31:14 +0000419 /// The selector slot. Under the MandatoryCleanup model, all landing pads
420 /// write the current selector value into this alloca.
John McCall9b382dd2011-05-28 21:13:02 +0000421 llvm::AllocaInst *EHSelectorSlot;
422
Reid Kleckner9fe7f232015-07-07 00:36:30 +0000423 /// A stack of exception code slots. Entering an __except block pushes a slot
424 /// on the stack and leaving pops one. The __exception_code() intrinsic loads
425 /// a value from the top of the stack.
John McCall7f416cc2015-09-08 08:05:57 +0000426 SmallVector<Address, 1> SEHCodeSlotStack;
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +0000427
Reid Kleckner9fe7f232015-07-07 00:36:30 +0000428 /// Value returned by __exception_info intrinsic.
429 llvm::Value *SEHInfo = nullptr;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000430
John McCallbd309292010-07-06 01:34:17 +0000431 /// Emits a landing pad for the current EH stack.
432 llvm::BasicBlock *EmitLandingPad();
433
434 llvm::BasicBlock *getInvokeDestImpl();
435
John McCallce1de612011-01-26 04:00:11 +0000436 template <class T>
John McCallcb5f77f2011-01-28 10:53:53 +0000437 typename DominatingValue<T>::saved_type saveValueInCond(T value) {
438 return DominatingValue<T>::save(*this, value);
John McCallce1de612011-01-26 04:00:11 +0000439 }
440
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +0000441public:
Anders Carlsson33c1b652009-02-10 06:07:49 +0000442 /// ObjCEHValueStack - Stack of Objective-C exception values, used for
443 /// rethrows.
Chris Lattner01cf8db2011-07-20 06:58:45 +0000444 SmallVector<llvm::Value*, 8> ObjCEHValueStack;
Mike Stumpfc496822009-02-08 23:14:22 +0000445
John McCall6b0feb72011-06-22 02:32:12 +0000446 /// A class controlling the emission of a finally block.
447 class FinallyInfo {
448 /// Where the catchall's edge through the cleanup should go.
449 JumpDest RethrowDest;
Anders Carlsson66c384a2009-02-08 07:46:24 +0000450
John McCall6b0feb72011-06-22 02:32:12 +0000451 /// A function to call to enter the catch.
452 llvm::Constant *BeginCatchFn;
453
454 /// An i1 variable indicating whether or not the @finally is
455 /// running for an exception.
456 llvm::AllocaInst *ForEHVar;
457
458 /// An i8* variable into which the exception pointer to rethrow
459 /// has been saved.
460 llvm::AllocaInst *SavedExnVar;
461
462 public:
463 void enter(CodeGenFunction &CGF, const Stmt *Finally,
464 llvm::Constant *beginCatchFn, llvm::Constant *endCatchFn,
465 llvm::Constant *rethrowFn);
466 void exit(CodeGenFunction &CGF);
467 };
Mike Stumpaff69af2009-12-09 03:35:49 +0000468
Reid Kleckner11c033e2015-02-12 23:40:45 +0000469 /// Returns true inside SEH __try blocks.
470 bool isSEHTryScope() const { return !SEHTryEpilogueStack.empty(); }
471
Reid Klecknera002bd52015-10-28 23:06:42 +0000472 /// Returns true while emitting a cleanuppad.
David Majnemer4e52d6f2015-12-12 05:39:21 +0000473 bool isCleanupPadScope() const {
474 return CurrentFuncletPad && isa<llvm::CleanupPadInst>(CurrentFuncletPad);
475 }
Reid Klecknera002bd52015-10-28 23:06:42 +0000476
John McCallce1de612011-01-26 04:00:11 +0000477 /// pushFullExprCleanup - Push a cleanup to be run at the end of the
478 /// current full-expression. Safe against the possibility that
479 /// we're currently inside a conditionally-evaluated expression.
Benjamin Kramer51680bc2015-03-12 23:41:40 +0000480 template <class T, class... As>
481 void pushFullExprCleanup(CleanupKind kind, As... A) {
John McCalle4df6c82011-01-28 08:37:24 +0000482 // If we're not in a conditional branch, or if none of the
483 // arguments requires saving, then use the unconditional cleanup.
John McCall5fcf8da2011-07-12 00:15:30 +0000484 if (!isInConditionalBranch())
Benjamin Kramer51680bc2015-03-12 23:41:40 +0000485 return EHStack.pushCleanup<T>(kind, A...);
John McCalle4df6c82011-01-28 08:37:24 +0000486
Benjamin Kramer51680bc2015-03-12 23:41:40 +0000487 // Stash values in a tuple so we can guarantee the order of saves.
488 typedef std::tuple<typename DominatingValue<As>::saved_type...> SavedTuple;
489 SavedTuple Saved{saveValueInCond(A)...};
John McCalle4df6c82011-01-28 08:37:24 +0000490
Benjamin Kramer51680bc2015-03-12 23:41:40 +0000491 typedef EHScopeStack::ConditionalCleanup<T, As...> CleanupType;
Benjamin Kramer7f1f6b52015-03-12 23:46:55 +0000492 EHStack.pushCleanupTuple<CleanupType>(kind, Saved);
John McCall4bd0fb12011-07-12 16:41:08 +0000493 initFullExprCleanup();
494 }
495
Richard Smith736a9472013-06-12 20:42:33 +0000496 /// \brief Queue a cleanup to be pushed after finishing the current
497 /// full-expression.
Benjamin Kramer51680bc2015-03-12 23:41:40 +0000498 template <class T, class... As>
499 void pushCleanupAfterFullExpr(CleanupKind Kind, As... A) {
Richard Smith736a9472013-06-12 20:42:33 +0000500 assert(!isInConditionalBranch() && "can't defer conditional cleanup");
501
502 LifetimeExtendedCleanupHeader Header = { sizeof(T), Kind };
503
504 size_t OldSize = LifetimeExtendedCleanupStack.size();
505 LifetimeExtendedCleanupStack.resize(
506 LifetimeExtendedCleanupStack.size() + sizeof(Header) + Header.Size);
507
Benjamin Kramerc3f89252016-10-20 14:27:22 +0000508 static_assert(sizeof(Header) % alignof(T) == 0,
Justin Bognerbdff2192015-07-01 00:59:27 +0000509 "Cleanup will be allocated on misaligned address");
Richard Smith736a9472013-06-12 20:42:33 +0000510 char *Buffer = &LifetimeExtendedCleanupStack[OldSize];
511 new (Buffer) LifetimeExtendedCleanupHeader(Header);
Benjamin Kramer51680bc2015-03-12 23:41:40 +0000512 new (Buffer + sizeof(Header)) T(A...);
Richard Smith736a9472013-06-12 20:42:33 +0000513 }
514
John McCallf4beacd2011-11-10 10:43:54 +0000515 /// Set up the last cleaup that was pushed as a conditional
516 /// full-expression cleanup.
517 void initFullExprCleanup();
518
John McCallbd309292010-07-06 01:34:17 +0000519 /// PushDestructorCleanup - Push a cleanup to call the
520 /// complete-object destructor of an object of the given type at the
521 /// given address. Does nothing if T is not a C++ class type with a
522 /// non-trivial destructor.
John McCall7f416cc2015-09-08 08:05:57 +0000523 void PushDestructorCleanup(QualType T, Address Addr);
John McCallbd309292010-07-06 01:34:17 +0000524
John McCall8680f872010-07-21 06:29:51 +0000525 /// PushDestructorCleanup - Push a cleanup to call the
526 /// complete-object variant of the given destructor on the object at
527 /// the given address.
John McCall7f416cc2015-09-08 08:05:57 +0000528 void PushDestructorCleanup(const CXXDestructorDecl *Dtor, Address Addr);
John McCall8680f872010-07-21 06:29:51 +0000529
John McCallbd309292010-07-06 01:34:17 +0000530 /// PopCleanupBlock - Will pop the cleanup entry on the stack and
531 /// process all branch fixups.
Adrian Prantldc237b52013-05-16 00:41:26 +0000532 void PopCleanupBlock(bool FallThroughIsBranchThrough = false);
John McCallbd309292010-07-06 01:34:17 +0000533
John McCall824c2f52010-09-14 07:57:04 +0000534 /// DeactivateCleanupBlock - Deactivates the given cleanup block.
535 /// The block cannot be reactivated. Pops it if it's the top of the
536 /// stack.
John McCallf4beacd2011-11-10 10:43:54 +0000537 ///
538 /// \param DominatingIP - An instruction which is known to
539 /// dominate the current IP (if set) and which lies along
540 /// all paths of execution between the current IP and the
541 /// the point at which the cleanup comes into scope.
542 void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
543 llvm::Instruction *DominatingIP);
John McCall824c2f52010-09-14 07:57:04 +0000544
545 /// ActivateCleanupBlock - Activates an initially-inactive cleanup.
546 /// Cannot be used to resurrect a deactivated cleanup.
John McCallf4beacd2011-11-10 10:43:54 +0000547 ///
548 /// \param DominatingIP - An instruction which is known to
549 /// dominate the current IP (if set) and which lies along
550 /// all paths of execution between the current IP and the
551 /// the point at which the cleanup comes into scope.
552 void ActivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
553 llvm::Instruction *DominatingIP);
John McCall612942d2010-08-13 21:20:51 +0000554
John McCallbd309292010-07-06 01:34:17 +0000555 /// \brief Enters a new scope for capturing cleanups, all of which
556 /// will be executed once the scope is exited.
557 class RunCleanupsScope {
John McCallbd309292010-07-06 01:34:17 +0000558 EHScopeStack::stable_iterator CleanupStackDepth;
Richard Smith736a9472013-06-12 20:42:33 +0000559 size_t LifetimeExtendedCleanupStackSize;
Douglas Gregor965f4502009-11-24 16:43:22 +0000560 bool OldDidCallStackSave;
John McCall07e60262013-03-01 01:24:35 +0000561 protected:
Douglas Gregor680f8612009-11-24 21:15:44 +0000562 bool PerformCleanup;
John McCall07e60262013-03-01 01:24:35 +0000563 private:
Douglas Gregor965f4502009-11-24 16:43:22 +0000564
Aaron Ballmanabc18922015-02-15 22:54:08 +0000565 RunCleanupsScope(const RunCleanupsScope &) = delete;
566 void operator=(const RunCleanupsScope &) = delete;
Douglas Gregor965f4502009-11-24 16:43:22 +0000567
Eric Christophera9d34972011-10-19 00:43:52 +0000568 protected:
569 CodeGenFunction& CGF;
Will Dietzf54319c2013-01-18 11:30:38 +0000570
Douglas Gregor965f4502009-11-24 16:43:22 +0000571 public:
572 /// \brief Enter a new cleanup scope.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000573 explicit RunCleanupsScope(CodeGenFunction &CGF)
Eric Christophera9d34972011-10-19 00:43:52 +0000574 : PerformCleanup(true), CGF(CGF)
Douglas Gregor680f8612009-11-24 21:15:44 +0000575 {
John McCallbd309292010-07-06 01:34:17 +0000576 CleanupStackDepth = CGF.EHStack.stable_begin();
Richard Smith736a9472013-06-12 20:42:33 +0000577 LifetimeExtendedCleanupStackSize =
578 CGF.LifetimeExtendedCleanupStack.size();
Douglas Gregor965f4502009-11-24 16:43:22 +0000579 OldDidCallStackSave = CGF.DidCallStackSave;
Argyrios Kyrtzidis9efa1ce2010-09-14 00:42:34 +0000580 CGF.DidCallStackSave = false;
Douglas Gregor965f4502009-11-24 16:43:22 +0000581 }
582
583 /// \brief Exit this cleanup scope, emitting any accumulated
584 /// cleanups.
John McCallbd309292010-07-06 01:34:17 +0000585 ~RunCleanupsScope() {
Douglas Gregor680f8612009-11-24 21:15:44 +0000586 if (PerformCleanup) {
587 CGF.DidCallStackSave = OldDidCallStackSave;
Richard Smith736a9472013-06-12 20:42:33 +0000588 CGF.PopCleanupBlocks(CleanupStackDepth,
589 LifetimeExtendedCleanupStackSize);
Douglas Gregor680f8612009-11-24 21:15:44 +0000590 }
591 }
592
593 /// \brief Determine whether this scope requires any cleanups.
594 bool requiresCleanups() const {
John McCallbd309292010-07-06 01:34:17 +0000595 return CGF.EHStack.stable_begin() != CleanupStackDepth;
Douglas Gregor680f8612009-11-24 21:15:44 +0000596 }
597
598 /// \brief Force the emission of cleanups now, instead of waiting
599 /// until this object is destroyed.
600 void ForceCleanup() {
601 assert(PerformCleanup && "Already forced cleanup");
Douglas Gregor965f4502009-11-24 16:43:22 +0000602 CGF.DidCallStackSave = OldDidCallStackSave;
Richard Smith736a9472013-06-12 20:42:33 +0000603 CGF.PopCleanupBlocks(CleanupStackDepth,
604 LifetimeExtendedCleanupStackSize);
Douglas Gregor680f8612009-11-24 21:15:44 +0000605 PerformCleanup = false;
Douglas Gregor965f4502009-11-24 16:43:22 +0000606 }
607 };
608
David Blaikie93be0b22014-08-22 21:37:04 +0000609 class LexicalScope : public RunCleanupsScope {
Eric Christophera9d34972011-10-19 00:43:52 +0000610 SourceRange Range;
Nadav Rotem1da30942013-03-23 06:43:35 +0000611 SmallVector<const LabelDecl*, 4> Labels;
612 LexicalScope *ParentScope;
Eric Christophera9d34972011-10-19 00:43:52 +0000613
Aaron Ballmanabc18922015-02-15 22:54:08 +0000614 LexicalScope(const LexicalScope &) = delete;
615 void operator=(const LexicalScope &) = delete;
Eric Christophera9d34972011-10-19 00:43:52 +0000616
617 public:
618 /// \brief Enter a new cleanup scope.
619 explicit LexicalScope(CodeGenFunction &CGF, SourceRange Range)
Nadav Rotem1da30942013-03-23 06:43:35 +0000620 : RunCleanupsScope(CGF), Range(Range), ParentScope(CGF.CurLexicalScope) {
621 CGF.CurLexicalScope = this;
Eric Christophera9d34972011-10-19 00:43:52 +0000622 if (CGDebugInfo *DI = CGF.getDebugInfo())
623 DI->EmitLexicalBlockStart(CGF.Builder, Range.getBegin());
624 }
625
Nadav Rotem1da30942013-03-23 06:43:35 +0000626 void addLabel(const LabelDecl *label) {
627 assert(PerformCleanup && "adding label to dead scope?");
628 Labels.push_back(label);
629 }
630
Eric Christophera9d34972011-10-19 00:43:52 +0000631 /// \brief Exit this cleanup scope, emitting any accumulated
632 /// cleanups.
633 ~LexicalScope() {
Adrian Prantl5d5b67c2013-04-01 19:02:06 +0000634 if (CGDebugInfo *DI = CGF.getDebugInfo())
635 DI->EmitLexicalBlockEnd(CGF.Builder, Range.getEnd());
636
Nadav Rotem1da30942013-03-23 06:43:35 +0000637 // If we should perform a cleanup, force them now. Note that
638 // this ends the cleanup scope before rescoping any labels.
David Blaikie4d524432015-02-04 19:47:54 +0000639 if (PerformCleanup) {
640 ApplyDebugLocation DL(CGF, Range.getEnd());
641 ForceCleanup();
642 }
Eric Christophera9d34972011-10-19 00:43:52 +0000643 }
644
645 /// \brief Force the emission of cleanups now, instead of waiting
646 /// until this object is destroyed.
647 void ForceCleanup() {
Nadav Rotem1da30942013-03-23 06:43:35 +0000648 CGF.CurLexicalScope = ParentScope;
Adrian Prantl5d5b67c2013-04-01 19:02:06 +0000649 RunCleanupsScope::ForceCleanup();
650
Nadav Rotem1da30942013-03-23 06:43:35 +0000651 if (!Labels.empty())
652 rescopeLabels();
Eric Christophera9d34972011-10-19 00:43:52 +0000653 }
Nadav Rotem1da30942013-03-23 06:43:35 +0000654
Akira Hatanakafdcd18b2017-01-25 22:55:13 +0000655 bool hasLabels() const {
656 return !Labels.empty();
657 }
658
Nadav Rotem1da30942013-03-23 06:43:35 +0000659 void rescopeLabels();
Eric Christophera9d34972011-10-19 00:43:52 +0000660 };
661
John McCall7f416cc2015-09-08 08:05:57 +0000662 typedef llvm::DenseMap<const Decl *, Address> DeclMapTy;
663
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000664 /// \brief The scope used to remap some variables as private in the OpenMP
665 /// loop body (or other captured region emitted without outlining), and to
666 /// restore old vars back on exit.
667 class OMPPrivateScope : public RunCleanupsScope {
John McCall7f416cc2015-09-08 08:05:57 +0000668 DeclMapTy SavedLocals;
669 DeclMapTy SavedPrivates;
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000670
671 private:
Aaron Ballmanabc18922015-02-15 22:54:08 +0000672 OMPPrivateScope(const OMPPrivateScope &) = delete;
673 void operator=(const OMPPrivateScope &) = delete;
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000674
675 public:
676 /// \brief Enter a new OpenMP private scope.
677 explicit OMPPrivateScope(CodeGenFunction &CGF) : RunCleanupsScope(CGF) {}
678
679 /// \brief Registers \a LocalVD variable as a private and apply \a
680 /// PrivateGen function for it to generate corresponding private variable.
681 /// \a PrivateGen returns an address of the generated private variable.
682 /// \return true if the variable is registered as private, false if it has
683 /// been privatized already.
684 bool
685 addPrivate(const VarDecl *LocalVD,
John McCall7f416cc2015-09-08 08:05:57 +0000686 llvm::function_ref<Address()> PrivateGen) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000687 assert(PerformCleanup && "adding private to dead scope");
John McCall7f416cc2015-09-08 08:05:57 +0000688
689 // Only save it once.
690 if (SavedLocals.count(LocalVD)) return false;
691
692 // Copy the existing local entry to SavedLocals.
693 auto it = CGF.LocalDeclMap.find(LocalVD);
694 if (it != CGF.LocalDeclMap.end()) {
695 SavedLocals.insert({LocalVD, it->second});
696 } else {
697 SavedLocals.insert({LocalVD, Address::invalid()});
698 }
699
700 // Generate the private entry.
701 Address Addr = PrivateGen();
Alexey Bataevcaacd532015-09-04 11:26:21 +0000702 QualType VarTy = LocalVD->getType();
703 if (VarTy->isReferenceType()) {
John McCall7f416cc2015-09-08 08:05:57 +0000704 Address Temp = CGF.CreateMemTemp(VarTy);
705 CGF.Builder.CreateStore(Addr.getPointer(), Temp);
706 Addr = Temp;
Alexey Bataevcaacd532015-09-04 11:26:21 +0000707 }
John McCall7f416cc2015-09-08 08:05:57 +0000708 SavedPrivates.insert({LocalVD, Addr});
709
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000710 return true;
711 }
712
713 /// \brief Privatizes local variables previously registered as private.
714 /// Registration is separate from the actual privatization to allow
715 /// initializers use values of the original variables, not the private one.
716 /// This is important, for example, if the private variable is a class
717 /// variable initialized by a constructor that references other private
718 /// variables. But at initialization original variables must be used, not
719 /// private copies.
720 /// \return true if at least one variable was privatized, false otherwise.
721 bool Privatize() {
John McCall7f416cc2015-09-08 08:05:57 +0000722 copyInto(SavedPrivates, CGF.LocalDeclMap);
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000723 SavedPrivates.clear();
724 return !SavedLocals.empty();
725 }
726
727 void ForceCleanup() {
728 RunCleanupsScope::ForceCleanup();
John McCall7f416cc2015-09-08 08:05:57 +0000729 copyInto(SavedLocals, CGF.LocalDeclMap);
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000730 SavedLocals.clear();
731 }
732
733 /// \brief Exit scope - all the mapped variables are restored.
Alexey Bataeva63048e2015-03-23 06:18:07 +0000734 ~OMPPrivateScope() {
735 if (PerformCleanup)
736 ForceCleanup();
737 }
John McCall7f416cc2015-09-08 08:05:57 +0000738
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000739 /// Checks if the global variable is captured in current function.
740 bool isGlobalVarCaptured(const VarDecl *VD) const {
741 return !VD->isLocalVarDeclOrParm() && CGF.LocalDeclMap.count(VD) > 0;
742 }
743
John McCall7f416cc2015-09-08 08:05:57 +0000744 private:
745 /// Copy all the entries in the source map over the corresponding
746 /// entries in the destination, which must exist.
747 static void copyInto(const DeclMapTy &src, DeclMapTy &dest) {
748 for (auto &pair : src) {
749 if (!pair.second.isValid()) {
750 dest.erase(pair.first);
751 continue;
752 }
753
754 auto it = dest.find(pair.first);
755 if (it != dest.end()) {
756 it->second = pair.second;
757 } else {
758 dest.insert(pair);
759 }
760 }
761 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000762 };
Anders Carlssonb9fd57f2010-03-30 03:14:41 +0000763
Richard Smith736a9472013-06-12 20:42:33 +0000764 /// \brief Takes the old cleanup stack size and emits the cleanup blocks
765 /// that have been added.
Adrian Prantldc237b52013-05-16 00:41:26 +0000766 void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize);
Anders Carlssonb9fd57f2010-03-30 03:14:41 +0000767
Richard Smith736a9472013-06-12 20:42:33 +0000768 /// \brief Takes the old cleanup stack size and emits the cleanup blocks
769 /// that have been added, then adds all lifetime-extended cleanups from
770 /// the given position to the stack.
771 void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize,
772 size_t OldLifetimeExtendedStackSize);
773
John McCallad5d61e2010-07-23 21:56:41 +0000774 void ResolveBranchFixups(llvm::BasicBlock *Target);
775
John McCallbd309292010-07-06 01:34:17 +0000776 /// The given basic block lies in the current EH scope, but may be a
777 /// target of a potentially scope-crossing jump; get a stable handle
778 /// to which we can perform this jump later.
John McCallad5d61e2010-07-23 21:56:41 +0000779 JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target) {
John McCallba803902010-07-28 01:07:35 +0000780 return JumpDest(Target,
781 EHStack.getInnermostNormalCleanup(),
782 NextCleanupDestIndex++);
John McCallbd309292010-07-06 01:34:17 +0000783 }
Anders Carlssonbe0f76a2009-02-07 23:50:39 +0000784
John McCallbd309292010-07-06 01:34:17 +0000785 /// The given basic block lies in the current EH scope, but may be a
786 /// target of a potentially scope-crossing jump; get a stable handle
787 /// to which we can perform this jump later.
Chris Lattner01cf8db2011-07-20 06:58:45 +0000788 JumpDest getJumpDestInCurrentScope(StringRef Name = StringRef()) {
John McCallad5d61e2010-07-23 21:56:41 +0000789 return getJumpDestInCurrentScope(createBasicBlock(Name));
John McCallbd309292010-07-06 01:34:17 +0000790 }
791
792 /// EmitBranchThroughCleanup - Emit a branch from the current insert
793 /// block through the normal cleanup handling code (if any) and then
794 /// on to \arg Dest.
795 void EmitBranchThroughCleanup(JumpDest Dest);
Chris Lattnerbc204c82011-04-17 00:54:30 +0000796
Justin Bognere25ffdf2014-01-21 00:35:11 +0000797 /// isObviouslyBranchWithoutCleanups - Return true if a branch to the
798 /// specified destination obviously has no cleanups to run. 'false' is always
799 /// a conservatively correct answer for this method.
800 bool isObviouslyBranchWithoutCleanups(JumpDest Dest) const;
801
John McCall8e4c74b2011-08-11 02:22:43 +0000802 /// popCatchScope - Pops the catch scope at the top of the EHScope
803 /// stack, emitting any required code (other than the catch handlers
804 /// themselves).
805 void popCatchScope();
John McCallad5d61e2010-07-23 21:56:41 +0000806
David Chisnall9a837be2012-11-07 16:50:40 +0000807 llvm::BasicBlock *getEHResumeBlock(bool isCleanup);
John McCall8e4c74b2011-08-11 02:22:43 +0000808 llvm::BasicBlock *getEHDispatchBlock(EHScopeStack::stable_iterator scope);
David Majnemerdbf10452015-07-31 17:58:45 +0000809 llvm::BasicBlock *getMSVCDispatchBlock(EHScopeStack::stable_iterator scope);
Mike Stumpfc496822009-02-08 23:14:22 +0000810
John McCallce1de612011-01-26 04:00:11 +0000811 /// An object to manage conditionally-evaluated expressions.
812 class ConditionalEvaluation {
813 llvm::BasicBlock *StartBB;
Mike Stump11289f42009-09-09 15:08:12 +0000814
John McCallce1de612011-01-26 04:00:11 +0000815 public:
816 ConditionalEvaluation(CodeGenFunction &CGF)
817 : StartBB(CGF.Builder.GetInsertBlock()) {}
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000818
John McCallce1de612011-01-26 04:00:11 +0000819 void begin(CodeGenFunction &CGF) {
820 assert(CGF.OutermostConditional != this);
821 if (!CGF.OutermostConditional)
822 CGF.OutermostConditional = this;
823 }
824
825 void end(CodeGenFunction &CGF) {
Craig Topper8a13c412014-05-21 05:09:00 +0000826 assert(CGF.OutermostConditional != nullptr);
John McCallce1de612011-01-26 04:00:11 +0000827 if (CGF.OutermostConditional == this)
Craig Topper8a13c412014-05-21 05:09:00 +0000828 CGF.OutermostConditional = nullptr;
John McCallce1de612011-01-26 04:00:11 +0000829 }
830
831 /// Returns a block which will be executed prior to each
832 /// evaluation of the conditional code.
833 llvm::BasicBlock *getStartingBlock() const {
834 return StartBB;
835 }
836 };
Mike Stump11289f42009-09-09 15:08:12 +0000837
John McCall7f9c92a2010-09-17 00:50:28 +0000838 /// isInConditionalBranch - Return true if we're currently emitting
839 /// one branch or the other of a conditional expression.
Craig Topper8a13c412014-05-21 05:09:00 +0000840 bool isInConditionalBranch() const { return OutermostConditional != nullptr; }
John McCallce1de612011-01-26 04:00:11 +0000841
John McCall7f416cc2015-09-08 08:05:57 +0000842 void setBeforeOutermostConditional(llvm::Value *value, Address addr) {
John McCallf4beacd2011-11-10 10:43:54 +0000843 assert(isInConditionalBranch());
844 llvm::BasicBlock *block = OutermostConditional->getStartingBlock();
John McCall7f416cc2015-09-08 08:05:57 +0000845 auto store = new llvm::StoreInst(value, addr.getPointer(), &block->back());
846 store->setAlignment(addr.getAlignment().getQuantity());
John McCallf4beacd2011-11-10 10:43:54 +0000847 }
848
John McCallce1de612011-01-26 04:00:11 +0000849 /// An RAII object to record that we're evaluating a statement
850 /// expression.
851 class StmtExprEvaluation {
852 CodeGenFunction &CGF;
853
854 /// We have to save the outermost conditional: cleanups in a
855 /// statement expression aren't conditional just because the
856 /// StmtExpr is.
857 ConditionalEvaluation *SavedOutermostConditional;
858
859 public:
860 StmtExprEvaluation(CodeGenFunction &CGF)
861 : CGF(CGF), SavedOutermostConditional(CGF.OutermostConditional) {
Craig Topper8a13c412014-05-21 05:09:00 +0000862 CGF.OutermostConditional = nullptr;
John McCallce1de612011-01-26 04:00:11 +0000863 }
864
865 ~StmtExprEvaluation() {
866 CGF.OutermostConditional = SavedOutermostConditional;
867 CGF.EnsureInsertPoint();
868 }
869 };
John McCall1bf58462011-02-16 08:02:54 +0000870
John McCallc07a0c72011-02-17 10:25:35 +0000871 /// An object which temporarily prevents a value from being
872 /// destroyed by aggressive peephole optimizations that assume that
873 /// all uses of a value have been realized in the IR.
874 class PeepholeProtection {
875 llvm::Instruction *Inst;
876 friend class CodeGenFunction;
877
878 public:
Craig Topper8a13c412014-05-21 05:09:00 +0000879 PeepholeProtection() : Inst(nullptr) {}
John McCallfe96e0b2011-11-06 09:01:30 +0000880 };
John McCallc07a0c72011-02-17 10:25:35 +0000881
John McCallfe96e0b2011-11-06 09:01:30 +0000882 /// A non-RAII class containing all the information about a bound
883 /// opaque value. OpaqueValueMapping, below, is a RAII wrapper for
884 /// this which makes individual mappings very simple; using this
885 /// class directly is useful when you have a variable number of
886 /// opaque values or don't want the RAII functionality for some
887 /// reason.
888 class OpaqueValueMappingData {
John McCall1bf58462011-02-16 08:02:54 +0000889 const OpaqueValueExpr *OpaqueValue;
John McCallc07a0c72011-02-17 10:25:35 +0000890 bool BoundLValue;
891 CodeGenFunction::PeepholeProtection Protection;
John McCall1bf58462011-02-16 08:02:54 +0000892
John McCallfe96e0b2011-11-06 09:01:30 +0000893 OpaqueValueMappingData(const OpaqueValueExpr *ov,
894 bool boundLValue)
895 : OpaqueValue(ov), BoundLValue(boundLValue) {}
John McCall1bf58462011-02-16 08:02:54 +0000896 public:
Craig Topper8a13c412014-05-21 05:09:00 +0000897 OpaqueValueMappingData() : OpaqueValue(nullptr) {}
John McCallfe96e0b2011-11-06 09:01:30 +0000898
John McCallc07a0c72011-02-17 10:25:35 +0000899 static bool shouldBindAsLValue(const Expr *expr) {
John McCall9a549612011-11-08 22:54:08 +0000900 // gl-values should be bound as l-values for obvious reasons.
901 // Records should be bound as l-values because IR generation
902 // always keeps them in memory. Expressions of function type
903 // act exactly like l-values but are formally required to be
904 // r-values in C.
905 return expr->isGLValue() ||
Fariborz Jahanian77411012014-02-14 19:37:25 +0000906 expr->getType()->isFunctionType() ||
907 hasAggregateEvaluationKind(expr->getType());
John McCallc07a0c72011-02-17 10:25:35 +0000908 }
909
John McCallfe96e0b2011-11-06 09:01:30 +0000910 static OpaqueValueMappingData bind(CodeGenFunction &CGF,
911 const OpaqueValueExpr *ov,
912 const Expr *e) {
913 if (shouldBindAsLValue(ov))
914 return bind(CGF, ov, CGF.EmitLValue(e));
915 return bind(CGF, ov, CGF.EmitAnyExpr(e));
916 }
917
918 static OpaqueValueMappingData bind(CodeGenFunction &CGF,
919 const OpaqueValueExpr *ov,
920 const LValue &lv) {
921 assert(shouldBindAsLValue(ov));
922 CGF.OpaqueLValues.insert(std::make_pair(ov, lv));
923 return OpaqueValueMappingData(ov, true);
924 }
925
926 static OpaqueValueMappingData bind(CodeGenFunction &CGF,
927 const OpaqueValueExpr *ov,
928 const RValue &rv) {
929 assert(!shouldBindAsLValue(ov));
930 CGF.OpaqueRValues.insert(std::make_pair(ov, rv));
931
932 OpaqueValueMappingData data(ov, false);
933
934 // Work around an extremely aggressive peephole optimization in
935 // EmitScalarConversion which assumes that all other uses of a
936 // value are extant.
937 data.Protection = CGF.protectFromPeepholes(rv);
938
939 return data;
940 }
941
Craig Topper8a13c412014-05-21 05:09:00 +0000942 bool isValid() const { return OpaqueValue != nullptr; }
943 void clear() { OpaqueValue = nullptr; }
John McCallfe96e0b2011-11-06 09:01:30 +0000944
945 void unbind(CodeGenFunction &CGF) {
946 assert(OpaqueValue && "no data to unbind!");
947
948 if (BoundLValue) {
949 CGF.OpaqueLValues.erase(OpaqueValue);
950 } else {
951 CGF.OpaqueRValues.erase(OpaqueValue);
952 CGF.unprotectFromPeepholes(Protection);
953 }
954 }
955 };
956
957 /// An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
958 class OpaqueValueMapping {
959 CodeGenFunction &CGF;
960 OpaqueValueMappingData Data;
961
962 public:
963 static bool shouldBindAsLValue(const Expr *expr) {
964 return OpaqueValueMappingData::shouldBindAsLValue(expr);
965 }
966
John McCallc07a0c72011-02-17 10:25:35 +0000967 /// Build the opaque value mapping for the given conditional
968 /// operator if it's the GNU ?: extension. This is a common
969 /// enough pattern that the convenience operator is really
970 /// helpful.
971 ///
972 OpaqueValueMapping(CodeGenFunction &CGF,
973 const AbstractConditionalOperator *op) : CGF(CGF) {
John McCallfe96e0b2011-11-06 09:01:30 +0000974 if (isa<ConditionalOperator>(op))
975 // Leave Data empty.
John McCallc07a0c72011-02-17 10:25:35 +0000976 return;
John McCallc07a0c72011-02-17 10:25:35 +0000977
978 const BinaryConditionalOperator *e = cast<BinaryConditionalOperator>(op);
John McCallfe96e0b2011-11-06 09:01:30 +0000979 Data = OpaqueValueMappingData::bind(CGF, e->getOpaqueValue(),
980 e->getCommon());
John McCallc07a0c72011-02-17 10:25:35 +0000981 }
982
Richard Smith410306b2016-12-12 02:53:20 +0000983 /// Build the opaque value mapping for an OpaqueValueExpr whose source
984 /// expression is set to the expression the OVE represents.
985 OpaqueValueMapping(CodeGenFunction &CGF, const OpaqueValueExpr *OV)
986 : CGF(CGF) {
987 if (OV) {
988 assert(OV->getSourceExpr() && "wrong form of OpaqueValueMapping used "
989 "for OVE with no source expression");
990 Data = OpaqueValueMappingData::bind(CGF, OV, OV->getSourceExpr());
991 }
992 }
993
John McCall1bf58462011-02-16 08:02:54 +0000994 OpaqueValueMapping(CodeGenFunction &CGF,
995 const OpaqueValueExpr *opaqueValue,
John McCallc07a0c72011-02-17 10:25:35 +0000996 LValue lvalue)
John McCallfe96e0b2011-11-06 09:01:30 +0000997 : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, lvalue)) {
John McCallc07a0c72011-02-17 10:25:35 +0000998 }
999
1000 OpaqueValueMapping(CodeGenFunction &CGF,
1001 const OpaqueValueExpr *opaqueValue,
1002 RValue rvalue)
John McCallfe96e0b2011-11-06 09:01:30 +00001003 : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, rvalue)) {
John McCall1bf58462011-02-16 08:02:54 +00001004 }
1005
1006 void pop() {
John McCallfe96e0b2011-11-06 09:01:30 +00001007 Data.unbind(CGF);
1008 Data.clear();
John McCall1bf58462011-02-16 08:02:54 +00001009 }
1010
1011 ~OpaqueValueMapping() {
John McCallfe96e0b2011-11-06 09:01:30 +00001012 if (Data.isValid()) Data.unbind(CGF);
John McCall1bf58462011-02-16 08:02:54 +00001013 }
1014 };
Fariborz Jahaniana3e54bd2010-11-16 19:29:39 +00001015
Chris Lattner2da04b32007-08-24 05:35:26 +00001016private:
Chris Lattner6c4d2552009-10-28 23:59:40 +00001017 CGDebugInfo *DebugInfo;
Devang Pateld6ffebb2011-03-07 18:45:56 +00001018 bool DisableDebugInfo;
Mike Stumpc6ea7c12009-02-17 17:00:02 +00001019
John McCall9b382dd2011-05-28 21:13:02 +00001020 /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid
1021 /// calling llvm.stacksave for multiple VLAs in the same scope.
1022 bool DidCallStackSave;
1023
Mike Stumpe5311b02009-11-30 20:08:49 +00001024 /// IndirectBranch - The first time an indirect goto is seen we create a block
1025 /// with an indirect branch. Every time we see the address of a label taken,
1026 /// we add the label to the indirect goto. Every subsequent indirect goto is
1027 /// codegen'd as a jump to the IndirectBranch's basic block.
Chris Lattner6c4d2552009-10-28 23:59:40 +00001028 llvm::IndirectBrInst *IndirectBranch;
Daniel Dunbar88402ce2008-08-04 16:51:22 +00001029
Mike Stumpfc496822009-02-08 23:14:22 +00001030 /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C
1031 /// decls.
John McCall351762c2011-02-07 10:33:21 +00001032 DeclMapTy LocalDeclMap;
Chris Lattner84915fa2007-06-02 04:16:21 +00001033
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001034 /// SizeArguments - If a ParmVarDecl had the pass_object_size attribute, this
1035 /// will contain a mapping from said ParmVarDecl to its implicit "object_size"
1036 /// parameter.
1037 llvm::SmallDenseMap<const ParmVarDecl *, const ImplicitParamDecl *, 2>
1038 SizeArguments;
1039
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001040 /// Track escaped local variables with auto storage. Used during SEH
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001041 /// outlining to produce a call to llvm.localescape.
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001042 llvm::DenseMap<llvm::AllocaInst *, int> EscapedLocals;
1043
Chris Lattnerac248202007-05-30 00:13:02 +00001044 /// LabelMap - This keeps track of the LLVM basic block for each C label.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00001045 llvm::DenseMap<const LabelDecl*, JumpDest> LabelMap;
Mike Stumpfc496822009-02-08 23:14:22 +00001046
Mike Stumpfc496822009-02-08 23:14:22 +00001047 // BreakContinueStack - This keeps track of where break and continue
Bob Wilsonbf854f02014-02-17 19:21:09 +00001048 // statements should jump to.
Chris Lattnere73e4322007-07-16 21:28:45 +00001049 struct BreakContinue {
Bob Wilsonbf854f02014-02-17 19:21:09 +00001050 BreakContinue(JumpDest Break, JumpDest Continue)
1051 : BreakBlock(Break), ContinueBlock(Continue) {}
Mike Stumpfc496822009-02-08 23:14:22 +00001052
John McCallbd309292010-07-06 01:34:17 +00001053 JumpDest BreakBlock;
1054 JumpDest ContinueBlock;
Mike Stumpfc496822009-02-08 23:14:22 +00001055 };
Chris Lattner01cf8db2011-07-20 06:58:45 +00001056 SmallVector<BreakContinue, 8> BreakContinueStack;
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00001057
Alexey Bataev957d8562016-11-17 15:12:05 +00001058 /// Handles cancellation exit points in OpenMP-related constructs.
1059 class OpenMPCancelExitStack {
1060 /// Tracks cancellation exit point and join point for cancel-related exit
1061 /// and normal exit.
1062 struct CancelExit {
1063 CancelExit() = default;
1064 CancelExit(OpenMPDirectiveKind Kind, JumpDest ExitBlock,
1065 JumpDest ContBlock)
1066 : Kind(Kind), ExitBlock(ExitBlock), ContBlock(ContBlock) {}
1067 OpenMPDirectiveKind Kind = OMPD_unknown;
1068 /// true if the exit block has been emitted already by the special
1069 /// emitExit() call, false if the default codegen is used.
1070 bool HasBeenEmitted = false;
1071 JumpDest ExitBlock;
1072 JumpDest ContBlock;
1073 };
1074
1075 SmallVector<CancelExit, 8> Stack;
1076
1077 public:
1078 OpenMPCancelExitStack() : Stack(1) {}
1079 ~OpenMPCancelExitStack() = default;
1080 /// Fetches the exit block for the current OpenMP construct.
1081 JumpDest getExitBlock() const { return Stack.back().ExitBlock; }
1082 /// Emits exit block with special codegen procedure specific for the related
1083 /// OpenMP construct + emits code for normal construct cleanup.
1084 void emitExit(CodeGenFunction &CGF, OpenMPDirectiveKind Kind,
1085 const llvm::function_ref<void(CodeGenFunction &)> &CodeGen) {
1086 if (Stack.back().Kind == Kind && getExitBlock().isValid()) {
1087 assert(CGF.getOMPCancelDestination(Kind).isValid());
1088 assert(CGF.HaveInsertPoint());
1089 assert(!Stack.back().HasBeenEmitted);
1090 auto IP = CGF.Builder.saveAndClearIP();
1091 CGF.EmitBlock(Stack.back().ExitBlock.getBlock());
1092 CodeGen(CGF);
1093 CGF.EmitBranchThroughCleanup(Stack.back().ContBlock);
1094 CGF.Builder.restoreIP(IP);
1095 Stack.back().HasBeenEmitted = true;
1096 }
1097 CodeGen(CGF);
1098 }
1099 /// Enter the cancel supporting \a Kind construct.
1100 /// \param Kind OpenMP directive that supports cancel constructs.
1101 /// \param HasCancel true, if the construct has inner cancel directive,
1102 /// false otherwise.
1103 void enter(CodeGenFunction &CGF, OpenMPDirectiveKind Kind, bool HasCancel) {
1104 Stack.push_back({Kind,
1105 HasCancel ? CGF.getJumpDestInCurrentScope("cancel.exit")
1106 : JumpDest(),
1107 HasCancel ? CGF.getJumpDestInCurrentScope("cancel.cont")
1108 : JumpDest()});
1109 }
1110 /// Emits default exit point for the cancel construct (if the special one
1111 /// has not be used) + join point for cancel/normal exits.
1112 void exit(CodeGenFunction &CGF) {
1113 if (getExitBlock().isValid()) {
1114 assert(CGF.getOMPCancelDestination(Stack.back().Kind).isValid());
1115 bool HaveIP = CGF.HaveInsertPoint();
1116 if (!Stack.back().HasBeenEmitted) {
1117 if (HaveIP)
1118 CGF.EmitBranchThroughCleanup(Stack.back().ContBlock);
1119 CGF.EmitBlock(Stack.back().ExitBlock.getBlock());
1120 CGF.EmitBranchThroughCleanup(Stack.back().ContBlock);
1121 }
1122 CGF.EmitBlock(Stack.back().ContBlock.getBlock());
1123 if (!HaveIP) {
1124 CGF.Builder.CreateUnreachable();
1125 CGF.Builder.ClearInsertionPoint();
1126 }
1127 }
1128 Stack.pop_back();
1129 }
1130 };
1131 OpenMPCancelExitStack OMPCancelStack;
1132
1133 /// Controls insertion of cancellation exit blocks in worksharing constructs.
1134 class OMPCancelStackRAII {
1135 CodeGenFunction &CGF;
1136
1137 public:
1138 OMPCancelStackRAII(CodeGenFunction &CGF, OpenMPDirectiveKind Kind,
1139 bool HasCancel)
1140 : CGF(CGF) {
1141 CGF.OMPCancelStack.enter(CGF, Kind, HasCancel);
1142 }
1143 ~OMPCancelStackRAII() { CGF.OMPCancelStack.exit(CGF); }
1144 };
1145
Justin Bogneref512b92014-01-06 22:27:43 +00001146 CodeGenPGO PGO;
1147
Justin Bogner65512642015-05-02 05:00:55 +00001148 /// Calculate branch weights appropriate for PGO data
1149 llvm::MDNode *createProfileWeights(uint64_t TrueCount, uint64_t FalseCount);
1150 llvm::MDNode *createProfileWeights(ArrayRef<uint64_t> Weights);
1151 llvm::MDNode *createProfileWeightsForLoop(const Stmt *Cond,
1152 uint64_t LoopCount);
1153
Justin Bogneref512b92014-01-06 22:27:43 +00001154public:
Vedant Kumar502bbfa2017-02-25 06:35:45 +00001155 /// Increment the profiler's counter for the given statement by \p StepV.
1156 /// If \p StepV is null, the default increment is 1.
1157 void incrementProfileCounter(const Stmt *S, llvm::Value *StepV = nullptr) {
Rong Xu9837ef52016-02-04 18:39:09 +00001158 if (CGM.getCodeGenOpts().hasProfileClangInstr())
Vedant Kumar502bbfa2017-02-25 06:35:45 +00001159 PGO.emitCounterIncrement(Builder, S, StepV);
Justin Bogner66242d62015-04-23 23:06:47 +00001160 PGO.setCurrentStmt(S);
Justin Bogneref512b92014-01-06 22:27:43 +00001161 }
Justin Bogner66242d62015-04-23 23:06:47 +00001162
1163 /// Get the profiler's count for the given statement.
1164 uint64_t getProfileCount(const Stmt *S) {
1165 Optional<uint64_t> Count = PGO.getStmtCount(S);
1166 if (!Count.hasValue())
1167 return 0;
1168 return *Count;
1169 }
1170
1171 /// Set the profiler's current count.
1172 void setCurrentProfileCount(uint64_t Count) {
1173 PGO.setCurrentRegionCount(Count);
1174 }
1175
1176 /// Get the profiler's current count. This is generally the count for the most
1177 /// recently incremented counter.
1178 uint64_t getCurrentProfileCount() {
1179 return PGO.getCurrentRegionCount();
1180 }
1181
Justin Bogneref512b92014-01-06 22:27:43 +00001182private:
1183
Zhongxing Xu82846ea2012-01-14 09:08:15 +00001184 /// SwitchInsn - This is nearest current switch instruction. It is null if
Mike Stumpfc496822009-02-08 23:14:22 +00001185 /// current context is not in a switch.
Devang Patelda5d6bb2007-10-04 23:45:31 +00001186 llvm::SwitchInst *SwitchInsn;
Justin Bogneref512b92014-01-06 22:27:43 +00001187 /// The branch weights of SwitchInsn when doing instrumentation based PGO.
1188 SmallVector<uint64_t, 16> *SwitchWeights;
Devang Patelda5d6bb2007-10-04 23:45:31 +00001189
Mike Stumpfc496822009-02-08 23:14:22 +00001190 /// CaseRangeBlock - This block holds if condition check for last case
Devang Patel49a44f32007-10-09 17:08:50 +00001191 /// statement range in current switch instruction.
Devang Patel11663122007-10-08 20:57:48 +00001192 llvm::BasicBlock *CaseRangeBlock;
1193
John McCallc07a0c72011-02-17 10:25:35 +00001194 /// OpaqueLValues - Keeps track of the current set of opaque value
John McCall1bf58462011-02-16 08:02:54 +00001195 /// expressions.
John McCallc07a0c72011-02-17 10:25:35 +00001196 llvm::DenseMap<const OpaqueValueExpr *, LValue> OpaqueLValues;
1197 llvm::DenseMap<const OpaqueValueExpr *, RValue> OpaqueRValues;
John McCall1bf58462011-02-16 08:02:54 +00001198
Mike Stumpfc496822009-02-08 23:14:22 +00001199 // VLASizeMap - This keeps track of the associated size for each VLA type.
Eli Friedman04fddf02009-08-15 02:50:32 +00001200 // We track this by the size expression rather than the type itself because
1201 // in certain situations, like a const qualifier applied to an VLA typedef,
1202 // multiple VLA types can share the same size expression.
Mike Stumpfc496822009-02-08 23:14:22 +00001203 // FIXME: Maybe this could be a stack of maps that is pushed/popped as we
1204 // enter/leave scopes.
Eli Friedman04fddf02009-08-15 02:50:32 +00001205 llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap;
Mike Stumpfc496822009-02-08 23:14:22 +00001206
John McCallbd309292010-07-06 01:34:17 +00001207 /// A block containing a single 'unreachable' instruction. Created
1208 /// lazily by getUnreachableBlock().
1209 llvm::BasicBlock *UnreachableBlock;
Mike Stumpfc496822009-02-08 23:14:22 +00001210
Adrian Prantl52bf3c42013-05-03 20:11:48 +00001211 /// Counts of the number return expressions in the function.
1212 unsigned NumReturnExprs;
Adrian Prantl3be10542013-05-02 17:30:20 +00001213
1214 /// Count the number of simple (constant) return expressions in the function.
1215 unsigned NumSimpleReturnExprs;
1216
Adrian Prantl52bf3c42013-05-03 20:11:48 +00001217 /// The last regular (non-return) debug location (breakpoint) in the function.
Adrian Prantle83b1302014-01-07 22:05:52 +00001218 SourceLocation LastStopPoint;
Adrian Prantl3be10542013-05-02 17:30:20 +00001219
Richard Smith852c9db2013-04-20 22:23:05 +00001220public:
1221 /// A scope within which we are constructing the fields of an object which
1222 /// might use a CXXDefaultInitExpr. This stashes away a 'this' value to use
1223 /// if we need to evaluate a CXXDefaultInitExpr within the evaluation.
1224 class FieldConstructionScope {
1225 public:
John McCall7f416cc2015-09-08 08:05:57 +00001226 FieldConstructionScope(CodeGenFunction &CGF, Address This)
Richard Smith852c9db2013-04-20 22:23:05 +00001227 : CGF(CGF), OldCXXDefaultInitExprThis(CGF.CXXDefaultInitExprThis) {
1228 CGF.CXXDefaultInitExprThis = This;
1229 }
1230 ~FieldConstructionScope() {
1231 CGF.CXXDefaultInitExprThis = OldCXXDefaultInitExprThis;
1232 }
1233
1234 private:
1235 CodeGenFunction &CGF;
John McCall7f416cc2015-09-08 08:05:57 +00001236 Address OldCXXDefaultInitExprThis;
Richard Smith852c9db2013-04-20 22:23:05 +00001237 };
1238
1239 /// The scope of a CXXDefaultInitExpr. Within this scope, the value of 'this'
1240 /// is overridden to be the object under construction.
1241 class CXXDefaultInitExprScope {
1242 public:
1243 CXXDefaultInitExprScope(CodeGenFunction &CGF)
John McCall7f416cc2015-09-08 08:05:57 +00001244 : CGF(CGF), OldCXXThisValue(CGF.CXXThisValue),
1245 OldCXXThisAlignment(CGF.CXXThisAlignment) {
1246 CGF.CXXThisValue = CGF.CXXDefaultInitExprThis.getPointer();
1247 CGF.CXXThisAlignment = CGF.CXXDefaultInitExprThis.getAlignment();
Richard Smith852c9db2013-04-20 22:23:05 +00001248 }
1249 ~CXXDefaultInitExprScope() {
1250 CGF.CXXThisValue = OldCXXThisValue;
John McCall7f416cc2015-09-08 08:05:57 +00001251 CGF.CXXThisAlignment = OldCXXThisAlignment;
Richard Smith852c9db2013-04-20 22:23:05 +00001252 }
1253
1254 public:
1255 CodeGenFunction &CGF;
1256 llvm::Value *OldCXXThisValue;
John McCall7f416cc2015-09-08 08:05:57 +00001257 CharUnits OldCXXThisAlignment;
Richard Smith852c9db2013-04-20 22:23:05 +00001258 };
1259
Richard Smith410306b2016-12-12 02:53:20 +00001260 /// The scope of an ArrayInitLoopExpr. Within this scope, the value of the
1261 /// current loop index is overridden.
1262 class ArrayInitLoopExprScope {
1263 public:
1264 ArrayInitLoopExprScope(CodeGenFunction &CGF, llvm::Value *Index)
1265 : CGF(CGF), OldArrayInitIndex(CGF.ArrayInitIndex) {
1266 CGF.ArrayInitIndex = Index;
1267 }
1268 ~ArrayInitLoopExprScope() {
1269 CGF.ArrayInitIndex = OldArrayInitIndex;
1270 }
1271
1272 private:
1273 CodeGenFunction &CGF;
1274 llvm::Value *OldArrayInitIndex;
1275 };
1276
Richard Smith5179eb72016-06-28 19:03:57 +00001277 class InlinedInheritingConstructorScope {
1278 public:
1279 InlinedInheritingConstructorScope(CodeGenFunction &CGF, GlobalDecl GD)
1280 : CGF(CGF), OldCurGD(CGF.CurGD), OldCurFuncDecl(CGF.CurFuncDecl),
1281 OldCurCodeDecl(CGF.CurCodeDecl),
1282 OldCXXABIThisDecl(CGF.CXXABIThisDecl),
1283 OldCXXABIThisValue(CGF.CXXABIThisValue),
1284 OldCXXThisValue(CGF.CXXThisValue),
1285 OldCXXABIThisAlignment(CGF.CXXABIThisAlignment),
1286 OldCXXThisAlignment(CGF.CXXThisAlignment),
1287 OldReturnValue(CGF.ReturnValue), OldFnRetTy(CGF.FnRetTy),
1288 OldCXXInheritedCtorInitExprArgs(
1289 std::move(CGF.CXXInheritedCtorInitExprArgs)) {
1290 CGF.CurGD = GD;
1291 CGF.CurFuncDecl = CGF.CurCodeDecl =
1292 cast<CXXConstructorDecl>(GD.getDecl());
1293 CGF.CXXABIThisDecl = nullptr;
1294 CGF.CXXABIThisValue = nullptr;
1295 CGF.CXXThisValue = nullptr;
1296 CGF.CXXABIThisAlignment = CharUnits();
1297 CGF.CXXThisAlignment = CharUnits();
1298 CGF.ReturnValue = Address::invalid();
1299 CGF.FnRetTy = QualType();
1300 CGF.CXXInheritedCtorInitExprArgs.clear();
1301 }
1302 ~InlinedInheritingConstructorScope() {
1303 CGF.CurGD = OldCurGD;
1304 CGF.CurFuncDecl = OldCurFuncDecl;
1305 CGF.CurCodeDecl = OldCurCodeDecl;
1306 CGF.CXXABIThisDecl = OldCXXABIThisDecl;
1307 CGF.CXXABIThisValue = OldCXXABIThisValue;
1308 CGF.CXXThisValue = OldCXXThisValue;
1309 CGF.CXXABIThisAlignment = OldCXXABIThisAlignment;
1310 CGF.CXXThisAlignment = OldCXXThisAlignment;
1311 CGF.ReturnValue = OldReturnValue;
1312 CGF.FnRetTy = OldFnRetTy;
1313 CGF.CXXInheritedCtorInitExprArgs =
1314 std::move(OldCXXInheritedCtorInitExprArgs);
1315 }
1316
1317 private:
1318 CodeGenFunction &CGF;
1319 GlobalDecl OldCurGD;
1320 const Decl *OldCurFuncDecl;
1321 const Decl *OldCurCodeDecl;
1322 ImplicitParamDecl *OldCXXABIThisDecl;
1323 llvm::Value *OldCXXABIThisValue;
1324 llvm::Value *OldCXXThisValue;
1325 CharUnits OldCXXABIThisAlignment;
1326 CharUnits OldCXXThisAlignment;
1327 Address OldReturnValue;
1328 QualType OldFnRetTy;
1329 CallArgList OldCXXInheritedCtorInitExprArgs;
1330 };
1331
Richard Smith852c9db2013-04-20 22:23:05 +00001332private:
Anders Carlsson82ba57c2009-11-25 03:15:49 +00001333 /// CXXThisDecl - When generating code for a C++ member function,
1334 /// this will hold the implicit 'this' declaration.
Eli Friedman9fbeba02012-02-11 02:57:39 +00001335 ImplicitParamDecl *CXXABIThisDecl;
1336 llvm::Value *CXXABIThisValue;
John McCall347132b2010-02-16 22:04:33 +00001337 llvm::Value *CXXThisValue;
John McCall7f416cc2015-09-08 08:05:57 +00001338 CharUnits CXXABIThisAlignment;
1339 CharUnits CXXThisAlignment;
Mike Stump11289f42009-09-09 15:08:12 +00001340
Richard Smith852c9db2013-04-20 22:23:05 +00001341 /// The value of 'this' to use when evaluating CXXDefaultInitExprs within
1342 /// this expression.
John McCall7f416cc2015-09-08 08:05:57 +00001343 Address CXXDefaultInitExprThis = Address::invalid();
Richard Smith852c9db2013-04-20 22:23:05 +00001344
Richard Smith410306b2016-12-12 02:53:20 +00001345 /// The current array initialization index when evaluating an
1346 /// ArrayInitIndexExpr within an ArrayInitLoopExpr.
1347 llvm::Value *ArrayInitIndex = nullptr;
1348
Richard Smith5179eb72016-06-28 19:03:57 +00001349 /// The values of function arguments to use when evaluating
1350 /// CXXInheritedCtorInitExprs within this context.
1351 CallArgList CXXInheritedCtorInitExprArgs;
1352
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001353 /// CXXStructorImplicitParamDecl - When generating code for a constructor or
1354 /// destructor, this will hold the implicit argument (e.g. VTT).
1355 ImplicitParamDecl *CXXStructorImplicitParamDecl;
1356 llvm::Value *CXXStructorImplicitParamValue;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001357
John McCallce1de612011-01-26 04:00:11 +00001358 /// OutermostConditional - Points to the outermost active
1359 /// conditional control. This is used so that we know if a
1360 /// temporary should be destroyed conditionally.
1361 ConditionalEvaluation *OutermostConditional;
Mike Stump11289f42009-09-09 15:08:12 +00001362
Nadav Rotem1da30942013-03-23 06:43:35 +00001363 /// The current lexical scope.
1364 LexicalScope *CurLexicalScope;
Anders Carlsson0168f4b2009-09-12 02:14:24 +00001365
Adrian Prantldc237b52013-05-16 00:41:26 +00001366 /// The current source location that should be used for exception
1367 /// handling code.
1368 SourceLocation CurEHLocation;
1369
John McCall7f416cc2015-09-08 08:05:57 +00001370 /// BlockByrefInfos - For each __block variable, contains
1371 /// information about the layout of the variable.
1372 llvm::DenseMap<const ValueDecl *, BlockByrefInfo> BlockByrefInfos;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001373
John McCallbd309292010-07-06 01:34:17 +00001374 llvm::BasicBlock *TerminateLandingPad;
Mike Stumpf5cbb082009-12-10 00:02:42 +00001375 llvm::BasicBlock *TerminateHandler;
Chris Lattnerf2f38702010-07-20 21:07:09 +00001376 llvm::BasicBlock *TrapBB;
Eli Friedmand5bc94e2009-12-10 02:21:21 +00001377
Vitaly Buka1c943322016-10-26 01:59:57 +00001378 /// True if we need emit the life-time markers.
1379 const bool ShouldEmitLifetimeMarkers;
1380
Tanya Lattnerbcffcdf2012-07-09 22:06:01 +00001381 /// Add a kernel metadata node to the named metadata node 'opencl.kernels'.
1382 /// In the kernel metadata node, reference the kernel function and metadata
1383 /// nodes for its optional attribute qualifiers (OpenCL 1.1 6.7.2):
Joey Goulyaba589c2013-03-08 09:42:32 +00001384 /// - A node for the vec_type_hint(<type>) qualifier contains string
1385 /// "vec_type_hint", an undefined value of the <type> data type,
1386 /// and a Boolean that is true if the <type> is integer and signed.
Tanya Lattnerbcffcdf2012-07-09 22:06:01 +00001387 /// - A node for the work_group_size_hint(X,Y,Z) qualifier contains string
1388 /// "work_group_size_hint", and three 32-bit integers X, Y and Z.
1389 /// - A node for the reqd_work_group_size(X,Y,Z) qualifier contains string
1390 /// "reqd_work_group_size", and three 32-bit integers X, Y and Z.
1391 void EmitOpenCLKernelMetadata(const FunctionDecl *FD,
1392 llvm::Function *Fn);
1393
Chris Lattnerbed31442007-05-28 01:07:47 +00001394public:
Fariborz Jahanian63628032012-06-26 16:06:38 +00001395 CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext=false);
John McCall08ef4662011-11-10 08:15:53 +00001396 ~CodeGenFunction();
Mike Stumpfc496822009-02-08 23:14:22 +00001397
John McCall8ed55a52010-09-02 09:58:18 +00001398 CodeGenTypes &getTypes() const { return CGM.getTypes(); }
John McCall745ae282011-05-15 02:34:36 +00001399 ASTContext &getContext() const { return CGM.getContext(); }
Devang Pateld6ffebb2011-03-07 18:45:56 +00001400 CGDebugInfo *getDebugInfo() {
1401 if (DisableDebugInfo)
Craig Topper8a13c412014-05-21 05:09:00 +00001402 return nullptr;
Devang Pateld6ffebb2011-03-07 18:45:56 +00001403 return DebugInfo;
1404 }
1405 void disableDebugInfo() { DisableDebugInfo = true; }
1406 void enableDebugInfo() { DisableDebugInfo = false; }
1407
John McCall31168b02011-06-15 23:02:42 +00001408 bool shouldUseFusedARCCalls() {
1409 return CGM.getCodeGenOpts().OptimizationLevel == 0;
1410 }
Chris Lattner6db1fb82007-06-02 22:49:07 +00001411
David Blaikiebbafb8a2012-03-11 07:00:24 +00001412 const LangOptions &getLangOpts() const { return CGM.getLangOpts(); }
John McCallad7c5c12011-02-08 08:22:06 +00001413
Bill Wendlingf0724e82011-09-19 20:31:14 +00001414 /// Returns a pointer to the function's exception object and selector slot,
1415 /// which is assigned in every landing pad.
John McCall7f416cc2015-09-08 08:05:57 +00001416 Address getExceptionSlot();
1417 Address getEHSelectorSlot();
John McCallbd309292010-07-06 01:34:17 +00001418
Bill Wendling79a70e42011-09-15 18:57:19 +00001419 /// Returns the contents of the function's exception object and selector
1420 /// slots.
1421 llvm::Value *getExceptionFromSlot();
1422 llvm::Value *getSelectorFromSlot();
1423
John McCall7f416cc2015-09-08 08:05:57 +00001424 Address getNormalCleanupDestSlot();
John McCallad5d61e2010-07-23 21:56:41 +00001425
John McCallbd309292010-07-06 01:34:17 +00001426 llvm::BasicBlock *getUnreachableBlock() {
1427 if (!UnreachableBlock) {
1428 UnreachableBlock = createBasicBlock("unreachable");
1429 new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock);
1430 }
1431 return UnreachableBlock;
1432 }
1433
1434 llvm::BasicBlock *getInvokeDest() {
Craig Topper8a13c412014-05-21 05:09:00 +00001435 if (!EHStack.requiresLandingPad()) return nullptr;
John McCallbd309292010-07-06 01:34:17 +00001436 return getInvokeDestImpl();
1437 }
Daniel Dunbar12347492009-02-23 17:26:39 +00001438
David Majnemer25eb1652016-03-01 19:42:53 +00001439 bool currentFunctionUsesSEHTry() const { return CurSEHParent != nullptr; }
Reid Klecknere7b3f7c2015-02-11 00:00:21 +00001440
John McCallc8e01702013-04-16 22:48:15 +00001441 const TargetInfo &getTarget() const { return Target; }
John McCallad7c5c12011-02-08 08:22:06 +00001442 llvm::LLVMContext &getLLVMContext() { return CGM.getLLVMContext(); }
Owen Andersonae86c192009-07-13 04:10:07 +00001443
Daniel Dunbar12347492009-02-23 17:26:39 +00001444 //===--------------------------------------------------------------------===//
John McCall82fe67b2011-07-09 01:37:26 +00001445 // Cleanups
1446 //===--------------------------------------------------------------------===//
1447
John McCall7f416cc2015-09-08 08:05:57 +00001448 typedef void Destroyer(CodeGenFunction &CGF, Address addr, QualType ty);
John McCall82fe67b2011-07-09 01:37:26 +00001449
John McCall178360e2011-07-11 08:38:19 +00001450 void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
John McCall7f416cc2015-09-08 08:05:57 +00001451 Address arrayEndPointer,
John McCall178360e2011-07-11 08:38:19 +00001452 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00001453 CharUnits elementAlignment,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001454 Destroyer *destroyer);
John McCall178360e2011-07-11 08:38:19 +00001455 void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1456 llvm::Value *arrayEnd,
1457 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00001458 CharUnits elementAlignment,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001459 Destroyer *destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00001460
John McCall4bd0fb12011-07-12 16:41:08 +00001461 void pushDestroy(QualType::DestructionKind dtorKind,
John McCall7f416cc2015-09-08 08:05:57 +00001462 Address addr, QualType type);
John McCall12cc42a2013-02-01 05:11:40 +00001463 void pushEHDestroy(QualType::DestructionKind dtorKind,
John McCall7f416cc2015-09-08 08:05:57 +00001464 Address addr, QualType type);
1465 void pushDestroy(CleanupKind kind, Address addr, QualType type,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001466 Destroyer *destroyer, bool useEHCleanupForArray);
John McCall7f416cc2015-09-08 08:05:57 +00001467 void pushLifetimeExtendedDestroy(CleanupKind kind, Address addr,
Richard Smith736a9472013-06-12 20:42:33 +00001468 QualType type, Destroyer *destroyer,
1469 bool useEHCleanupForArray);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001470 void pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
1471 llvm::Value *CompletePtr,
1472 QualType ElementType);
John McCall7f416cc2015-09-08 08:05:57 +00001473 void pushStackRestore(CleanupKind kind, Address SPMem);
1474 void emitDestroy(Address addr, QualType type, Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00001475 bool useEHCleanupForArray);
John McCall7f416cc2015-09-08 08:05:57 +00001476 llvm::Function *generateDestroyHelper(Address addr, QualType type,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001477 Destroyer *destroyer,
David Blaikieebe87e12013-08-27 23:57:18 +00001478 bool useEHCleanupForArray,
1479 const VarDecl *VD);
John McCall82fe67b2011-07-09 01:37:26 +00001480 void emitArrayDestroy(llvm::Value *begin, llvm::Value *end,
John McCall7f416cc2015-09-08 08:05:57 +00001481 QualType elementType, CharUnits elementAlign,
1482 Destroyer *destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00001483 bool checkZeroLength, bool useEHCleanup);
John McCall82fe67b2011-07-09 01:37:26 +00001484
Peter Collingbourne1425b452012-01-26 03:33:36 +00001485 Destroyer *getDestroyer(QualType::DestructionKind destructionKind);
John McCall4bd0fb12011-07-12 16:41:08 +00001486
John McCall82fe67b2011-07-09 01:37:26 +00001487 /// Determines whether an EH cleanup is required to destroy a type
1488 /// with the given destruction kind.
1489 bool needsEHCleanup(QualType::DestructionKind kind) {
1490 switch (kind) {
1491 case QualType::DK_none:
1492 return false;
1493 case QualType::DK_cxx_destructor:
1494 case QualType::DK_objc_weak_lifetime:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001495 return getLangOpts().Exceptions;
John McCall82fe67b2011-07-09 01:37:26 +00001496 case QualType::DK_objc_strong_lifetime:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001497 return getLangOpts().Exceptions &&
John McCall82fe67b2011-07-09 01:37:26 +00001498 CGM.getCodeGenOpts().ObjCAutoRefCountExceptions;
1499 }
1500 llvm_unreachable("bad destruction kind");
1501 }
1502
John McCall4bd0fb12011-07-12 16:41:08 +00001503 CleanupKind getCleanupKind(QualType::DestructionKind kind) {
1504 return (needsEHCleanup(kind) ? NormalAndEHCleanup : NormalCleanup);
1505 }
1506
John McCall82fe67b2011-07-09 01:37:26 +00001507 //===--------------------------------------------------------------------===//
Daniel Dunbar12347492009-02-23 17:26:39 +00001508 // Objective-C
1509 //===--------------------------------------------------------------------===//
1510
Chris Lattner4bd55962008-03-30 23:03:07 +00001511 void GenerateObjCMethod(const ObjCMethodDecl *OMD);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001512
David Blaikief1425802015-01-14 00:04:42 +00001513 void StartObjCMethod(const ObjCMethodDecl *MD, const ObjCContainerDecl *CD);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001514
Mike Stumpfc496822009-02-08 23:14:22 +00001515 /// GenerateObjCGetter - Synthesize an Objective-C property getter function.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00001516 void GenerateObjCGetter(ObjCImplementationDecl *IMP,
1517 const ObjCPropertyImplDecl *PID);
John McCallf4528ae2011-09-13 03:34:09 +00001518 void generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanian4b501a22012-01-07 18:56:22 +00001519 const ObjCPropertyImplDecl *propImpl,
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +00001520 const ObjCMethodDecl *GetterMothodDecl,
Fariborz Jahanian4b501a22012-01-07 18:56:22 +00001521 llvm::Constant *AtomicHelperFn);
Fariborz Jahanian302a3d42011-02-18 19:15:13 +00001522
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001523 void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1524 ObjCMethodDecl *MD, bool ctor);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001525
Mike Stumpfc496822009-02-08 23:14:22 +00001526 /// GenerateObjCSetter - Synthesize an Objective-C property setter function
1527 /// for the given property.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00001528 void GenerateObjCSetter(ObjCImplementationDecl *IMP,
1529 const ObjCPropertyImplDecl *PID);
John McCall7f16c422011-09-10 09:17:20 +00001530 void generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001531 const ObjCPropertyImplDecl *propImpl,
1532 llvm::Constant *AtomicHelperFn);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001533
Mike Stumpcb2fbcb2009-02-21 20:00:35 +00001534 //===--------------------------------------------------------------------===//
1535 // Block Bits
1536 //===--------------------------------------------------------------------===//
1537
John McCall351762c2011-02-07 10:33:21 +00001538 llvm::Value *EmitBlockLiteral(const BlockExpr *);
John McCall08ef4662011-11-10 08:15:53 +00001539 static void destroyBlockInfos(CGBlockInfo *info);
Mike Stumpcb2fbcb2009-02-21 20:00:35 +00001540
Fariborz Jahanian9b5528d2010-06-24 00:08:06 +00001541 llvm::Function *GenerateBlockFunction(GlobalDecl GD,
John McCall351762c2011-02-07 10:33:21 +00001542 const CGBlockInfo &Info,
Eli Friedman2495ab02012-02-25 02:48:22 +00001543 const DeclMapTy &ldm,
1544 bool IsLambdaConversionToBlock);
Mike Stumpcb2fbcb2009-02-21 20:00:35 +00001545
John McCallad7c5c12011-02-08 08:22:06 +00001546 llvm::Constant *GenerateCopyHelperFunction(const CGBlockInfo &blockInfo);
1547 llvm::Constant *GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001548 llvm::Constant *GenerateObjCAtomicSetterCopyHelperFunction(
1549 const ObjCPropertyImplDecl *PID);
1550 llvm::Constant *GenerateObjCAtomicGetterCopyHelperFunction(
1551 const ObjCPropertyImplDecl *PID);
Eli Friedmanec75fec2012-02-28 01:08:45 +00001552 llvm::Value *EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty);
John McCallad7c5c12011-02-08 08:22:06 +00001553
John McCallad7c5c12011-02-08 08:22:06 +00001554 void BuildBlockRelease(llvm::Value *DeclPtr, BlockFieldFlags flags);
1555
John McCall73064872011-03-31 01:59:53 +00001556 class AutoVarEmission;
1557
1558 void emitByrefStructureInit(const AutoVarEmission &emission);
1559 void enterByrefCleanup(const AutoVarEmission &emission);
1560
John McCall7f416cc2015-09-08 08:05:57 +00001561 void setBlockContextParameter(const ImplicitParamDecl *D, unsigned argNum,
1562 llvm::Value *ptr);
1563
1564 Address LoadBlockStruct();
John McCall7f416cc2015-09-08 08:05:57 +00001565 Address GetAddrOfBlockDecl(const VarDecl *var, bool ByRef);
1566
1567 /// BuildBlockByrefAddress - Computes the location of the
1568 /// data in a variable which is declared as __block.
1569 Address emitBlockByrefAddress(Address baseAddr, const VarDecl *V,
1570 bool followForward = true);
1571 Address emitBlockByrefAddress(Address baseAddr,
1572 const BlockByrefInfo &info,
1573 bool followForward,
1574 const llvm::Twine &name);
1575
1576 const BlockByrefInfo &getBlockByrefInfo(const VarDecl *var);
Mike Stump97d01d52009-03-04 03:23:46 +00001577
Richard Smith5179eb72016-06-28 19:03:57 +00001578 QualType BuildFunctionArgList(GlobalDecl GD, FunctionArgList &Args);
1579
John McCalla738c252011-03-09 04:27:21 +00001580 void GenerateCode(GlobalDecl GD, llvm::Function *Fn,
1581 const CGFunctionInfo &FnInfo);
Adrian Prantl42d71b92014-04-10 23:21:53 +00001582 /// \brief Emit code for the start of a function.
1583 /// \param Loc The location to be associated with the function.
1584 /// \param StartLoc The location of the function body.
John McCalldec348f72013-05-03 07:33:41 +00001585 void StartFunction(GlobalDecl GD,
1586 QualType RetTy,
Daniel Dunbarbc915f42008-09-09 23:14:03 +00001587 llvm::Function *Fn,
John McCalla738c252011-03-09 04:27:21 +00001588 const CGFunctionInfo &FnInfo,
Daniel Dunbar354d2782008-10-18 18:22:23 +00001589 const FunctionArgList &Args,
Adrian Prantl22e66b42014-04-11 01:13:04 +00001590 SourceLocation Loc = SourceLocation(),
1591 SourceLocation StartLoc = SourceLocation());
Daniel Dunbar5c7e3932008-11-11 23:11:34 +00001592
Vedant Kumar7f809b22017-02-24 01:15:19 +00001593 static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor);
1594
John McCallb81884d2010-02-19 09:25:03 +00001595 void EmitConstructorBody(FunctionArgList &Args);
1596 void EmitDestructorBody(FunctionArgList &Args);
Lang Hamesbf122742013-02-17 07:22:09 +00001597 void emitImplicitAssignmentOperatorBody(FunctionArgList &Args);
Richard Smithb47c36f2013-11-05 09:12:18 +00001598 void EmitFunctionBody(FunctionArgList &Args, const Stmt *Body);
Justin Bogner66242d62015-04-23 23:06:47 +00001599 void EmitBlockWithFallThrough(llvm::BasicBlock *BB, const Stmt *S);
John McCall89b12b32010-02-18 03:17:58 +00001600
Faisal Vali571df122013-09-29 08:45:24 +00001601 void EmitForwardingCallToLambda(const CXXMethodDecl *LambdaCallOperator,
Eli Friedman2495ab02012-02-25 02:48:22 +00001602 CallArgList &CallArgs);
Eli Friedman5a6d5072012-02-16 01:37:33 +00001603 void EmitLambdaToBlockPointerBody(FunctionArgList &Args);
Eli Friedman2495ab02012-02-25 02:48:22 +00001604 void EmitLambdaBlockInvokeBody();
Douglas Gregor355efbb2012-02-17 03:02:34 +00001605 void EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD);
1606 void EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD);
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00001607 void EmitAsanPrologueOrEpilogue(bool Prologue);
Eli Friedman5a6d5072012-02-16 01:37:33 +00001608
David Blaikiea0a1a872015-01-18 02:48:07 +00001609 /// \brief Emit the unified return block, trying to avoid its emission when
1610 /// possible.
1611 /// \return The debug location of the user written return statement if the
1612 /// return block is is avoided.
David Blaikie66e41972015-01-14 07:38:27 +00001613 llvm::DebugLoc EmitReturnBlock();
Daniel Dunbarfd346a32009-01-26 23:27:52 +00001614
Mike Stumpfc496822009-02-08 23:14:22 +00001615 /// FinishFunction - Complete IR generation of the current function. It is
1616 /// legal to call this function even if there is no current insertion point.
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001617 void FinishFunction(SourceLocation EndLoc=SourceLocation());
Daniel Dunbar613855c2008-09-09 23:27:19 +00001618
Nico Weber1bebad12015-02-11 22:33:32 +00001619 void StartThunk(llvm::Function *Fn, GlobalDecl GD,
1620 const CGFunctionInfo &FnInfo);
Hans Wennborg88497d62013-11-15 17:24:45 +00001621
John McCallb92ab1a2016-10-26 23:46:34 +00001622 void EmitCallAndReturnForThunk(llvm::Constant *Callee,
1623 const ThunkInfo *Thunk);
Hans Wennborg88497d62013-11-15 17:24:45 +00001624
John McCall7f416cc2015-09-08 08:05:57 +00001625 void FinishThunk();
1626
Reid Klecknerab2090d2014-07-26 01:34:32 +00001627 /// Emit a musttail call for a thunk with a potentially adjusted this pointer.
1628 void EmitMustTailThunk(const CXXMethodDecl *MD, llvm::Value *AdjustedThisPtr,
1629 llvm::Value *Callee);
1630
Rafael Espindolad6e66942015-07-13 06:07:58 +00001631 /// Generate a thunk for the given method.
1632 void generateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo,
John McCalla738c252011-03-09 04:27:21 +00001633 GlobalDecl GD, const ThunkInfo &Thunk);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001634
Peter Collingbournee286b0e2015-06-30 22:08:44 +00001635 llvm::Function *GenerateVarArgsThunk(llvm::Function *Fn,
1636 const CGFunctionInfo &FnInfo,
1637 GlobalDecl GD, const ThunkInfo &Thunk);
Eli Friedman49a94b12011-05-06 17:27:27 +00001638
Douglas Gregor94f9a482010-05-05 05:51:00 +00001639 void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type,
1640 FunctionArgList &Args);
Mike Stump11289f42009-09-09 15:08:12 +00001641
Richard Smith30e304e2016-12-14 00:03:17 +00001642 void EmitInitializerForField(FieldDecl *Field, LValue LHS, Expr *Init);
Eli Friedman5f1a04f2012-02-14 02:31:03 +00001643
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001644 /// Struct with all informations about dynamic [sub]class needed to set vptr.
1645 struct VPtr {
1646 BaseSubobject Base;
1647 const CXXRecordDecl *NearestVBase;
1648 CharUnits OffsetFromNearestVBase;
1649 const CXXRecordDecl *VTableClass;
1650 };
1651
1652 /// Initialize the vtable pointer of the given subobject.
1653 void InitializeVTablePointer(const VPtr &vptr);
1654
1655 typedef llvm::SmallVector<VPtr, 4> VPtrsVector;
Anders Carlssone87fae92010-03-28 19:40:00 +00001656
1657 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001658 VPtrsVector getVTablePointers(const CXXRecordDecl *VTableClass);
1659
1660 void getVTablePointers(BaseSubobject Base, const CXXRecordDecl *NearestVBase,
1661 CharUnits OffsetFromNearestVBase,
1662 bool BaseIsNonVirtualPrimaryBase,
1663 const CXXRecordDecl *VTableClass,
1664 VisitedVirtualBasesSetTy &VBases, VPtrsVector &vptrs);
Eli Friedmanbb5008a2009-12-08 06:46:18 +00001665
Anders Carlssond5895932010-03-28 21:07:49 +00001666 void InitializeVTablePointers(const CXXRecordDecl *ClassDecl);
Anders Carlssone87fae92010-03-28 19:40:00 +00001667
Dan Gohman8fc50c22010-10-26 18:44:08 +00001668 /// GetVTablePtr - Return the Value of the vtable pointer member pointed
1669 /// to by This.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001670 llvm::Value *GetVTablePtr(Address This, llvm::Type *VTableTy,
1671 const CXXRecordDecl *VTableClass);
Anders Carlssone87fae92010-03-28 19:40:00 +00001672
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001673 enum CFITypeCheckKind {
1674 CFITCK_VCall,
1675 CFITCK_NVCall,
1676 CFITCK_DerivedCast,
1677 CFITCK_UnrelatedCast,
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00001678 CFITCK_ICall,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001679 };
1680
Peter Collingbourned2926c92015-03-14 02:42:25 +00001681 /// \brief Derived is the presumed address of an object of type T after a
1682 /// cast. If T is a polymorphic class type, emit a check that the virtual
1683 /// table for Derived belongs to a class derived from T.
1684 void EmitVTablePtrCheckForCast(QualType T, llvm::Value *Derived,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001685 bool MayBeNull, CFITypeCheckKind TCK,
1686 SourceLocation Loc);
Peter Collingbourned2926c92015-03-14 02:42:25 +00001687
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001688 /// EmitVTablePtrCheckForCall - Virtual method MD is being called via VTable.
1689 /// If vptr CFI is enabled, emit a check that VTable is valid.
Peter Collingbournefb532b92016-02-24 20:46:36 +00001690 void EmitVTablePtrCheckForCall(const CXXRecordDecl *RD, llvm::Value *VTable,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001691 CFITypeCheckKind TCK, SourceLocation Loc);
Benjamin Kramer7463ed72013-08-25 22:46:27 +00001692
Peter Collingbourned2926c92015-03-14 02:42:25 +00001693 /// EmitVTablePtrCheck - Emit a check that VTable is a valid virtual table for
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001694 /// RD using llvm.type.test.
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001695 void EmitVTablePtrCheck(const CXXRecordDecl *RD, llvm::Value *VTable,
1696 CFITypeCheckKind TCK, SourceLocation Loc);
Peter Collingbourned2926c92015-03-14 02:42:25 +00001697
Peter Collingbournefb532b92016-02-24 20:46:36 +00001698 /// If whole-program virtual table optimization is enabled, emit an assumption
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001699 /// that VTable is a member of RD's type identifier. Or, if vptr CFI is
1700 /// enabled, emit a check that VTable is a member of RD's type identifier.
1701 void EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD,
1702 llvm::Value *VTable, SourceLocation Loc);
Peter Collingbournefb532b92016-02-24 20:46:36 +00001703
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001704 /// Returns whether we should perform a type checked load when loading a
1705 /// virtual function for virtual calls to members of RD. This is generally
1706 /// true when both vcall CFI and whole-program-vtables are enabled.
1707 bool ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD);
1708
1709 /// Emit a type checked load from the given vtable.
1710 llvm::Value *EmitVTableTypeCheckedLoad(const CXXRecordDecl *RD, llvm::Value *VTable,
1711 uint64_t VTableByteOffset);
1712
Benjamin Kramer7463ed72013-08-25 22:46:27 +00001713 /// CanDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
1714 /// expr can be devirtualized.
1715 bool CanDevirtualizeMemberFunctionCall(const Expr *Base,
1716 const CXXMethodDecl *MD);
1717
John McCallf99a6312010-07-21 05:30:47 +00001718 /// EnterDtorCleanups - Enter the cleanups necessary to complete the
1719 /// given phase of destruction for a destructor. The end result
1720 /// should call destructors on members and base classes in reverse
1721 /// order of their construction.
1722 void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type);
Mike Stump11289f42009-09-09 15:08:12 +00001723
Chris Lattner3c77a352010-06-22 00:03:40 +00001724 /// ShouldInstrumentFunction - Return true if the current function should be
1725 /// instrumented with __cyg_profile_func_* calls
1726 bool ShouldInstrumentFunction();
1727
Aaron Ballman7d2aecb2016-07-13 22:32:15 +00001728 /// ShouldXRayInstrument - Return true if the current function should be
1729 /// instrumented with XRay nop sleds.
1730 bool ShouldXRayInstrumentFunction() const;
1731
Chris Lattner3c77a352010-06-22 00:03:40 +00001732 /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
1733 /// instrumentation function with the current function and the call site, if
1734 /// function instrumentation is enabled.
1735 void EmitFunctionInstrumentation(const char *Fn);
1736
Roman Divacky178e01602011-02-10 16:52:03 +00001737 /// EmitMCountInstrumentation - Emit call to .mcount.
1738 void EmitMCountInstrumentation();
1739
Mike Stumpfc496822009-02-08 23:14:22 +00001740 /// EmitFunctionProlog - Emit the target specific LLVM code to load the
1741 /// arguments for the given function. This is also responsible for naming the
1742 /// LLVM function arguments.
Daniel Dunbard931a872009-02-02 22:03:45 +00001743 void EmitFunctionProlog(const CGFunctionInfo &FI,
1744 llvm::Function *Fn,
Daniel Dunbar613855c2008-09-09 23:27:19 +00001745 const FunctionArgList &Args);
1746
Mike Stumpfc496822009-02-08 23:14:22 +00001747 /// EmitFunctionEpilog - Emit the target specific LLVM code to return the
1748 /// given temporary.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001749 void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc,
1750 SourceLocation EndLoc);
Daniel Dunbar613855c2008-09-09 23:27:19 +00001751
Mike Stump1d849212009-12-07 23:38:24 +00001752 /// EmitStartEHSpec - Emit the start of the exception spec.
1753 void EmitStartEHSpec(const Decl *D);
1754
1755 /// EmitEndEHSpec - Emit the end of the exception spec.
1756 void EmitEndEHSpec(const Decl *D);
1757
John McCallbd309292010-07-06 01:34:17 +00001758 /// getTerminateLandingPad - Return a landing pad that just calls terminate.
1759 llvm::BasicBlock *getTerminateLandingPad();
1760
1761 /// getTerminateHandler - Return a handler (not a landing pad, just
1762 /// a catch handler) that just calls terminate. This is used when
1763 /// a terminate scope encloses a try.
Mike Stump2b488872009-12-09 22:59:31 +00001764 llvm::BasicBlock *getTerminateHandler();
1765
Chris Lattnera5f58b02011-07-09 17:41:47 +00001766 llvm::Type *ConvertTypeForMem(QualType T);
1767 llvm::Type *ConvertType(QualType T);
1768 llvm::Type *ConvertType(const TypeDecl *T) {
John McCall6ce74722010-02-16 04:15:37 +00001769 return ConvertType(getContext().getTypeDeclType(T));
1770 }
Chris Lattner5506f8c2008-04-04 04:07:35 +00001771
Mike Stumpfc496822009-02-08 23:14:22 +00001772 /// LoadObjCSelf - Load the value of self. This function is only valid while
1773 /// generating code for an Objective-C method.
Chris Lattner5506f8c2008-04-04 04:07:35 +00001774 llvm::Value *LoadObjCSelf();
Mike Stumpfc496822009-02-08 23:14:22 +00001775
1776 /// TypeOfSelfObject - Return type of object that this self represents.
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00001777 QualType TypeOfSelfObject();
Chris Lattner5696e7b2008-06-17 18:05:57 +00001778
Chris Lattner54fb19e2007-06-22 22:02:34 +00001779 /// hasAggregateLLVMType - Return true if the specified AST type will map into
1780 /// an aggregate LLVM type or is void.
John McCall47fb9502013-03-07 21:37:08 +00001781 static TypeEvaluationKind getEvaluationKind(QualType T);
1782
1783 static bool hasScalarEvaluationKind(QualType T) {
1784 return getEvaluationKind(T) == TEK_Scalar;
1785 }
1786
1787 static bool hasAggregateEvaluationKind(QualType T) {
1788 return getEvaluationKind(T) == TEK_Aggregate;
1789 }
Daniel Dunbar75283ff2008-11-11 02:29:29 +00001790
1791 /// createBasicBlock - Create an LLVM basic block.
Richard Smithe30752c2012-10-09 19:52:38 +00001792 llvm::BasicBlock *createBasicBlock(const Twine &name = "",
Craig Topper8a13c412014-05-21 05:09:00 +00001793 llvm::Function *parent = nullptr,
1794 llvm::BasicBlock *before = nullptr) {
Daniel Dunbar851eec12008-11-12 00:01:12 +00001795#ifdef NDEBUG
John McCallad7c5c12011-02-08 08:22:06 +00001796 return llvm::BasicBlock::Create(getLLVMContext(), "", parent, before);
Daniel Dunbar851eec12008-11-12 00:01:12 +00001797#else
John McCallad7c5c12011-02-08 08:22:06 +00001798 return llvm::BasicBlock::Create(getLLVMContext(), name, parent, before);
Daniel Dunbar851eec12008-11-12 00:01:12 +00001799#endif
Daniel Dunbar75283ff2008-11-11 02:29:29 +00001800 }
Mike Stumpfc496822009-02-08 23:14:22 +00001801
Chris Lattnerac248202007-05-30 00:13:02 +00001802 /// getBasicBlockForLabel - Return the LLVM basicblock that the specified
1803 /// label maps to.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00001804 JumpDest getJumpDestForLabel(const LabelDecl *S);
Mike Stumpfc496822009-02-08 23:14:22 +00001805
Mike Stumpe5311b02009-11-30 20:08:49 +00001806 /// SimplifyForwardingBlocks - If the given basic block is only a branch to
1807 /// another basic block, simplify it. This assumes that no other code could
1808 /// potentially reference the basic block.
Daniel Dunbarf77e2922009-04-01 04:37:47 +00001809 void SimplifyForwardingBlocks(llvm::BasicBlock *BB);
1810
Mike Stumpfc496822009-02-08 23:14:22 +00001811 /// EmitBlock - Emit the given block \arg BB and set it as the insert point,
1812 /// adding a fall-through branch from the current insert block if
1813 /// necessary. It is legal to call this function even if there is no current
1814 /// insertion point.
Daniel Dunbarfcac22e2008-11-13 01:24:05 +00001815 ///
Mike Stumpfc496822009-02-08 23:14:22 +00001816 /// IsFinished - If true, indicates that the caller has finished emitting
1817 /// branches to the given block and does not expect to emit code into it. This
1818 /// means the block can be ignored if it is unreachable.
Daniel Dunbarfcac22e2008-11-13 01:24:05 +00001819 void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false);
Daniel Dunbar29ac59f2008-11-11 04:34:23 +00001820
John McCall8e4c74b2011-08-11 02:22:43 +00001821 /// EmitBlockAfterUses - Emit the given block somewhere hopefully
1822 /// near its uses, and leave the insertion point in it.
1823 void EmitBlockAfterUses(llvm::BasicBlock *BB);
1824
Mike Stumpfc496822009-02-08 23:14:22 +00001825 /// EmitBranch - Emit a branch to the specified basic block from the current
1826 /// insert block, taking care to avoid creation of branches from dummy
1827 /// blocks. It is legal to call this function even if there is no current
1828 /// insertion point.
Daniel Dunbarab197eb2008-11-11 22:06:59 +00001829 ///
Mike Stumpfc496822009-02-08 23:14:22 +00001830 /// This function clears the current insertion point. The caller should follow
1831 /// calls to this function with calls to Emit*Block prior to generation new
1832 /// code.
Daniel Dunbarc56e6762008-11-11 09:41:28 +00001833 void EmitBranch(llvm::BasicBlock *Block);
1834
Mike Stumpfc496822009-02-08 23:14:22 +00001835 /// HaveInsertPoint - True if an insertion point is defined. If not, this
1836 /// indicates that the current code being emitted is unreachable.
1837 bool HaveInsertPoint() const {
Craig Topper8a13c412014-05-21 05:09:00 +00001838 return Builder.GetInsertBlock() != nullptr;
Daniel Dunbar5c7e3932008-11-11 23:11:34 +00001839 }
1840
Mike Stumpfc496822009-02-08 23:14:22 +00001841 /// EnsureInsertPoint - Ensure that an insertion point is defined so that
1842 /// emitted IR has a place to go. Note that by definition, if this function
1843 /// creates a block then that block is unreachable; callers may do better to
1844 /// detect when no insertion point is defined and simply skip IR generation.
Daniel Dunbar5c7e3932008-11-11 23:11:34 +00001845 void EnsureInsertPoint() {
1846 if (!HaveInsertPoint())
1847 EmitBlock(createBasicBlock());
1848 }
Mike Stumpfc496822009-02-08 23:14:22 +00001849
Daniel Dunbara7c8cf62008-08-16 00:56:44 +00001850 /// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerfc944342007-12-02 01:43:38 +00001851 /// specified stmt yet.
David Blaikie4a9ec7b2013-08-19 21:02:26 +00001852 void ErrorUnsupported(const Stmt *S, const char *Type);
Chris Lattner84915fa2007-06-02 04:16:21 +00001853
Chris Lattnere9a64532007-06-22 21:44:33 +00001854 //===--------------------------------------------------------------------===//
1855 // Helpers
1856 //===--------------------------------------------------------------------===//
Mike Stumpfc496822009-02-08 23:14:22 +00001857
John McCall7f416cc2015-09-08 08:05:57 +00001858 LValue MakeAddrLValue(Address Addr, QualType T,
1859 AlignmentSource AlignSource = AlignmentSource::Type) {
1860 return LValue::MakeAddr(Addr, T, getContext(), AlignSource,
Dan Gohman947c9af2010-10-14 23:06:10 +00001861 CGM.getTBAAInfo(T));
Daniel Dunbar93b00a92010-08-21 02:53:44 +00001862 }
John McCall4e8ca4f2012-07-02 23:58:38 +00001863
John McCall7f416cc2015-09-08 08:05:57 +00001864 LValue MakeAddrLValue(llvm::Value *V, QualType T, CharUnits Alignment,
1865 AlignmentSource AlignSource = AlignmentSource::Type) {
1866 return LValue::MakeAddr(Address(V, Alignment), T, getContext(),
1867 AlignSource, CGM.getTBAAInfo(T));
1868 }
1869
1870 LValue MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T);
David Majnemer99281062014-09-18 22:05:54 +00001871 LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T);
John McCall7f416cc2015-09-08 08:05:57 +00001872 CharUnits getNaturalTypeAlignment(QualType T,
1873 AlignmentSource *Source = nullptr,
1874 bool forPointeeType = false);
1875 CharUnits getNaturalPointeeTypeAlignment(QualType T,
1876 AlignmentSource *Source = nullptr);
1877
1878 Address EmitLoadOfReference(Address Ref, const ReferenceType *RefTy,
1879 AlignmentSource *Source = nullptr);
1880 LValue EmitLoadOfReferenceLValue(Address Ref, const ReferenceType *RefTy);
Daniel Dunbar93b00a92010-08-21 02:53:44 +00001881
Alexey Bataev31300ed2016-02-04 11:27:03 +00001882 Address EmitLoadOfPointer(Address Ptr, const PointerType *PtrTy,
1883 AlignmentSource *Source = nullptr);
1884 LValue EmitLoadOfPointerLValue(Address Ptr, const PointerType *PtrTy);
1885
Chris Lattnere9a64532007-06-22 21:44:33 +00001886 /// CreateTempAlloca - This creates a alloca and inserts it into the entry
Daniel Dunbara7566f12010-02-09 02:48:28 +00001887 /// block. The caller is responsible for setting an appropriate alignment on
1888 /// the alloca.
Chris Lattner2192fe52011-07-18 04:24:23 +00001889 llvm::AllocaInst *CreateTempAlloca(llvm::Type *Ty,
Chris Lattner62ff6e82011-07-20 07:06:53 +00001890 const Twine &Name = "tmp");
John McCall7f416cc2015-09-08 08:05:57 +00001891 Address CreateTempAlloca(llvm::Type *Ty, CharUnits align,
1892 const Twine &Name = "tmp");
Mike Stumpfc496822009-02-08 23:14:22 +00001893
John McCall7f416cc2015-09-08 08:05:57 +00001894 /// CreateDefaultAlignedTempAlloca - This creates an alloca with the
1895 /// default ABI alignment of the given LLVM type.
1896 ///
1897 /// IMPORTANT NOTE: This is *not* generally the right alignment for
1898 /// any given AST type that happens to have been lowered to the
1899 /// given IR type. This should only ever be used for function-local,
1900 /// IR-driven manipulations like saving and restoring a value. Do
1901 /// not hand this address off to arbitrary IRGen routines, and especially
1902 /// do not pass it as an argument to a function that might expect a
1903 /// properly ABI-aligned value.
1904 Address CreateDefaultAlignTempAlloca(llvm::Type *Ty,
1905 const Twine &Name = "tmp");
1906
1907 /// InitTempAlloca - Provide an initial value for the given alloca which
1908 /// will be observable at all locations in the function.
1909 ///
1910 /// The address should be something that was returned from one of
1911 /// the CreateTempAlloca or CreateMemTemp routines, and the
1912 /// initializer must be valid in the entry block (i.e. it must
1913 /// either be a constant or an argument value).
1914 void InitTempAlloca(Address Alloca, llvm::Value *Value);
John McCall2e6567a2010-04-22 01:10:34 +00001915
Daniel Dunbard0049182010-02-16 19:44:13 +00001916 /// CreateIRTemp - Create a temporary IR object of the given type, with
1917 /// appropriate alignment. This routine should only be used when an temporary
1918 /// value needs to be stored into an alloca (for example, to avoid explicit
1919 /// PHI construction), but the type is the IR type, not the type appropriate
1920 /// for storing in memory.
John McCall7f416cc2015-09-08 08:05:57 +00001921 ///
1922 /// That is, this is exactly equivalent to CreateMemTemp, but calling
1923 /// ConvertType instead of ConvertTypeForMem.
1924 Address CreateIRTemp(QualType T, const Twine &Name = "tmp");
Daniel Dunbard0049182010-02-16 19:44:13 +00001925
Daniel Dunbara7566f12010-02-09 02:48:28 +00001926 /// CreateMemTemp - Create a temporary memory object of the given type, with
1927 /// appropriate alignment.
John McCall7f416cc2015-09-08 08:05:57 +00001928 Address CreateMemTemp(QualType T, const Twine &Name = "tmp");
1929 Address CreateMemTemp(QualType T, CharUnits Align, const Twine &Name = "tmp");
Daniel Dunbara7566f12010-02-09 02:48:28 +00001930
John McCall7a626f62010-09-15 10:14:12 +00001931 /// CreateAggTemp - Create a temporary memory object for the given
1932 /// aggregate type.
Chris Lattner62ff6e82011-07-20 07:06:53 +00001933 AggValueSlot CreateAggTemp(QualType T, const Twine &Name = "tmp") {
John McCall7f416cc2015-09-08 08:05:57 +00001934 return AggValueSlot::forAddr(CreateMemTemp(T, Name),
Eli Friedmanc1d85b92011-12-03 00:54:26 +00001935 T.getQualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +00001936 AggValueSlot::IsNotDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001937 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001938 AggValueSlot::IsNotAliased);
John McCall7a626f62010-09-15 10:14:12 +00001939 }
1940
John McCallad7c5c12011-02-08 08:22:06 +00001941 /// Emit a cast to void* in the appropriate address space.
1942 llvm::Value *EmitCastToVoidPtr(llvm::Value *value);
1943
Chris Lattner8394d792007-06-05 20:53:16 +00001944 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
1945 /// expression and compare the result against zero, returning an Int1Ty value.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001946 llvm::Value *EvaluateExprAsBool(const Expr *E);
Chris Lattnere9a64532007-06-22 21:44:33 +00001947
John McCalla2342eb2010-12-05 02:00:02 +00001948 /// EmitIgnoredExpr - Emit an expression in a context which ignores the result.
1949 void EmitIgnoredExpr(const Expr *E);
1950
Chris Lattner4647a212007-08-31 22:49:20 +00001951 /// EmitAnyExpr - Emit code to compute the specified expression which can have
1952 /// any type. The result is returned as an RValue struct. If this is an
1953 /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
1954 /// the result should be returned.
Mike Stumpec3cbfe2009-05-26 22:03:21 +00001955 ///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00001956 /// \param ignoreResult True if the resulting value isn't used.
John McCall7a626f62010-09-15 10:14:12 +00001957 RValue EmitAnyExpr(const Expr *E,
John McCall4e8ca4f2012-07-02 23:58:38 +00001958 AggValueSlot aggSlot = AggValueSlot::ignored(),
1959 bool ignoreResult = false);
Devang Patel8ec4f832007-09-28 21:49:18 +00001960
Mike Stumpfc496822009-02-08 23:14:22 +00001961 // EmitVAListRef - Emit a "reference" to a va_list; this is either the address
1962 // or the value of the expression, depending on how va_list is defined.
John McCall7f416cc2015-09-08 08:05:57 +00001963 Address EmitVAListRef(const Expr *E);
Eli Friedmanddea0ad2009-01-20 17:46:04 +00001964
Charles Davisc7d5c942015-09-17 20:55:33 +00001965 /// Emit a "reference" to a __builtin_ms_va_list; this is
1966 /// always the value of the expression, because a __builtin_ms_va_list is a
1967 /// pointer to a char.
1968 Address EmitMSVAListRef(const Expr *E);
1969
Mike Stumpfc496822009-02-08 23:14:22 +00001970 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
1971 /// always be accessible even if no aggregate location is provided.
John McCall7a626f62010-09-15 10:14:12 +00001972 RValue EmitAnyExprToTemp(const Expr *E);
Daniel Dunbar41cf9de2008-09-09 01:06:48 +00001973
John McCall91ca10f2011-03-08 09:11:50 +00001974 /// EmitAnyExprToMem - Emits the code necessary to evaluate an
Chad Rosier615ed1a2012-03-29 17:37:10 +00001975 /// arbitrary expression into the given memory location.
John McCall7f416cc2015-09-08 08:05:57 +00001976 void EmitAnyExprToMem(const Expr *E, Address Location,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001977 Qualifiers Quals, bool IsInitializer);
John McCall21886962010-04-21 10:05:39 +00001978
John McCall7f416cc2015-09-08 08:05:57 +00001979 void EmitAnyExprToExn(const Expr *E, Address Addr);
David Majnemer7c237072015-03-05 00:46:22 +00001980
John McCall91ca10f2011-03-08 09:11:50 +00001981 /// EmitExprAsInit - Emits the code necessary to initialize a
1982 /// location in memory with the given initializer.
David Blaikie73ca5692014-12-09 00:32:22 +00001983 void EmitExprAsInit(const Expr *init, const ValueDecl *D, LValue lvalue,
David Blaikie66e41972015-01-14 07:38:27 +00001984 bool capturedByInit);
John McCall91ca10f2011-03-08 09:11:50 +00001985
Fariborz Jahanian78652202013-01-25 23:57:05 +00001986 /// hasVolatileMember - returns true if aggregate type has a volatile
1987 /// member.
1988 bool hasVolatileMember(QualType T) {
1989 if (const RecordType *RT = T->getAs<RecordType>()) {
1990 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
1991 return RD->hasVolatileMember();
1992 }
1993 return false;
1994 }
Arnaud A. de Grandmaison49c04462013-02-05 09:06:17 +00001995 /// EmitAggregateCopy - Emit an aggregate assignment.
Benjamin Kramer1ca66912012-09-30 12:43:37 +00001996 ///
1997 /// The difference to EmitAggregateCopy is that tail padding is not copied.
1998 /// This is required for correctness when assigning non-POD structures in C++.
John McCall7f416cc2015-09-08 08:05:57 +00001999 void EmitAggregateAssign(Address DestPtr, Address SrcPtr,
Fariborz Jahanian78652202013-01-25 23:57:05 +00002000 QualType EltTy) {
2001 bool IsVolatile = hasVolatileMember(EltTy);
John McCall7f416cc2015-09-08 08:05:57 +00002002 EmitAggregateCopy(DestPtr, SrcPtr, EltTy, IsVolatile, true);
Benjamin Kramer1ca66912012-09-30 12:43:37 +00002003 }
2004
John McCall7f416cc2015-09-08 08:05:57 +00002005 void EmitAggregateCopyCtor(Address DestPtr, Address SrcPtr,
2006 QualType DestTy, QualType SrcTy) {
David Majnemerfd1e7392015-02-03 23:04:06 +00002007 EmitAggregateCopy(DestPtr, SrcPtr, SrcTy, /*IsVolatile=*/false,
David Majnemerfd1e7392015-02-03 23:04:06 +00002008 /*IsAssignment=*/false);
2009 }
2010
Arnaud A. de Grandmaison49c04462013-02-05 09:06:17 +00002011 /// EmitAggregateCopy - Emit an aggregate copy.
Mike Stump5e9e61b2009-05-23 22:29:41 +00002012 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00002013 /// \param isVolatile - True iff either the source or the destination is
Mike Stump5e9e61b2009-05-23 22:29:41 +00002014 /// volatile.
Benjamin Kramer1ca66912012-09-30 12:43:37 +00002015 /// \param isAssignment - If false, allow padding to be copied. This often
2016 /// yields more efficient.
John McCall7f416cc2015-09-08 08:05:57 +00002017 void EmitAggregateCopy(Address DestPtr, Address SrcPtr,
Eli Friedman6d694a32011-12-05 22:23:28 +00002018 QualType EltTy, bool isVolatile=false,
Benjamin Kramer1ca66912012-09-30 12:43:37 +00002019 bool isAssignment = false);
Daniel Dunbar0bc8e862008-09-09 20:49:46 +00002020
Anders Carlsson9396a892008-09-11 09:15:33 +00002021 /// GetAddrOfLocalVar - Return the address of a local variable.
John McCall7f416cc2015-09-08 08:05:57 +00002022 Address GetAddrOfLocalVar(const VarDecl *VD) {
2023 auto it = LocalDeclMap.find(VD);
2024 assert(it != LocalDeclMap.end() &&
2025 "Invalid argument to GetAddrOfLocalVar(), no decl!");
2026 return it->second;
John McCall5d865c322010-08-31 07:33:07 +00002027 }
Mike Stumpfc496822009-02-08 23:14:22 +00002028
John McCallc07a0c72011-02-17 10:25:35 +00002029 /// getOpaqueLValueMapping - Given an opaque value expression (which
2030 /// must be mapped to an l-value), return its mapping.
2031 const LValue &getOpaqueLValueMapping(const OpaqueValueExpr *e) {
2032 assert(OpaqueValueMapping::shouldBindAsLValue(e));
2033
2034 llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator
2035 it = OpaqueLValues.find(e);
2036 assert(it != OpaqueLValues.end() && "no mapping for opaque value!");
2037 return it->second;
2038 }
2039
2040 /// getOpaqueRValueMapping - Given an opaque value expression (which
2041 /// must be mapped to an r-value), return its mapping.
2042 const RValue &getOpaqueRValueMapping(const OpaqueValueExpr *e) {
2043 assert(!OpaqueValueMapping::shouldBindAsLValue(e));
2044
2045 llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator
2046 it = OpaqueRValues.find(e);
2047 assert(it != OpaqueRValues.end() && "no mapping for opaque value!");
John McCall1bf58462011-02-16 08:02:54 +00002048 return it->second;
2049 }
2050
Richard Smith410306b2016-12-12 02:53:20 +00002051 /// Get the index of the current ArrayInitLoopExpr, if any.
2052 llvm::Value *getArrayInitIndex() { return ArrayInitIndex; }
2053
Dan Gohman75d69da2008-05-22 00:50:06 +00002054 /// getAccessedFieldNo - Given an encoded value and a result number, return
2055 /// the input field number being accessed.
2056 static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts);
2057
Chris Lattnerc8e630e2011-02-17 07:39:24 +00002058 llvm::BlockAddress *GetAddrOfLabel(const LabelDecl *L);
Chris Lattner2bb5cb42009-10-13 06:55:33 +00002059 llvm::BasicBlock *GetIndirectGotoBlock();
Daniel Dunbar88402ce2008-08-04 16:51:22 +00002060
Vedant Kumare550d112017-02-23 01:22:38 +00002061 /// Check if \p E is a reference, or a C++ "this" pointer wrapped in value-
2062 /// preserving casts.
2063 static bool IsDeclRefOrWrappedCXXThis(const Expr *E);
Vedant Kumar34b1fd62017-02-17 23:22:59 +00002064
Anders Carlssonc0964b62010-05-22 17:35:42 +00002065 /// EmitNullInitialization - Generate code to set a value of the given type to
2066 /// null, If the type contains data member pointers, they will be initialized
2067 /// to -1 in accordance with the Itanium C++ ABI.
John McCall7f416cc2015-09-08 08:05:57 +00002068 void EmitNullInitialization(Address DestPtr, QualType Ty);
Anders Carlsson13abd7e2008-11-04 05:30:00 +00002069
Charles Davisc7d5c942015-09-17 20:55:33 +00002070 /// Emits a call to an LLVM variable-argument intrinsic, either
2071 /// \c llvm.va_start or \c llvm.va_end.
2072 /// \param ArgValue A reference to the \c va_list as emitted by either
2073 /// \c EmitVAListRef or \c EmitMSVAListRef.
2074 /// \param IsStart If \c true, emits a call to \c llvm.va_start; otherwise,
2075 /// calls \c llvm.va_end.
2076 llvm::Value *EmitVAStartEnd(llvm::Value *ArgValue, bool IsStart);
2077
2078 /// Generate code to get an argument from the passed in pointer
2079 /// and update it accordingly.
2080 /// \param VE The \c VAArgExpr for which to generate code.
2081 /// \param VAListAddr Receives a reference to the \c va_list as emitted by
2082 /// either \c EmitVAListRef or \c EmitMSVAListRef.
2083 /// \returns A pointer to the argument.
Anders Carlsson13abd7e2008-11-04 05:30:00 +00002084 // FIXME: We should be able to get rid of this method and use the va_arg
Mike Stumpfc496822009-02-08 23:14:22 +00002085 // instruction in LLVM instead once it works well enough.
Charles Davisc7d5c942015-09-17 20:55:33 +00002086 Address EmitVAArg(VAArgExpr *VE, Address &VAListAddr);
Anders Carlssone388a5b2008-12-20 20:27:15 +00002087
John McCall82fe67b2011-07-09 01:37:26 +00002088 /// emitArrayLength - Compute the length of an array, even if it's a
2089 /// VLA, and drill down to the base element type.
2090 llvm::Value *emitArrayLength(const ArrayType *arrayType,
2091 QualType &baseType,
John McCall7f416cc2015-09-08 08:05:57 +00002092 Address &addr);
John McCall82fe67b2011-07-09 01:37:26 +00002093
John McCall23c29fe2011-06-24 21:55:10 +00002094 /// EmitVLASize - Capture all the sizes for the VLA expressions in
2095 /// the given variably-modified type and store them in the VLASizeMap.
Daniel Dunbarb6adc432009-07-19 06:58:07 +00002096 ///
2097 /// This function can be called with a null (unreachable) insert point.
John McCall23c29fe2011-06-24 21:55:10 +00002098 void EmitVariablyModifiedType(QualType Ty);
Mike Stumpfc496822009-02-08 23:14:22 +00002099
John McCall23c29fe2011-06-24 21:55:10 +00002100 /// getVLASize - Returns an LLVM value that corresponds to the size,
2101 /// in non-variably-sized elements, of a variable length array type,
2102 /// plus that largest non-variably-sized element type. Assumes that
2103 /// the type has already been emitted with EmitVariablyModifiedType.
2104 std::pair<llvm::Value*,QualType> getVLASize(const VariableArrayType *vla);
2105 std::pair<llvm::Value*,QualType> getVLASize(QualType vla);
Anders Carlssonccbe9202008-12-12 07:19:02 +00002106
Anders Carlssona5d077d2009-04-14 16:58:56 +00002107 /// LoadCXXThis - Load the value of 'this'. This function is only valid while
2108 /// generating code for an C++ member function.
John McCall347132b2010-02-16 22:04:33 +00002109 llvm::Value *LoadCXXThis() {
2110 assert(CXXThisValue && "no 'this' value for this function");
2111 return CXXThisValue;
2112 }
John McCall7f416cc2015-09-08 08:05:57 +00002113 Address LoadCXXThisAddress();
Mike Stump11289f42009-09-09 15:08:12 +00002114
Anders Carlssone36a6b32010-01-02 01:01:18 +00002115 /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have
2116 /// virtual bases.
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00002117 // FIXME: Every place that calls LoadCXXVTT is something
2118 // that needs to be abstracted properly.
John McCall347132b2010-02-16 22:04:33 +00002119 llvm::Value *LoadCXXVTT() {
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00002120 assert(CXXStructorImplicitParamValue && "no VTT value for this function");
2121 return CXXStructorImplicitParamValue;
2122 }
2123
John McCall6ce74722010-02-16 04:15:37 +00002124 /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +00002125 /// complete class to the given direct base.
John McCall7f416cc2015-09-08 08:05:57 +00002126 Address
2127 GetAddressOfDirectBaseInCompleteClass(Address Value,
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +00002128 const CXXRecordDecl *Derived,
2129 const CXXRecordDecl *Base,
2130 bool BaseIsVirtual);
Anders Carlssonbea9e742010-04-24 21:51:08 +00002131
John McCall7f416cc2015-09-08 08:05:57 +00002132 static bool ShouldNullCheckClassCastValue(const CastExpr *Cast);
2133
Mike Stumpe5311b02009-11-30 20:08:49 +00002134 /// GetAddressOfBaseClass - This function will add the necessary delta to the
2135 /// load of 'this' and returns address of the base class.
John McCall7f416cc2015-09-08 08:05:57 +00002136 Address GetAddressOfBaseClass(Address Value,
2137 const CXXRecordDecl *Derived,
2138 CastExpr::path_const_iterator PathBegin,
2139 CastExpr::path_const_iterator PathEnd,
2140 bool NullCheckValue, SourceLocation Loc);
Anders Carlssond829a022010-04-24 21:06:20 +00002141
John McCall7f416cc2015-09-08 08:05:57 +00002142 Address GetAddressOfDerivedClass(Address Value,
2143 const CXXRecordDecl *Derived,
2144 CastExpr::path_const_iterator PathBegin,
2145 CastExpr::path_const_iterator PathEnd,
2146 bool NullCheckValue);
Anders Carlsson8c793172009-11-23 17:57:54 +00002147
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00002148 /// GetVTTParameter - Return the VTT parameter that should be passed to a
2149 /// base constructor/destructor with virtual bases.
2150 /// FIXME: VTTs are Itanium ABI-specific, so the definition should move
2151 /// to ItaniumCXXABI.cpp together with all the references to VTT.
2152 llvm::Value *GetVTTParameter(GlobalDecl GD, bool ForVirtualBase,
2153 bool Delegating);
2154
John McCallf8ff7b92010-02-23 00:48:20 +00002155 void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
2156 CXXCtorType CtorType,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002157 const FunctionArgList &Args,
2158 SourceLocation Loc);
Alexis Hunt61bc1732011-05-01 07:04:31 +00002159 // It's important not to confuse this and the previous function. Delegating
2160 // constructors are the C++0x feature. The constructor delegate optimization
2161 // is used to reduce duplication in the base and complete consturctors where
2162 // they are substantially the same.
2163 void EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
2164 const FunctionArgList &Args);
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002165
Richard Smith5179eb72016-06-28 19:03:57 +00002166 /// Emit a call to an inheriting constructor (that is, one that invokes a
2167 /// constructor inherited from a base class) by inlining its definition. This
2168 /// is necessary if the ABI does not support forwarding the arguments to the
2169 /// base class constructor (because they're variadic or similar).
2170 void EmitInlinedInheritingCXXConstructorCall(const CXXConstructorDecl *Ctor,
2171 CXXCtorType CtorType,
2172 bool ForVirtualBase,
2173 bool Delegating,
2174 CallArgList &Args);
2175
2176 /// Emit a call to a constructor inherited from a base class, passing the
2177 /// current constructor's arguments along unmodified (without even making
2178 /// a copy).
2179 void EmitInheritedCXXConstructorCall(const CXXConstructorDecl *D,
2180 bool ForVirtualBase, Address This,
2181 bool InheritedFromVBase,
2182 const CXXInheritedCtorInitExpr *E);
2183
Anders Carlssone11f9ce2010-05-02 23:20:53 +00002184 void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
Douglas Gregor61535002013-01-31 05:50:40 +00002185 bool ForVirtualBase, bool Delegating,
John McCall7f416cc2015-09-08 08:05:57 +00002186 Address This, const CXXConstructExpr *E);
Alexey Samsonov70b9c012014-08-21 20:26:47 +00002187
Richard Smith5179eb72016-06-28 19:03:57 +00002188 void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
2189 bool ForVirtualBase, bool Delegating,
2190 Address This, CallArgList &Args);
2191
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002192 /// Emit assumption load for all bases. Requires to be be called only on
2193 /// most-derived class and not under construction of the object.
2194 void EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl, Address This);
2195
2196 /// Emit assumption that vptr load == global vtable.
2197 void EmitVTableAssumptionLoad(const VPtr &vptr, Address This);
2198
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002199 void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
John McCall7f416cc2015-09-08 08:05:57 +00002200 Address This, Address Src,
2201 const CXXConstructExpr *E);
Mike Stump11289f42009-09-09 15:08:12 +00002202
Fariborz Jahanian431c8832009-08-19 20:55:16 +00002203 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
Alexey Bataeve7545b32016-04-29 09:39:50 +00002204 const ArrayType *ArrayTy,
John McCall7f416cc2015-09-08 08:05:57 +00002205 Address ArrayPtr,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00002206 const CXXConstructExpr *E,
Douglas Gregor05fc5be2010-07-21 01:10:17 +00002207 bool ZeroInitialization = false);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002208
Anders Carlssond49844b2009-09-23 02:45:36 +00002209 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
2210 llvm::Value *NumElements,
John McCall7f416cc2015-09-08 08:05:57 +00002211 Address ArrayPtr,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00002212 const CXXConstructExpr *E,
Douglas Gregor05fc5be2010-07-21 01:10:17 +00002213 bool ZeroInitialization = false);
Anders Carlssonb7f8f592009-04-17 00:06:03 +00002214
John McCall82fe67b2011-07-09 01:37:26 +00002215 static Destroyer destroyCXXObject;
2216
Anders Carlsson0a637412009-05-29 21:03:38 +00002217 void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type,
Douglas Gregor61535002013-01-31 05:50:40 +00002218 bool ForVirtualBase, bool Delegating,
John McCall7f416cc2015-09-08 08:05:57 +00002219 Address This);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002220
John McCall99210dc2011-09-15 06:49:18 +00002221 void EmitNewArrayInitializer(const CXXNewExpr *E, QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00002222 llvm::Type *ElementTy, Address NewPtr,
David Blaikiefb901c7a2015-04-04 15:12:29 +00002223 llvm::Value *NumElements,
Richard Smith06a67e22014-06-03 06:58:52 +00002224 llvm::Value *AllocSizeWithoutCookie);
Mike Stump11289f42009-09-09 15:08:12 +00002225
Peter Collingbourne702b2842011-11-27 22:09:22 +00002226 void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType,
John McCall7f416cc2015-09-08 08:05:57 +00002227 Address Ptr);
Mike Stump11289f42009-09-09 15:08:12 +00002228
David Majnemerdc012fa2015-04-22 21:38:15 +00002229 llvm::Value *EmitLifetimeStart(uint64_t Size, llvm::Value *Addr);
2230 void EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr);
2231
Anders Carlsson4a7b49b2009-05-31 01:40:14 +00002232 llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E);
Anders Carlsson81f0df92009-08-16 21:13:42 +00002233 void EmitCXXDeleteExpr(const CXXDeleteExpr *E);
Mike Stump11289f42009-09-09 15:08:12 +00002234
Eli Friedman24f55432009-11-18 00:57:03 +00002235 void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr,
Richard Smithb2f0f052016-10-10 18:54:32 +00002236 QualType DeleteTy, llvm::Value *NumElements = nullptr,
2237 CharUnits CookieSize = CharUnits());
Eli Friedman24f55432009-11-18 00:57:03 +00002238
Richard Smith760520b2014-06-03 23:27:44 +00002239 RValue EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
2240 const Expr *Arg, bool IsDelete);
2241
John McCall7f416cc2015-09-08 08:05:57 +00002242 llvm::Value *EmitCXXTypeidExpr(const CXXTypeidExpr *E);
2243 llvm::Value *EmitDynamicCast(Address V, const CXXDynamicCastExpr *DCE);
2244 Address EmitCXXUuidofExpr(const CXXUuidofExpr *E);
Mike Stumpc9b231c2009-11-15 08:09:41 +00002245
Richard Smith69d0d262012-08-24 00:54:33 +00002246 /// \brief Situations in which we might emit a check for the suitability of a
2247 /// pointer or glvalue.
Richard Smith4d1458e2012-09-08 02:08:36 +00002248 enum TypeCheckKind {
Richard Smith69d0d262012-08-24 00:54:33 +00002249 /// Checking the operand of a load. Must be suitably sized and aligned.
Richard Smith4d1458e2012-09-08 02:08:36 +00002250 TCK_Load,
Richard Smith69d0d262012-08-24 00:54:33 +00002251 /// Checking the destination of a store. Must be suitably sized and aligned.
Richard Smith4d1458e2012-09-08 02:08:36 +00002252 TCK_Store,
Richard Smith69d0d262012-08-24 00:54:33 +00002253 /// Checking the bound value in a reference binding. Must be suitably sized
2254 /// and aligned, but is not required to refer to an object (until the
2255 /// reference is used), per core issue 453.
Richard Smith4d1458e2012-09-08 02:08:36 +00002256 TCK_ReferenceBinding,
Richard Smith69d0d262012-08-24 00:54:33 +00002257 /// Checking the object expression in a non-static data member access. Must
2258 /// be an object within its lifetime.
Richard Smith4d1458e2012-09-08 02:08:36 +00002259 TCK_MemberAccess,
Richard Smith69d0d262012-08-24 00:54:33 +00002260 /// Checking the 'this' pointer for a call to a non-static member function.
2261 /// Must be an object within its lifetime.
Richard Smith4d3110a2012-10-25 02:14:12 +00002262 TCK_MemberCall,
2263 /// Checking the 'this' pointer for a constructor call.
Richard Smith2c5868c2013-02-13 21:18:23 +00002264 TCK_ConstructorCall,
2265 /// Checking the operand of a static_cast to a derived pointer type. Must be
2266 /// null or an object within its lifetime.
2267 TCK_DowncastPointer,
2268 /// Checking the operand of a static_cast to a derived reference type. Must
2269 /// be an object within its lifetime.
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +00002270 TCK_DowncastReference,
2271 /// Checking the operand of a cast to a base object. Must be suitably sized
2272 /// and aligned.
2273 TCK_Upcast,
2274 /// Checking the operand of a cast to a virtual base object. Must be an
2275 /// object within its lifetime.
2276 TCK_UpcastToVirtualBase
Richard Smith69d0d262012-08-24 00:54:33 +00002277 };
2278
Alexey Samsonovac4afe42014-07-07 23:59:57 +00002279 /// \brief Whether any type-checking sanitizers are enabled. If \c false,
2280 /// calls to EmitTypeCheck can be skipped.
2281 bool sanitizePerformTypeCheck() const;
2282
Richard Smith4d1458e2012-09-08 02:08:36 +00002283 /// \brief Emit a check that \p V is the address of storage of the
Richard Smith69d0d262012-08-24 00:54:33 +00002284 /// appropriate size and alignment for an object of type \p Type.
Richard Smithe30752c2012-10-09 19:52:38 +00002285 void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, llvm::Value *V,
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +00002286 QualType Type, CharUnits Alignment = CharUnits::Zero(),
Vedant Kumar18348ea2017-02-17 23:22:55 +00002287 SanitizerSet SkippedChecks = SanitizerSet());
Mike Stump3f6f9fe2009-12-16 02:57:00 +00002288
Richard Smith539e4a72013-02-23 02:53:19 +00002289 /// \brief Emit a check that \p Base points into an array object, which
2290 /// we can access at index \p Index. \p Accessed should be \c false if we
2291 /// this expression is used as an lvalue, for instance in "&Arr[Idx]".
2292 void EmitBoundsCheck(const Expr *E, const Expr *Base, llvm::Value *Index,
2293 QualType IndexType, bool Accessed);
2294
Chris Lattner116ce8f2010-01-09 21:40:03 +00002295 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2296 bool isInc, bool isPre);
2297 ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
2298 bool isInc, bool isPre);
Hal Finkelbcc06082014-09-07 22:58:14 +00002299
2300 void EmitAlignmentAssumption(llvm::Value *PtrValue, unsigned Alignment,
Hal Finkel6fae8492014-10-15 23:45:08 +00002301 llvm::Value *OffsetValue = nullptr) {
2302 Builder.CreateAlignmentAssumption(CGM.getDataLayout(), PtrValue, Alignment,
2303 OffsetValue);
2304 }
Hal Finkelbcc06082014-09-07 22:58:14 +00002305
Amara Emerson652795d2016-11-10 14:44:30 +00002306 /// Converts Location to a DebugLoc, if debug information is enabled.
2307 llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Location);
2308
2309
Chris Lattner8394d792007-06-05 20:53:16 +00002310 //===--------------------------------------------------------------------===//
Chris Lattner53621a52007-06-13 20:44:40 +00002311 // Declaration Emission
Chris Lattner84915fa2007-06-02 04:16:21 +00002312 //===--------------------------------------------------------------------===//
Mike Stumpfc496822009-02-08 23:14:22 +00002313
Daniel Dunbarb6adc432009-07-19 06:58:07 +00002314 /// EmitDecl - Emit a declaration.
2315 ///
2316 /// This function can be called with a null (unreachable) insert point.
Chris Lattner1ad38f82007-06-09 01:20:56 +00002317 void EmitDecl(const Decl &D);
Daniel Dunbarb6adc432009-07-19 06:58:07 +00002318
John McCall1c9c3fd2010-10-15 04:57:14 +00002319 /// EmitVarDecl - Emit a local variable declaration.
Daniel Dunbarb6adc432009-07-19 06:58:07 +00002320 ///
2321 /// This function can be called with a null (unreachable) insert point.
John McCall1c9c3fd2010-10-15 04:57:14 +00002322 void EmitVarDecl(const VarDecl &D);
Daniel Dunbarb6adc432009-07-19 06:58:07 +00002323
David Blaikie73ca5692014-12-09 00:32:22 +00002324 void EmitScalarInit(const Expr *init, const ValueDecl *D, LValue lvalue,
David Blaikie66e41972015-01-14 07:38:27 +00002325 bool capturedByInit);
John McCall31168b02011-06-15 23:02:42 +00002326
John McCallbd309292010-07-06 01:34:17 +00002327 typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D,
2328 llvm::Value *Address);
2329
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002330 /// \brief Determine whether the given initializer is trivial in the sense
2331 /// that it requires no code to be generated.
2332 bool isTrivialInitializer(const Expr *Init);
2333
John McCall1c9c3fd2010-10-15 04:57:14 +00002334 /// EmitAutoVarDecl - Emit an auto variable declaration.
Daniel Dunbarb6adc432009-07-19 06:58:07 +00002335 ///
2336 /// This function can be called with a null (unreachable) insert point.
John McCallc533cb72011-02-22 06:44:22 +00002337 void EmitAutoVarDecl(const VarDecl &D);
2338
2339 class AutoVarEmission {
2340 friend class CodeGenFunction;
2341
John McCall9e2e22f2011-02-22 07:16:58 +00002342 const VarDecl *Variable;
John McCallc533cb72011-02-22 06:44:22 +00002343
John McCall7f416cc2015-09-08 08:05:57 +00002344 /// The address of the alloca. Invalid if the variable was emitted
John McCallc533cb72011-02-22 06:44:22 +00002345 /// as a global constant.
John McCall7f416cc2015-09-08 08:05:57 +00002346 Address Addr;
John McCallc533cb72011-02-22 06:44:22 +00002347
2348 llvm::Value *NRVOFlag;
2349
2350 /// True if the variable is a __block variable.
2351 bool IsByRef;
2352
2353 /// True if the variable is of aggregate type and has a constant
2354 /// initializer.
2355 bool IsConstantAggregate;
2356
Nadav Rotem1da30942013-03-23 06:43:35 +00002357 /// Non-null if we should use lifetime annotations.
2358 llvm::Value *SizeForLifetimeMarkers;
2359
John McCall9e2e22f2011-02-22 07:16:58 +00002360 struct Invalid {};
John McCall7f416cc2015-09-08 08:05:57 +00002361 AutoVarEmission(Invalid) : Variable(nullptr), Addr(Address::invalid()) {}
John McCall9e2e22f2011-02-22 07:16:58 +00002362
John McCallc533cb72011-02-22 06:44:22 +00002363 AutoVarEmission(const VarDecl &variable)
John McCall7f416cc2015-09-08 08:05:57 +00002364 : Variable(&variable), Addr(Address::invalid()), NRVOFlag(nullptr),
Nadav Rotem1da30942013-03-23 06:43:35 +00002365 IsByRef(false), IsConstantAggregate(false),
Craig Topper8a13c412014-05-21 05:09:00 +00002366 SizeForLifetimeMarkers(nullptr) {}
John McCallc533cb72011-02-22 06:44:22 +00002367
John McCall7f416cc2015-09-08 08:05:57 +00002368 bool wasEmittedAsGlobal() const { return !Addr.isValid(); }
John McCallc533cb72011-02-22 06:44:22 +00002369
2370 public:
John McCall9e2e22f2011-02-22 07:16:58 +00002371 static AutoVarEmission invalid() { return AutoVarEmission(Invalid()); }
2372
Craig Topper8a13c412014-05-21 05:09:00 +00002373 bool useLifetimeMarkers() const {
2374 return SizeForLifetimeMarkers != nullptr;
2375 }
Nadav Rotem1da30942013-03-23 06:43:35 +00002376 llvm::Value *getSizeForLifetimeMarkers() const {
2377 assert(useLifetimeMarkers());
2378 return SizeForLifetimeMarkers;
2379 }
2380
2381 /// Returns the raw, allocated address, which is not necessarily
2382 /// the address of the object itself.
John McCall7f416cc2015-09-08 08:05:57 +00002383 Address getAllocatedAddress() const {
2384 return Addr;
Nadav Rotem1da30942013-03-23 06:43:35 +00002385 }
2386
John McCallc533cb72011-02-22 06:44:22 +00002387 /// Returns the address of the object within this declaration.
2388 /// Note that this does not chase the forwarding pointer for
2389 /// __block decls.
John McCall7f416cc2015-09-08 08:05:57 +00002390 Address getObjectAddress(CodeGenFunction &CGF) const {
2391 if (!IsByRef) return Addr;
John McCallc533cb72011-02-22 06:44:22 +00002392
John McCall7f416cc2015-09-08 08:05:57 +00002393 return CGF.emitBlockByrefAddress(Addr, Variable, /*forward*/ false);
John McCallc533cb72011-02-22 06:44:22 +00002394 }
2395 };
2396 AutoVarEmission EmitAutoVarAlloca(const VarDecl &var);
2397 void EmitAutoVarInit(const AutoVarEmission &emission);
2398 void EmitAutoVarCleanups(const AutoVarEmission &emission);
John McCall82fe67b2011-07-09 01:37:26 +00002399 void emitAutoVarTypeCleanup(const AutoVarEmission &emission,
2400 QualType::DestructionKind dtorKind);
Daniel Dunbarb6adc432009-07-19 06:58:07 +00002401
John McCall1c9c3fd2010-10-15 04:57:14 +00002402 void EmitStaticVarDecl(const VarDecl &D,
2403 llvm::GlobalValue::LinkageTypes Linkage);
Daniel Dunbara94ecd22008-08-16 03:19:19 +00002404
John McCall7f416cc2015-09-08 08:05:57 +00002405 class ParamValue {
2406 llvm::Value *Value;
2407 unsigned Alignment;
2408 ParamValue(llvm::Value *V, unsigned A) : Value(V), Alignment(A) {}
2409 public:
2410 static ParamValue forDirect(llvm::Value *value) {
2411 return ParamValue(value, 0);
2412 }
2413 static ParamValue forIndirect(Address addr) {
2414 assert(!addr.getAlignment().isZero());
2415 return ParamValue(addr.getPointer(), addr.getAlignment().getQuantity());
2416 }
2417
2418 bool isIndirect() const { return Alignment != 0; }
2419 llvm::Value *getAnyValue() const { return Value; }
2420
2421 llvm::Value *getDirectValue() const {
2422 assert(!isIndirect());
2423 return Value;
2424 }
2425
2426 Address getIndirectAddress() const {
2427 assert(isIndirect());
2428 return Address(Value, CharUnits::fromQuantity(Alignment));
2429 }
2430 };
2431
Daniel Dunbara94ecd22008-08-16 03:19:19 +00002432 /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
John McCall7f416cc2015-09-08 08:05:57 +00002433 void EmitParmDecl(const VarDecl &D, ParamValue Arg, unsigned ArgNo);
Mike Stumpfc496822009-02-08 23:14:22 +00002434
John McCallc07a0c72011-02-17 10:25:35 +00002435 /// protectFromPeepholes - Protect a value that we're intending to
2436 /// store to the side, but which will probably be used later, from
2437 /// aggressive peepholing optimizations that might delete it.
2438 ///
2439 /// Pass the result to unprotectFromPeepholes to declare that
2440 /// protection is no longer required.
2441 ///
2442 /// There's no particular reason why this shouldn't apply to
2443 /// l-values, it's just that no existing peepholes work on pointers.
2444 PeepholeProtection protectFromPeepholes(RValue rvalue);
2445 void unprotectFromPeepholes(PeepholeProtection protection);
2446
Chris Lattner84915fa2007-06-02 04:16:21 +00002447 //===--------------------------------------------------------------------===//
Chris Lattner308f4312007-05-29 23:50:05 +00002448 // Statement Emission
2449 //===--------------------------------------------------------------------===//
2450
Mike Stumpfc496822009-02-08 23:14:22 +00002451 /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
Daniel Dunbar5fc28712008-11-12 08:21:33 +00002452 void EmitStopPoint(const Stmt *S);
2453
Mike Stumpfc496822009-02-08 23:14:22 +00002454 /// EmitStmt - Emit the code for the statement \arg S. It is legal to call
2455 /// this function even if there is no current insertion point.
2456 ///
2457 /// This function may clear the current insertion point; callers should use
2458 /// EnsureInsertPoint if they wish to subsequently generate code without first
2459 /// calling EmitBlock, EmitBranch, or EmitStmt.
Chris Lattner308f4312007-05-29 23:50:05 +00002460 void EmitStmt(const Stmt *S);
Daniel Dunbar5c7e3932008-11-11 23:11:34 +00002461
Daniel Dunbar5fc28712008-11-12 08:21:33 +00002462 /// EmitSimpleStmt - Try to emit a "simple" statement which does not
Mike Stumpfc496822009-02-08 23:14:22 +00002463 /// necessarily require an insertion point or debug information; typically
2464 /// because the statement amounts to a jump or a container of other
2465 /// statements.
Daniel Dunbar5fc28712008-11-12 08:21:33 +00002466 ///
2467 /// \return True if the statement was handled.
2468 bool EmitSimpleStmt(const Stmt *S);
2469
John McCall7f416cc2015-09-08 08:05:57 +00002470 Address EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
2471 AggValueSlot AVS = AggValueSlot::ignored());
2472 Address EmitCompoundStmtWithoutScope(const CompoundStmt &S,
2473 bool GetLast = false,
2474 AggValueSlot AVS =
Eli Friedman4871a462013-06-10 22:04:49 +00002475 AggValueSlot::ignored());
Daniel Dunbar5c7e3932008-11-11 23:11:34 +00002476
Mike Stumpfc496822009-02-08 23:14:22 +00002477 /// EmitLabel - Emit the block for the given label. It is legal to call this
2478 /// function even if there is no current insertion point.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00002479 void EmitLabel(const LabelDecl *D); // helper for EmitLabelStmt.
Daniel Dunbar5c7e3932008-11-11 23:11:34 +00002480
Chris Lattnerac248202007-05-30 00:13:02 +00002481 void EmitLabelStmt(const LabelStmt &S);
Richard Smithc202b282012-04-14 00:33:13 +00002482 void EmitAttributedStmt(const AttributedStmt &S);
Chris Lattnerac248202007-05-30 00:13:02 +00002483 void EmitGotoStmt(const GotoStmt &S);
Daniel Dunbar88402ce2008-08-04 16:51:22 +00002484 void EmitIndirectGotoStmt(const IndirectGotoStmt &S);
Chris Lattner5269c032007-05-30 21:03:58 +00002485 void EmitIfStmt(const IfStmt &S);
Aaron Ballmanb06b15a2014-06-06 12:40:24 +00002486
Aaron Ballmanb06b15a2014-06-06 12:40:24 +00002487 void EmitWhileStmt(const WhileStmt &S,
Craig Topper3cb91b22014-08-27 06:28:16 +00002488 ArrayRef<const Attr *> Attrs = None);
2489 void EmitDoStmt(const DoStmt &S, ArrayRef<const Attr *> Attrs = None);
Aaron Ballmanb06b15a2014-06-06 12:40:24 +00002490 void EmitForStmt(const ForStmt &S,
Craig Topper3cb91b22014-08-27 06:28:16 +00002491 ArrayRef<const Attr *> Attrs = None);
Chris Lattner3f3dbee2007-06-02 03:19:07 +00002492 void EmitReturnStmt(const ReturnStmt &S);
Chris Lattner1ad38f82007-06-09 01:20:56 +00002493 void EmitDeclStmt(const DeclStmt &S);
Daniel Dunbar5fc28712008-11-12 08:21:33 +00002494 void EmitBreakStmt(const BreakStmt &S);
2495 void EmitContinueStmt(const ContinueStmt &S);
Devang Patelda5d6bb2007-10-04 23:45:31 +00002496 void EmitSwitchStmt(const SwitchStmt &S);
2497 void EmitDefaultStmt(const DefaultStmt &S);
2498 void EmitCaseStmt(const CaseStmt &S);
Devang Patel11663122007-10-08 20:57:48 +00002499 void EmitCaseStmtRange(const CaseStmt &S);
Chad Rosier6051bb92012-08-28 18:54:39 +00002500 void EmitAsmStmt(const AsmStmt &S);
Mike Stumpfc496822009-02-08 23:14:22 +00002501
Anders Carlsson2e744e82008-08-30 19:51:14 +00002502 void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S);
Anders Carlsson1963b0c2008-09-09 10:04:29 +00002503 void EmitObjCAtTryStmt(const ObjCAtTryStmt &S);
2504 void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S);
Chris Lattnere132e242008-11-15 21:26:17 +00002505 void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S);
John McCall31168b02011-06-15 23:02:42 +00002506 void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S);
Mike Stumpfc496822009-02-08 23:14:22 +00002507
Gor Nishanov8df64e92016-10-27 16:28:31 +00002508 void EmitCoroutineBody(const CoroutineBodyStmt &S);
Gor Nishanov90be1212017-03-06 21:12:54 +00002509 void EmitCoreturnStmt(const CoreturnStmt &S);
Gor Nishanov97e3b6d2016-10-03 22:44:48 +00002510 RValue EmitCoroutineIntrinsic(const CallExpr *E, unsigned int IID);
2511
John McCallb609d3f2010-07-07 06:56:46 +00002512 void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
2513 void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
John McCallb81884d2010-02-19 09:25:03 +00002514
Anders Carlsson52d78a52009-09-27 18:58:34 +00002515 void EmitCXXTryStmt(const CXXTryStmt &S);
Reid Kleckner543a16c2013-09-16 21:46:30 +00002516 void EmitSEHTryStmt(const SEHTryStmt &S);
Nico Weber9b982072014-07-07 00:12:30 +00002517 void EmitSEHLeaveStmt(const SEHLeaveStmt &S);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00002518 void EnterSEHTryStmt(const SEHTryStmt &S);
2519 void ExitSEHTryStmt(const SEHTryStmt &S);
2520
Reid Kleckner9fe7f232015-07-07 00:36:30 +00002521 void startOutlinedSEHHelper(CodeGenFunction &ParentCGF, bool IsFilter,
Reid Klecknerebaf28d2015-04-14 20:59:00 +00002522 const Stmt *OutlinedStmt);
Reid Kleckner1d59f992015-01-22 01:36:17 +00002523
2524 llvm::Function *GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
2525 const SEHExceptStmt &Except);
2526
Reid Klecknerebaf28d2015-04-14 20:59:00 +00002527 llvm::Function *GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF,
2528 const SEHFinallyStmt &Finally);
2529
Reid Kleckner9fe7f232015-07-07 00:36:30 +00002530 void EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF,
2531 llvm::Value *ParentFP,
2532 llvm::Value *EntryEBP);
Reid Kleckner1d59f992015-01-22 01:36:17 +00002533 llvm::Value *EmitSEHExceptionCode();
2534 llvm::Value *EmitSEHExceptionInfo();
Reid Kleckneraca01db2015-02-04 22:37:07 +00002535 llvm::Value *EmitSEHAbnormalTermination();
Reid Kleckner1d59f992015-01-22 01:36:17 +00002536
Reid Kleckner31a1bb02015-04-08 22:23:48 +00002537 /// Scan the outlined statement for captures from the parent function. For
2538 /// each capture, mark the capture as escaped and emit a call to
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00002539 /// llvm.localrecover. Insert the localrecover result into the LocalDeclMap.
Reid Kleckner0b9bbbf2015-06-09 17:49:42 +00002540 void EmitCapturedLocals(CodeGenFunction &ParentCGF, const Stmt *OutlinedStmt,
Reid Kleckner9fe7f232015-07-07 00:36:30 +00002541 bool IsFilter);
2542
2543 /// Recovers the address of a local in a parent function. ParentVar is the
2544 /// address of the variable used in the immediate parent function. It can
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00002545 /// either be an alloca or a call to llvm.localrecover if there are nested
Reid Kleckner9fe7f232015-07-07 00:36:30 +00002546 /// outlined functions. ParentFP is the frame pointer of the outermost parent
2547 /// frame.
John McCall7f416cc2015-09-08 08:05:57 +00002548 Address recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF,
2549 Address ParentVar,
2550 llvm::Value *ParentFP);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00002551
Aaron Ballmanb06b15a2014-06-06 12:40:24 +00002552 void EmitCXXForRangeStmt(const CXXForRangeStmt &S,
Craig Topper3cb91b22014-08-27 06:28:16 +00002553 ArrayRef<const Attr *> Attrs = None);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002554
Alexey Bataev1189bd02016-01-26 12:20:39 +00002555 /// Returns calculated size of the specified type.
2556 llvm::Value *getTypeSize(QualType Ty);
Alexey Bataev330de032014-10-29 12:21:55 +00002557 LValue InitCapturedStruct(const CapturedStmt &S);
Ben Langmuir3b4c30b2013-05-09 19:17:11 +00002558 llvm::Function *EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K);
Alexey Bataevaca7fcf2014-06-30 02:55:54 +00002559 llvm::Function *GenerateCapturedStmtFunction(const CapturedStmt &S);
John McCall7f416cc2015-09-08 08:05:57 +00002560 Address GenerateCapturedStmtArgument(const CapturedStmt &S);
Samuel Antao6d004262016-06-16 18:39:34 +00002561 llvm::Function *GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S);
Alexey Bataev2377fe92015-09-10 08:12:02 +00002562 void GenerateOpenMPCapturedVars(const CapturedStmt &S,
Samuel Antao4af1b7b2015-12-02 17:44:43 +00002563 SmallVectorImpl<llvm::Value *> &CapturedVars);
Alexey Bataev8524d152016-01-21 12:35:58 +00002564 void emitOMPSimpleStore(LValue LVal, RValue RVal, QualType RValTy,
2565 SourceLocation Loc);
Alexey Bataev420d45b2015-04-14 05:11:24 +00002566 /// \brief Perform element by element copying of arrays with type \a
2567 /// OriginalType from \a SrcAddr to \a DestAddr using copying procedure
2568 /// generated by \a CopyGen.
2569 ///
2570 /// \param DestAddr Address of the destination array.
2571 /// \param SrcAddr Address of the source array.
2572 /// \param OriginalType Type of destination and source arrays.
2573 /// \param CopyGen Copying procedure that copies value of single array element
2574 /// to another single array element.
2575 void EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +00002576 Address DestAddr, Address SrcAddr, QualType OriginalType,
2577 const llvm::function_ref<void(Address, Address)> &CopyGen);
Alexey Bataev420d45b2015-04-14 05:11:24 +00002578 /// \brief Emit proper copying of data from one variable to another.
2579 ///
2580 /// \param OriginalType Original type of the copied variables.
2581 /// \param DestAddr Destination address.
2582 /// \param SrcAddr Source address.
2583 /// \param DestVD Destination variable used in \a CopyExpr (for arrays, has
2584 /// type of the base array element).
2585 /// \param SrcVD Source variable used in \a CopyExpr (for arrays, has type of
2586 /// the base array element).
2587 /// \param Copy Actual copygin expression for copying data from \a SrcVD to \a
2588 /// DestVD.
John McCall7f416cc2015-09-08 08:05:57 +00002589 void EmitOMPCopy(QualType OriginalType,
2590 Address DestAddr, Address SrcAddr,
Alexey Bataev420d45b2015-04-14 05:11:24 +00002591 const VarDecl *DestVD, const VarDecl *SrcVD,
2592 const Expr *Copy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002593 /// \brief Emit atomic update code for constructs: \a X = \a X \a BO \a E or
2594 /// \a X = \a E \a BO \a E.
2595 ///
2596 /// \param X Value to be updated.
2597 /// \param E Update value.
2598 /// \param BO Binary operation for update operation.
2599 /// \param IsXLHSInRHSPart true if \a X is LHS in RHS part of the update
2600 /// expression, false otherwise.
2601 /// \param AO Atomic ordering of the generated atomic instructions.
2602 /// \param CommonGen Code generator for complex expressions that cannot be
2603 /// expressed through atomicrmw instruction.
Alexey Bataev5e018f92015-04-23 06:35:10 +00002604 /// \returns <true, OldAtomicValue> if simple 'atomicrmw' instruction was
2605 /// generated, <false, RValue::get(nullptr)> otherwise.
2606 std::pair<bool, RValue> EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002607 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
2608 llvm::AtomicOrdering AO, SourceLocation Loc,
2609 const llvm::function_ref<RValue(RValue)> &CommonGen);
Alexey Bataev69c62a92015-04-15 04:52:20 +00002610 bool EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
Alexey Bataev435ad7b2014-10-10 09:48:26 +00002611 OMPPrivateScope &PrivateScope);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002612 void EmitOMPPrivateClause(const OMPExecutableDirective &D,
2613 OMPPrivateScope &PrivateScope);
Samuel Antaocc10b852016-07-28 14:23:26 +00002614 void EmitOMPUseDevicePtrClause(
2615 const OMPClause &C, OMPPrivateScope &PrivateScope,
2616 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002617 /// \brief Emit code for copyin clause in \a D directive. The next code is
2618 /// generated at the start of outlined functions for directives:
2619 /// \code
2620 /// threadprivate_var1 = master_threadprivate_var1;
2621 /// operator=(threadprivate_var2, master_threadprivate_var2);
2622 /// ...
2623 /// __kmpc_barrier(&loc, global_tid);
2624 /// \endcode
2625 ///
2626 /// \param D OpenMP directive possibly with 'copyin' clause(s).
2627 /// \returns true if at least one copyin variable is found, false otherwise.
2628 bool EmitOMPCopyinClause(const OMPExecutableDirective &D);
Alexey Bataev38e89532015-04-16 04:54:05 +00002629 /// \brief Emit initial code for lastprivate variables. If some variable is
2630 /// not also firstprivate, then the default initialization is used. Otherwise
2631 /// initialization of this variable is performed by EmitOMPFirstprivateClause
2632 /// method.
2633 ///
2634 /// \param D Directive that may have 'lastprivate' directives.
2635 /// \param PrivateScope Private scope for capturing lastprivate variables for
2636 /// proper codegen in internal captured statement.
2637 ///
2638 /// \returns true if there is at least one lastprivate variable, false
2639 /// otherwise.
2640 bool EmitOMPLastprivateClauseInit(const OMPExecutableDirective &D,
2641 OMPPrivateScope &PrivateScope);
2642 /// \brief Emit final copying of lastprivate values to original variables at
2643 /// the end of the worksharing or simd directive.
2644 ///
2645 /// \param D Directive that has at least one 'lastprivate' directives.
2646 /// \param IsLastIterCond Boolean condition that must be set to 'i1 true' if
2647 /// it is the last iteration of the loop code in associated directive, or to
Alexey Bataevfc087ec2015-06-16 13:14:42 +00002648 /// 'i1 false' otherwise. If this item is nullptr, no final check is required.
Alexey Bataev38e89532015-04-16 04:54:05 +00002649 void EmitOMPLastprivateClauseFinal(const OMPExecutableDirective &D,
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002650 bool NoFinals,
Alexey Bataevfc087ec2015-06-16 13:14:42 +00002651 llvm::Value *IsLastIterCond = nullptr);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002652 /// Emit initial code for linear clauses.
2653 void EmitOMPLinearClause(const OMPLoopDirective &D,
2654 CodeGenFunction::OMPPrivateScope &PrivateScope);
2655 /// Emit final code for linear clauses.
2656 /// \param CondGen Optional conditional code for final part of codegen for
2657 /// linear clause.
2658 void EmitOMPLinearClauseFinal(
2659 const OMPLoopDirective &D,
2660 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002661 /// \brief Emit initial code for reduction variables. Creates reduction copies
2662 /// and initializes them with the values according to OpenMP standard.
2663 ///
2664 /// \param D Directive (possibly) with the 'reduction' clause.
2665 /// \param PrivateScope Private scope for capturing reduction variables for
2666 /// proper codegen in internal captured statement.
2667 ///
2668 void EmitOMPReductionClauseInit(const OMPExecutableDirective &D,
2669 OMPPrivateScope &PrivateScope);
2670 /// \brief Emit final update of reduction values to original variables at
2671 /// the end of the directive.
2672 ///
2673 /// \param D Directive that has at least one 'reduction' directives.
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002674 /// \param ReductionKind The kind of reduction to perform.
2675 void EmitOMPReductionClauseFinal(const OMPExecutableDirective &D,
2676 const OpenMPDirectiveKind ReductionKind);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002677 /// \brief Emit initial code for linear variables. Creates private copies
2678 /// and initializes them with the values according to OpenMP standard.
2679 ///
2680 /// \param D Directive (possibly) with the 'linear' clause.
2681 void EmitOMPLinearClauseInit(const OMPLoopDirective &D);
Alexey Bataev9959db52014-05-06 10:08:46 +00002682
Alexey Bataev7292c292016-04-25 12:22:29 +00002683 typedef const llvm::function_ref<void(CodeGenFunction & /*CGF*/,
2684 llvm::Value * /*OutlinedFn*/,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002685 const OMPTaskDataTy & /*Data*/)>
Alexey Bataev7292c292016-04-25 12:22:29 +00002686 TaskGenTy;
2687 void EmitOMPTaskBasedDirective(const OMPExecutableDirective &S,
2688 const RegionCodeGenTy &BodyGen,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002689 const TaskGenTy &TaskGen, OMPTaskDataTy &Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00002690
Alexey Bataev9959db52014-05-06 10:08:46 +00002691 void EmitOMPParallelDirective(const OMPParallelDirective &S);
Alexander Musman515ad8c2014-05-22 08:54:05 +00002692 void EmitOMPSimdDirective(const OMPSimdDirective &S);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002693 void EmitOMPForDirective(const OMPForDirective &S);
Alexander Musmanf82886e2014-09-18 05:12:34 +00002694 void EmitOMPForSimdDirective(const OMPForSimdDirective &S);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002695 void EmitOMPSectionsDirective(const OMPSectionsDirective &S);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002696 void EmitOMPSectionDirective(const OMPSectionDirective &S);
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002697 void EmitOMPSingleDirective(const OMPSingleDirective &S);
Alexander Musman80c22892014-07-17 08:54:58 +00002698 void EmitOMPMasterDirective(const OMPMasterDirective &S);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002699 void EmitOMPCriticalDirective(const OMPCriticalDirective &S);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002700 void EmitOMPParallelForDirective(const OMPParallelForDirective &S);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002701 void EmitOMPParallelForSimdDirective(const OMPParallelForSimdDirective &S);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002702 void EmitOMPParallelSectionsDirective(const OMPParallelSectionsDirective &S);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002703 void EmitOMPTaskDirective(const OMPTaskDirective &S);
Alexey Bataev68446b72014-07-18 07:47:19 +00002704 void EmitOMPTaskyieldDirective(const OMPTaskyieldDirective &S);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002705 void EmitOMPBarrierDirective(const OMPBarrierDirective &S);
Alexey Bataev2df347a2014-07-18 10:17:07 +00002706 void EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002707 void EmitOMPTaskgroupDirective(const OMPTaskgroupDirective &S);
Alexey Bataev6125da92014-07-21 11:26:11 +00002708 void EmitOMPFlushDirective(const OMPFlushDirective &S);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002709 void EmitOMPOrderedDirective(const OMPOrderedDirective &S);
Alexey Bataev0162e452014-07-22 10:10:35 +00002710 void EmitOMPAtomicDirective(const OMPAtomicDirective &S);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002711 void EmitOMPTargetDirective(const OMPTargetDirective &S);
Michael Wong65f367f2015-07-21 13:44:28 +00002712 void EmitOMPTargetDataDirective(const OMPTargetDataDirective &S);
Samuel Antaodf67fc42016-01-19 19:15:56 +00002713 void EmitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective &S);
Samuel Antao72590762016-01-19 20:04:50 +00002714 void EmitOMPTargetExitDataDirective(const OMPTargetExitDataDirective &S);
Samuel Antao686c70c2016-05-26 17:30:50 +00002715 void EmitOMPTargetUpdateDirective(const OMPTargetUpdateDirective &S);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002716 void EmitOMPTargetParallelDirective(const OMPTargetParallelDirective &S);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002717 void
2718 EmitOMPTargetParallelForDirective(const OMPTargetParallelForDirective &S);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002719 void EmitOMPTeamsDirective(const OMPTeamsDirective &S);
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002720 void
2721 EmitOMPCancellationPointDirective(const OMPCancellationPointDirective &S);
Alexey Bataev80909872015-07-02 11:25:17 +00002722 void EmitOMPCancelDirective(const OMPCancelDirective &S);
Alexey Bataev7292c292016-04-25 12:22:29 +00002723 void EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002724 void EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002725 void EmitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective &S);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002726 void EmitOMPDistributeDirective(const OMPDistributeDirective &S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002727 void EmitOMPDistributeLoop(const OMPDistributeDirective &S);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002728 void EmitOMPDistributeParallelForDirective(
2729 const OMPDistributeParallelForDirective &S);
Kelvin Li4a39add2016-07-05 05:00:15 +00002730 void EmitOMPDistributeParallelForSimdDirective(
2731 const OMPDistributeParallelForSimdDirective &S);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002732 void EmitOMPDistributeSimdDirective(const OMPDistributeSimdDirective &S);
Kelvin Lia579b912016-07-14 02:54:56 +00002733 void EmitOMPTargetParallelForSimdDirective(
2734 const OMPTargetParallelForSimdDirective &S);
Kelvin Li986330c2016-07-20 22:57:10 +00002735 void EmitOMPTargetSimdDirective(const OMPTargetSimdDirective &S);
Kelvin Li02532872016-08-05 14:37:37 +00002736 void EmitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective &S);
Kelvin Li4e325f72016-10-25 12:50:55 +00002737 void
2738 EmitOMPTeamsDistributeSimdDirective(const OMPTeamsDistributeSimdDirective &S);
Kelvin Li579e41c2016-11-30 23:51:03 +00002739 void EmitOMPTeamsDistributeParallelForSimdDirective(
2740 const OMPTeamsDistributeParallelForSimdDirective &S);
Kelvin Li7ade93f2016-12-09 03:24:30 +00002741 void EmitOMPTeamsDistributeParallelForDirective(
2742 const OMPTeamsDistributeParallelForDirective &S);
Kelvin Libf594a52016-12-17 05:48:59 +00002743 void EmitOMPTargetTeamsDirective(const OMPTargetTeamsDirective &S);
Kelvin Li83c451e2016-12-25 04:52:54 +00002744 void EmitOMPTargetTeamsDistributeDirective(
2745 const OMPTargetTeamsDistributeDirective &S);
Kelvin Li80e8f562016-12-29 22:16:30 +00002746 void EmitOMPTargetTeamsDistributeParallelForDirective(
2747 const OMPTargetTeamsDistributeParallelForDirective &S);
Kelvin Li1851df52017-01-03 05:23:48 +00002748 void EmitOMPTargetTeamsDistributeParallelForSimdDirective(
2749 const OMPTargetTeamsDistributeParallelForSimdDirective &S);
Kelvin Lida681182017-01-10 18:08:18 +00002750 void EmitOMPTargetTeamsDistributeSimdDirective(
2751 const OMPTargetTeamsDistributeSimdDirective &S);
Ben Langmuir3b4c30b2013-05-09 19:17:11 +00002752
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00002753 /// Emit device code for the target directive.
2754 static void EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
2755 StringRef ParentName,
2756 const OMPTargetDirective &S);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002757 static void
2758 EmitOMPTargetParallelDeviceFunction(CodeGenModule &CGM, StringRef ParentName,
2759 const OMPTargetParallelDirective &S);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002760 static void
2761 EmitOMPTargetTeamsDeviceFunction(CodeGenModule &CGM, StringRef ParentName,
2762 const OMPTargetTeamsDirective &S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002763 /// \brief Emit inner loop of the worksharing/simd construct.
2764 ///
2765 /// \param S Directive, for which the inner loop must be emitted.
2766 /// \param RequiresCleanup true, if directive has some associated private
2767 /// variables.
2768 /// \param LoopCond Bollean condition for loop continuation.
2769 /// \param IncExpr Increment expression for loop control variable.
2770 /// \param BodyGen Generator for the inner body of the inner loop.
2771 /// \param PostIncGen Genrator for post-increment code (required for ordered
2772 /// loop directvies).
2773 void EmitOMPInnerLoop(
2774 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
2775 const Expr *IncExpr,
2776 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
2777 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002778
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002779 JumpDest getOMPCancelDestination(OpenMPDirectiveKind Kind);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002780 /// Emit initial code for loop counters of loop-based directives.
2781 void EmitOMPPrivateLoopCounters(const OMPLoopDirective &S,
2782 OMPPrivateScope &LoopScope);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002783
Alexander Musmanc6388682014-12-15 07:07:06 +00002784private:
George Burgess IVe3763372016-12-22 02:50:20 +00002785 /// Helpers for blocks
2786 llvm::Value *EmitBlockLiteral(const CGBlockInfo &Info);
2787
Alexander Musmanc6388682014-12-15 07:07:06 +00002788 /// Helpers for the OpenMP loop directives.
Alexey Bataev0f34da12015-07-02 04:17:07 +00002789 void EmitOMPLoopBody(const OMPLoopDirective &D, JumpDest LoopExit);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002790 void EmitOMPSimdInit(const OMPLoopDirective &D, bool IsMonotonic = false);
Alexey Bataevef549a82016-03-09 09:49:09 +00002791 void EmitOMPSimdFinal(
2792 const OMPLoopDirective &D,
2793 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen);
Alexey Bataev38e89532015-04-16 04:54:05 +00002794 /// \brief Emit code for the worksharing loop-based directive.
2795 /// \return true, if this construct has any lastprivate clause, false -
2796 /// otherwise.
2797 bool EmitOMPWorksharingLoop(const OMPLoopDirective &S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002798 void EmitOMPOuterLoop(bool IsMonotonic, bool DynamicOrOrdered,
2799 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
2800 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002801 void EmitOMPForOuterLoop(const OpenMPScheduleTy &ScheduleKind,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002802 bool IsMonotonic, const OMPLoopDirective &S,
2803 OMPPrivateScope &LoopScope, bool Ordered, Address LB,
2804 Address UB, Address ST, Address IL,
2805 llvm::Value *Chunk);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002806 void EmitOMPDistributeOuterLoop(
2807 OpenMPDistScheduleClauseKind ScheduleKind,
2808 const OMPDistributeDirective &S, OMPPrivateScope &LoopScope,
2809 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk);
Alexey Bataev0f34da12015-07-02 04:17:07 +00002810 /// \brief Emit code for sections directive.
Alexey Bataev3392d762016-02-16 11:18:12 +00002811 void EmitSections(const OMPExecutableDirective &S);
Alexander Musmanc6388682014-12-15 07:07:06 +00002812
2813public:
Alexander Musmana5f070a2014-10-01 06:03:56 +00002814
Chris Lattner208ae962007-05-30 17:57:17 +00002815 //===--------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +00002816 // LValue Expression Emission
2817 //===--------------------------------------------------------------------===//
Chris Lattner8394d792007-06-05 20:53:16 +00002818
Daniel Dunbarc79407f2009-02-05 07:09:07 +00002819 /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
2820 RValue GetUndefRValue(QualType Ty);
2821
Daniel Dunbarbb197e42009-01-09 16:50:52 +00002822 /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E
2823 /// and issue an ErrorUnsupported style diagnostic (using the
2824 /// provided Name).
2825 RValue EmitUnsupportedRValue(const Expr *E,
2826 const char *Name);
2827
Mike Stumpfc496822009-02-08 23:14:22 +00002828 /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue
2829 /// an ErrorUnsupported style diagnostic (using the provided Name).
Daniel Dunbarf2e69882008-08-25 20:45:57 +00002830 LValue EmitUnsupportedLValue(const Expr *E,
2831 const char *Name);
2832
Chris Lattner8394d792007-06-05 20:53:16 +00002833 /// EmitLValue - Emit code to compute a designator that specifies the location
2834 /// of the expression.
2835 ///
2836 /// This can return one of two things: a simple address or a bitfield
2837 /// reference. In either case, the LLVM Value* in the LValue structure is
2838 /// guaranteed to be an LLVM pointer type.
2839 ///
2840 /// If this returns a bitfield reference, nothing about the pointee type of
2841 /// the LLVM value is known: For example, it may not be a pointer to an
2842 /// integer.
2843 ///
2844 /// If this returns a normal address, and if the lvalue's C type is fixed
2845 /// size, this method guarantees that the returned pointer type will point to
2846 /// an LLVM type of the same size of the lvalue's type. If the lvalue has a
2847 /// variable length type, this is not possible.
2848 ///
Chris Lattnerd7f58862007-06-02 05:24:33 +00002849 LValue EmitLValue(const Expr *E);
Mike Stumpfc496822009-02-08 23:14:22 +00002850
Richard Smith4d1458e2012-09-08 02:08:36 +00002851 /// \brief Same as EmitLValue but additionally we generate checking code to
2852 /// guard against undefined behavior. This is only suitable when we know
2853 /// that the address will be used to access the object.
2854 LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK);
Mike Stump3f6f9fe2009-12-16 02:57:00 +00002855
John McCall7f416cc2015-09-08 08:05:57 +00002856 RValue convertTempToRValue(Address addr, QualType type,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002857 SourceLocation Loc);
John McCall47fb9502013-03-07 21:37:08 +00002858
John McCalla8ec7eb2013-03-07 21:37:17 +00002859 void EmitAtomicInit(Expr *E, LValue lvalue);
2860
David Majnemera5b195a2015-02-14 01:35:12 +00002861 bool LValueIsSuitableForInlineAtomic(LValue Src);
David Majnemera5b195a2015-02-14 01:35:12 +00002862
2863 RValue EmitAtomicLoad(LValue LV, SourceLocation SL,
2864 AggValueSlot Slot = AggValueSlot::ignored());
2865
Nick Lewycky2d84e842013-10-02 02:29:49 +00002866 RValue EmitAtomicLoad(LValue lvalue, SourceLocation loc,
David Majnemera5b195a2015-02-14 01:35:12 +00002867 llvm::AtomicOrdering AO, bool IsVolatile = false,
John McCalla8ec7eb2013-03-07 21:37:17 +00002868 AggValueSlot slot = AggValueSlot::ignored());
2869
2870 void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit);
2871
David Majnemera5b195a2015-02-14 01:35:12 +00002872 void EmitAtomicStore(RValue rvalue, LValue lvalue, llvm::AtomicOrdering AO,
2873 bool IsVolatile, bool isInit);
2874
Alexey Bataevb4505a72015-03-30 05:20:59 +00002875 std::pair<RValue, llvm::Value *> EmitAtomicCompareExchange(
Alexey Bataev452d8e12014-12-15 05:25:25 +00002876 LValue Obj, RValue Expected, RValue Desired, SourceLocation Loc,
JF Bastien92f4ef12016-04-06 17:26:42 +00002877 llvm::AtomicOrdering Success =
2878 llvm::AtomicOrdering::SequentiallyConsistent,
2879 llvm::AtomicOrdering Failure =
2880 llvm::AtomicOrdering::SequentiallyConsistent,
Alexey Bataev452d8e12014-12-15 05:25:25 +00002881 bool IsWeak = false, AggValueSlot Slot = AggValueSlot::ignored());
2882
Alexey Bataevb4505a72015-03-30 05:20:59 +00002883 void EmitAtomicUpdate(LValue LVal, llvm::AtomicOrdering AO,
Alexey Bataevf0ab5532015-05-15 08:36:34 +00002884 const llvm::function_ref<RValue(RValue)> &UpdateOp,
Alexey Bataevb4505a72015-03-30 05:20:59 +00002885 bool IsVolatile);
2886
John McCall3a7f6922010-10-27 20:58:56 +00002887 /// EmitToMemory - Change a scalar value from its value
2888 /// representation to its in-memory representation.
2889 llvm::Value *EmitToMemory(llvm::Value *Value, QualType Ty);
2890
2891 /// EmitFromMemory - Change a scalar value from its memory
2892 /// representation to its value representation.
2893 llvm::Value *EmitFromMemory(llvm::Value *Value, QualType Ty);
2894
Vedant Kumar5a972652017-02-27 19:46:19 +00002895 /// Check if the scalar \p Value is within the valid range for the given
2896 /// type \p Ty.
2897 ///
2898 /// Returns true if a check is needed (even if the range is unknown).
2899 bool EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
2900 SourceLocation Loc);
2901
Daniel Dunbar1d425462009-02-10 00:57:50 +00002902 /// EmitLoadOfScalar - Load a scalar value from an address, taking
2903 /// care to appropriately convert from the memory representation to
2904 /// the LLVM value representation.
John McCall7f416cc2015-09-08 08:05:57 +00002905 llvm::Value *EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002906 SourceLocation Loc,
John McCall7f416cc2015-09-08 08:05:57 +00002907 AlignmentSource AlignSource =
2908 AlignmentSource::Type,
Craig Topper8a13c412014-05-21 05:09:00 +00002909 llvm::MDNode *TBAAInfo = nullptr,
Manman Renc451e572013-04-04 21:53:22 +00002910 QualType TBAABaseTy = QualType(),
Michael Zolotukhin84df1232015-09-08 23:52:33 +00002911 uint64_t TBAAOffset = 0,
2912 bool isNontemporal = false);
John McCall55e1fbc2011-06-25 02:11:03 +00002913
2914 /// EmitLoadOfScalar - Load a scalar value from an address, taking
2915 /// care to appropriately convert from the memory representation to
2916 /// the LLVM value representation. The l-value must be a simple
2917 /// l-value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002918 llvm::Value *EmitLoadOfScalar(LValue lvalue, SourceLocation Loc);
Daniel Dunbar1d425462009-02-10 00:57:50 +00002919
2920 /// EmitStoreOfScalar - Store a scalar value to an address, taking
2921 /// care to appropriately convert from the memory representation to
2922 /// the LLVM value representation.
John McCall7f416cc2015-09-08 08:05:57 +00002923 void EmitStoreOfScalar(llvm::Value *Value, Address Addr,
2924 bool Volatile, QualType Ty,
2925 AlignmentSource AlignSource = AlignmentSource::Type,
Craig Topper8a13c412014-05-21 05:09:00 +00002926 llvm::MDNode *TBAAInfo = nullptr, bool isInit = false,
Manman Renc451e572013-04-04 21:53:22 +00002927 QualType TBAABaseTy = QualType(),
Michael Zolotukhin84df1232015-09-08 23:52:33 +00002928 uint64_t TBAAOffset = 0, bool isNontemporal = false);
John McCall55e1fbc2011-06-25 02:11:03 +00002929
2930 /// EmitStoreOfScalar - Store a scalar value to an address, taking
2931 /// care to appropriately convert from the memory representation to
2932 /// the LLVM value representation. The l-value must be a simple
David Chisnallfa35df62012-01-16 17:27:18 +00002933 /// l-value. The isInit flag indicates whether this is an initialization.
2934 /// If so, atomic qualifiers are ignored and the store is always non-atomic.
2935 void EmitStoreOfScalar(llvm::Value *value, LValue lvalue, bool isInit=false);
Daniel Dunbar1d425462009-02-10 00:57:50 +00002936
Chris Lattner8394d792007-06-05 20:53:16 +00002937 /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
2938 /// this method emits the address of the lvalue, then loads the result as an
2939 /// rvalue, returning the rvalue.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002940 RValue EmitLoadOfLValue(LValue V, SourceLocation Loc);
John McCall55e1fbc2011-06-25 02:11:03 +00002941 RValue EmitLoadOfExtVectorElementLValue(LValue V);
2942 RValue EmitLoadOfBitfieldLValue(LValue LV);
Renato Golin230c5eb2014-05-19 18:15:42 +00002943 RValue EmitLoadOfGlobalRegLValue(LValue LV);
Mike Stumpfc496822009-02-08 23:14:22 +00002944
Chris Lattner8394d792007-06-05 20:53:16 +00002945 /// EmitStoreThroughLValue - Store the specified rvalue into the specified
2946 /// lvalue, where both are guaranteed to the have the same type, and that type
2947 /// is 'Ty'.
David Blaikie66e41972015-01-14 07:38:27 +00002948 void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit = false);
John McCall55e1fbc2011-06-25 02:11:03 +00002949 void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst);
Renato Golin230c5eb2014-05-19 18:15:42 +00002950 void EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst);
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00002951
Nick Lewycky2d84e842013-10-02 02:29:49 +00002952 /// EmitStoreThroughBitfieldLValue - Store Src into Dst with same constraints
2953 /// as EmitStoreThroughLValue.
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00002954 ///
Mike Stumpfc496822009-02-08 23:14:22 +00002955 /// \param Result [out] - If non-null, this will be set to a Value* for the
2956 /// bit-field contents after the store, appropriate for use as the result of
2957 /// an assignment to the bit-field.
John McCall55e1fbc2011-06-25 02:11:03 +00002958 void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
Craig Topper8a13c412014-05-21 05:09:00 +00002959 llvm::Value **Result=nullptr);
Mike Stumpfc496822009-02-08 23:14:22 +00002960
John McCall4f29b492010-11-16 23:07:28 +00002961 /// Emit an l-value for an assignment (simple or compound) of complex type.
2962 LValue EmitComplexAssignmentLValue(const BinaryOperator *E);
John McCalla2342eb2010-12-05 02:00:02 +00002963 LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E);
Richard Smith527473d2015-02-12 21:23:20 +00002964 LValue EmitScalarCompoundAssignWithComplex(const CompoundAssignOperator *E,
2965 llvm::Value *&Result);
John McCall4f29b492010-11-16 23:07:28 +00002966
Chris Lattner57540c52011-04-15 05:22:18 +00002967 // Note: only available for agg return types
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00002968 LValue EmitBinaryOperatorLValue(const BinaryOperator *E);
John McCalla2342eb2010-12-05 02:00:02 +00002969 LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E);
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00002970 // Note: only available for agg return types
Christopher Lambd91c3d42007-12-29 05:02:41 +00002971 LValue EmitCallExprLValue(const CallExpr *E);
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00002972 // Note: only available for agg return types
2973 LValue EmitVAArgExprLValue(const VAArgExpr *E);
Chris Lattnerd7f58862007-06-02 05:24:33 +00002974 LValue EmitDeclRefLValue(const DeclRefExpr *E);
Chris Lattner4347e3692007-06-06 04:54:52 +00002975 LValue EmitStringLiteralLValue(const StringLiteral *E);
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002976 LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E);
Chris Lattner6307f192008-08-10 01:53:14 +00002977 LValue EmitPredefinedLValue(const PredefinedExpr *E);
Chris Lattner8394d792007-06-05 20:53:16 +00002978 LValue EmitUnaryOpLValue(const UnaryOperator *E);
Richard Smith539e4a72013-02-23 02:53:19 +00002979 LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
2980 bool Accessed = false);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002981 LValue EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
2982 bool IsLowerBound = true);
Nate Begemance4d7fc2008-04-18 23:10:10 +00002983 LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E);
Devang Patel3e11cce2007-10-23 02:10:49 +00002984 LValue EmitMemberExpr(const MemberExpr *E);
Fariborz Jahanian531c16f2009-12-09 23:35:29 +00002985 LValue EmitObjCIsaExpr(const ObjCIsaExpr *E);
Eli Friedman9fd8b682008-05-13 23:18:27 +00002986 LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E);
Richard Smithbb653bd2012-05-14 21:57:21 +00002987 LValue EmitInitListLValue(const InitListExpr *E);
John McCallc07a0c72011-02-17 10:25:35 +00002988 LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E);
Chris Lattner28bcf1a2009-03-18 18:28:57 +00002989 LValue EmitCastLValue(const CastExpr *E);
Douglas Gregorfe314812011-06-21 17:03:29 +00002990 LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
John McCall1bf58462011-02-16 08:02:54 +00002991 LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e);
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00002992
John McCall7f416cc2015-09-08 08:05:57 +00002993 Address EmitExtVectorElementLValue(LValue V);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002994
Nick Lewycky2d84e842013-10-02 02:29:49 +00002995 RValue EmitRValueForField(LValue LV, const FieldDecl *FD, SourceLocation Loc);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002996
John McCall7f416cc2015-09-08 08:05:57 +00002997 Address EmitArrayToPointerDecay(const Expr *Array,
2998 AlignmentSource *AlignSource = nullptr);
2999
John McCall71335052012-03-10 03:05:10 +00003000 class ConstantEmission {
3001 llvm::PointerIntPair<llvm::Constant*, 1, bool> ValueAndIsReference;
3002 ConstantEmission(llvm::Constant *C, bool isReference)
3003 : ValueAndIsReference(C, isReference) {}
3004 public:
3005 ConstantEmission() {}
3006 static ConstantEmission forReference(llvm::Constant *C) {
3007 return ConstantEmission(C, true);
3008 }
3009 static ConstantEmission forValue(llvm::Constant *C) {
3010 return ConstantEmission(C, false);
3011 }
3012
Aaron Ballman67347662015-02-15 22:00:28 +00003013 explicit operator bool() const {
Craig Topper8a13c412014-05-21 05:09:00 +00003014 return ValueAndIsReference.getOpaqueValue() != nullptr;
3015 }
John McCall71335052012-03-10 03:05:10 +00003016
3017 bool isReference() const { return ValueAndIsReference.getInt(); }
3018 LValue getReferenceLValue(CodeGenFunction &CGF, Expr *refExpr) const {
3019 assert(isReference());
3020 return CGF.MakeNaturalAlignAddrLValue(ValueAndIsReference.getPointer(),
3021 refExpr->getType());
3022 }
3023
3024 llvm::Constant *getValue() const {
3025 assert(!isReference());
3026 return ValueAndIsReference.getPointer();
3027 }
3028 };
3029
John McCall113bee02012-03-10 09:33:50 +00003030 ConstantEmission tryEmitAsConstant(DeclRefExpr *refExpr);
John McCall71335052012-03-10 03:05:10 +00003031
John McCallfe96e0b2011-11-06 09:01:30 +00003032 RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e,
3033 AggValueSlot slot = AggValueSlot::ignored());
3034 LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e);
3035
Daniel Dunbar722f4242009-04-22 05:08:15 +00003036 llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003037 const ObjCIvarDecl *Ivar);
Eli Friedman7f1ff602012-04-16 03:54:45 +00003038 LValue EmitLValueForField(LValue Base, const FieldDecl* Field);
John McCalldec348f72013-05-03 07:33:41 +00003039 LValue EmitLValueForLambdaField(const FieldDecl *Field);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003040
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003041 /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that
3042 /// if the Field is a reference, this will return the address of the reference
3043 /// and not the address of the value stored in the reference.
Eli Friedman7f1ff602012-04-16 03:54:45 +00003044 LValue EmitLValueForFieldInitialization(LValue Base,
3045 const FieldDecl* Field);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003046
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00003047 LValue EmitLValueForIvar(QualType ObjectTy,
3048 llvm::Value* Base, const ObjCIvarDecl *Ivar,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003049 unsigned CVRQualifiers);
3050
Anders Carlsson3be22e22009-05-30 23:23:33 +00003051 LValue EmitCXXConstructLValue(const CXXConstructExpr *E);
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00003052 LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E);
Eli Friedman5bc17122012-02-08 05:34:55 +00003053 LValue EmitLambdaLValue(const LambdaExpr *E);
Mike Stumpc9b231c2009-11-15 08:09:41 +00003054 LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E);
Nico Webercf4ff5862012-10-11 10:13:44 +00003055 LValue EmitCXXUuidofLValue(const CXXUuidofExpr *E);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003056
Daniel Dunbarc8317a42008-08-23 10:51:21 +00003057 LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E);
Chris Lattner4bd55962008-03-30 23:03:07 +00003058 LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E);
Chris Lattnera4185c52009-04-25 19:35:26 +00003059 LValue EmitStmtExprLValue(const StmtExpr *E);
Fariborz Jahanianffba6622009-10-22 22:57:31 +00003060 LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E);
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00003061 LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E);
Peter Collingbourneeeb56ab2016-09-13 01:13:19 +00003062 void EmitDeclRefExprDbgValue(const DeclRefExpr *E, const APValue &Init);
John McCallc07a0c72011-02-17 10:25:35 +00003063
Chris Lattnerd7f58862007-06-02 05:24:33 +00003064 //===--------------------------------------------------------------------===//
Chris Lattner6278e6a2007-08-11 00:04:45 +00003065 // Scalar Expression Emission
Chris Lattner208ae962007-05-30 17:57:17 +00003066 //===--------------------------------------------------------------------===//
3067
Mike Stumpfc496822009-02-08 23:14:22 +00003068 /// EmitCall - Generate a call of the given function, expecting the given
3069 /// result type, and using the given argument list which specifies both the
3070 /// LLVM arguments and the types they were derived from.
John McCallb92ab1a2016-10-26 23:46:34 +00003071 RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee,
Samuel Antao798f11c2015-11-23 22:04:44 +00003072 ReturnValueSlot ReturnValue, const CallArgList &Args,
Craig Topper8a13c412014-05-21 05:09:00 +00003073 llvm::Instruction **callOrInvoke = nullptr);
Mike Stump11289f42009-09-09 15:08:12 +00003074
John McCallb92ab1a2016-10-26 23:46:34 +00003075 RValue EmitCall(QualType FnType, const CGCallee &Callee, const CallExpr *E,
Anders Carlsson17490832009-12-24 20:40:36 +00003076 ReturnValueSlot ReturnValue,
Peter Collingbournef7706832014-12-12 23:41:25 +00003077 llvm::Value *Chain = nullptr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003078 RValue EmitCallExpr(const CallExpr *E,
Anders Carlsson17490832009-12-24 20:40:36 +00003079 ReturnValueSlot ReturnValue = ReturnValueSlot());
John McCallb92ab1a2016-10-26 23:46:34 +00003080 RValue EmitSimpleCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
3081 CGCallee EmitCallee(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00003082
Eric Christopherc7e79db2015-11-12 00:44:04 +00003083 void checkTargetFeatures(const CallExpr *E, const FunctionDecl *TargetDecl);
Eric Christopher15709992015-10-15 23:47:11 +00003084
John McCall882987f2013-02-28 19:01:20 +00003085 llvm::CallInst *EmitRuntimeCall(llvm::Value *callee,
3086 const Twine &name = "");
3087 llvm::CallInst *EmitRuntimeCall(llvm::Value *callee,
3088 ArrayRef<llvm::Value*> args,
3089 const Twine &name = "");
3090 llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee,
3091 const Twine &name = "");
3092 llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee,
3093 ArrayRef<llvm::Value*> args,
3094 const Twine &name = "");
3095
John McCallbd309292010-07-06 01:34:17 +00003096 llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee,
Chris Lattner54b16772011-07-23 17:14:25 +00003097 ArrayRef<llvm::Value *> Args,
Chris Lattner62ff6e82011-07-20 07:06:53 +00003098 const Twine &Name = "");
John McCall882987f2013-02-28 19:01:20 +00003099 llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee,
3100 ArrayRef<llvm::Value*> args,
3101 const Twine &name = "");
3102 llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee,
3103 const Twine &name = "");
3104 void EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
3105 ArrayRef<llvm::Value*> args);
John McCallbd309292010-07-06 01:34:17 +00003106
John McCallb92ab1a2016-10-26 23:46:34 +00003107 CGCallee BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
3108 NestedNameSpecifier *Qual,
3109 llvm::Type *Ty);
Fariborz Jahanian265c3252011-02-01 23:22:34 +00003110
John McCallb92ab1a2016-10-26 23:46:34 +00003111 CGCallee BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD,
3112 CXXDtorType Type,
3113 const CXXRecordDecl *RD);
Anders Carlssone828c362009-11-13 04:45:41 +00003114
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00003115 RValue
John McCallb92ab1a2016-10-26 23:46:34 +00003116 EmitCXXMemberOrOperatorCall(const CXXMethodDecl *Method,
3117 const CGCallee &Callee,
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00003118 ReturnValueSlot ReturnValue, llvm::Value *This,
3119 llvm::Value *ImplicitParam,
Richard Smith762672a2016-09-28 19:09:10 +00003120 QualType ImplicitParamTy, const CallExpr *E,
3121 CallArgList *RtlArgs);
John McCallb92ab1a2016-10-26 23:46:34 +00003122 RValue EmitCXXDestructorCall(const CXXDestructorDecl *DD,
3123 const CGCallee &Callee,
Alexey Samsonovae81bbb2016-03-10 00:20:37 +00003124 llvm::Value *This, llvm::Value *ImplicitParam,
3125 QualType ImplicitParamTy, const CallExpr *E,
3126 StructorType Type);
Anders Carlssonbfb36712009-12-24 21:13:40 +00003127 RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E,
3128 ReturnValueSlot ReturnValue);
Nico Weberaad4af62014-12-03 01:21:41 +00003129 RValue EmitCXXMemberOrOperatorMemberCallExpr(const CallExpr *CE,
3130 const CXXMethodDecl *MD,
3131 ReturnValueSlot ReturnValue,
3132 bool HasQualifier,
3133 NestedNameSpecifier *Qualifier,
3134 bool IsArrow, const Expr *Base);
3135 // Compute the object pointer.
John McCall7f416cc2015-09-08 08:05:57 +00003136 Address EmitCXXMemberDataPointerAddress(const Expr *E, Address base,
3137 llvm::Value *memberPtr,
3138 const MemberPointerType *memberPtrType,
3139 AlignmentSource *AlignSource = nullptr);
Anders Carlssonbfb36712009-12-24 21:13:40 +00003140 RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
3141 ReturnValueSlot ReturnValue);
Ted Kremenek08e17112008-06-17 02:43:46 +00003142
Anders Carlsson4034a952009-05-27 04:18:27 +00003143 RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
Anders Carlssonbfb36712009-12-24 21:13:40 +00003144 const CXXMethodDecl *MD,
3145 ReturnValueSlot ReturnValue);
John McCallb92ab1a2016-10-26 23:46:34 +00003146 RValue EmitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
Mike Stump11289f42009-09-09 15:08:12 +00003147
Peter Collingbournefe883422011-10-06 18:29:37 +00003148 RValue EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
3149 ReturnValueSlot ReturnValue);
3150
Arpith Chacko Jacobcdda3daa2017-01-29 20:49:31 +00003151 RValue EmitNVPTXDevicePrintfCallExpr(const CallExpr *E,
3152 ReturnValueSlot ReturnValue);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003153
Mike Stump11289f42009-09-09 15:08:12 +00003154 RValue EmitBuiltinExpr(const FunctionDecl *FD,
Peter Collingbournef7706832014-12-12 23:41:25 +00003155 unsigned BuiltinID, const CallExpr *E,
3156 ReturnValueSlot ReturnValue);
Chris Lattner8394d792007-06-05 20:53:16 +00003157
Anders Carlssonbfb36712009-12-24 21:13:40 +00003158 RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
Mike Stumpc6ea7c12009-02-17 17:00:02 +00003159
Mike Stumpfc496822009-02-08 23:14:22 +00003160 /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call
3161 /// is unhandled by the current target.
Daniel Dunbareca513d2008-10-10 00:24:54 +00003162 llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3163
Kevin Qin1718af62013-11-14 02:45:18 +00003164 llvm::Value *EmitAArch64CompareBuiltinExpr(llvm::Value *Op, llvm::Type *Ty,
3165 const llvm::CmpInst::Predicate Fp,
3166 const llvm::CmpInst::Predicate Ip,
3167 const llvm::Twine &Name = "");
Chris Lattner5cc15e02010-03-03 19:03:45 +00003168 llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
Tim Northover8fe03d62014-02-21 11:57:24 +00003169
3170 llvm::Value *EmitCommonNeonBuiltinExpr(unsigned BuiltinID,
3171 unsigned LLVMIntrinsic,
3172 unsigned AltLLVMIntrinsic,
3173 const char *NameHint,
3174 unsigned Modifier,
3175 const CallExpr *E,
Tim Northover027b4ee2014-01-31 10:46:45 +00003176 SmallVectorImpl<llvm::Value *> &Ops,
John McCall7f416cc2015-09-08 08:05:57 +00003177 Address PtrOp0, Address PtrOp1);
Tim Northover8fe03d62014-02-21 11:57:24 +00003178 llvm::Function *LookupNeonLLVMIntrinsic(unsigned IntrinsicID,
3179 unsigned Modifier, llvm::Type *ArgTy,
3180 const CallExpr *E);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003181 llvm::Value *EmitNeonCall(llvm::Function *F,
Chris Lattner01cf8db2011-07-20 06:58:45 +00003182 SmallVectorImpl<llvm::Value*> &O,
Bob Wilson482afae2010-12-08 22:37:56 +00003183 const char *name,
Nate Begeman91e1fea2010-06-14 05:21:25 +00003184 unsigned shift = 0, bool rightshift = false);
Bob Wilson210f6dd2010-12-07 22:40:02 +00003185 llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx);
Chris Lattner2192fe52011-07-18 04:24:23 +00003186 llvm::Value *EmitNeonShiftVector(llvm::Value *V, llvm::Type *Ty,
Nate Begeman91e1fea2010-06-14 05:21:25 +00003187 bool negateForRightShift);
Amaury de la Vieuville21bf6ed2013-10-04 13:13:15 +00003188 llvm::Value *EmitNeonRShiftImm(llvm::Value *Vec, llvm::Value *Amt,
3189 llvm::Type *Ty, bool usgn, const char *name);
Tim Northovera2ee4332014-03-29 15:09:45 +00003190 llvm::Value *vectorWrapScalar16(llvm::Value *Op);
Tim Northover573cbee2014-05-24 12:52:07 +00003191 llvm::Value *EmitAArch64BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003192
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00003193 llvm::Value *BuildVector(ArrayRef<llvm::Value*> Ops);
Anders Carlsson895af082007-12-09 23:17:02 +00003194 llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3195 llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
Matt Arsenault3ea39f92015-06-19 17:54:10 +00003196 llvm::Value *EmitAMDGPUBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00003197 llvm::Value *EmitSystemZBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
Artem Belevichd21e5c62015-06-25 18:29:42 +00003198 llvm::Value *EmitNVPTXBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
Dan Gohmanc2853072015-09-03 22:51:53 +00003199 llvm::Value *EmitWebAssemblyBuiltinExpr(unsigned BuiltinID,
3200 const CallExpr *E);
Mike Stumpfc496822009-02-08 23:14:22 +00003201
Albert Gutowski2a0621e2016-10-12 22:01:05 +00003202private:
3203 enum class MSVCIntrin;
3204
3205public:
3206 llvm::Value *EmitMSVCBuiltinExpr(MSVCIntrin BuiltinID, const CallExpr *E);
3207
Erik Pilkington9c42a8d2017-02-23 21:08:08 +00003208 llvm::Value *EmitBuiltinAvailable(ArrayRef<llvm::Value *> Args);
3209
Daniel Dunbar66912a12008-08-20 00:28:19 +00003210 llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
Chris Lattner2da04b32007-08-24 05:35:26 +00003211 llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
Patrick Beard0caa3942012-04-19 00:25:12 +00003212 llvm::Value *EmitObjCBoxedExpr(const ObjCBoxedExpr *E);
Ted Kremeneke65b0862012-03-06 20:05:56 +00003213 llvm::Value *EmitObjCArrayLiteral(const ObjCArrayLiteral *E);
3214 llvm::Value *EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E);
3215 llvm::Value *EmitObjCCollectionLiteral(const Expr *E,
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +00003216 const ObjCMethodDecl *MethodWithObjects);
Chris Lattnerb1d329d2008-06-24 17:04:18 +00003217 llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E);
John McCall78a15112010-05-22 01:48:05 +00003218 RValue EmitObjCMessageExpr(const ObjCMessageExpr *E,
3219 ReturnValueSlot Return = ReturnValueSlot());
Chris Lattnerb1d329d2008-06-24 17:04:18 +00003220
John McCall31168b02011-06-15 23:02:42 +00003221 /// Retrieves the default cleanup kind for an ARC cleanup.
3222 /// Except under -fobjc-arc-eh, ARC cleanups are normal-only.
3223 CleanupKind getARCCleanupKind() {
3224 return CGM.getCodeGenOpts().ObjCAutoRefCountExceptions
3225 ? NormalAndEHCleanup : NormalCleanup;
3226 }
3227
3228 // ARC primitives.
John McCall7f416cc2015-09-08 08:05:57 +00003229 void EmitARCInitWeak(Address addr, llvm::Value *value);
3230 void EmitARCDestroyWeak(Address addr);
John McCallb04ecb72015-10-21 18:06:43 +00003231 llvm::Value *EmitARCLoadWeak(Address addr);
John McCall7f416cc2015-09-08 08:05:57 +00003232 llvm::Value *EmitARCLoadWeakRetained(Address addr);
3233 llvm::Value *EmitARCStoreWeak(Address addr, llvm::Value *value, bool ignored);
3234 void EmitARCCopyWeak(Address dst, Address src);
3235 void EmitARCMoveWeak(Address dst, Address src);
John McCall31168b02011-06-15 23:02:42 +00003236 llvm::Value *EmitARCRetainAutorelease(QualType type, llvm::Value *value);
3237 llvm::Value *EmitARCRetainAutoreleaseNonBlock(llvm::Value *value);
John McCall55e1fbc2011-06-25 02:11:03 +00003238 llvm::Value *EmitARCStoreStrong(LValue lvalue, llvm::Value *value,
John McCallcdda29c2013-03-13 03:10:54 +00003239 bool resultIgnored);
John McCall7f416cc2015-09-08 08:05:57 +00003240 llvm::Value *EmitARCStoreStrongCall(Address addr, llvm::Value *value,
John McCallcdda29c2013-03-13 03:10:54 +00003241 bool resultIgnored);
John McCall31168b02011-06-15 23:02:42 +00003242 llvm::Value *EmitARCRetain(QualType type, llvm::Value *value);
Pete Cooper94867712016-03-21 20:50:03 +00003243 llvm::Value *EmitARCRetainNonBlock(llvm::Value *value);
John McCallff613032011-10-04 06:23:45 +00003244 llvm::Value *EmitARCRetainBlock(llvm::Value *value, bool mandatory);
John McCall7f416cc2015-09-08 08:05:57 +00003245 void EmitARCDestroyStrong(Address addr, ARCPreciseLifetime_t precise);
John McCallcdda29c2013-03-13 03:10:54 +00003246 void EmitARCRelease(llvm::Value *value, ARCPreciseLifetime_t precise);
Pete Cooper94867712016-03-21 20:50:03 +00003247 llvm::Value *EmitARCAutorelease(llvm::Value *value);
John McCall31168b02011-06-15 23:02:42 +00003248 llvm::Value *EmitARCAutoreleaseReturnValue(llvm::Value *value);
3249 llvm::Value *EmitARCRetainAutoreleaseReturnValue(llvm::Value *value);
3250 llvm::Value *EmitARCRetainAutoreleasedReturnValue(llvm::Value *value);
John McCalle399e5b2016-01-27 18:32:30 +00003251 llvm::Value *EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value);
John McCall31168b02011-06-15 23:02:42 +00003252
3253 std::pair<LValue,llvm::Value*>
3254 EmitARCStoreAutoreleasing(const BinaryOperator *e);
3255 std::pair<LValue,llvm::Value*>
3256 EmitARCStoreStrong(const BinaryOperator *e, bool ignored);
John McCalle399e5b2016-01-27 18:32:30 +00003257 std::pair<LValue,llvm::Value*>
3258 EmitARCStoreUnsafeUnretained(const BinaryOperator *e, bool ignored);
John McCall31168b02011-06-15 23:02:42 +00003259
John McCall248512a2011-10-01 10:32:24 +00003260 llvm::Value *EmitObjCThrowOperand(const Expr *expr);
John McCall31168b02011-06-15 23:02:42 +00003261 llvm::Value *EmitObjCConsumeObject(QualType T, llvm::Value *Ptr);
3262 llvm::Value *EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr);
3263
John McCallff613032011-10-04 06:23:45 +00003264 llvm::Value *EmitARCExtendBlockObject(const Expr *expr);
John McCalle399e5b2016-01-27 18:32:30 +00003265 llvm::Value *EmitARCReclaimReturnedObject(const Expr *e,
3266 bool allowUnsafeClaim);
John McCall31168b02011-06-15 23:02:42 +00003267 llvm::Value *EmitARCRetainScalarExpr(const Expr *expr);
3268 llvm::Value *EmitARCRetainAutoreleaseScalarExpr(const Expr *expr);
John McCalle399e5b2016-01-27 18:32:30 +00003269 llvm::Value *EmitARCUnsafeUnretainedScalarExpr(const Expr *expr);
John McCall31168b02011-06-15 23:02:42 +00003270
Craig Topper00bbdcf2014-06-28 23:22:23 +00003271 void EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values);
John McCalleff18842013-03-23 02:35:54 +00003272
John McCall82fe67b2011-07-09 01:37:26 +00003273 static Destroyer destroyARCStrongImprecise;
3274 static Destroyer destroyARCStrongPrecise;
3275 static Destroyer destroyARCWeak;
3276
John McCall31168b02011-06-15 23:02:42 +00003277 void EmitObjCAutoreleasePoolPop(llvm::Value *Ptr);
3278 llvm::Value *EmitObjCAutoreleasePoolPush();
3279 llvm::Value *EmitObjCMRRAutoreleasePoolPush();
3280 void EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr);
3281 void EmitObjCMRRAutoreleasePoolPop(llvm::Value *Ptr);
3282
Richard Smitha1c9d4d2013-06-12 23:38:09 +00003283 /// \brief Emits a reference binding to the passed in expression.
3284 RValue EmitReferenceBindingToExpr(const Expr *E);
Anders Carlssonab0ddb52010-01-31 18:34:51 +00003285
Chris Lattner6278e6a2007-08-11 00:04:45 +00003286 //===--------------------------------------------------------------------===//
Chris Lattnerbda69f82007-08-26 23:13:56 +00003287 // Expression Emission
Chris Lattner6278e6a2007-08-11 00:04:45 +00003288 //===--------------------------------------------------------------------===//
Chris Lattnerbda69f82007-08-26 23:13:56 +00003289
3290 // Expressions are broken into three classes: scalar, complex, aggregate.
Mike Stumpfc496822009-02-08 23:14:22 +00003291
3292 /// EmitScalarExpr - Emit the computation of the specified expression of LLVM
3293 /// scalar type, returning the result.
Anders Carlsson5b106a72009-08-16 07:36:22 +00003294 llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false);
Mike Stumpfc496822009-02-08 23:14:22 +00003295
Filipe Cabecinhas650d7f72015-08-05 06:19:26 +00003296 /// Emit a conversion from the specified type to the specified destination
3297 /// type, both of which are LLVM scalar types.
Chris Lattner3474c202007-08-26 06:48:56 +00003298 llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003299 QualType DstTy, SourceLocation Loc);
Mike Stumpfc496822009-02-08 23:14:22 +00003300
Filipe Cabecinhas650d7f72015-08-05 06:19:26 +00003301 /// Emit a conversion from the specified complex type to the specified
3302 /// destination type, where the destination type is an LLVM scalar type.
Chris Lattner42e6b812007-08-26 16:34:22 +00003303 llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003304 QualType DstTy,
3305 SourceLocation Loc);
Mike Stumpfc496822009-02-08 23:14:22 +00003306
John McCall7a626f62010-09-15 10:14:12 +00003307 /// EmitAggExpr - Emit the computation of the specified expression
3308 /// of aggregate type. The result is computed into the given slot,
3309 /// which may be null to indicate that the value is not needed.
John McCall4e8ca4f2012-07-02 23:58:38 +00003310 void EmitAggExpr(const Expr *E, AggValueSlot AS);
Mike Stumpfc496822009-02-08 23:14:22 +00003311
Daniel Dunbard0bc7b92010-02-05 19:38:31 +00003312 /// EmitAggExprToLValue - Emit the computation of the specified expression of
3313 /// aggregate type into a temporary LValue.
3314 LValue EmitAggExprToLValue(const Expr *E);
3315
John McCall1bd25562011-06-24 23:21:27 +00003316 /// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
3317 /// make sure it survives garbage collection until this point.
3318 void EmitExtendGCLifetime(llvm::Value *object);
3319
Chris Lattnercbfc73b2007-08-21 05:54:00 +00003320 /// EmitComplexExpr - Emit the computation of the specified expression of
Chris Lattner08b15df2007-08-23 23:43:33 +00003321 /// complex type, returning the result.
John McCall07bb1962010-11-16 10:08:07 +00003322 ComplexPairTy EmitComplexExpr(const Expr *E,
3323 bool IgnoreReal = false,
3324 bool IgnoreImag = false);
Mike Stumpfc496822009-02-08 23:14:22 +00003325
John McCall47fb9502013-03-07 21:37:08 +00003326 /// EmitComplexExprIntoLValue - Emit the given expression of complex
3327 /// type and place its result into the specified l-value.
David Blaikie66e41972015-01-14 07:38:27 +00003328 void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit);
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +00003329
John McCall47fb9502013-03-07 21:37:08 +00003330 /// EmitStoreOfComplex - Store a complex number into the specified l-value.
David Blaikie66e41972015-01-14 07:38:27 +00003331 void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit);
John McCall47fb9502013-03-07 21:37:08 +00003332
3333 /// EmitLoadOfComplex - Load a complex number from the specified l-value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00003334 ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc);
Chris Lattnerb781dc792008-05-08 05:58:21 +00003335
John McCall7f416cc2015-09-08 08:05:57 +00003336 Address emitAddrOfRealComponent(Address complex, QualType complexType);
3337 Address emitAddrOfImagComponent(Address complex, QualType complexType);
3338
Chandler Carruth84537952012-03-30 19:44:53 +00003339 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
3340 /// global variable that has already been created for it. If the initializer
3341 /// has a different type than GV does, this may free GV and return a different
3342 /// one. Otherwise it just returns GV.
3343 llvm::GlobalVariable *
3344 AddInitializerToStaticVarDecl(const VarDecl &D,
3345 llvm::GlobalVariable *GV);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003346
Daniel Dunbar22a87f92009-02-25 19:24:29 +00003347
Anders Carlssonf40886a2009-08-08 21:45:14 +00003348 /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++
3349 /// variable with global storage.
Richard Smith6331c402012-02-13 22:16:19 +00003350 void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr,
3351 bool PerformInit);
Anders Carlssonf40886a2009-08-08 21:45:14 +00003352
David Majnemerb3341ea2014-10-05 05:05:40 +00003353 llvm::Constant *createAtExitStub(const VarDecl &VD, llvm::Constant *Dtor,
3354 llvm::Constant *Addr);
3355
John McCallc84ed6a2012-05-01 06:13:13 +00003356 /// Call atexit() with a function that passes the given argument to
3357 /// the given function.
David Blaikieebe87e12013-08-27 23:57:18 +00003358 void registerGlobalDtorWithAtExit(const VarDecl &D, llvm::Constant *fn,
3359 llvm::Constant *addr);
Mike Stump11289f42009-09-09 15:08:12 +00003360
John McCallcdf7ef52010-11-06 09:44:32 +00003361 /// Emit code in this function to perform a guarded variable
3362 /// initialization. Guarded initializations are used when it's not
3363 /// possible to prove that an initialization will be done exactly
3364 /// once, e.g. with a static local variable or a static data member
3365 /// of a class template.
Chandler Carruth84537952012-03-30 19:44:53 +00003366 void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr,
Richard Smith6331c402012-02-13 22:16:19 +00003367 bool PerformInit);
John McCall68ff0372010-09-08 01:44:27 +00003368
Daniel Dunbarfe06df42010-03-20 04:15:41 +00003369 /// GenerateCXXGlobalInitFunc - Generates code for initializing global
3370 /// variables.
3371 void GenerateCXXGlobalInitFunc(llvm::Function *Fn,
David Majnemerb3341ea2014-10-05 05:05:40 +00003372 ArrayRef<llvm::Function *> CXXThreadLocals,
John McCall7f416cc2015-09-08 08:05:57 +00003373 Address Guard = Address::invalid());
Daniel Dunbarfe06df42010-03-20 04:15:41 +00003374
John McCallee08c532012-04-06 18:21:03 +00003375 /// GenerateCXXGlobalDtorsFunc - Generates code for destroying global
Daniel Dunbarfe06df42010-03-20 04:15:41 +00003376 /// variables.
John McCallee08c532012-04-06 18:21:03 +00003377 void GenerateCXXGlobalDtorsFunc(llvm::Function *Fn,
3378 const std::vector<std::pair<llvm::WeakVH,
3379 llvm::Constant*> > &DtorsAndObjects);
Daniel Dunbarfe06df42010-03-20 04:15:41 +00003380
John McCalla738c252011-03-09 04:27:21 +00003381 void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
3382 const VarDecl *D,
Richard Smith6331c402012-02-13 22:16:19 +00003383 llvm::GlobalVariable *Addr,
3384 bool PerformInit);
Daniel Dunbarfe06df42010-03-20 04:15:41 +00003385
John McCall7a626f62010-09-15 10:14:12 +00003386 void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00003387
John McCall7f416cc2015-09-08 08:05:57 +00003388 void EmitSynthesizedCXXCopyCtor(Address Dest, Address Src, const Expr *Exp);
Mike Stump11289f42009-09-09 15:08:12 +00003389
John McCall08ef4662011-11-10 08:15:53 +00003390 void enterFullExpression(const ExprWithCleanups *E) {
3391 if (E->getNumObjects() == 0) return;
3392 enterNonTrivialFullExpression(E);
3393 }
3394 void enterNonTrivialFullExpression(const ExprWithCleanups *E);
Mike Stump11289f42009-09-09 15:08:12 +00003395
Richard Smithea852322013-05-07 21:53:22 +00003396 void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint = true);
Douglas Gregorc278d1b2010-05-16 00:44:00 +00003397
Eli Friedmanc370a7e2012-02-09 03:32:31 +00003398 void EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Dest);
3399
Tim Northovercc2a6e02015-11-09 19:56:35 +00003400 RValue EmitAtomicExpr(AtomicExpr *E);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003401
Daniel Dunbar88402ce2008-08-04 16:51:22 +00003402 //===--------------------------------------------------------------------===//
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003403 // Annotations Emission
3404 //===--------------------------------------------------------------------===//
3405
3406 /// Emit an annotation call (intrinsic or builtin).
3407 llvm::Value *EmitAnnotationCall(llvm::Value *AnnotationFn,
3408 llvm::Value *AnnotatedVal,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003409 StringRef AnnotationStr,
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003410 SourceLocation Location);
3411
3412 /// Emit local annotations for the local variable V, declared by D.
3413 void EmitVarAnnotations(const VarDecl *D, llvm::Value *V);
3414
3415 /// Emit field annotations for the given field & value. Returns the
3416 /// annotation result.
John McCall7f416cc2015-09-08 08:05:57 +00003417 Address EmitFieldAnnotations(const FieldDecl *D, Address V);
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003418
3419 //===--------------------------------------------------------------------===//
Daniel Dunbar88402ce2008-08-04 16:51:22 +00003420 // Internal Helpers
3421 //===--------------------------------------------------------------------===//
Mike Stumpfc496822009-02-08 23:14:22 +00003422
Chris Lattner5b1964b2008-11-11 07:41:27 +00003423 /// ContainsLabel - Return true if the statement contains a label in it. If
3424 /// this statement is not executed normally, it not containing a label means
3425 /// that we can just remove the code.
3426 static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false);
Mike Stumpfc496822009-02-08 23:14:22 +00003427
Chris Lattner29911cc2011-02-28 00:18:40 +00003428 /// containsBreak - Return true if the statement contains a break out of it.
3429 /// If the statement (recursively) contains a switch or loop with a break
3430 /// inside of it, this is fine.
3431 static bool containsBreak(const Stmt *S);
Richard Smithd8e3ac32016-09-16 23:30:39 +00003432
3433 /// Determine if the given statement might introduce a declaration into the
3434 /// current scope, by being a (possibly-labelled) DeclStmt.
3435 static bool mightAddDeclToScope(const Stmt *S);
Chris Lattner29911cc2011-02-28 00:18:40 +00003436
Daniel Dunbar682712c2008-11-12 10:12:14 +00003437 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
Chris Lattner41c6ab52011-02-27 23:02:32 +00003438 /// to a constant, or if it does but contains a label, return false. If it
3439 /// constant folds return true and set the boolean result in Result.
Richard Smithb130fe72016-06-23 19:16:49 +00003440 bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result,
3441 bool AllowLabels = false);
Mike Stumpfc496822009-02-08 23:14:22 +00003442
Chris Lattner29911cc2011-02-28 00:18:40 +00003443 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
3444 /// to a constant, or if it does but contains a label, return false. If it
3445 /// constant folds return true and set the folded value.
Richard Smithb130fe72016-06-23 19:16:49 +00003446 bool ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &Result,
3447 bool AllowLabels = false);
3448
Chris Lattnercd439292008-11-12 08:04:58 +00003449 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an
3450 /// if statement) to the specified blocks. Based on the condition, this might
3451 /// try to simplify the codegen of the conditional based on the branch.
Justin Bogneref512b92014-01-06 22:27:43 +00003452 /// TrueCount should be the number of times we expect the condition to
3453 /// evaluate to true based on PGO data.
Chris Lattnerb7a9e162008-11-12 07:46:33 +00003454 void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock,
Justin Bogneref512b92014-01-06 22:27:43 +00003455 llvm::BasicBlock *FalseBlock, uint64_t TrueCount);
Mike Stumpba6a0c42009-12-14 21:58:14 +00003456
Richard Smithe30752c2012-10-09 19:52:38 +00003457 /// \brief Emit a description of a type in a format suitable for passing to
3458 /// a runtime sanitizer handler.
3459 llvm::Constant *EmitCheckTypeDescriptor(QualType T);
3460
3461 /// \brief Convert a value into a format suitable for passing to a runtime
3462 /// sanitizer handler.
3463 llvm::Value *EmitCheckValue(llvm::Value *V);
3464
3465 /// \brief Emit a description of a source location in a format suitable for
3466 /// passing to a runtime sanitizer handler.
3467 llvm::Constant *EmitCheckSourceLocation(SourceLocation Loc);
3468
Richard Smithde670682012-11-01 22:15:34 +00003469 /// \brief Create a basic block that will call a handler function in a
3470 /// sanitizer runtime with the provided arguments, and create a conditional
3471 /// branch to it.
Peter Collingbourne3eea6772015-05-11 21:39:14 +00003472 void EmitCheck(ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00003473 SanitizerHandler Check, ArrayRef<llvm::Constant *> StaticArgs,
Alexey Samsonove396bfc2014-11-11 22:03:54 +00003474 ArrayRef<llvm::Value *> DynamicArgs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003475
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00003476 /// \brief Emit a slow path cross-DSO CFI check which calls __cfi_slowpath
3477 /// if Cond if false.
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00003478 void EmitCfiSlowPathCheck(SanitizerMask Kind, llvm::Value *Cond,
3479 llvm::ConstantInt *TypeId, llvm::Value *Ptr,
3480 ArrayRef<llvm::Constant *> StaticArgs);
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00003481
Richard Smithde670682012-11-01 22:15:34 +00003482 /// \brief Create a basic block that will call the trap intrinsic, and emit a
3483 /// conditional branch to it, for the -ftrapv checks.
Chad Rosierae229d52013-01-29 23:31:22 +00003484 void EmitTrapCheck(llvm::Value *Checked);
Richard Smithde670682012-11-01 22:15:34 +00003485
Akira Hatanaka85365cd2015-07-02 22:15:41 +00003486 /// \brief Emit a call to trap or debugtrap and attach function attribute
3487 /// "trap-func-name" if specified.
3488 llvm::CallInst *EmitTrapCall(llvm::Intrinsic::ID IntrID);
3489
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00003490 /// \brief Emit a cross-DSO CFI failure handling function.
3491 void EmitCfiCheckFail();
3492
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003493 /// \brief Create a check for a function parameter that may potentially be
3494 /// declared as non-null.
3495 void EmitNonNullArgCheck(RValue RV, QualType ArgType, SourceLocation ArgLoc,
Vedant Kumared00ea02017-03-06 05:28:22 +00003496 AbstractCallee AC, unsigned ParmNum);
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003497
Anders Carlsson093bdff2010-03-30 03:27:09 +00003498 /// EmitCallArg - Emit a single call argument.
John McCall32ea9692011-03-11 20:59:21 +00003499 void EmitCallArg(CallArgList &args, const Expr *E, QualType ArgType);
Anders Carlsson093bdff2010-03-30 03:27:09 +00003500
John McCall23f66262010-05-26 22:34:26 +00003501 /// EmitDelegateCallArg - We are performing a delegate call; that
3502 /// is, the current function is delegating to another one. Produce
3503 /// a r-value suitable for passing the given parameter.
Nick Lewycky2d84e842013-10-02 02:29:49 +00003504 void EmitDelegateCallArg(CallArgList &args, const VarDecl *param,
3505 SourceLocation loc);
John McCall23f66262010-05-26 22:34:26 +00003506
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003507 /// SetFPAccuracy - Set the minimum required accuracy of the given floating
3508 /// point operation, expressed as the maximum relative error in ulp.
Duncan Sandse81111c2012-04-10 08:23:07 +00003509 void SetFPAccuracy(llvm::Value *Val, float Accuracy);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003510
Chris Lattnercd439292008-11-12 08:04:58 +00003511private:
Rafael Espindola5c0034a2012-03-24 16:50:34 +00003512 llvm::MDNode *getRangeForLoadFromType(QualType Ty);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003513 void EmitReturnOfRValue(RValue RV, QualType Ty);
3514
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003515 void deferPlaceholderReplacement(llvm::Instruction *Old, llvm::Value *New);
3516
3517 llvm::SmallVector<std::pair<llvm::Instruction *, llvm::Value *>, 4>
3518 DeferredReplacements;
3519
John McCall7f416cc2015-09-08 08:05:57 +00003520 /// Set the address of a local variable.
3521 void setAddrOfLocalVar(const VarDecl *VD, Address Addr) {
3522 assert(!LocalDeclMap.count(VD) && "Decl already exists in LocalDeclMap!");
3523 LocalDeclMap.insert({VD, Addr});
3524 }
3525
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003526 /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty
3527 /// from function arguments into \arg Dst. See ABIArgInfo::Expand.
3528 ///
3529 /// \param AI - The first function argument of the expansion.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003530 void ExpandTypeFromArgs(QualType Ty, LValue Dst,
John McCall12f23522016-04-04 18:33:08 +00003531 SmallVectorImpl<llvm::Value *>::iterator &AI);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003532
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003533 /// ExpandTypeToArgs - Expand an RValue \arg RV, with the LLVM type for \arg
3534 /// Ty, into individual arguments on the provided vector \arg IRCallArgs,
3535 /// starting at index \arg IRCallArgPos. See ABIArgInfo::Expand.
3536 void ExpandTypeToArgs(QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy,
3537 SmallVectorImpl<llvm::Value *> &IRCallArgs,
3538 unsigned &IRCallArgPos);
Anders Carlsson03aaf112009-01-11 19:40:10 +00003539
Chad Rosier59df25b2012-08-23 20:00:18 +00003540 llvm::Value* EmitAsmInput(const TargetInfo::ConstraintInfo &Info,
Anders Carlsson03aaf112009-01-11 19:40:10 +00003541 const Expr *InputExpr, std::string &ConstraintStr);
Mike Stumpfc496822009-02-08 23:14:22 +00003542
Chad Rosier59df25b2012-08-23 20:00:18 +00003543 llvm::Value* EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info,
Eli Friedmaneca55af2010-07-16 00:55:21 +00003544 LValue InputValue, QualType InputType,
Nick Lewycky2d84e842013-10-02 02:29:49 +00003545 std::string &ConstraintStr,
3546 SourceLocation Loc);
Eli Friedmaneca55af2010-07-16 00:55:21 +00003547
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003548 /// \brief Attempts to statically evaluate the object size of E. If that
3549 /// fails, emits code to figure the size of E out for us. This is
3550 /// pass_object_size aware.
George Burgess IV0d6592a2017-02-23 05:59:56 +00003551 ///
3552 /// If EmittedExpr is non-null, this will use that instead of re-emitting E.
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003553 llvm::Value *evaluateOrEmitBuiltinObjectSize(const Expr *E, unsigned Type,
George Burgess IV0d6592a2017-02-23 05:59:56 +00003554 llvm::IntegerType *ResType,
3555 llvm::Value *EmittedE);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003556
3557 /// \brief Emits the size of E, as required by __builtin_object_size. This
3558 /// function is aware of pass_object_size parameters, and will act accordingly
3559 /// if E is a parameter with the pass_object_size attribute.
3560 llvm::Value *emitBuiltinObjectSize(const Expr *E, unsigned Type,
George Burgess IV0d6592a2017-02-23 05:59:56 +00003561 llvm::IntegerType *ResType,
3562 llvm::Value *EmittedE);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003563
Reid Kleckner89077a12013-12-17 19:46:40 +00003564public:
Douglas Gregore83b9562015-07-07 03:57:53 +00003565#ifndef NDEBUG
3566 // Determine whether the given argument is an Objective-C method
3567 // that may have type parameters in its signature.
3568 static bool isObjCMethodWithTypeParams(const ObjCMethodDecl *method) {
3569 const DeclContext *dc = method->getDeclContext();
3570 if (const ObjCInterfaceDecl *classDecl= dyn_cast<ObjCInterfaceDecl>(dc)) {
3571 return classDecl->getTypeParamListAsWritten();
3572 }
3573
3574 if (const ObjCCategoryDecl *catDecl = dyn_cast<ObjCCategoryDecl>(dc)) {
3575 return catDecl->getTypeParamList();
3576 }
3577
3578 return false;
3579 }
3580
3581 template<typename T>
3582 static bool isObjCMethodWithTypeParams(const T *) { return false; }
3583#endif
3584
Richard Smitha560ccf2016-09-29 21:30:12 +00003585 enum class EvaluationOrder {
3586 ///! No language constraints on evaluation order.
3587 Default,
3588 ///! Language semantics require left-to-right evaluation.
3589 ForceLeftToRight,
3590 ///! Language semantics require right-to-left evaluation.
3591 ForceRightToLeft
3592 };
3593
Anders Carlsson60ce3fe2009-04-08 20:47:54 +00003594 /// EmitCallArgs - Emit call arguments for a function.
Reid Kleckner739756c2013-12-04 19:23:12 +00003595 template <typename T>
3596 void EmitCallArgs(CallArgList &Args, const T *CallArgTypeInfo,
David Blaikief05779e2015-07-21 18:37:18 +00003597 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
Vedant Kumared00ea02017-03-06 05:28:22 +00003598 AbstractCallee AC = AbstractCallee(),
Richard Smith762672a2016-09-28 19:09:10 +00003599 unsigned ParamsToSkip = 0,
Richard Smitha560ccf2016-09-29 21:30:12 +00003600 EvaluationOrder Order = EvaluationOrder::Default) {
Reid Kleckner739756c2013-12-04 19:23:12 +00003601 SmallVector<QualType, 16> ArgTypes;
David Blaikief05779e2015-07-21 18:37:18 +00003602 CallExpr::const_arg_iterator Arg = ArgRange.begin();
Anders Carlsson60ce3fe2009-04-08 20:47:54 +00003603
Alexey Samsonovcbe875a2014-08-28 00:22:11 +00003604 assert((ParamsToSkip == 0 || CallArgTypeInfo) &&
3605 "Can't skip parameters if type info is not provided");
3606 if (CallArgTypeInfo) {
Douglas Gregore83b9562015-07-07 03:57:53 +00003607#ifndef NDEBUG
3608 bool isGenericMethod = isObjCMethodWithTypeParams(CallArgTypeInfo);
3609#endif
3610
Alexey Samsonovcbe875a2014-08-28 00:22:11 +00003611 // First, use the argument types that the type info knows about
3612 for (auto I = CallArgTypeInfo->param_type_begin() + ParamsToSkip,
3613 E = CallArgTypeInfo->param_type_end();
3614 I != E; ++I, ++Arg) {
David Blaikief05779e2015-07-21 18:37:18 +00003615 assert(Arg != ArgRange.end() && "Running over edge of argument list!");
Aaron Ballman7c04eae2015-07-07 13:25:57 +00003616 assert((isGenericMethod ||
3617 ((*I)->isVariablyModifiedType() ||
3618 (*I).getNonReferenceType()->isObjCRetainableType() ||
3619 getContext()
3620 .getCanonicalType((*I).getNonReferenceType())
3621 .getTypePtr() ==
3622 getContext()
Benjamin Kramerf48ee442015-07-18 14:35:53 +00003623 .getCanonicalType((*Arg)->getType())
Aaron Ballman7c04eae2015-07-07 13:25:57 +00003624 .getTypePtr())) &&
3625 "type mismatch in call argument!");
Alexey Samsonovcbe875a2014-08-28 00:22:11 +00003626 ArgTypes.push_back(*I);
3627 }
Anders Carlsson603d6af2009-04-18 20:20:22 +00003628 }
Mike Stump11289f42009-09-09 15:08:12 +00003629
Reid Kleckner739756c2013-12-04 19:23:12 +00003630 // Either we've emitted all the call args, or we have a call to variadic
Alexey Samsonovcbe875a2014-08-28 00:22:11 +00003631 // function.
David Blaikief05779e2015-07-21 18:37:18 +00003632 assert((Arg == ArgRange.end() || !CallArgTypeInfo ||
3633 CallArgTypeInfo->isVariadic()) &&
3634 "Extra arguments in non-variadic function!");
Reid Kleckner739756c2013-12-04 19:23:12 +00003635
Anders Carlsson603d6af2009-04-18 20:20:22 +00003636 // If we still have any arguments, emit them using the type of the argument.
David Blaikiefd7c2192015-07-21 18:59:10 +00003637 for (auto *A : llvm::make_range(Arg, ArgRange.end()))
Reid Klecknerd2ad9df2017-01-03 21:23:35 +00003638 ArgTypes.push_back(CallArgTypeInfo ? getVarArgType(A) : A->getType());
Adrian Prantlca64c3e2013-07-26 20:42:57 +00003639
Vedant Kumared00ea02017-03-06 05:28:22 +00003640 EmitCallArgs(Args, ArgTypes, ArgRange, AC, ParamsToSkip, Order);
Anders Carlsson603d6af2009-04-18 20:20:22 +00003641 }
John McCalld4f4b7f2010-03-03 04:15:11 +00003642
Reid Kleckner739756c2013-12-04 19:23:12 +00003643 void EmitCallArgs(CallArgList &Args, ArrayRef<QualType> ArgTypes,
David Blaikief05779e2015-07-21 18:37:18 +00003644 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
Vedant Kumared00ea02017-03-06 05:28:22 +00003645 AbstractCallee AC = AbstractCallee(),
Richard Smith762672a2016-09-28 19:09:10 +00003646 unsigned ParamsToSkip = 0,
Richard Smitha560ccf2016-09-29 21:30:12 +00003647 EvaluationOrder Order = EvaluationOrder::Default);
Reid Kleckner739756c2013-12-04 19:23:12 +00003648
John McCall7f416cc2015-09-08 08:05:57 +00003649 /// EmitPointerWithAlignment - Given an expression with a pointer
3650 /// type, emit the value and compute our best estimate of the
3651 /// alignment of the pointee.
3652 ///
3653 /// Note that this function will conservatively fall back on the type
3654 /// when it doesn't
3655 ///
3656 /// \param Source - If non-null, this will be initialized with
3657 /// information about the source of the alignment. Note that this
3658 /// function will conservatively fall back on the type when it
3659 /// doesn't recognize the expression, which means that sometimes
3660 ///
3661 /// a worst-case One
3662 /// reasonable way to use this information is when there's a
3663 /// language guarantee that the pointer must be aligned to some
3664 /// stricter value, and we're simply trying to ensure that
3665 /// sufficiently obvious uses of under-aligned objects don't get
3666 /// miscompiled; for example, a placement new into the address of
3667 /// a local variable. In such a case, it's quite reasonable to
3668 /// just ignore the returned alignment when it isn't from an
3669 /// explicit source.
3670 Address EmitPointerWithAlignment(const Expr *Addr,
3671 AlignmentSource *Source = nullptr);
3672
Peter Collingbournedc134532016-01-16 00:31:22 +00003673 void EmitSanitizerStatReport(llvm::SanitizerStatKind SSK);
3674
Reid Kleckner89077a12013-12-17 19:46:40 +00003675private:
Reid Kleckner79b0fd72014-10-10 00:05:45 +00003676 QualType getVarArgType(const Expr *Arg);
3677
John McCalld4f4b7f2010-03-03 04:15:11 +00003678 const TargetCodeGenInfo &getTargetHooks() const {
3679 return CGM.getTargetCodeGenInfo();
3680 }
John McCall09ae0322010-07-06 23:57:41 +00003681
3682 void EmitDeclMetadata();
John McCallf9b056b2011-03-31 08:03:29 +00003683
John McCall7f416cc2015-09-08 08:05:57 +00003684 BlockByrefHelpers *buildByrefHelpers(llvm::StructType &byrefType,
3685 const AutoVarEmission &emission);
Dan Gohman515a60d2012-02-16 00:57:37 +00003686
3687 void AddObjCARCExceptionMetadata(llvm::Instruction *Inst);
Jay Foadb0f33442012-03-02 18:34:30 +00003688
Saleem Abdulrasoola14ac3f42014-12-04 04:52:37 +00003689 llvm::Value *GetValueForARMHint(unsigned BuiltinID);
Chris Lattnerbed31442007-05-28 01:07:47 +00003690};
Mike Stump11289f42009-09-09 15:08:12 +00003691
John McCallce1de612011-01-26 04:00:11 +00003692/// Helper class with most of the code for saving a value for a
3693/// conditional expression cleanup.
John McCallcb5f77f2011-01-28 10:53:53 +00003694struct DominatingLLVMValue {
John McCallce1de612011-01-26 04:00:11 +00003695 typedef llvm::PointerIntPair<llvm::Value*, 1, bool> saved_type;
3696
3697 /// Answer whether the given value needs extra work to be saved.
3698 static bool needsSaving(llvm::Value *value) {
3699 // If it's not an instruction, we don't need to save.
3700 if (!isa<llvm::Instruction>(value)) return false;
3701
3702 // If it's an instruction in the entry block, we don't need to save.
3703 llvm::BasicBlock *block = cast<llvm::Instruction>(value)->getParent();
3704 return (block != &block->getParent()->getEntryBlock());
3705 }
3706
3707 /// Try to save the given value.
3708 static saved_type save(CodeGenFunction &CGF, llvm::Value *value) {
3709 if (!needsSaving(value)) return saved_type(value, false);
3710
John McCall7f416cc2015-09-08 08:05:57 +00003711 // Otherwise, we need an alloca.
3712 auto align = CharUnits::fromQuantity(
3713 CGF.CGM.getDataLayout().getPrefTypeAlignment(value->getType()));
3714 Address alloca =
3715 CGF.CreateTempAlloca(value->getType(), align, "cond-cleanup.save");
John McCallce1de612011-01-26 04:00:11 +00003716 CGF.Builder.CreateStore(value, alloca);
3717
John McCall7f416cc2015-09-08 08:05:57 +00003718 return saved_type(alloca.getPointer(), true);
John McCallce1de612011-01-26 04:00:11 +00003719 }
3720
3721 static llvm::Value *restore(CodeGenFunction &CGF, saved_type value) {
John McCall7f416cc2015-09-08 08:05:57 +00003722 // If the value says it wasn't saved, trust that it's still dominating.
John McCallce1de612011-01-26 04:00:11 +00003723 if (!value.getInt()) return value.getPointer();
John McCall7f416cc2015-09-08 08:05:57 +00003724
3725 // Otherwise, it should be an alloca instruction, as set up in save().
3726 auto alloca = cast<llvm::AllocaInst>(value.getPointer());
3727 return CGF.Builder.CreateAlignedLoad(alloca, alloca->getAlignment());
John McCallce1de612011-01-26 04:00:11 +00003728 }
3729};
3730
John McCallcb5f77f2011-01-28 10:53:53 +00003731/// A partial specialization of DominatingValue for llvm::Values that
3732/// might be llvm::Instructions.
3733template <class T> struct DominatingPointer<T,true> : DominatingLLVMValue {
3734 typedef T *type;
John McCallce1de612011-01-26 04:00:11 +00003735 static type restore(CodeGenFunction &CGF, saved_type value) {
John McCallcb5f77f2011-01-28 10:53:53 +00003736 return static_cast<T*>(DominatingLLVMValue::restore(CGF, value));
3737 }
3738};
3739
John McCall7f416cc2015-09-08 08:05:57 +00003740/// A specialization of DominatingValue for Address.
3741template <> struct DominatingValue<Address> {
3742 typedef Address type;
3743
3744 struct saved_type {
3745 DominatingLLVMValue::saved_type SavedValue;
3746 CharUnits Alignment;
3747 };
3748
3749 static bool needsSaving(type value) {
3750 return DominatingLLVMValue::needsSaving(value.getPointer());
3751 }
3752 static saved_type save(CodeGenFunction &CGF, type value) {
3753 return { DominatingLLVMValue::save(CGF, value.getPointer()),
3754 value.getAlignment() };
3755 }
3756 static type restore(CodeGenFunction &CGF, saved_type value) {
3757 return Address(DominatingLLVMValue::restore(CGF, value.SavedValue),
3758 value.Alignment);
3759 }
3760};
3761
John McCallcb5f77f2011-01-28 10:53:53 +00003762/// A specialization of DominatingValue for RValue.
3763template <> struct DominatingValue<RValue> {
3764 typedef RValue type;
3765 class saved_type {
3766 enum Kind { ScalarLiteral, ScalarAddress, AggregateLiteral,
3767 AggregateAddress, ComplexAddress };
3768
3769 llvm::Value *Value;
John McCall7f416cc2015-09-08 08:05:57 +00003770 unsigned K : 3;
3771 unsigned Align : 29;
3772 saved_type(llvm::Value *v, Kind k, unsigned a = 0)
3773 : Value(v), K(k), Align(a) {}
John McCallcb5f77f2011-01-28 10:53:53 +00003774
3775 public:
3776 static bool needsSaving(RValue value);
3777 static saved_type save(CodeGenFunction &CGF, RValue value);
3778 RValue restore(CodeGenFunction &CGF);
3779
John McCall7f416cc2015-09-08 08:05:57 +00003780 // implementations in CGCleanup.cpp
John McCallcb5f77f2011-01-28 10:53:53 +00003781 };
3782
3783 static bool needsSaving(type value) {
3784 return saved_type::needsSaving(value);
3785 }
3786 static saved_type save(CodeGenFunction &CGF, type value) {
3787 return saved_type::save(CGF, value);
3788 }
3789 static type restore(CodeGenFunction &CGF, saved_type value) {
3790 return value.restore(CGF);
John McCallce1de612011-01-26 04:00:11 +00003791 }
3792};
3793
Chris Lattnerbed31442007-05-28 01:07:47 +00003794} // end namespace CodeGen
3795} // end namespace clang
Fariborz Jahanian715fdd52012-01-29 20:27:13 +00003796
Chris Lattnerbed31442007-05-28 01:07:47 +00003797#endif