blob: 8801c3b3f256d541a46bcf6292f2fd14439357e9 [file] [log] [blame]
Chris Lattnerbed31442007-05-28 01:07:47 +00001//===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
2//
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//
10// This coordinates the per-function state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
John McCall7f416cc2015-09-08 08:05:57 +000015#include "CGBlocks.h"
David Majnemerdc012fa2015-04-22 21:38:15 +000016#include "CGCleanup.h"
Peter Collingbournefa4d6032011-10-06 18:51:56 +000017#include "CGCUDARuntime.h"
John McCall5d865c322010-08-31 07:33:07 +000018#include "CGCXXABI.h"
Eli Friedman17630752008-05-22 01:40:10 +000019#include "CGDebugInfo.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000020#include "CGOpenMPRuntime.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "CodeGenModule.h"
Justin Bogneref512b92014-01-06 22:27:43 +000022#include "CodeGenPGO.h"
Peter Collingbourneb453cd62013-10-20 21:29:19 +000023#include "TargetInfo.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000024#include "clang/AST/ASTContext.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000025#include "clang/AST/Decl.h"
Anders Carlsson468fa632009-04-04 20:47:02 +000026#include "clang/AST/DeclCXX.h"
Mike Stumpbee78dd2009-12-04 23:26:17 +000027#include "clang/AST/StmtCXX.h"
Sanjay Patela24296b2015-09-02 20:01:30 +000028#include "clang/Basic/Builtins.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000029#include "clang/Basic/TargetInfo.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000030#include "clang/CodeGen/CGFunctionInfo.h"
Chris Lattner3c77a352010-06-22 00:03:40 +000031#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000032#include "llvm/IR/DataLayout.h"
33#include "llvm/IR/Intrinsics.h"
34#include "llvm/IR/MDBuilder.h"
35#include "llvm/IR/Operator.h"
Chris Lattnerbed31442007-05-28 01:07:47 +000036using namespace clang;
37using namespace CodeGen;
38
Fariborz Jahanian63628032012-06-26 16:06:38 +000039CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext)
David Blaikie92848de2013-08-26 20:33:21 +000040 : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()),
John McCall7f416cc2015-09-08 08:05:57 +000041 Builder(cgm, cgm.getModule().getContext(), llvm::ConstantFolder(),
David Blaikie8e90d222014-10-14 17:09:38 +000042 CGBuilderInserterTy(this)),
John McCall7f416cc2015-09-08 08:05:57 +000043 CurFn(nullptr), ReturnValue(Address::invalid()),
44 CapturedStmtInfo(nullptr),
Alexey Samsonov035462c2014-10-30 19:33:44 +000045 SanOpts(CGM.getLangOpts().Sanitize), IsSanitizerScope(false),
David Blaikie8e90d222014-10-14 17:09:38 +000046 CurFuncIsThunk(false), AutoreleaseResult(false), SawAsmBlock(false),
John McCall7f416cc2015-09-08 08:05:57 +000047 IsOutlinedSEHHelper(false),
48 BlockInfo(nullptr), BlockPointer(nullptr),
Reid Kleckner19819442014-07-25 21:39:46 +000049 LambdaThisCaptureField(nullptr), NormalCleanupDest(nullptr),
50 NextCleanupDestIndex(1), FirstBlockInfo(nullptr), EHResumeBlock(nullptr),
Reid Kleckneraca01db2015-02-04 22:37:07 +000051 ExceptionSlot(nullptr), EHSelectorSlot(nullptr),
Reid Kleckner9fe7f232015-07-07 00:36:30 +000052 DebugInfo(CGM.getModuleDebugInfo()),
53 DisableDebugInfo(false), DidCallStackSave(false), IndirectBranch(nullptr),
54 PGO(cgm), SwitchInsn(nullptr), SwitchWeights(nullptr),
55 CaseRangeBlock(nullptr), UnreachableBlock(nullptr), NumReturnExprs(0),
56 NumSimpleReturnExprs(0), CXXABIThisDecl(nullptr),
57 CXXABIThisValue(nullptr), CXXThisValue(nullptr),
John McCall7f416cc2015-09-08 08:05:57 +000058 CXXStructorImplicitParamDecl(nullptr),
Craig Topper8a13c412014-05-21 05:09:00 +000059 CXXStructorImplicitParamValue(nullptr), OutermostConditional(nullptr),
60 CurLexicalScope(nullptr), TerminateLandingPad(nullptr),
61 TerminateHandler(nullptr), TrapBB(nullptr) {
Fariborz Jahanian63628032012-06-26 16:06:38 +000062 if (!suppressNewContext)
63 CGM.getCXXABI().getMangleContext().startNewFunction();
Michael Ilseman7a167ee2012-12-04 00:36:06 +000064
65 llvm::FastMathFlags FMF;
66 if (CGM.getLangOpts().FastMath)
Benjamin Kramer7464efc2012-12-09 21:58:24 +000067 FMF.setUnsafeAlgebra();
Michael Ilseman7a167ee2012-12-04 00:36:06 +000068 if (CGM.getLangOpts().FiniteMathOnly) {
Benjamin Kramer7464efc2012-12-09 21:58:24 +000069 FMF.setNoNaNs();
70 FMF.setNoInfs();
Michael Ilseman7a167ee2012-12-04 00:36:06 +000071 }
Pekka Jaaskelainen37014502014-12-10 16:41:14 +000072 if (CGM.getCodeGenOpts().NoNaNsFPMath) {
73 FMF.setNoNaNs();
74 }
75 if (CGM.getCodeGenOpts().NoSignedZeros) {
76 FMF.setNoSignedZeros();
77 }
Sanjay Patel359b1052015-04-09 15:03:23 +000078 if (CGM.getCodeGenOpts().ReciprocalMath) {
79 FMF.setAllowReciprocal();
80 }
Michael Ilseman7a167ee2012-12-04 00:36:06 +000081 Builder.SetFastMathFlags(FMF);
Chris Lattner5696e7b2008-06-17 18:05:57 +000082}
Chris Lattnerd1af2d22007-05-29 23:17:50 +000083
John McCall08ef4662011-11-10 08:15:53 +000084CodeGenFunction::~CodeGenFunction() {
Richard Smith736a9472013-06-12 20:42:33 +000085 assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup");
86
John McCall08ef4662011-11-10 08:15:53 +000087 // If there are any unclaimed block infos, go ahead and destroy them
88 // now. This can happen if IR-gen gets clever and skips evaluating
89 // something.
90 if (FirstBlockInfo)
91 destroyBlockInfos(FirstBlockInfo);
Alexey Bataev9959db52014-05-06 10:08:46 +000092
93 if (getLangOpts().OpenMP) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +000094 CGM.getOpenMPRuntime().functionFinished(*this);
Alexey Bataev9959db52014-05-06 10:08:46 +000095 }
John McCall08ef4662011-11-10 08:15:53 +000096}
97
John McCall7f416cc2015-09-08 08:05:57 +000098CharUnits CodeGenFunction::getNaturalPointeeTypeAlignment(QualType T,
99 AlignmentSource *Source) {
100 return getNaturalTypeAlignment(T->getPointeeType(), Source,
101 /*forPointee*/ true);
David Majnemer99281062014-09-18 22:05:54 +0000102}
Chris Lattnerd1af2d22007-05-29 23:17:50 +0000103
John McCall7f416cc2015-09-08 08:05:57 +0000104CharUnits CodeGenFunction::getNaturalTypeAlignment(QualType T,
105 AlignmentSource *Source,
106 bool forPointeeType) {
107 // Honor alignment typedef attributes even on incomplete types.
108 // We also honor them straight for C++ class types, even as pointees;
109 // there's an expressivity gap here.
110 if (auto TT = T->getAs<TypedefType>()) {
111 if (auto Align = TT->getDecl()->getMaxAlignment()) {
112 if (Source) *Source = AlignmentSource::AttributedType;
113 return getContext().toCharUnitsFromBits(Align);
114 }
115 }
116
117 if (Source) *Source = AlignmentSource::Type;
118
119 CharUnits Alignment;
David Majnemer9df56372015-09-10 21:52:00 +0000120 if (T->isIncompleteType()) {
John McCall7f416cc2015-09-08 08:05:57 +0000121 Alignment = CharUnits::One(); // Shouldn't be used, but pessimistic is best.
122 } else {
123 // For C++ class pointees, we don't know whether we're pointing at a
124 // base or a complete object, so we generally need to use the
125 // non-virtual alignment.
126 const CXXRecordDecl *RD;
127 if (forPointeeType && (RD = T->getAsCXXRecordDecl())) {
128 Alignment = CGM.getClassPointerAlignment(RD);
129 } else {
130 Alignment = getContext().getTypeAlignInChars(T);
131 }
132
133 // Cap to the global maximum type alignment unless the alignment
134 // was somehow explicit on the type.
135 if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) {
136 if (Alignment.getQuantity() > MaxAlign &&
137 !getContext().isAlignmentRequired(T))
138 Alignment = CharUnits::fromQuantity(MaxAlign);
139 }
140 }
141 return Alignment;
142}
143
144LValue CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) {
145 AlignmentSource AlignSource;
146 CharUnits Alignment = getNaturalTypeAlignment(T, &AlignSource);
147 return LValue::MakeAddr(Address(V, Alignment), T, getContext(), AlignSource,
148 CGM.getTBAAInfo(T));
149}
150
151/// Given a value of type T* that may not be to a complete object,
152/// construct an l-value with the natural pointee alignment of T.
153LValue
154CodeGenFunction::MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T) {
155 AlignmentSource AlignSource;
156 CharUnits Align = getNaturalTypeAlignment(T, &AlignSource, /*pointee*/ true);
157 return MakeAddrLValue(Address(V, Align), T, AlignSource);
158}
159
160
Chris Lattnera5f58b02011-07-09 17:41:47 +0000161llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
Daniel Dunbaree3da872009-02-03 23:03:55 +0000162 return CGM.getTypes().ConvertTypeForMem(T);
163}
164
Chris Lattnera5f58b02011-07-09 17:41:47 +0000165llvm::Type *CodeGenFunction::ConvertType(QualType T) {
Chris Lattnerf033c142007-06-22 19:05:19 +0000166 return CGM.getTypes().ConvertType(T);
Chris Lattner45bb9142007-06-09 02:28:57 +0000167}
Chris Lattnerd1af2d22007-05-29 23:17:50 +0000168
John McCall47fb9502013-03-07 21:37:08 +0000169TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) {
170 type = type.getCanonicalType();
171 while (true) {
172 switch (type->getTypeClass()) {
John McCall745ae282011-05-15 02:34:36 +0000173#define TYPE(name, parent)
174#define ABSTRACT_TYPE(name, parent)
175#define NON_CANONICAL_TYPE(name, parent) case Type::name:
176#define DEPENDENT_TYPE(name, parent) case Type::name:
177#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
178#include "clang/AST/TypeNodes.def"
John McCall47fb9502013-03-07 21:37:08 +0000179 llvm_unreachable("non-canonical or dependent type in IR-generation");
John McCall745ae282011-05-15 02:34:36 +0000180
Richard Smith27d807c2013-04-30 13:56:41 +0000181 case Type::Auto:
182 llvm_unreachable("undeduced auto type in IR-generation");
183
John McCall47fb9502013-03-07 21:37:08 +0000184 // Various scalar types.
185 case Type::Builtin:
186 case Type::Pointer:
187 case Type::BlockPointer:
188 case Type::LValueReference:
189 case Type::RValueReference:
190 case Type::MemberPointer:
191 case Type::Vector:
192 case Type::ExtVector:
193 case Type::FunctionProto:
194 case Type::FunctionNoProto:
195 case Type::Enum:
196 case Type::ObjCObjectPointer:
197 return TEK_Scalar;
John McCall745ae282011-05-15 02:34:36 +0000198
John McCall47fb9502013-03-07 21:37:08 +0000199 // Complexes.
200 case Type::Complex:
201 return TEK_Complex;
Eli Friedman0dfb8892011-10-06 23:00:33 +0000202
John McCall47fb9502013-03-07 21:37:08 +0000203 // Arrays, records, and Objective-C objects.
204 case Type::ConstantArray:
205 case Type::IncompleteArray:
206 case Type::VariableArray:
207 case Type::Record:
208 case Type::ObjCObject:
209 case Type::ObjCInterface:
210 return TEK_Aggregate;
211
212 // We operate on atomic values according to their underlying type.
213 case Type::Atomic:
214 type = cast<AtomicType>(type)->getValueType();
215 continue;
216 }
217 llvm_unreachable("unknown type kind!");
John McCall745ae282011-05-15 02:34:36 +0000218 }
Chris Lattner54fb19e2007-06-22 22:02:34 +0000219}
220
David Blaikie66e41972015-01-14 07:38:27 +0000221llvm::DebugLoc CodeGenFunction::EmitReturnBlock() {
Daniel Dunbarfd346a32009-01-26 23:27:52 +0000222 // For cleanliness, we try to avoid emitting the return block for
223 // simple cases.
224 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
225
226 if (CurBB) {
227 assert(!CurBB->getTerminator() && "Unexpected terminated block.");
228
Daniel Dunbarea3060a2009-07-19 08:24:34 +0000229 // We have a valid insert point, reuse it if it is empty or there are no
230 // explicit jumps to the return block.
John McCallad5d61e2010-07-23 21:56:41 +0000231 if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
232 ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
233 delete ReturnBlock.getBlock();
Daniel Dunbarea3060a2009-07-19 08:24:34 +0000234 } else
John McCallad5d61e2010-07-23 21:56:41 +0000235 EmitBlock(ReturnBlock.getBlock());
David Blaikie66e41972015-01-14 07:38:27 +0000236 return llvm::DebugLoc();
Daniel Dunbarfd346a32009-01-26 23:27:52 +0000237 }
238
239 // Otherwise, if the return block is the target of a single direct
240 // branch then we can just put the code in that block instead. This
241 // cleans up functions which started with a unified return block.
John McCallad5d61e2010-07-23 21:56:41 +0000242 if (ReturnBlock.getBlock()->hasOneUse()) {
Mike Stump11289f42009-09-09 15:08:12 +0000243 llvm::BranchInst *BI =
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000244 dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin());
John McCallbd309292010-07-06 01:34:17 +0000245 if (BI && BI->isUnconditional() &&
John McCallad5d61e2010-07-23 21:56:41 +0000246 BI->getSuccessor(0) == ReturnBlock.getBlock()) {
David Blaikie66e41972015-01-14 07:38:27 +0000247 // Record/return the DebugLoc of the simple 'return' expression to be used
248 // later by the actual 'ret' instruction.
249 llvm::DebugLoc Loc = BI->getDebugLoc();
Daniel Dunbarfd346a32009-01-26 23:27:52 +0000250 Builder.SetInsertPoint(BI->getParent());
251 BI->eraseFromParent();
John McCallad5d61e2010-07-23 21:56:41 +0000252 delete ReturnBlock.getBlock();
David Blaikie66e41972015-01-14 07:38:27 +0000253 return Loc;
Daniel Dunbarfd346a32009-01-26 23:27:52 +0000254 }
255 }
256
Mike Stump18bb9282009-05-16 07:57:57 +0000257 // FIXME: We are at an unreachable point, there is no reason to emit the block
258 // unless it has uses. However, we still need a place to put the debug
259 // region.end for now.
Daniel Dunbarfd346a32009-01-26 23:27:52 +0000260
John McCallad5d61e2010-07-23 21:56:41 +0000261 EmitBlock(ReturnBlock.getBlock());
David Blaikie66e41972015-01-14 07:38:27 +0000262 return llvm::DebugLoc();
John McCallbd309292010-07-06 01:34:17 +0000263}
264
265static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
266 if (!BB) return;
267 if (!BB->use_empty())
268 return CGF.CurFn->getBasicBlockList().push_back(BB);
269 delete BB;
Daniel Dunbarfd346a32009-01-26 23:27:52 +0000270}
271
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000272void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
Chris Lattnere73e4322007-07-16 21:28:45 +0000273 assert(BreakContinueStack.empty() &&
274 "mismatched push/pop in break/continue stack!");
Mike Stump11289f42009-09-09 15:08:12 +0000275
Adrian Prantl52bf3c42013-05-03 20:11:48 +0000276 bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
Adrian Prantl524ba1f2013-07-25 00:23:42 +0000277 && NumSimpleReturnExprs == NumReturnExprs
278 && ReturnBlock.getBlock()->use_empty();
279 // Usually the return expression is evaluated before the cleanup
280 // code. If the function contains only a simple return statement,
281 // such as a constant, the location before the cleanup code becomes
282 // the last useful breakpoint in the function, because the simple
283 // return expression will be evaluated after the cleanup code. To be
284 // safe, set the debug location for cleanup code to the location of
285 // the return statement. Otherwise the cleanup code should be at the
286 // end of the function's lexical scope.
287 //
288 // If there are multiple branches to the return block, the branch
289 // instructions will get the location of the return statements and
290 // all will be fine.
Adrian Prantl3be10542013-05-02 17:30:20 +0000291 if (CGDebugInfo *DI = getDebugInfo()) {
Adrian Prantl52bf3c42013-05-03 20:11:48 +0000292 if (OnlySimpleReturnStmts)
Adrian Prantle83b1302014-01-07 22:05:52 +0000293 DI->EmitLocation(Builder, LastStopPoint);
Adrian Prantl3be10542013-05-02 17:30:20 +0000294 else
Adrian Prantle83b1302014-01-07 22:05:52 +0000295 DI->EmitLocation(Builder, EndLoc);
Adrian Prantl3be10542013-05-02 17:30:20 +0000296 }
David Blaikie357aafb2013-02-01 19:09:49 +0000297
John McCall31168b02011-06-15 23:02:42 +0000298 // Pop any cleanups that might have been associated with the
299 // parameters. Do this in whatever block we're currently in; it's
300 // important to do this before we enter the return block or return
301 // edges will be *really* confused.
David Majnemerdc012fa2015-04-22 21:38:15 +0000302 bool HasCleanups = EHStack.stable_begin() != PrologueCleanupDepth;
303 bool HasOnlyLifetimeMarkers =
304 HasCleanups && EHStack.containsOnlyLifetimeMarkers(PrologueCleanupDepth);
305 bool EmitRetDbgLoc = !HasCleanups || HasOnlyLifetimeMarkers;
306 if (HasCleanups) {
Adrian Prantl3be10542013-05-02 17:30:20 +0000307 // Make sure the line table doesn't jump back into the body for
308 // the ret after it's been at EndLoc.
Adrian Prantl3be10542013-05-02 17:30:20 +0000309 if (CGDebugInfo *DI = getDebugInfo())
Adrian Prantl52bf3c42013-05-03 20:11:48 +0000310 if (OnlySimpleReturnStmts)
Adrian Prantle83b1302014-01-07 22:05:52 +0000311 DI->EmitLocation(Builder, EndLoc);
David Blaikie4d524432015-02-04 19:47:54 +0000312
313 PopCleanupBlocks(PrologueCleanupDepth);
Adrian Prantl3be10542013-05-02 17:30:20 +0000314 }
315
Mike Stump11289f42009-09-09 15:08:12 +0000316 // Emit function epilog (to return).
David Blaikie66e41972015-01-14 07:38:27 +0000317 llvm::DebugLoc Loc = EmitReturnBlock();
Daniel Dunbarfab3f932008-11-11 20:59:54 +0000318
Daniel Dunbar468a8f82011-02-10 17:32:22 +0000319 if (ShouldInstrumentFunction())
320 EmitFunctionInstrumentation("__cyg_profile_func_exit");
Chris Lattner3c77a352010-06-22 00:03:40 +0000321
Daniel Dunbarfab3f932008-11-11 20:59:54 +0000322 // Emit debug descriptor for function end.
David Blaikie66e41972015-01-14 07:38:27 +0000323 if (CGDebugInfo *DI = getDebugInfo())
Devang Patel0884a602010-07-22 22:29:16 +0000324 DI->EmitFunctionEnd(Builder);
Daniel Dunbarfab3f932008-11-11 20:59:54 +0000325
David Blaikie66e41972015-01-14 07:38:27 +0000326 // Reset the debug location to that of the simple 'return' expression, if any
327 // rather than that of the end of the function's scope '}'.
328 ApplyDebugLocation AL(*this, Loc);
Nick Lewycky2d84e842013-10-02 02:29:49 +0000329 EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc);
Mike Stump1d849212009-12-07 23:38:24 +0000330 EmitEndEHSpec(CurCodeDecl);
Daniel Dunbar54bb1932008-09-09 21:00:17 +0000331
John McCallbd309292010-07-06 01:34:17 +0000332 assert(EHStack.empty() &&
333 "did not remove all scopes from cleanup stack!");
334
Chris Lattner6c4d2552009-10-28 23:59:40 +0000335 // If someone did an indirect goto, emit the indirect goto block at the end of
336 // the function.
337 if (IndirectBranch) {
338 EmitBlock(IndirectBranch->getParent());
339 Builder.ClearInsertionPoint();
340 }
Michael Ilseman686240a2012-12-04 00:29:55 +0000341
Reid Kleckner98cb8ba2015-07-07 22:26:07 +0000342 // If some of our locals escaped, insert a call to llvm.localescape in the
Reid Kleckner31a1bb02015-04-08 22:23:48 +0000343 // entry block.
344 if (!EscapedLocals.empty()) {
345 // Invert the map from local to index into a simple vector. There should be
346 // no holes.
347 SmallVector<llvm::Value *, 4> EscapeArgs;
348 EscapeArgs.resize(EscapedLocals.size());
349 for (auto &Pair : EscapedLocals)
350 EscapeArgs[Pair.second] = Pair.first;
351 llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration(
Reid Kleckner98cb8ba2015-07-07 22:26:07 +0000352 &CGM.getModule(), llvm::Intrinsic::localescape);
John McCall7f416cc2015-09-08 08:05:57 +0000353 CGBuilderTy(*this, AllocaInsertPt).CreateCall(FrameEscapeFn, EscapeArgs);
Reid Kleckner31a1bb02015-04-08 22:23:48 +0000354 }
355
Chris Lattnerc48023b2007-12-02 06:32:24 +0000356 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
Chris Lattner2739d2b2009-03-31 22:17:44 +0000357 llvm::Instruction *Ptr = AllocaInsertPt;
Craig Topper8a13c412014-05-21 05:09:00 +0000358 AllocaInsertPt = nullptr;
Chris Lattner2739d2b2009-03-31 22:17:44 +0000359 Ptr->eraseFromParent();
Michael Ilseman686240a2012-12-04 00:29:55 +0000360
Chris Lattner6c4d2552009-10-28 23:59:40 +0000361 // If someone took the address of a label but never did an indirect goto, we
362 // made a zero entry PHI node, which is illegal, zap it now.
363 if (IndirectBranch) {
364 llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
365 if (PN->getNumIncomingValues() == 0) {
366 PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
367 PN->eraseFromParent();
368 }
369 }
John McCallbd309292010-07-06 01:34:17 +0000370
John McCall8e4c74b2011-08-11 02:22:43 +0000371 EmitIfUsed(*this, EHResumeBlock);
John McCallbd309292010-07-06 01:34:17 +0000372 EmitIfUsed(*this, TerminateLandingPad);
373 EmitIfUsed(*this, TerminateHandler);
374 EmitIfUsed(*this, UnreachableBlock);
John McCall09ae0322010-07-06 23:57:41 +0000375
376 if (CGM.getCodeGenOpts().EmitDeclMetadata)
377 EmitDeclMetadata();
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000378
379 for (SmallVectorImpl<std::pair<llvm::Instruction *, llvm::Value *> >::iterator
380 I = DeferredReplacements.begin(),
381 E = DeferredReplacements.end();
382 I != E; ++I) {
383 I->first->replaceAllUsesWith(I->second);
384 I->first->eraseFromParent();
385 }
Chris Lattnerd1af2d22007-05-29 23:17:50 +0000386}
Chris Lattner308f4312007-05-29 23:50:05 +0000387
Chris Lattner3c77a352010-06-22 00:03:40 +0000388/// ShouldInstrumentFunction - Return true if the current function should be
389/// instrumented with __cyg_profile_func_* calls
390bool CodeGenFunction::ShouldInstrumentFunction() {
391 if (!CGM.getCodeGenOpts().InstrumentFunctions)
392 return false;
Ted Kremenekc249c412011-05-16 23:49:20 +0000393 if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
Chris Lattner3c77a352010-06-22 00:03:40 +0000394 return false;
395 return true;
396}
397
398/// EmitFunctionInstrumentation - Emit LLVM code to call the specified
399/// instrumentation function with the current function and the call site, if
400/// function instrumentation is enabled.
401void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) {
Chris Lattnerb48a2d52010-06-23 05:21:28 +0000402 // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site);
Chris Lattnera5f58b02011-07-09 17:41:47 +0000403 llvm::PointerType *PointerTy = Int8PtrTy;
404 llvm::Type *ProfileFuncArgs[] = { PointerTy, PointerTy };
Chris Lattner2192fe52011-07-18 04:24:23 +0000405 llvm::FunctionType *FunctionTy =
Chris Lattnerece04092012-02-07 00:39:47 +0000406 llvm::FunctionType::get(VoidTy, ProfileFuncArgs, false);
Chris Lattner3c77a352010-06-22 00:03:40 +0000407
408 llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn);
409 llvm::CallInst *CallSite = Builder.CreateCall(
Benjamin Kramer8d375ce2011-07-14 17:45:50 +0000410 CGM.getIntrinsic(llvm::Intrinsic::returnaddress),
Chris Lattner5e016ae2010-06-27 07:15:29 +0000411 llvm::ConstantInt::get(Int32Ty, 0),
Chris Lattner3c77a352010-06-22 00:03:40 +0000412 "callsite");
413
John McCall882987f2013-02-28 19:01:20 +0000414 llvm::Value *args[] = {
415 llvm::ConstantExpr::getBitCast(CurFn, PointerTy),
416 CallSite
417 };
418
419 EmitNounwindRuntimeCall(F, args);
Chris Lattner3c77a352010-06-22 00:03:40 +0000420}
421
Roman Divacky178e01602011-02-10 16:52:03 +0000422void CodeGenFunction::EmitMCountInstrumentation() {
Chris Lattnerece04092012-02-07 00:39:47 +0000423 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
Roman Divacky178e01602011-02-10 16:52:03 +0000424
John McCallc8e01702013-04-16 22:48:15 +0000425 llvm::Constant *MCountFn =
426 CGM.CreateRuntimeFunction(FTy, getTarget().getMCountName());
John McCall882987f2013-02-28 19:01:20 +0000427 EmitNounwindRuntimeCall(MCountFn);
Roman Divacky178e01602011-02-10 16:52:03 +0000428}
429
Tanya Lattner7445ada2012-07-11 23:02:10 +0000430// OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument
431// information in the program executable. The argument information stored
432// includes the argument name, its type, the address and access qualifiers used.
Tanya Lattner7445ada2012-07-11 23:02:10 +0000433static void GenOpenCLArgMetadata(const FunctionDecl *FD, llvm::Function *Fn,
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +0000434 CodeGenModule &CGM, llvm::LLVMContext &Context,
435 SmallVector<llvm::Metadata *, 5> &kernelMDArgs,
436 CGBuilderTy &Builder, ASTContext &ASTCtx) {
Guy Benyeifb36ede2013-03-24 13:58:12 +0000437 // Create MDNodes that represent the kernel arg metadata.
Tanya Lattner7445ada2012-07-11 23:02:10 +0000438 // Each MDNode is a list in the form of "key", N number of values which is
439 // the same number of values as their are kernel arguments.
Michael Ilseman686240a2012-12-04 00:29:55 +0000440
Joey Gouly92a47442014-04-04 13:43:57 +0000441 const PrintingPolicy &Policy = ASTCtx.getPrintingPolicy();
442
Guy Benyeifb36ede2013-03-24 13:58:12 +0000443 // MDNode for the kernel argument address space qualifiers.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +0000444 SmallVector<llvm::Metadata *, 8> addressQuals;
Guy Benyeifb36ede2013-03-24 13:58:12 +0000445 addressQuals.push_back(llvm::MDString::get(Context, "kernel_arg_addr_space"));
446
447 // MDNode for the kernel argument access qualifiers (images only).
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +0000448 SmallVector<llvm::Metadata *, 8> accessQuals;
Guy Benyeifb36ede2013-03-24 13:58:12 +0000449 accessQuals.push_back(llvm::MDString::get(Context, "kernel_arg_access_qual"));
450
451 // MDNode for the kernel argument type names.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +0000452 SmallVector<llvm::Metadata *, 8> argTypeNames;
Guy Benyeifb36ede2013-03-24 13:58:12 +0000453 argTypeNames.push_back(llvm::MDString::get(Context, "kernel_arg_type"));
454
Fraser Cormackdadc3712014-07-30 14:39:53 +0000455 // MDNode for the kernel argument base type names.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +0000456 SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
Fraser Cormackdadc3712014-07-30 14:39:53 +0000457 argBaseTypeNames.push_back(
458 llvm::MDString::get(Context, "kernel_arg_base_type"));
459
Guy Benyeifb36ede2013-03-24 13:58:12 +0000460 // MDNode for the kernel argument type qualifiers.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +0000461 SmallVector<llvm::Metadata *, 8> argTypeQuals;
Guy Benyeifb36ede2013-03-24 13:58:12 +0000462 argTypeQuals.push_back(llvm::MDString::get(Context, "kernel_arg_type_qual"));
463
Tanya Lattner7445ada2012-07-11 23:02:10 +0000464 // MDNode for the kernel argument names.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +0000465 SmallVector<llvm::Metadata *, 8> argNames;
Tanya Lattner7445ada2012-07-11 23:02:10 +0000466 argNames.push_back(llvm::MDString::get(Context, "kernel_arg_name"));
Michael Ilseman686240a2012-12-04 00:29:55 +0000467
Tanya Lattner7445ada2012-07-11 23:02:10 +0000468 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
469 const ParmVarDecl *parm = FD->getParamDecl(i);
Guy Benyeifb36ede2013-03-24 13:58:12 +0000470 QualType ty = parm->getType();
471 std::string typeQuals;
472
473 if (ty->isPointerType()) {
474 QualType pointeeTy = ty->getPointeeType();
475
476 // Get address qualifier.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +0000477 addressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(
478 ASTCtx.getTargetAddressSpace(pointeeTy.getAddressSpace()))));
Guy Benyeifb36ede2013-03-24 13:58:12 +0000479
480 // Get argument type name.
Joey Gouly92a47442014-04-04 13:43:57 +0000481 std::string typeName =
482 pointeeTy.getUnqualifiedType().getAsString(Policy) + "*";
Guy Benyeifb36ede2013-03-24 13:58:12 +0000483
484 // Turn "unsigned type" to "utype"
485 std::string::size_type pos = typeName.find("unsigned");
Fraser Cormack152493b2014-07-30 13:41:12 +0000486 if (pointeeTy.isCanonical() && pos != std::string::npos)
Benjamin Krameref89ae02013-03-24 16:04:55 +0000487 typeName.erase(pos+1, 8);
Guy Benyeifb36ede2013-03-24 13:58:12 +0000488
489 argTypeNames.push_back(llvm::MDString::get(Context, typeName));
490
Fraser Cormackdadc3712014-07-30 14:39:53 +0000491 std::string baseTypeName =
492 pointeeTy.getUnqualifiedType().getCanonicalType().getAsString(
493 Policy) +
494 "*";
495
496 // Turn "unsigned type" to "utype"
497 pos = baseTypeName.find("unsigned");
498 if (pos != std::string::npos)
499 baseTypeName.erase(pos+1, 8);
500
501 argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
502
Guy Benyeifb36ede2013-03-24 13:58:12 +0000503 // Get argument type qualifiers:
504 if (ty.isRestrictQualified())
505 typeQuals = "restrict";
506 if (pointeeTy.isConstQualified() ||
507 (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
Benjamin Krameref89ae02013-03-24 16:04:55 +0000508 typeQuals += typeQuals.empty() ? "const" : " const";
Guy Benyeifb36ede2013-03-24 13:58:12 +0000509 if (pointeeTy.isVolatileQualified())
Benjamin Krameref89ae02013-03-24 16:04:55 +0000510 typeQuals += typeQuals.empty() ? "volatile" : " volatile";
Guy Benyeifb36ede2013-03-24 13:58:12 +0000511 } else {
Pekka Jaaskelainen3587b322014-01-09 13:37:30 +0000512 uint32_t AddrSpc = 0;
513 if (ty->isImageType())
514 AddrSpc =
515 CGM.getContext().getTargetAddressSpace(LangAS::opencl_global);
Bob Wilson95a27b02014-02-17 19:20:59 +0000516
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +0000517 addressQuals.push_back(
518 llvm::ConstantAsMetadata::get(Builder.getInt32(AddrSpc)));
Guy Benyeifb36ede2013-03-24 13:58:12 +0000519
520 // Get argument type name.
Joey Gouly92a47442014-04-04 13:43:57 +0000521 std::string typeName = ty.getUnqualifiedType().getAsString(Policy);
Guy Benyeifb36ede2013-03-24 13:58:12 +0000522
523 // Turn "unsigned type" to "utype"
524 std::string::size_type pos = typeName.find("unsigned");
Fraser Cormack152493b2014-07-30 13:41:12 +0000525 if (ty.isCanonical() && pos != std::string::npos)
Benjamin Krameref89ae02013-03-24 16:04:55 +0000526 typeName.erase(pos+1, 8);
Guy Benyeifb36ede2013-03-24 13:58:12 +0000527
528 argTypeNames.push_back(llvm::MDString::get(Context, typeName));
529
Fraser Cormackdadc3712014-07-30 14:39:53 +0000530 std::string baseTypeName =
531 ty.getUnqualifiedType().getCanonicalType().getAsString(Policy);
532
533 // Turn "unsigned type" to "utype"
534 pos = baseTypeName.find("unsigned");
535 if (pos != std::string::npos)
536 baseTypeName.erase(pos+1, 8);
537
538 argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
539
Guy Benyeifb36ede2013-03-24 13:58:12 +0000540 // Get argument type qualifiers:
541 if (ty.isConstQualified())
542 typeQuals = "const";
543 if (ty.isVolatileQualified())
Benjamin Krameref89ae02013-03-24 16:04:55 +0000544 typeQuals += typeQuals.empty() ? "volatile" : " volatile";
Guy Benyeifb36ede2013-03-24 13:58:12 +0000545 }
Justin Bogner0f066062013-11-22 10:20:40 +0000546
Guy Benyeifb36ede2013-03-24 13:58:12 +0000547 argTypeQuals.push_back(llvm::MDString::get(Context, typeQuals));
548
549 // Get image access qualifier:
550 if (ty->isImageType()) {
Aaron Ballmanc4327992013-12-19 03:09:10 +0000551 const OpenCLImageAccessAttr *A = parm->getAttr<OpenCLImageAccessAttr>();
Aaron Ballman26891332014-01-14 17:41:53 +0000552 if (A && A->isWriteOnly())
Guy Benyeifb36ede2013-03-24 13:58:12 +0000553 accessQuals.push_back(llvm::MDString::get(Context, "write_only"));
554 else
555 accessQuals.push_back(llvm::MDString::get(Context, "read_only"));
Aaron Ballman26891332014-01-14 17:41:53 +0000556 // FIXME: what about read_write?
Guy Benyeifb36ede2013-03-24 13:58:12 +0000557 } else
558 accessQuals.push_back(llvm::MDString::get(Context, "none"));
Michael Ilseman686240a2012-12-04 00:29:55 +0000559
Tanya Lattner7445ada2012-07-11 23:02:10 +0000560 // Get argument name.
561 argNames.push_back(llvm::MDString::get(Context, parm->getName()));
Tanya Lattner7445ada2012-07-11 23:02:10 +0000562 }
Guy Benyeifb36ede2013-03-24 13:58:12 +0000563
564 kernelMDArgs.push_back(llvm::MDNode::get(Context, addressQuals));
565 kernelMDArgs.push_back(llvm::MDNode::get(Context, accessQuals));
566 kernelMDArgs.push_back(llvm::MDNode::get(Context, argTypeNames));
Fraser Cormackdadc3712014-07-30 14:39:53 +0000567 kernelMDArgs.push_back(llvm::MDNode::get(Context, argBaseTypeNames));
Guy Benyeifb36ede2013-03-24 13:58:12 +0000568 kernelMDArgs.push_back(llvm::MDNode::get(Context, argTypeQuals));
Sameer Sahasrabuddhec6093fe2014-12-04 05:30:58 +0000569 if (CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
570 kernelMDArgs.push_back(llvm::MDNode::get(Context, argNames));
Tanya Lattner7445ada2012-07-11 23:02:10 +0000571}
572
Michael Ilseman686240a2012-12-04 00:29:55 +0000573void CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD,
Tanya Lattnerbcffcdf2012-07-09 22:06:01 +0000574 llvm::Function *Fn)
575{
576 if (!FD->hasAttr<OpenCLKernelAttr>())
577 return;
578
579 llvm::LLVMContext &Context = getLLVMContext();
580
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +0000581 SmallVector<llvm::Metadata *, 5> kernelMDArgs;
582 kernelMDArgs.push_back(llvm::ConstantAsMetadata::get(Fn));
Tanya Lattnerbcffcdf2012-07-09 22:06:01 +0000583
Sameer Sahasrabuddhec6093fe2014-12-04 05:30:58 +0000584 GenOpenCLArgMetadata(FD, Fn, CGM, Context, kernelMDArgs, Builder,
585 getContext());
Michael Ilseman686240a2012-12-04 00:29:55 +0000586
Aaron Ballmanc4327992013-12-19 03:09:10 +0000587 if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) {
588 QualType hintQTy = A->getTypeHint();
Joey Goulyaba589c2013-03-08 09:42:32 +0000589 const ExtVectorType *hintEltQTy = hintQTy->getAs<ExtVectorType>();
590 bool isSignedInteger =
591 hintQTy->isSignedIntegerType() ||
592 (hintEltQTy && hintEltQTy->getElementType()->isSignedIntegerType());
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +0000593 llvm::Metadata *attrMDArgs[] = {
594 llvm::MDString::get(Context, "vec_type_hint"),
595 llvm::ConstantAsMetadata::get(llvm::UndefValue::get(
596 CGM.getTypes().ConvertType(A->getTypeHint()))),
597 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
598 llvm::IntegerType::get(Context, 32),
599 llvm::APInt(32, (uint64_t)(isSignedInteger ? 1 : 0))))};
Joey Goulyaba589c2013-03-08 09:42:32 +0000600 kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
601 }
602
Aaron Ballmanc4327992013-12-19 03:09:10 +0000603 if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +0000604 llvm::Metadata *attrMDArgs[] = {
605 llvm::MDString::get(Context, "work_group_size_hint"),
606 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
607 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
608 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
Tanya Lattnerbcffcdf2012-07-09 22:06:01 +0000609 kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
610 }
611
Aaron Ballmanc4327992013-12-19 03:09:10 +0000612 if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +0000613 llvm::Metadata *attrMDArgs[] = {
614 llvm::MDString::get(Context, "reqd_work_group_size"),
615 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
616 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
617 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
Tanya Lattnerbcffcdf2012-07-09 22:06:01 +0000618 kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
619 }
620
621 llvm::MDNode *kernelMDNode = llvm::MDNode::get(Context, kernelMDArgs);
622 llvm::NamedMDNode *OpenCLKernelMetadata =
623 CGM.getModule().getOrInsertNamedMetadata("opencl.kernels");
624 OpenCLKernelMetadata->addOperand(kernelMDNode);
625}
626
Adrian Prantl2cede0f2014-04-29 01:07:59 +0000627/// Determine whether the function F ends with a return stmt.
628static bool endsWithReturn(const Decl* F) {
629 const Stmt *Body = nullptr;
630 if (auto *FD = dyn_cast_or_null<FunctionDecl>(F))
631 Body = FD->getBody();
632 else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F))
633 Body = OMD->getBody();
634
635 if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
636 auto LastStmt = CS->body_rbegin();
637 if (LastStmt != CS->body_rend())
638 return isa<ReturnStmt>(*LastStmt);
639 }
640 return false;
641}
642
John McCalldec348f72013-05-03 07:33:41 +0000643void CodeGenFunction::StartFunction(GlobalDecl GD,
644 QualType RetTy,
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000645 llvm::Function *Fn,
John McCalla738c252011-03-09 04:27:21 +0000646 const CGFunctionInfo &FnInfo,
Daniel Dunbar354d2782008-10-18 18:22:23 +0000647 const FunctionArgList &Args,
Adrian Prantl42d71b92014-04-10 23:21:53 +0000648 SourceLocation Loc,
Tilmann Scheller99cc30c2011-03-02 21:36:49 +0000649 SourceLocation StartLoc) {
David Blaikie8e6c36e2014-10-14 16:43:46 +0000650 assert(!CurFn &&
651 "Do not use a CodeGenFunction object for more than one function");
652
Anders Carlsson73fcc952009-09-11 00:07:24 +0000653 const Decl *D = GD.getDecl();
Michael Ilseman686240a2012-12-04 00:29:55 +0000654
Anders Carlssonf4478e92009-02-09 20:20:56 +0000655 DidCallStackSave = false;
John McCalldec348f72013-05-03 07:33:41 +0000656 CurCodeDecl = D;
Craig Topper8a13c412014-05-21 05:09:00 +0000657 CurFuncDecl = (D ? D->getNonClosureContext() : nullptr);
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000658 FnRetTy = RetTy;
Daniel Dunbar9c426522008-07-29 23:18:29 +0000659 CurFn = Fn;
John McCalla738c252011-03-09 04:27:21 +0000660 CurFnInfo = &FnInfo;
Chris Lattner5696e7b2008-06-17 18:05:57 +0000661 assert(CurFn->isDeclaration() && "Function already has body?");
662
Alexey Samsonov1444bb92014-10-17 00:20:19 +0000663 if (CGM.isInSanitizerBlacklist(Fn, Loc))
Alexey Samsonov035462c2014-10-30 19:33:44 +0000664 SanOpts.clear();
Will Dietzf54319c2013-01-18 11:30:38 +0000665
Peter Collingbourne915df992015-05-15 18:33:32 +0000666 if (D) {
667 // Apply the no_sanitize* attributes to SanOpts.
668 for (auto Attr : D->specific_attrs<NoSanitizeAttr>())
669 SanOpts.Mask &= ~Attr->getMask();
670 }
671
672 // Apply sanitizer attributes to the function.
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000673 if (SanOpts.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress))
Peter Collingbourne915df992015-05-15 18:33:32 +0000674 Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
675 if (SanOpts.has(SanitizerKind::Thread))
676 Fn->addFnAttr(llvm::Attribute::SanitizeThread);
677 if (SanOpts.has(SanitizerKind::Memory))
678 Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
Peter Collingbournec4122c12015-06-15 21:08:13 +0000679 if (SanOpts.has(SanitizerKind::SafeStack))
680 Fn->addFnAttr(llvm::Attribute::SafeStack);
Peter Collingbourne915df992015-05-15 18:33:32 +0000681
Jakob Stoklund Olesen819e54b2010-02-09 00:10:00 +0000682 // Pass inline keyword to optimizer if it appears explicitly on any
Roman Divackydd9bfb22014-01-15 19:07:16 +0000683 // declaration. Also, in the case of -fno-inline attach NoInline
David Majnemer19d7d542014-02-25 10:51:14 +0000684 // attribute to all function that are not marked AlwaysInline.
Roman Divackydd9bfb22014-01-15 19:07:16 +0000685 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
686 if (!CGM.getCodeGenOpts().NoInline) {
Aaron Ballman86c93902014-03-06 23:45:36 +0000687 for (auto RI : FD->redecls())
Chad Rosier883b2572012-03-14 23:32:11 +0000688 if (RI->isInlineSpecified()) {
Bill Wendling207f0532012-12-20 19:27:06 +0000689 Fn->addFnAttr(llvm::Attribute::InlineHint);
Chad Rosier883b2572012-03-14 23:32:11 +0000690 break;
691 }
David Majnemer67e541e1c2014-02-25 09:53:29 +0000692 } else if (!FD->hasAttr<AlwaysInlineAttr>())
Roman Divackydd9bfb22014-01-15 19:07:16 +0000693 Fn->addFnAttr(llvm::Attribute::NoInline);
694 }
Jakob Stoklund Olesen819e54b2010-02-09 00:10:00 +0000695
Richard Smith9c6890a2012-11-01 22:30:59 +0000696 if (getLangOpts().OpenCL) {
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +0000697 // Add metadata for a kernel function.
698 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
Tanya Lattnerbcffcdf2012-07-09 22:06:01 +0000699 EmitOpenCLKernelMetadata(FD, Fn);
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +0000700 }
701
Peter Collingbourneb453cd62013-10-20 21:29:19 +0000702 // If we are checking function types, emit a function type signature as
Peter Collingbourne1a0a9a32014-12-03 02:08:51 +0000703 // prologue data.
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000704 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function)) {
Peter Collingbourneb453cd62013-10-20 21:29:19 +0000705 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Peter Collingbourne1a0a9a32014-12-03 02:08:51 +0000706 if (llvm::Constant *PrologueSig =
Peter Collingbourneb453cd62013-10-20 21:29:19 +0000707 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
708 llvm::Constant *FTRTTIConst =
709 CGM.GetAddrOfRTTIDescriptor(FD->getType(), /*ForEH=*/true);
Peter Collingbourne1a0a9a32014-12-03 02:08:51 +0000710 llvm::Constant *PrologueStructElems[] = { PrologueSig, FTRTTIConst };
711 llvm::Constant *PrologueStructConst =
712 llvm::ConstantStruct::getAnon(PrologueStructElems, /*Packed=*/true);
713 Fn->setPrologueData(PrologueStructConst);
Peter Collingbourneb453cd62013-10-20 21:29:19 +0000714 }
715 }
716 }
717
Daniel Dunbar75283ff2008-11-11 02:29:29 +0000718 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
Daniel Dunbar54bb1932008-09-09 21:00:17 +0000719
Chris Lattner5696e7b2008-06-17 18:05:57 +0000720 // Create a marker to make it easy to insert allocas into the entryblock
721 // later. Don't create this with the builder, because we don't want it
722 // folded.
Chris Lattner5e016ae2010-06-27 07:15:29 +0000723 llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
724 AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "", EntryBB);
Chris Lattner47640222009-03-22 00:24:14 +0000725 if (Builder.isNamePreserving())
726 AllocaInsertPt->setName("allocapt");
Mike Stump11289f42009-09-09 15:08:12 +0000727
John McCallbd309292010-07-06 01:34:17 +0000728 ReturnBlock = getJumpDestInCurrentScope("return");
Mike Stump11289f42009-09-09 15:08:12 +0000729
Chris Lattner5696e7b2008-06-17 18:05:57 +0000730 Builder.SetInsertPoint(EntryBB);
Mike Stump11289f42009-09-09 15:08:12 +0000731
Sanjiv Gupta1e8b6082008-07-04 11:04:26 +0000732 // Emit subprogram debug descriptor.
Anders Carlsson63784f42009-02-13 08:11:52 +0000733 if (CGDebugInfo *DI = getDebugInfo()) {
Jordan Rose5c382722013-03-08 21:51:21 +0000734 SmallVector<QualType, 16> ArgTypes;
Eric Christopher4b4beb22011-10-21 23:30:10 +0000735 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
736 i != e; ++i) {
Jordan Rose5c382722013-03-08 21:51:21 +0000737 ArgTypes.push_back((*i)->getType());
Eric Christopher4b4beb22011-10-21 23:30:10 +0000738 }
739
John McCalldb40c7f2010-12-14 08:05:40 +0000740 QualType FnType =
Jordan Rose5c382722013-03-08 21:51:21 +0000741 getContext().getFunctionType(RetTy, ArgTypes,
John McCalldb40c7f2010-12-14 08:05:40 +0000742 FunctionProtoType::ExtProtoInfo());
Adrian Prantl42d71b92014-04-10 23:21:53 +0000743 DI->EmitFunctionStart(GD, Loc, StartLoc, FnType, CurFn, Builder);
Sanjiv Gupta1e8b6082008-07-04 11:04:26 +0000744 }
745
Daniel Dunbar468a8f82011-02-10 17:32:22 +0000746 if (ShouldInstrumentFunction())
747 EmitFunctionInstrumentation("__cyg_profile_func_enter");
Chris Lattner3c77a352010-06-22 00:03:40 +0000748
Roman Divacky178e01602011-02-10 16:52:03 +0000749 if (CGM.getCodeGenOpts().InstrumentForProfiling)
750 EmitMCountInstrumentation();
751
Eli Friedman4b1942c2009-12-04 02:43:40 +0000752 if (RetTy->isVoidType()) {
753 // Void type; nothing to return.
John McCall7f416cc2015-09-08 08:05:57 +0000754 ReturnValue = Address::invalid();
Adrian Prantl2cede0f2014-04-29 01:07:59 +0000755
756 // Count the implicit return.
757 if (!endsWithReturn(D))
758 ++NumReturnExprs;
Eli Friedman4b1942c2009-12-04 02:43:40 +0000759 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
John McCall47fb9502013-03-07 21:37:08 +0000760 !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
Eli Friedman4b1942c2009-12-04 02:43:40 +0000761 // Indirect aggregate return; emit returned value directly into sret slot.
Daniel Dunbarfd09df72010-02-16 19:45:20 +0000762 // This reduces code size, and affects correctness in C++.
Reid Kleckner37abaca2014-05-09 22:46:15 +0000763 auto AI = CurFn->arg_begin();
764 if (CurFnInfo->getReturnInfo().isSRetAfterThis())
765 ++AI;
John McCall7f416cc2015-09-08 08:05:57 +0000766 ReturnValue = Address(AI, CurFnInfo->getReturnInfo().getIndirectAlign());
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000767 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
768 !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
769 // Load the sret pointer from the argument struct and return into that.
770 unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
771 llvm::Function::arg_iterator EI = CurFn->arg_end();
772 --EI;
David Blaikie1ed728c2015-04-05 22:45:47 +0000773 llvm::Value *Addr = Builder.CreateStructGEP(nullptr, EI, Idx);
John McCall7f416cc2015-09-08 08:05:57 +0000774 Addr = Builder.CreateAlignedLoad(Addr, getPointerAlign(), "agg.result");
775 ReturnValue = Address(Addr, getNaturalTypeAlignment(RetTy));
Eli Friedman4b1942c2009-12-04 02:43:40 +0000776 } else {
Daniel Dunbarfd09df72010-02-16 19:45:20 +0000777 ReturnValue = CreateIRTemp(RetTy, "retval");
John McCall31168b02011-06-15 23:02:42 +0000778
779 // Tell the epilog emitter to autorelease the result. We do this
780 // now so that various specialized functions can suppress it
781 // during their IR-generation.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000782 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000783 !CurFnInfo->isReturnsRetained() &&
784 RetTy->isObjCRetainableType())
785 AutoreleaseResult = true;
Eli Friedman4b1942c2009-12-04 02:43:40 +0000786 }
787
Mike Stump1d849212009-12-07 23:38:24 +0000788 EmitStartEHSpec(CurCodeDecl);
John McCall31168b02011-06-15 23:02:42 +0000789
790 PrologueCleanupDepth = EHStack.stable_begin();
Daniel Dunbard931a872009-02-02 22:03:45 +0000791 EmitFunctionProlog(*CurFnInfo, CurFn, Args);
Mike Stump11289f42009-09-09 15:08:12 +0000792
Eli Friedman9fbeba02012-02-11 02:57:39 +0000793 if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
John McCall5d865c322010-08-31 07:33:07 +0000794 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
Eli Friedman9fbeba02012-02-11 02:57:39 +0000795 const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
796 if (MD->getParent()->isLambda() &&
797 MD->getOverloadedOperator() == OO_Call) {
798 // We're in a lambda; figure out the captures.
799 MD->getParent()->getCaptureFields(LambdaCaptureFields,
800 LambdaThisCaptureField);
801 if (LambdaThisCaptureField) {
802 // If this lambda captures this, load it.
John McCalldec348f72013-05-03 07:33:41 +0000803 LValue ThisLValue = EmitLValueForLambdaField(LambdaThisCaptureField);
Nick Lewycky2d84e842013-10-02 02:29:49 +0000804 CXXThisValue = EmitLoadOfLValue(ThisLValue,
805 SourceLocation()).getScalarVal();
Eli Friedman9fbeba02012-02-11 02:57:39 +0000806 }
Alexey Bataev39c81e22014-08-28 04:28:19 +0000807 for (auto *FD : MD->getParent()->fields()) {
808 if (FD->hasCapturedVLAType()) {
809 auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD),
810 SourceLocation()).getScalarVal();
811 auto VAT = FD->getCapturedVLAType();
812 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
813 }
814 }
Eli Friedman9fbeba02012-02-11 02:57:39 +0000815 } else {
816 // Not in a lambda; just use 'this' from the method.
817 // FIXME: Should we generate a new load for each use of 'this'? The
818 // fast register allocator would be happier...
819 CXXThisValue = CXXABIThisValue;
820 }
821 }
John McCall347132b2010-02-16 22:04:33 +0000822
Anders Carlssonc20879a2008-12-20 21:28:43 +0000823 // If any of the arguments have a variably modified type, make sure to
824 // emit the type size.
825 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
826 i != e; ++i) {
Eli Friedman1f576832012-11-14 22:09:59 +0000827 const VarDecl *VD = *i;
828
829 // Dig out the type as written from ParmVarDecls; it's unclear whether
830 // the standard (C99 6.9.1p10) requires this, but we're following the
831 // precedent set by gcc.
832 QualType Ty;
833 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
834 Ty = PVD->getOriginalType();
835 else
836 Ty = VD->getType();
Anders Carlssonc20879a2008-12-20 21:28:43 +0000837
838 if (Ty->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000839 EmitVariablyModifiedType(Ty);
Anders Carlssonc20879a2008-12-20 21:28:43 +0000840 }
Eric Christopher7cdf9482011-10-13 21:45:18 +0000841 // Emit a location at the end of the prologue.
842 if (CGDebugInfo *DI = getDebugInfo())
843 DI->EmitLocation(Builder, StartLoc);
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000844}
Eli Friedman3d421e12008-08-25 21:31:01 +0000845
Richard Smithb47c36f2013-11-05 09:12:18 +0000846void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args,
847 const Stmt *Body) {
Justin Bogner66242d62015-04-23 23:06:47 +0000848 incrementProfileCounter(Body);
Richard Smithb47c36f2013-11-05 09:12:18 +0000849 if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
David Blaikie0a21d0d2013-01-26 22:16:26 +0000850 EmitCompoundStmtWithoutScope(*S);
851 else
Richard Smithb47c36f2013-11-05 09:12:18 +0000852 EmitStmt(Body);
John McCall89b12b32010-02-18 03:17:58 +0000853}
854
Bob Wilsonbf854f02014-02-17 19:21:09 +0000855/// When instrumenting to collect profile data, the counts for some blocks
856/// such as switch cases need to not include the fall-through counts, so
857/// emit a branch around the instrumentation code. When not instrumenting,
858/// this just calls EmitBlock().
859void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB,
Justin Bogner66242d62015-04-23 23:06:47 +0000860 const Stmt *S) {
Craig Topper8a13c412014-05-21 05:09:00 +0000861 llvm::BasicBlock *SkipCountBB = nullptr;
Bob Wilsonbf854f02014-02-17 19:21:09 +0000862 if (HaveInsertPoint() && CGM.getCodeGenOpts().ProfileInstrGenerate) {
863 // When instrumenting for profiling, the fallthrough to certain
864 // statements needs to skip over the instrumentation code so that we
865 // get an accurate count.
866 SkipCountBB = createBasicBlock("skipcount");
867 EmitBranch(SkipCountBB);
868 }
869 EmitBlock(BB);
Justin Bogner66242d62015-04-23 23:06:47 +0000870 uint64_t CurrentCount = getCurrentProfileCount();
871 incrementProfileCounter(S);
872 setCurrentProfileCount(getCurrentProfileCount() + CurrentCount);
Bob Wilsonbf854f02014-02-17 19:21:09 +0000873 if (SkipCountBB)
874 EmitBlock(SkipCountBB);
875}
876
John McCall8601a752010-08-03 22:46:07 +0000877/// Tries to mark the given function nounwind based on the
878/// non-existence of any throwing calls within it. We believe this is
879/// lightweight enough to do at -O0.
880static void TryMarkNoThrow(llvm::Function *F) {
John McCall59966992010-08-11 22:38:33 +0000881 // LLVM treats 'nounwind' on a function as part of the type, so we
882 // can't do this on functions that can be overwritten.
883 if (F->mayBeOverridden()) return;
884
David Majnemerdbf10452015-07-31 17:58:45 +0000885 for (llvm::BasicBlock &BB : *F)
886 for (llvm::Instruction &I : BB)
887 if (I.mayThrow())
Bill Wendlingf0724e82011-09-19 20:31:14 +0000888 return;
David Majnemerdbf10452015-07-31 17:58:45 +0000889
Bill Wendling73e465e2012-10-10 03:13:20 +0000890 F->setDoesNotThrow();
John McCall8601a752010-08-03 22:46:07 +0000891}
892
John McCalla738c252011-03-09 04:27:21 +0000893void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
894 const CGFunctionInfo &FnInfo) {
Anders Carlsson73fcc952009-09-11 00:07:24 +0000895 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
Michael Ilseman686240a2012-12-04 00:29:55 +0000896
Anders Carlsson63784f42009-02-13 08:11:52 +0000897 // Check if we should generate debug info for this function.
David Blaikie92848de2013-08-26 20:33:21 +0000898 if (FD->hasAttr<NoDebugAttr>())
Craig Topper8a13c412014-05-21 05:09:00 +0000899 DebugInfo = nullptr; // disable debug info indefinitely for this function
Mike Stump11289f42009-09-09 15:08:12 +0000900
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000901 FunctionArgList Args;
Alp Toker314cc812014-01-25 16:55:45 +0000902 QualType ResTy = FD->getReturnType();
Mike Stump11289f42009-09-09 15:08:12 +0000903
Mike Stumpbee78dd2009-12-04 23:26:17 +0000904 CurGD = GD;
Reid Kleckner89077a12013-12-17 19:46:40 +0000905 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
906 if (MD && MD->isInstance()) {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000907 if (CGM.getCXXABI().HasThisReturn(GD))
908 ResTy = MD->getThisType(getContext());
David Majnemer0c0b6d92014-10-31 20:09:12 +0000909 else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
910 ResTy = CGM.getContext().VoidPtrTy;
Reid Kleckner89077a12013-12-17 19:46:40 +0000911 CGM.getCXXABI().buildThisParam(*this, Args);
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000912 }
Justin Bogner66242d62015-04-23 23:06:47 +0000913
Alexey Samsonov3551e312014-08-13 20:06:24 +0000914 Args.append(FD->param_begin(), FD->param_end());
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000915
Reid Kleckner89077a12013-12-17 19:46:40 +0000916 if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)))
917 CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args);
918
John McCall89b12b32010-02-18 03:17:58 +0000919 SourceRange BodyRange;
920 if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
Adrian Prantldc237b52013-05-16 00:41:26 +0000921 CurEHLocation = BodyRange.getEnd();
Anders Carlsson438cf922009-11-06 02:55:43 +0000922
Adrian Prantl42d71b92014-04-10 23:21:53 +0000923 // Use the location of the start of the function to determine where
924 // the function definition is located. By default use the location
925 // of the declaration as the location for the subprogram. A function
926 // may lack a declaration in the source code if it is created by code
927 // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
Alexey Samsonovcb1ad6f2014-07-08 20:23:18 +0000928 SourceLocation Loc = FD->getLocation();
Adrian Prantl42d71b92014-04-10 23:21:53 +0000929
Alexey Samsonovcb1ad6f2014-07-08 20:23:18 +0000930 // If this is a function specialization then use the pattern body
931 // as the location for the function.
932 if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern())
933 if (SpecDecl->hasBody(SpecDecl))
934 Loc = SpecDecl->getLocation();
Adrian Prantl42d71b92014-04-10 23:21:53 +0000935
John McCall89b12b32010-02-18 03:17:58 +0000936 // Emit the standard function prologue.
Adrian Prantl42d71b92014-04-10 23:21:53 +0000937 StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin());
Anders Carlsson438cf922009-11-06 02:55:43 +0000938
John McCall89b12b32010-02-18 03:17:58 +0000939 // Generate the body of the function.
Alex Lorenzee024992014-08-04 18:41:51 +0000940 PGO.checkGlobalDecl(GD);
Bob Wilsonda1ebed2014-03-06 04:55:41 +0000941 PGO.assignRegionCounters(GD.getDecl(), CurFn);
John McCallb81884d2010-02-19 09:25:03 +0000942 if (isa<CXXDestructorDecl>(FD))
943 EmitDestructorBody(Args);
944 else if (isa<CXXConstructorDecl>(FD))
945 EmitConstructorBody(Args);
Richard Smith9c6890a2012-11-01 22:30:59 +0000946 else if (getLangOpts().CUDA &&
Artem Belevichf3d3db62015-03-19 18:58:18 +0000947 !getLangOpts().CUDAIsDevice &&
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000948 FD->hasAttr<CUDAGlobalAttr>())
Artem Belevich52cc4872015-05-07 19:34:16 +0000949 CGM.getCUDARuntime().emitDeviceStub(*this, Args);
Eli Friedman5a6d5072012-02-16 01:37:33 +0000950 else if (isa<CXXConversionDecl>(FD) &&
Douglas Gregor355efbb2012-02-17 03:02:34 +0000951 cast<CXXConversionDecl>(FD)->isLambdaToBlockPointerConversion()) {
952 // The lambda conversion to block pointer is special; the semantics can't be
953 // expressed in the AST, so IRGen needs to special-case it.
954 EmitLambdaToBlockPointerBody(Args);
955 } else if (isa<CXXMethodDecl>(FD) &&
956 cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
Faisal Vali2b391ab2013-09-26 19:54:12 +0000957 // The lambda static invoker function is special, because it forwards or
Douglas Gregor355efbb2012-02-17 03:02:34 +0000958 // clones the body of the function call operator (but is actually static).
959 EmitLambdaStaticInvokeFunction(cast<CXXMethodDecl>(FD));
Lang Hamesbf122742013-02-17 07:22:09 +0000960 } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) &&
Nick Lewyckyb39be1f2013-09-10 05:14:39 +0000961 (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
962 cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
Lang Hamesbf122742013-02-17 07:22:09 +0000963 // Implicit copy-assignment gets the same special treatment as implicit
964 // copy-constructors.
965 emitImplicitAssignmentOperatorBody(Args);
Richard Smithb47c36f2013-11-05 09:12:18 +0000966 } else if (Stmt *Body = FD->getBody()) {
967 EmitFunctionBody(Args, Body);
Richard Smithb47c36f2013-11-05 09:12:18 +0000968 } else
969 llvm_unreachable("no definition for emitted function");
Anders Carlssonff8cce42010-02-07 19:45:40 +0000970
Richard Smith9f9e5822012-10-04 23:52:29 +0000971 // C++11 [stmt.return]p2:
972 // Flowing off the end of a function [...] results in undefined behavior in
973 // a value-returning function.
974 // C11 6.9.1p12:
975 // If the '}' that terminates a function is reached, and the value of the
976 // function call is used by the caller, the behavior is undefined.
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000977 if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && !SawAsmBlock &&
Alp Toker314cc812014-01-25 16:55:45 +0000978 !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000979 if (SanOpts.has(SanitizerKind::Return)) {
Alexey Samsonov24cad992014-07-17 18:46:27 +0000980 SanitizerScope SanScope(this);
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000981 llvm::Value *IsFalse = Builder.getFalse();
982 EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return),
983 "missing_return", EmitCheckSourceLocation(FD->getLocation()),
984 None);
Akira Hatanaka85365cd2015-07-02 22:15:41 +0000985 } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
986 EmitTrapCall(llvm::Intrinsic::trap);
987 }
Richard Smith9f9e5822012-10-04 23:52:29 +0000988 Builder.CreateUnreachable();
989 Builder.ClearInsertionPoint();
990 }
991
John McCall89b12b32010-02-18 03:17:58 +0000992 // Emit the standard function epilogue.
993 FinishFunction(BodyRange.getEnd());
John McCall8601a752010-08-03 22:46:07 +0000994
995 // If we haven't marked the function nothrow through other means, do
996 // a quick pass now to see if we can.
997 if (!CurFn->doesNotThrow())
998 TryMarkNoThrow(CurFn);
Chris Lattner5696e7b2008-06-17 18:05:57 +0000999}
1000
Chris Lattner5b1964b2008-11-11 07:41:27 +00001001/// ContainsLabel - Return true if the statement contains a label in it. If
1002/// this statement is not executed normally, it not containing a label means
1003/// that we can just remove the code.
1004bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
1005 // Null statement, not a label!
Craig Topper8a13c412014-05-21 05:09:00 +00001006 if (!S) return false;
Mike Stump11289f42009-09-09 15:08:12 +00001007
Chris Lattner5b1964b2008-11-11 07:41:27 +00001008 // If this is a label, we have to emit the code, consider something like:
1009 // if (0) { ... foo: bar(); } goto foo;
Chris Lattner29911cc2011-02-28 00:18:40 +00001010 //
1011 // TODO: If anyone cared, we could track __label__'s, since we know that you
1012 // can't jump to one from outside their declared region.
Chris Lattner5b1964b2008-11-11 07:41:27 +00001013 if (isa<LabelStmt>(S))
1014 return true;
Michael Ilseman686240a2012-12-04 00:29:55 +00001015
Chris Lattner5b1964b2008-11-11 07:41:27 +00001016 // If this is a case/default statement, and we haven't seen a switch, we have
1017 // to emit the code.
1018 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
1019 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001020
Chris Lattner5b1964b2008-11-11 07:41:27 +00001021 // If this is a switch statement, we want to ignore cases below it.
1022 if (isa<SwitchStmt>(S))
1023 IgnoreCaseStmts = true;
Mike Stump11289f42009-09-09 15:08:12 +00001024
Chris Lattner5b1964b2008-11-11 07:41:27 +00001025 // Scan subexpressions for verboten labels.
Benjamin Kramer642f1732015-07-02 21:03:14 +00001026 for (const Stmt *SubStmt : S->children())
1027 if (ContainsLabel(SubStmt, IgnoreCaseStmts))
Chris Lattner5b1964b2008-11-11 07:41:27 +00001028 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001029
Chris Lattner5b1964b2008-11-11 07:41:27 +00001030 return false;
1031}
1032
Chris Lattner29911cc2011-02-28 00:18:40 +00001033/// containsBreak - Return true if the statement contains a break out of it.
1034/// If the statement (recursively) contains a switch or loop with a break
1035/// inside of it, this is fine.
1036bool CodeGenFunction::containsBreak(const Stmt *S) {
1037 // Null statement, not a label!
Craig Topper8a13c412014-05-21 05:09:00 +00001038 if (!S) return false;
Chris Lattner29911cc2011-02-28 00:18:40 +00001039
1040 // If this is a switch or loop that defines its own break scope, then we can
1041 // include it and anything inside of it.
1042 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
1043 isa<ForStmt>(S))
Chris Lattner30db8282011-02-28 00:42:31 +00001044 return false;
Michael Ilseman686240a2012-12-04 00:29:55 +00001045
Chris Lattner30db8282011-02-28 00:42:31 +00001046 if (isa<BreakStmt>(S))
Chris Lattner29911cc2011-02-28 00:18:40 +00001047 return true;
Michael Ilseman686240a2012-12-04 00:29:55 +00001048
Chris Lattner29911cc2011-02-28 00:18:40 +00001049 // Scan subexpressions for verboten breaks.
Benjamin Kramer642f1732015-07-02 21:03:14 +00001050 for (const Stmt *SubStmt : S->children())
1051 if (containsBreak(SubStmt))
Chris Lattner29911cc2011-02-28 00:18:40 +00001052 return true;
Michael Ilseman686240a2012-12-04 00:29:55 +00001053
Chris Lattner29911cc2011-02-28 00:18:40 +00001054 return false;
1055}
1056
Chris Lattnercd439292008-11-12 08:04:58 +00001057
Chris Lattner41c6ab52011-02-27 23:02:32 +00001058/// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1059/// to a constant, or if it does but contains a label, return false. If it
1060/// constant folds return true and set the boolean result in Result.
1061bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
1062 bool &ResultBool) {
Richard Trieuc320c742012-07-23 20:21:35 +00001063 llvm::APSInt ResultInt;
Chris Lattner29911cc2011-02-28 00:18:40 +00001064 if (!ConstantFoldsToSimpleInteger(Cond, ResultInt))
1065 return false;
Michael Ilseman686240a2012-12-04 00:29:55 +00001066
Chris Lattner29911cc2011-02-28 00:18:40 +00001067 ResultBool = ResultInt.getBoolValue();
1068 return true;
1069}
1070
1071/// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1072/// to a constant, or if it does but contains a label, return false. If it
1073/// constant folds return true and set the folded value.
1074bool CodeGenFunction::
Richard Trieuc320c742012-07-23 20:21:35 +00001075ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &ResultInt) {
Daniel Dunbarf32443c2008-11-12 22:37:10 +00001076 // FIXME: Rename and handle conversion of other evaluatable things
1077 // to bool.
Richard Smith5fab0c92011-12-28 19:48:30 +00001078 llvm::APSInt Int;
1079 if (!Cond->EvaluateAsInt(Int, getContext()))
Chris Lattner41c6ab52011-02-27 23:02:32 +00001080 return false; // Not foldable, not integer or not fully evaluatable.
Richard Smith5fab0c92011-12-28 19:48:30 +00001081
Chris Lattnercd439292008-11-12 08:04:58 +00001082 if (CodeGenFunction::ContainsLabel(Cond))
Chris Lattner41c6ab52011-02-27 23:02:32 +00001083 return false; // Contains a label.
Richard Smith5fab0c92011-12-28 19:48:30 +00001084
1085 ResultInt = Int;
Chris Lattner41c6ab52011-02-27 23:02:32 +00001086 return true;
Chris Lattnercd439292008-11-12 08:04:58 +00001087}
1088
1089
Chris Lattner29911cc2011-02-28 00:18:40 +00001090
Chris Lattnercd439292008-11-12 08:04:58 +00001091/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
1092/// statement) to the specified blocks. Based on the condition, this might try
1093/// to simplify the codegen of the conditional based on the branch.
1094///
1095void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
1096 llvm::BasicBlock *TrueBlock,
Justin Bogneref512b92014-01-06 22:27:43 +00001097 llvm::BasicBlock *FalseBlock,
1098 uint64_t TrueCount) {
Peter Collingbourne91147592011-04-15 00:35:48 +00001099 Cond = Cond->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +00001100
Chris Lattnercd439292008-11-12 08:04:58 +00001101 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
Justin Bogneref512b92014-01-06 22:27:43 +00001102
Chris Lattnercd439292008-11-12 08:04:58 +00001103 // Handle X && Y in a condition.
John McCalle3027922010-08-25 11:45:40 +00001104 if (CondBOp->getOpcode() == BO_LAnd) {
Chris Lattnercd439292008-11-12 08:04:58 +00001105 // If we have "1 && X", simplify the code. "0 && X" would have constant
1106 // folded if the case was simple enough.
Bill Wendling6c9540e2011-03-04 21:46:03 +00001107 bool ConstantBool = false;
Chris Lattner41c6ab52011-02-27 23:02:32 +00001108 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
1109 ConstantBool) {
Chris Lattnercd439292008-11-12 08:04:58 +00001110 // br(1 && X) -> br(X).
Justin Bogner66242d62015-04-23 23:06:47 +00001111 incrementProfileCounter(CondBOp);
Justin Bogneref512b92014-01-06 22:27:43 +00001112 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
1113 TrueCount);
Chris Lattnercd439292008-11-12 08:04:58 +00001114 }
Mike Stump11289f42009-09-09 15:08:12 +00001115
Chris Lattnercd439292008-11-12 08:04:58 +00001116 // If we have "X && 1", simplify the code to use an uncond branch.
1117 // "X && 0" would have been constant folded to 0.
Chris Lattner41c6ab52011-02-27 23:02:32 +00001118 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
1119 ConstantBool) {
Chris Lattnercd439292008-11-12 08:04:58 +00001120 // br(X && 1) -> br(X).
Justin Bogneref512b92014-01-06 22:27:43 +00001121 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
1122 TrueCount);
Chris Lattnercd439292008-11-12 08:04:58 +00001123 }
Mike Stump11289f42009-09-09 15:08:12 +00001124
Chris Lattnercd439292008-11-12 08:04:58 +00001125 // Emit the LHS as a conditional. If the LHS conditional is false, we
1126 // want to jump to the FalseBlock.
Daniel Dunbara612e792008-11-13 01:38:36 +00001127 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
Justin Bogneref512b92014-01-06 22:27:43 +00001128 // The counter tells us how often we evaluate RHS, and all of TrueCount
1129 // can be propagated to that branch.
Justin Bogner66242d62015-04-23 23:06:47 +00001130 uint64_t RHSCount = getProfileCount(CondBOp->getRHS());
John McCallce1de612011-01-26 04:00:11 +00001131
1132 ConditionalEvaluation eval(*this);
David Blaikie298720d2015-01-28 19:50:09 +00001133 {
1134 ApplyDebugLocation DL(*this, Cond);
1135 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount);
1136 EmitBlock(LHSTrue);
1137 }
Mike Stump11289f42009-09-09 15:08:12 +00001138
Justin Bogner66242d62015-04-23 23:06:47 +00001139 incrementProfileCounter(CondBOp);
1140 setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
1141
Anders Carlsson60ddba62010-01-24 00:20:05 +00001142 // Any temporaries created here are conditional.
John McCallce1de612011-01-26 04:00:11 +00001143 eval.begin(*this);
Justin Bogneref512b92014-01-06 22:27:43 +00001144 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, TrueCount);
John McCallce1de612011-01-26 04:00:11 +00001145 eval.end(*this);
Anders Carlsson60ddba62010-01-24 00:20:05 +00001146
Chris Lattnercd439292008-11-12 08:04:58 +00001147 return;
Chris Lattner41c6ab52011-02-27 23:02:32 +00001148 }
Michael Ilseman686240a2012-12-04 00:29:55 +00001149
Chris Lattner41c6ab52011-02-27 23:02:32 +00001150 if (CondBOp->getOpcode() == BO_LOr) {
Chris Lattnercd439292008-11-12 08:04:58 +00001151 // If we have "0 || X", simplify the code. "1 || X" would have constant
1152 // folded if the case was simple enough.
Bill Wendling6c9540e2011-03-04 21:46:03 +00001153 bool ConstantBool = false;
Chris Lattner41c6ab52011-02-27 23:02:32 +00001154 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
1155 !ConstantBool) {
Chris Lattnercd439292008-11-12 08:04:58 +00001156 // br(0 || X) -> br(X).
Justin Bogner66242d62015-04-23 23:06:47 +00001157 incrementProfileCounter(CondBOp);
Justin Bogneref512b92014-01-06 22:27:43 +00001158 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
1159 TrueCount);
Chris Lattnercd439292008-11-12 08:04:58 +00001160 }
Mike Stump11289f42009-09-09 15:08:12 +00001161
Chris Lattnercd439292008-11-12 08:04:58 +00001162 // If we have "X || 0", simplify the code to use an uncond branch.
1163 // "X || 1" would have been constant folded to 1.
Chris Lattner41c6ab52011-02-27 23:02:32 +00001164 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
1165 !ConstantBool) {
Chris Lattnercd439292008-11-12 08:04:58 +00001166 // br(X || 0) -> br(X).
Justin Bogneref512b92014-01-06 22:27:43 +00001167 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
1168 TrueCount);
Chris Lattnercd439292008-11-12 08:04:58 +00001169 }
Mike Stump11289f42009-09-09 15:08:12 +00001170
Chris Lattnercd439292008-11-12 08:04:58 +00001171 // Emit the LHS as a conditional. If the LHS conditional is true, we
1172 // want to jump to the TrueBlock.
Daniel Dunbara612e792008-11-13 01:38:36 +00001173 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
Justin Bogneref512b92014-01-06 22:27:43 +00001174 // We have the count for entry to the RHS and for the whole expression
1175 // being true, so we can divy up True count between the short circuit and
1176 // the RHS.
Justin Bogner66242d62015-04-23 23:06:47 +00001177 uint64_t LHSCount =
1178 getCurrentProfileCount() - getProfileCount(CondBOp->getRHS());
Justin Bogneref512b92014-01-06 22:27:43 +00001179 uint64_t RHSCount = TrueCount - LHSCount;
John McCallce1de612011-01-26 04:00:11 +00001180
1181 ConditionalEvaluation eval(*this);
David Blaikie298720d2015-01-28 19:50:09 +00001182 {
1183 ApplyDebugLocation DL(*this, Cond);
1184 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount);
1185 EmitBlock(LHSFalse);
1186 }
Mike Stump11289f42009-09-09 15:08:12 +00001187
Justin Bogner66242d62015-04-23 23:06:47 +00001188 incrementProfileCounter(CondBOp);
1189 setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
1190
Anders Carlsson60ddba62010-01-24 00:20:05 +00001191 // Any temporaries created here are conditional.
John McCallce1de612011-01-26 04:00:11 +00001192 eval.begin(*this);
Justin Bogneref512b92014-01-06 22:27:43 +00001193 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, RHSCount);
1194
John McCallce1de612011-01-26 04:00:11 +00001195 eval.end(*this);
Anders Carlsson60ddba62010-01-24 00:20:05 +00001196
Chris Lattnercd439292008-11-12 08:04:58 +00001197 return;
1198 }
Chris Lattnerd9537732008-11-12 08:13:36 +00001199 }
Mike Stump11289f42009-09-09 15:08:12 +00001200
Chris Lattnerd9537732008-11-12 08:13:36 +00001201 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
1202 // br(!x, t, f) -> br(x, f, t)
Justin Bogneref512b92014-01-06 22:27:43 +00001203 if (CondUOp->getOpcode() == UO_LNot) {
1204 // Negate the count.
Justin Bogner66242d62015-04-23 23:06:47 +00001205 uint64_t FalseCount = getCurrentProfileCount() - TrueCount;
Justin Bogneref512b92014-01-06 22:27:43 +00001206 // Negate the condition and swap the destination blocks.
1207 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock,
1208 FalseCount);
1209 }
Chris Lattnercd439292008-11-12 08:04:58 +00001210 }
Mike Stump11289f42009-09-09 15:08:12 +00001211
Daniel Dunbarbf3c22e2008-11-12 10:30:32 +00001212 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
Eli Friedman248f8982012-02-14 03:54:45 +00001213 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
1214 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
1215 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
Daniel Dunbarbf3c22e2008-11-12 10:30:32 +00001216
Eli Friedman248f8982012-02-14 03:54:45 +00001217 ConditionalEvaluation cond(*this);
Justin Bogner66242d62015-04-23 23:06:47 +00001218 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock,
1219 getProfileCount(CondOp));
Justin Bogneref512b92014-01-06 22:27:43 +00001220
1221 // When computing PGO branch weights, we only know the overall count for
1222 // the true block. This code is essentially doing tail duplication of the
1223 // naive code-gen, introducing new edges for which counts are not
1224 // available. Divide the counts proportionally between the LHS and RHS of
1225 // the conditional operator.
1226 uint64_t LHSScaledTrueCount = 0;
1227 if (TrueCount) {
Justin Bogner66242d62015-04-23 23:06:47 +00001228 double LHSRatio =
1229 getProfileCount(CondOp) / (double)getCurrentProfileCount();
Justin Bogneref512b92014-01-06 22:27:43 +00001230 LHSScaledTrueCount = TrueCount * LHSRatio;
1231 }
John McCallce1de612011-01-26 04:00:11 +00001232
Eli Friedman248f8982012-02-14 03:54:45 +00001233 cond.begin(*this);
1234 EmitBlock(LHSBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001235 incrementProfileCounter(CondOp);
David Blaikie298720d2015-01-28 19:50:09 +00001236 {
1237 ApplyDebugLocation DL(*this, Cond);
1238 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock,
1239 LHSScaledTrueCount);
1240 }
Eli Friedman248f8982012-02-14 03:54:45 +00001241 cond.end(*this);
John McCallce1de612011-01-26 04:00:11 +00001242
Eli Friedman248f8982012-02-14 03:54:45 +00001243 cond.begin(*this);
1244 EmitBlock(RHSBlock);
Justin Bogneref512b92014-01-06 22:27:43 +00001245 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock,
1246 TrueCount - LHSScaledTrueCount);
Eli Friedman248f8982012-02-14 03:54:45 +00001247 cond.end(*this);
John McCallce1de612011-01-26 04:00:11 +00001248
Eli Friedman248f8982012-02-14 03:54:45 +00001249 return;
Daniel Dunbarbf3c22e2008-11-12 10:30:32 +00001250 }
1251
Richard Smithea852322013-05-07 21:53:22 +00001252 if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
1253 // Conditional operator handling can give us a throw expression as a
1254 // condition for a case like:
1255 // br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
1256 // Fold this to:
1257 // br(c, throw x, br(y, t, f))
1258 EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
1259 return;
1260 }
1261
Sanjay Patela24296b2015-09-02 20:01:30 +00001262 // If the branch has a condition wrapped by __builtin_unpredictable,
1263 // create metadata that specifies that the branch is unpredictable.
1264 // Don't bother if not optimizing because that metadata would not be used.
1265 llvm::MDNode *Unpredictable = nullptr;
1266 if (CGM.getCodeGenOpts().OptimizationLevel != 0) {
1267 if (const CallExpr *Call = dyn_cast<CallExpr>(Cond)) {
1268 const Decl *TargetDecl = Call->getCalleeDecl();
1269 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
1270 if (FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
1271 llvm::MDBuilder MDHelper(getLLVMContext());
1272 Unpredictable = MDHelper.createUnpredictable();
1273 }
1274 }
1275 }
1276 }
1277
Justin Bogneref512b92014-01-06 22:27:43 +00001278 // Create branch weights based on the number of times we get here and the
1279 // number of times the condition should be true.
Justin Bogner66242d62015-04-23 23:06:47 +00001280 uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount);
Justin Bogner65512642015-05-02 05:00:55 +00001281 llvm::MDNode *Weights =
1282 createProfileWeights(TrueCount, CurrentCount - TrueCount);
Justin Bogneref512b92014-01-06 22:27:43 +00001283
Chris Lattnercd439292008-11-12 08:04:58 +00001284 // Emit the code with the fully general case.
David Blaikie303facb2015-01-31 01:10:11 +00001285 llvm::Value *CondV;
1286 {
1287 ApplyDebugLocation DL(*this, Cond);
1288 CondV = EvaluateExprAsBool(Cond);
1289 }
Sanjay Patela24296b2015-09-02 20:01:30 +00001290 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable);
Chris Lattnercd439292008-11-12 08:04:58 +00001291}
1292
Daniel Dunbara7c8cf62008-08-16 00:56:44 +00001293/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerfc944342007-12-02 01:43:38 +00001294/// specified stmt yet.
David Blaikie4a9ec7b2013-08-19 21:02:26 +00001295void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
1296 CGM.ErrorUnsupported(S, Type);
Chris Lattnerfc944342007-12-02 01:43:38 +00001297}
1298
John McCall2725aa12011-02-01 21:35:06 +00001299/// emitNonZeroVLAInit - Emit the "zero" initialization of a
1300/// variable-length array whose elements have a non-zero bit-pattern.
1301///
James Dennettbe302452012-06-15 22:10:14 +00001302/// \param baseType the inner-most element type of the array
John McCall2725aa12011-02-01 21:35:06 +00001303/// \param src - a char* pointing to the bit-pattern for a single
1304/// base element of the array
1305/// \param sizeInChars - the total size of the VLA, in chars
John McCall2725aa12011-02-01 21:35:06 +00001306static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
John McCall7f416cc2015-09-08 08:05:57 +00001307 Address dest, Address src,
John McCall2725aa12011-02-01 21:35:06 +00001308 llvm::Value *sizeInChars) {
John McCall2725aa12011-02-01 21:35:06 +00001309 CGBuilderTy &Builder = CGF.Builder;
1310
John McCall7f416cc2015-09-08 08:05:57 +00001311 CharUnits baseSize = CGF.getContext().getTypeSizeInChars(baseType);
John McCall2725aa12011-02-01 21:35:06 +00001312 llvm::Value *baseSizeInChars
John McCall7f416cc2015-09-08 08:05:57 +00001313 = llvm::ConstantInt::get(CGF.IntPtrTy, baseSize.getQuantity());
John McCall2725aa12011-02-01 21:35:06 +00001314
John McCall7f416cc2015-09-08 08:05:57 +00001315 Address begin =
1316 Builder.CreateElementBitCast(dest, CGF.Int8Ty, "vla.begin");
1317 llvm::Value *end =
1318 Builder.CreateInBoundsGEP(begin.getPointer(), sizeInChars, "vla.end");
John McCall2725aa12011-02-01 21:35:06 +00001319
1320 llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
1321 llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
1322 llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
1323
1324 // Make a loop over the VLA. C99 guarantees that the VLA element
1325 // count must be nonzero.
1326 CGF.EmitBlock(loopBB);
1327
John McCall7f416cc2015-09-08 08:05:57 +00001328 llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2, "vla.cur");
1329 cur->addIncoming(begin.getPointer(), originBB);
1330
1331 CharUnits curAlign =
1332 dest.getAlignment().alignmentOfArrayElement(baseSize);
John McCall2725aa12011-02-01 21:35:06 +00001333
1334 // memcpy the individual element bit-pattern.
John McCall7f416cc2015-09-08 08:05:57 +00001335 Builder.CreateMemCpy(Address(cur, curAlign), src, baseSizeInChars,
John McCall2725aa12011-02-01 21:35:06 +00001336 /*volatile*/ false);
1337
1338 // Go to the next element.
John McCall7f416cc2015-09-08 08:05:57 +00001339 llvm::Value *next =
1340 Builder.CreateInBoundsGEP(CGF.Int8Ty, cur, baseSizeInChars, "vla.next");
John McCall2725aa12011-02-01 21:35:06 +00001341
1342 // Leave if that's the end of the VLA.
1343 llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
1344 Builder.CreateCondBr(done, contBB, loopBB);
1345 cur->addIncoming(next, loopBB);
1346
1347 CGF.EmitBlock(contBB);
Michael Ilseman686240a2012-12-04 00:29:55 +00001348}
John McCall2725aa12011-02-01 21:35:06 +00001349
Anders Carlssonc0964b62010-05-22 17:35:42 +00001350void
John McCall7f416cc2015-09-08 08:05:57 +00001351CodeGenFunction::EmitNullInitialization(Address DestPtr, QualType Ty) {
Anders Carlsson16e94af2010-05-03 01:20:20 +00001352 // Ignore empty classes in C++.
Richard Smith9c6890a2012-11-01 22:30:59 +00001353 if (getLangOpts().CPlusPlus) {
Anders Carlsson16e94af2010-05-03 01:20:20 +00001354 if (const RecordType *RT = Ty->getAs<RecordType>()) {
1355 if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
1356 return;
1357 }
1358 }
John McCall7cd1d972010-08-07 08:21:30 +00001359
1360 // Cast the dest ptr to the appropriate i8 pointer type.
John McCall7f416cc2015-09-08 08:05:57 +00001361 if (DestPtr.getElementType() != Int8Ty)
1362 DestPtr = Builder.CreateElementBitCast(DestPtr, Int8Ty);
Anders Carlsson2e744e82008-08-30 19:51:14 +00001363
1364 // Get size and alignment info for this aggregate.
John McCall7f416cc2015-09-08 08:05:57 +00001365 CharUnits size = getContext().getTypeSizeInChars(Ty);
Anders Carlsson2e744e82008-08-30 19:51:14 +00001366
John McCalla08ffd22011-01-14 10:37:58 +00001367 llvm::Value *SizeVal;
John McCall2725aa12011-02-01 21:35:06 +00001368 const VariableArrayType *vla;
Mike Stump11289f42009-09-09 15:08:12 +00001369
John McCalla08ffd22011-01-14 10:37:58 +00001370 // Don't bother emitting a zero-byte memset.
John McCall7f416cc2015-09-08 08:05:57 +00001371 if (size.isZero()) {
John McCalla08ffd22011-01-14 10:37:58 +00001372 // But note that getTypeInfo returns 0 for a VLA.
1373 if (const VariableArrayType *vlaType =
1374 dyn_cast_or_null<VariableArrayType>(
1375 getContext().getAsArrayType(Ty))) {
John McCall23c29fe2011-06-24 21:55:10 +00001376 QualType eltType;
1377 llvm::Value *numElts;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001378 std::tie(numElts, eltType) = getVLASize(vlaType);
John McCall23c29fe2011-06-24 21:55:10 +00001379
1380 SizeVal = numElts;
1381 CharUnits eltSize = getContext().getTypeSizeInChars(eltType);
1382 if (!eltSize.isOne())
1383 SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
John McCall2725aa12011-02-01 21:35:06 +00001384 vla = vlaType;
John McCalla08ffd22011-01-14 10:37:58 +00001385 } else {
1386 return;
1387 }
1388 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001389 SizeVal = CGM.getSize(size);
Craig Topper8a13c412014-05-21 05:09:00 +00001390 vla = nullptr;
John McCalla08ffd22011-01-14 10:37:58 +00001391 }
John McCall7cd1d972010-08-07 08:21:30 +00001392
1393 // If the type contains a pointer to data member we can't memset it to zero.
1394 // Instead, create a null constant and copy it to the destination.
John McCall2725aa12011-02-01 21:35:06 +00001395 // TODO: there are other patterns besides zero that we can usefully memset,
1396 // like -1, which happens to be the pattern used by member-pointers.
John McCall614dbdc2010-08-22 21:01:12 +00001397 if (!CGM.getTypes().isZeroInitializable(Ty)) {
John McCall2725aa12011-02-01 21:35:06 +00001398 // For a VLA, emit a single element, then splat that over the VLA.
1399 if (vla) Ty = getContext().getBaseElementType(vla);
John McCalla08ffd22011-01-14 10:37:58 +00001400
John McCall7cd1d972010-08-07 08:21:30 +00001401 llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
1402
Michael Ilseman686240a2012-12-04 00:29:55 +00001403 llvm::GlobalVariable *NullVariable =
John McCall7cd1d972010-08-07 08:21:30 +00001404 new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
Michael Ilseman686240a2012-12-04 00:29:55 +00001405 /*isConstant=*/true,
John McCall7cd1d972010-08-07 08:21:30 +00001406 llvm::GlobalVariable::PrivateLinkage,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001407 NullConstant, Twine());
John McCall7f416cc2015-09-08 08:05:57 +00001408 CharUnits NullAlign = DestPtr.getAlignment();
1409 NullVariable->setAlignment(NullAlign.getQuantity());
1410 Address SrcPtr(Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy()),
1411 NullAlign);
John McCall7cd1d972010-08-07 08:21:30 +00001412
John McCall2725aa12011-02-01 21:35:06 +00001413 if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
1414
John McCall7cd1d972010-08-07 08:21:30 +00001415 // Get and call the appropriate llvm.memcpy overload.
John McCall7f416cc2015-09-08 08:05:57 +00001416 Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, false);
John McCall7cd1d972010-08-07 08:21:30 +00001417 return;
Michael Ilseman686240a2012-12-04 00:29:55 +00001418 }
1419
John McCall7cd1d972010-08-07 08:21:30 +00001420 // Otherwise, just memset the whole thing to zero. This is legal
1421 // because in LLVM, all default initializers (other than the ones we just
1422 // handled above) are guaranteed to have a bit pattern of all zeros.
John McCall7f416cc2015-09-08 08:05:57 +00001423 Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, false);
Anders Carlsson2e744e82008-08-30 19:51:14 +00001424}
1425
Chris Lattnerc8e630e2011-02-17 07:39:24 +00001426llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
Chris Lattner6c4d2552009-10-28 23:59:40 +00001427 // Make sure that there is a block for the indirect goto.
Craig Topper8a13c412014-05-21 05:09:00 +00001428 if (!IndirectBranch)
Chris Lattner6c4d2552009-10-28 23:59:40 +00001429 GetIndirectGotoBlock();
Michael Ilseman686240a2012-12-04 00:29:55 +00001430
John McCallad5d61e2010-07-23 21:56:41 +00001431 llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
Michael Ilseman686240a2012-12-04 00:29:55 +00001432
Chris Lattner6c4d2552009-10-28 23:59:40 +00001433 // Make sure the indirect branch includes all of the address-taken blocks.
1434 IndirectBranch->addDestination(BB);
1435 return llvm::BlockAddress::get(CurFn, BB);
Chris Lattner2bb5cb42009-10-13 06:55:33 +00001436}
1437
1438llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
Chris Lattner6c4d2552009-10-28 23:59:40 +00001439 // If we already made the indirect branch for indirect goto, return its block.
1440 if (IndirectBranch) return IndirectBranch->getParent();
Michael Ilseman686240a2012-12-04 00:29:55 +00001441
John McCall7f416cc2015-09-08 08:05:57 +00001442 CGBuilderTy TmpBuilder(*this, createBasicBlock("indirectgoto"));
Michael Ilseman686240a2012-12-04 00:29:55 +00001443
Chris Lattner2bb5cb42009-10-13 06:55:33 +00001444 // Create the PHI node that indirect gotos will add entries to.
Jay Foad20c0f022011-03-30 11:28:58 +00001445 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
1446 "indirect.goto.dest");
Michael Ilseman686240a2012-12-04 00:29:55 +00001447
Chris Lattner6c4d2552009-10-28 23:59:40 +00001448 // Create the indirect branch instruction.
1449 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
1450 return IndirectBranch->getParent();
Daniel Dunbar88402ce2008-08-04 16:51:22 +00001451}
Anders Carlsson13abd7e2008-11-04 05:30:00 +00001452
John McCall82fe67b2011-07-09 01:37:26 +00001453/// Computes the length of an array in elements, as well as the base
1454/// element type and a properly-typed first element pointer.
1455llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
1456 QualType &baseType,
John McCall7f416cc2015-09-08 08:05:57 +00001457 Address &addr) {
John McCall82fe67b2011-07-09 01:37:26 +00001458 const ArrayType *arrayType = origArrayType;
1459
1460 // If it's a VLA, we have to load the stored size. Note that
1461 // this is the size of the VLA in bytes, not its size in elements.
Craig Topper8a13c412014-05-21 05:09:00 +00001462 llvm::Value *numVLAElements = nullptr;
John McCall82fe67b2011-07-09 01:37:26 +00001463 if (isa<VariableArrayType>(arrayType)) {
1464 numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).first;
1465
1466 // Walk into all VLAs. This doesn't require changes to addr,
1467 // which has type T* where T is the first non-VLA element type.
1468 do {
1469 QualType elementType = arrayType->getElementType();
1470 arrayType = getContext().getAsArrayType(elementType);
1471
1472 // If we only have VLA components, 'addr' requires no adjustment.
1473 if (!arrayType) {
1474 baseType = elementType;
1475 return numVLAElements;
1476 }
1477 } while (isa<VariableArrayType>(arrayType));
1478
1479 // We get out here only if we find a constant array type
1480 // inside the VLA.
1481 }
1482
1483 // We have some number of constant-length arrays, so addr should
1484 // have LLVM type [M x [N x [...]]]*. Build a GEP that walks
1485 // down to the first element of addr.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001486 SmallVector<llvm::Value*, 8> gepIndices;
John McCall82fe67b2011-07-09 01:37:26 +00001487
1488 // GEP down to the array type.
1489 llvm::ConstantInt *zero = Builder.getInt32(0);
1490 gepIndices.push_back(zero);
1491
John McCall82fe67b2011-07-09 01:37:26 +00001492 uint64_t countFromCLAs = 1;
Richard Smithf3c37e82012-04-22 05:51:36 +00001493 QualType eltType;
John McCall82fe67b2011-07-09 01:37:26 +00001494
Chris Lattner2192fe52011-07-18 04:24:23 +00001495 llvm::ArrayType *llvmArrayType =
John McCall7f416cc2015-09-08 08:05:57 +00001496 dyn_cast<llvm::ArrayType>(addr.getElementType());
Richard Smithf3c37e82012-04-22 05:51:36 +00001497 while (llvmArrayType) {
John McCall82fe67b2011-07-09 01:37:26 +00001498 assert(isa<ConstantArrayType>(arrayType));
1499 assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
1500 == llvmArrayType->getNumElements());
1501
1502 gepIndices.push_back(zero);
1503 countFromCLAs *= llvmArrayType->getNumElements();
Richard Smithf3c37e82012-04-22 05:51:36 +00001504 eltType = arrayType->getElementType();
John McCall82fe67b2011-07-09 01:37:26 +00001505
1506 llvmArrayType =
1507 dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
John McCall82fe67b2011-07-09 01:37:26 +00001508 arrayType = getContext().getAsArrayType(arrayType->getElementType());
Richard Smithf3c37e82012-04-22 05:51:36 +00001509 assert((!llvmArrayType || arrayType) &&
1510 "LLVM and Clang types are out-of-synch");
John McCall82fe67b2011-07-09 01:37:26 +00001511 }
1512
Richard Smithf3c37e82012-04-22 05:51:36 +00001513 if (arrayType) {
1514 // From this point onwards, the Clang array type has been emitted
1515 // as some other type (probably a packed struct). Compute the array
1516 // size, and just emit the 'begin' expression as a bitcast.
1517 while (arrayType) {
1518 countFromCLAs *=
1519 cast<ConstantArrayType>(arrayType)->getSize().getZExtValue();
1520 eltType = arrayType->getElementType();
1521 arrayType = getContext().getAsArrayType(eltType);
1522 }
John McCall82fe67b2011-07-09 01:37:26 +00001523
John McCall7f416cc2015-09-08 08:05:57 +00001524 llvm::Type *baseType = ConvertType(eltType);
1525 addr = Builder.CreateElementBitCast(addr, baseType, "array.begin");
Richard Smithf3c37e82012-04-22 05:51:36 +00001526 } else {
1527 // Create the actual GEP.
John McCall7f416cc2015-09-08 08:05:57 +00001528 addr = Address(Builder.CreateInBoundsGEP(addr.getPointer(),
1529 gepIndices, "array.begin"),
1530 addr.getAlignment());
Richard Smithf3c37e82012-04-22 05:51:36 +00001531 }
1532
1533 baseType = eltType;
John McCall82fe67b2011-07-09 01:37:26 +00001534
1535 llvm::Value *numElements
1536 = llvm::ConstantInt::get(SizeTy, countFromCLAs);
1537
1538 // If we had any VLA dimensions, factor them in.
1539 if (numVLAElements)
1540 numElements = Builder.CreateNUWMul(numVLAElements, numElements);
1541
1542 return numElements;
1543}
1544
John McCall23c29fe2011-06-24 21:55:10 +00001545std::pair<llvm::Value*, QualType>
1546CodeGenFunction::getVLASize(QualType type) {
1547 const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
1548 assert(vla && "type was not a variable array type!");
1549 return getVLASize(vla);
Anders Carlssone388a5b2008-12-20 20:27:15 +00001550}
Anders Carlssonccbe9202008-12-12 07:19:02 +00001551
John McCall23c29fe2011-06-24 21:55:10 +00001552std::pair<llvm::Value*, QualType>
1553CodeGenFunction::getVLASize(const VariableArrayType *type) {
1554 // The number of elements so far; always size_t.
Craig Topper8a13c412014-05-21 05:09:00 +00001555 llvm::Value *numElements = nullptr;
John McCall23c29fe2011-06-24 21:55:10 +00001556
1557 QualType elementType;
1558 do {
1559 elementType = type->getElementType();
1560 llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
1561 assert(vlaSize && "no size for VLA!");
1562 assert(vlaSize->getType() == SizeTy);
1563
1564 if (!numElements) {
1565 numElements = vlaSize;
1566 } else {
1567 // It's undefined behavior if this wraps around, so mark it that way.
Alexey Samsonovcb3f8122014-03-20 10:48:29 +00001568 // FIXME: Teach -fsanitize=undefined to trap this.
John McCall23c29fe2011-06-24 21:55:10 +00001569 numElements = Builder.CreateNUWMul(numElements, vlaSize);
1570 }
1571 } while ((type = getContext().getAsVariableArrayType(elementType)));
1572
1573 return std::pair<llvm::Value*,QualType>(numElements, elementType);
1574}
1575
1576void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
1577 assert(type->isVariablyModifiedType() &&
Anders Carlsson8a01b792008-12-20 20:46:34 +00001578 "Must pass variably modified type to EmitVLASizes!");
Mike Stump11289f42009-09-09 15:08:12 +00001579
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001580 EnsureInsertPoint();
Mike Stump11289f42009-09-09 15:08:12 +00001581
John McCall23c29fe2011-06-24 21:55:10 +00001582 // We're going to walk down into the type and look for VLA
1583 // expressions.
John McCall23c29fe2011-06-24 21:55:10 +00001584 do {
1585 assert(type->isVariablyModifiedType());
Mike Stump11289f42009-09-09 15:08:12 +00001586
John McCall23c29fe2011-06-24 21:55:10 +00001587 const Type *ty = type.getTypePtr();
1588 switch (ty->getTypeClass()) {
Abramo Bagnara1cd83682012-01-07 10:52:36 +00001589
John McCall23c29fe2011-06-24 21:55:10 +00001590#define TYPE(Class, Base)
1591#define ABSTRACT_TYPE(Class, Base)
Abramo Bagnara1cd83682012-01-07 10:52:36 +00001592#define NON_CANONICAL_TYPE(Class, Base)
John McCall23c29fe2011-06-24 21:55:10 +00001593#define DEPENDENT_TYPE(Class, Base) case Type::Class:
Abramo Bagnara1cd83682012-01-07 10:52:36 +00001594#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
John McCall23c29fe2011-06-24 21:55:10 +00001595#include "clang/AST/TypeNodes.def"
Abramo Bagnara1cd83682012-01-07 10:52:36 +00001596 llvm_unreachable("unexpected dependent type!");
Mike Stump11289f42009-09-09 15:08:12 +00001597
John McCall23c29fe2011-06-24 21:55:10 +00001598 // These types are never variably-modified.
1599 case Type::Builtin:
1600 case Type::Complex:
1601 case Type::Vector:
1602 case Type::ExtVector:
1603 case Type::Record:
1604 case Type::Enum:
Abramo Bagnarafa95ed42012-01-11 08:19:46 +00001605 case Type::Elaborated:
1606 case Type::TemplateSpecialization:
John McCall23c29fe2011-06-24 21:55:10 +00001607 case Type::ObjCObject:
1608 case Type::ObjCInterface:
1609 case Type::ObjCObjectPointer:
1610 llvm_unreachable("type class is never variably-modified!");
Mike Stump11289f42009-09-09 15:08:12 +00001611
Reid Kleckner0503a872013-12-05 01:23:43 +00001612 case Type::Adjusted:
1613 type = cast<AdjustedType>(ty)->getAdjustedType();
1614 break;
1615
Reid Kleckner8a365022013-06-24 17:51:48 +00001616 case Type::Decayed:
1617 type = cast<DecayedType>(ty)->getPointeeType();
1618 break;
1619
John McCall23c29fe2011-06-24 21:55:10 +00001620 case Type::Pointer:
1621 type = cast<PointerType>(ty)->getPointeeType();
1622 break;
Mike Stump11289f42009-09-09 15:08:12 +00001623
John McCall23c29fe2011-06-24 21:55:10 +00001624 case Type::BlockPointer:
1625 type = cast<BlockPointerType>(ty)->getPointeeType();
1626 break;
1627
1628 case Type::LValueReference:
1629 case Type::RValueReference:
1630 type = cast<ReferenceType>(ty)->getPointeeType();
1631 break;
1632
1633 case Type::MemberPointer:
1634 type = cast<MemberPointerType>(ty)->getPointeeType();
1635 break;
1636
1637 case Type::ConstantArray:
1638 case Type::IncompleteArray:
1639 // Losing element qualification here is fine.
1640 type = cast<ArrayType>(ty)->getElementType();
1641 break;
1642
1643 case Type::VariableArray: {
1644 // Losing element qualification here is fine.
1645 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1646
1647 // Unknown size indication requires no size computation.
1648 // Otherwise, evaluate and record it.
1649 if (const Expr *size = vat->getSizeExpr()) {
1650 // It's possible that we might have emitted this already,
1651 // e.g. with a typedef and a pointer to it.
1652 llvm::Value *&entry = VLASizeMap[size];
1653 if (!entry) {
Richard Smith481652b2012-10-10 01:11:12 +00001654 llvm::Value *Size = EmitScalarExpr(size);
1655
1656 // C11 6.7.6.2p5:
1657 // If the size is an expression that is not an integer constant
1658 // expression [...] each time it is evaluated it shall have a value
1659 // greater than zero.
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001660 if (SanOpts.has(SanitizerKind::VLABound) &&
Richard Smithb1b0ab42012-11-05 22:21:05 +00001661 size->getType()->isSignedIntegerType()) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00001662 SanitizerScope SanScope(this);
Richard Smith481652b2012-10-10 01:11:12 +00001663 llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType());
1664 llvm::Constant *StaticArgs[] = {
1665 EmitCheckSourceLocation(size->getLocStart()),
1666 EmitCheckTypeDescriptor(size->getType())
1667 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +00001668 EmitCheck(std::make_pair(Builder.CreateICmpSGT(Size, Zero),
1669 SanitizerKind::VLABound),
1670 "vla_bound_not_positive", StaticArgs, Size);
Richard Smith481652b2012-10-10 01:11:12 +00001671 }
1672
John McCall23c29fe2011-06-24 21:55:10 +00001673 // Always zexting here would be wrong if it weren't
1674 // undefined behavior to have a negative bound.
Richard Smith8772bd82012-10-10 01:12:11 +00001675 entry = Builder.CreateIntCast(Size, SizeTy, /*signed*/ false);
John McCall23c29fe2011-06-24 21:55:10 +00001676 }
1677 }
1678 type = vat->getElementType();
1679 break;
Anders Carlsson8a01b792008-12-20 20:46:34 +00001680 }
Mike Stump11289f42009-09-09 15:08:12 +00001681
Abramo Bagnara1cd83682012-01-07 10:52:36 +00001682 case Type::FunctionProto:
John McCall23c29fe2011-06-24 21:55:10 +00001683 case Type::FunctionNoProto:
Alp Toker314cc812014-01-25 16:55:45 +00001684 type = cast<FunctionType>(ty)->getReturnType();
John McCall23c29fe2011-06-24 21:55:10 +00001685 break;
Eli Friedman0dfb8892011-10-06 23:00:33 +00001686
Abramo Bagnarafa95ed42012-01-11 08:19:46 +00001687 case Type::Paren:
1688 case Type::TypeOf:
1689 case Type::UnaryTransform:
1690 case Type::Attributed:
1691 case Type::SubstTemplateTypeParm:
David Blaikie66ed89d2013-07-13 21:08:08 +00001692 case Type::PackExpansion:
Abramo Bagnarafa95ed42012-01-11 08:19:46 +00001693 // Keep walking after single level desugaring.
1694 type = type.getSingleStepDesugaredType(getContext());
1695 break;
1696
1697 case Type::Typedef:
1698 case Type::Decltype:
1699 case Type::Auto:
1700 // Stop walking: nothing to do.
1701 return;
1702
1703 case Type::TypeOfExpr:
1704 // Stop walking: emit typeof expression.
1705 EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
1706 return;
1707
Eli Friedman0dfb8892011-10-06 23:00:33 +00001708 case Type::Atomic:
1709 type = cast<AtomicType>(ty)->getValueType();
1710 break;
John McCall23c29fe2011-06-24 21:55:10 +00001711 }
1712 } while (type->isVariablyModifiedType());
Anders Carlssonccbe9202008-12-12 07:19:02 +00001713}
Eli Friedmanddea0ad2009-01-20 17:46:04 +00001714
John McCall7f416cc2015-09-08 08:05:57 +00001715Address CodeGenFunction::EmitVAListRef(const Expr* E) {
Dan Gohmane9e32dc2010-10-29 22:47:07 +00001716 if (getContext().getBuiltinVaListType()->isArrayType())
John McCall7f416cc2015-09-08 08:05:57 +00001717 return EmitPointerWithAlignment(E);
Eli Friedmanddea0ad2009-01-20 17:46:04 +00001718 return EmitLValue(E).getAddress();
1719}
Anders Carlsson15cb75a2009-02-07 22:53:43 +00001720
Charles Davisc7d5c942015-09-17 20:55:33 +00001721Address CodeGenFunction::EmitMSVAListRef(const Expr *E) {
1722 return EmitLValue(E).getAddress();
1723}
1724
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001725void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
1726 llvm::Constant *Init) {
Devang Pateldc866e12010-08-10 17:53:33 +00001727 assert (Init && "Invalid DeclRefExpr initializer!");
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001728 if (CGDebugInfo *Dbg = getDebugInfo())
1729 if (CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
1730 Dbg->EmitGlobalVariable(E->getDecl(), Init);
Devang Patele03edfd2010-08-10 07:24:25 +00001731}
John McCallc07a0c72011-02-17 10:25:35 +00001732
1733CodeGenFunction::PeepholeProtection
1734CodeGenFunction::protectFromPeepholes(RValue rvalue) {
1735 // At the moment, the only aggressive peephole we do in IR gen
1736 // is trunc(zext) folding, but if we add more, we can easily
1737 // extend this protection.
1738
1739 if (!rvalue.isScalar()) return PeepholeProtection();
1740 llvm::Value *value = rvalue.getScalarVal();
1741 if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
1742
1743 // Just make an extra bitcast.
1744 assert(HaveInsertPoint());
1745 llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
1746 Builder.GetInsertBlock());
1747
1748 PeepholeProtection protection;
1749 protection.Inst = inst;
1750 return protection;
1751}
1752
1753void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
1754 if (!protection.Inst) return;
1755
1756 // In theory, we could try to duplicate the peepholes now, but whatever.
1757 protection.Inst->eraseFromParent();
1758}
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001759
1760llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Value *AnnotationFn,
1761 llvm::Value *AnnotatedVal,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001762 StringRef AnnotationStr,
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001763 SourceLocation Location) {
1764 llvm::Value *Args[4] = {
1765 AnnotatedVal,
1766 Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy),
1767 Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy),
1768 CGM.EmitAnnotationLineNo(Location)
1769 };
1770 return Builder.CreateCall(AnnotationFn, Args);
1771}
1772
1773void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
1774 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1775 // FIXME We create a new bitcast for every annotation because that's what
1776 // llvm-gcc was doing.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001777 for (const auto *I : D->specific_attrs<AnnotateAttr>())
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001778 EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation),
1779 Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()),
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001780 I->getAnnotation(), D->getLocation());
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001781}
1782
John McCall7f416cc2015-09-08 08:05:57 +00001783Address CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
1784 Address Addr) {
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001785 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
John McCall7f416cc2015-09-08 08:05:57 +00001786 llvm::Value *V = Addr.getPointer();
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001787 llvm::Type *VTy = V->getType();
1788 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
1789 CGM.Int8PtrTy);
1790
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001791 for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001792 // FIXME Always emit the cast inst so we can differentiate between
1793 // annotation on the first field of a struct and annotation on the struct
1794 // itself.
1795 if (VTy != CGM.Int8PtrTy)
1796 V = Builder.Insert(new llvm::BitCastInst(V, CGM.Int8PtrTy));
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001797 V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation());
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001798 V = Builder.CreateBitCast(V, VTy);
1799 }
1800
John McCall7f416cc2015-09-08 08:05:57 +00001801 return Address(V, Addr.getAlignment());
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001802}
Ben Langmuir3b4c30b2013-05-09 19:17:11 +00001803
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00001804CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { }
Alexander Musman515ad8c2014-05-22 08:54:05 +00001805
Alexey Samsonov24cad992014-07-17 18:46:27 +00001806CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF)
1807 : CGF(CGF) {
1808 assert(!CGF->IsSanitizerScope);
1809 CGF->IsSanitizerScope = true;
1810}
1811
1812CodeGenFunction::SanitizerScope::~SanitizerScope() {
1813 CGF->IsSanitizerScope = false;
1814}
1815
Alexander Musman515ad8c2014-05-22 08:54:05 +00001816void CodeGenFunction::InsertHelper(llvm::Instruction *I,
1817 const llvm::Twine &Name,
1818 llvm::BasicBlock *BB,
1819 llvm::BasicBlock::iterator InsertPt) const {
1820 LoopStack.InsertHelper(I);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001821 if (IsSanitizerScope)
1822 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(I);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001823}
1824
1825template <bool PreserveNames>
1826void CGBuilderInserter<PreserveNames>::InsertHelper(
1827 llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB,
1828 llvm::BasicBlock::iterator InsertPt) const {
1829 llvm::IRBuilderDefaultInserter<PreserveNames>::InsertHelper(I, Name, BB,
1830 InsertPt);
1831 if (CGF)
1832 CGF->InsertHelper(I, Name, BB, InsertPt);
1833}
1834
1835#ifdef NDEBUG
1836#define PreserveNames false
1837#else
1838#define PreserveNames true
1839#endif
1840template void CGBuilderInserter<PreserveNames>::InsertHelper(
1841 llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB,
1842 llvm::BasicBlock::iterator InsertPt) const;
1843#undef PreserveNames