MLIR 24.0.0git
InlinerInterfaceImpl.cpp
Go to the documentation of this file.
1//===- InlinerInterfaceImpl.cpp - Inlining for LLVM the dialect -----------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Logic for inlining LLVM functions and the definition of the
10// LLVMInliningInterface.
11//
12//===----------------------------------------------------------------------===//
13
27#include "mlir/IR/Matchers.h"
31#include "llvm/ADT/ScopeExit.h"
32#include "llvm/Support/Debug.h"
33
34#include "llvm/Support/DebugLog.h"
35
36#define DEBUG_TYPE "llvm-inliner"
37
38using namespace mlir;
39
40/// Check whether the given alloca is an input to a lifetime intrinsic,
41/// optionally passing through one or more casts on the way. This is not
42/// transitive through block arguments.
43static bool hasLifetimeMarkers(LLVM::AllocaOp allocaOp) {
44 SmallVector<Operation *> stack(allocaOp->getUsers().begin(),
45 allocaOp->getUsers().end());
46 while (!stack.empty()) {
47 Operation *op = stack.pop_back_val();
48 if (isa<LLVM::LifetimeStartOp, LLVM::LifetimeEndOp>(op))
49 return true;
50 if (isa<LLVM::BitcastOp>(op))
51 stack.append(op->getUsers().begin(), op->getUsers().end());
52 }
53 return false;
54}
55
56/// Handles alloca operations in the inlined blocks:
57/// - Moves all alloca operations with a constant size in the former entry block
58/// of the callee into the entry block of the caller, so they become part of
59/// the function prologue/epilogue during code generation.
60/// - Inserts lifetime intrinsics that limit the scope of inlined static allocas
61/// to the inlined blocks.
62/// - Inserts StackSave and StackRestore operations if dynamic allocas were
63/// inlined.
64static void
67 // Locate the entry block of the closest callsite ancestor that has either the
68 // IsolatedFromAbove or AutomaticAllocationScope trait. In pure LLVM dialect
69 // programs, this is the LLVMFuncOp containing the call site. However, in
70 // mixed-dialect programs, the callsite might be nested in another operation
71 // that carries one of these traits. In such scenarios, this traversal stops
72 // at the closest ancestor with either trait, ensuring visibility post
73 // relocation and respecting allocation scopes.
74 Block *callerEntryBlock = nullptr;
75 Operation *currentOp = call;
76 while (Operation *parentOp = currentOp->getParentOp()) {
77 if (parentOp->mightHaveTrait<OpTrait::IsIsolatedFromAbove>() ||
78 parentOp->mightHaveTrait<OpTrait::AutomaticAllocationScope>()) {
79 callerEntryBlock = &currentOp->getParentRegion()->front();
80 break;
81 }
82 currentOp = parentOp;
83 }
84
85 // Avoid relocating the alloca operations if the call has been inlined into
86 // the entry block already, which is typically the encompassing
87 // LLVM function, or if the relevant entry block cannot be identified.
88 Block *calleeEntryBlock = &(*inlinedBlocks.begin());
89 if (!callerEntryBlock || callerEntryBlock == calleeEntryBlock)
90 return;
91
93 bool shouldInsertLifetimes = false;
94 bool hasDynamicAlloca = false;
95 // Conservatively only move static alloca operations that are part of the
96 // entry block and do not inspect nested regions, since they may execute
97 // conditionally or have other unknown semantics.
98 for (auto allocaOp : calleeEntryBlock->getOps<LLVM::AllocaOp>()) {
99 IntegerAttr arraySize;
100 if (!matchPattern(allocaOp.getArraySize(), m_Constant(&arraySize))) {
101 hasDynamicAlloca = true;
102 continue;
103 }
104 bool shouldInsertLifetime =
105 arraySize.getValue() != 0 && !hasLifetimeMarkers(allocaOp);
106 shouldInsertLifetimes |= shouldInsertLifetime;
107 allocasToMove.emplace_back(allocaOp, arraySize, shouldInsertLifetime);
108 }
109 // Check the remaining inlined blocks for dynamic allocas as well.
110 for (Block &block : llvm::drop_begin(inlinedBlocks)) {
111 if (hasDynamicAlloca)
112 break;
113 hasDynamicAlloca =
114 llvm::any_of(block.getOps<LLVM::AllocaOp>(), [](auto allocaOp) {
115 return !matchPattern(allocaOp.getArraySize(), m_Constant());
116 });
117 }
118 if (allocasToMove.empty() && !hasDynamicAlloca)
119 return;
120 OpBuilder builder(calleeEntryBlock, calleeEntryBlock->begin());
121 Value stackPtr;
122 if (hasDynamicAlloca) {
123 // This may result in multiple stacksave/stackrestore intrinsics in the same
124 // scope if some are already present in the body of the caller. This is not
125 // invalid IR, but LLVM cleans these up in InstCombineCalls.cpp, along with
126 // other cases where the stacksave/stackrestore is redundant.
127 stackPtr = LLVM::StackSaveOp::create(
128 builder, call->getLoc(),
129 LLVM::LLVMPointerType::get(call->getContext()));
130 }
131 builder.setInsertionPointToStart(callerEntryBlock);
132 for (auto &[allocaOp, arraySize, shouldInsertLifetime] : allocasToMove) {
133 auto newConstant =
134 LLVM::ConstantOp::create(builder, allocaOp->getLoc(),
135 allocaOp.getArraySize().getType(), arraySize);
136 // Insert a lifetime start intrinsic where the alloca was before moving it.
137 if (shouldInsertLifetime) {
138 OpBuilder::InsertionGuard insertionGuard(builder);
139 builder.setInsertionPoint(allocaOp);
140 LLVM::LifetimeStartOp::create(builder, allocaOp.getLoc(),
141 allocaOp.getResult());
142 }
143 allocaOp->moveAfter(newConstant);
144 allocaOp.getArraySizeMutable().assign(newConstant.getResult());
145 }
146 if (!shouldInsertLifetimes && !hasDynamicAlloca)
147 return;
148 // Insert a lifetime end intrinsic before each return in the callee function.
149 for (Block &block : inlinedBlocks) {
150 if (!block.getTerminator()->hasTrait<OpTrait::ReturnLike>())
151 continue;
152 builder.setInsertionPoint(block.getTerminator());
153 if (hasDynamicAlloca)
154 LLVM::StackRestoreOp::create(builder, call->getLoc(), stackPtr);
155 for (auto &[allocaOp, arraySize, shouldInsertLifetime] : allocasToMove) {
156 if (shouldInsertLifetime)
157 LLVM::LifetimeEndOp::create(builder, allocaOp.getLoc(),
158 allocaOp.getResult());
159 }
160 }
161}
162
163/// Maps all alias scopes in the inlined operations to deep clones of the scopes
164/// and domain. This is required for code such as `foo(a, b); foo(a2, b2);` to
165/// not incorrectly return `noalias` for e.g. operations on `a` and `a2`.
166static void
169
170 // Register handles in the walker to create the deep clones.
171 // The walker ensures that an attribute is only ever walked once and does a
172 // post-order walk, ensuring the domain is visited prior to the scope.
173 AttrTypeWalker walker;
174
175 // Perform the deep clones while visiting. Builders create a distinct
176 // attribute to make sure that new instances are always created by the
177 // uniquer.
178 walker.addWalk([&](LLVM::AliasScopeDomainAttr domainAttr) {
179 mapping[domainAttr] = LLVM::AliasScopeDomainAttr::get(
180 domainAttr.getContext(), domainAttr.getDescription(),
181 domainAttr.getDisjointScopes());
182 });
183
184 walker.addWalk([&](LLVM::AliasScopeAttr scopeAttr) {
185 mapping[scopeAttr] = LLVM::AliasScopeAttr::get(
186 cast<LLVM::AliasScopeDomainAttr>(mapping.lookup(scopeAttr.getDomain())),
187 scopeAttr.getDescription());
188 });
189
190 // Map an array of scopes to an array of deep clones.
191 auto convertScopeList = [&](ArrayAttr arrayAttr) -> ArrayAttr {
192 if (!arrayAttr)
193 return nullptr;
194
195 // Create the deep clones if necessary.
196 walker.walk(arrayAttr);
197
198 return ArrayAttr::get(arrayAttr.getContext(),
199 llvm::map_to_vector(arrayAttr, [&](Attribute attr) {
200 return mapping.lookup(attr);
201 }));
202 };
203
204 for (Block &block : inlinedBlocks) {
205 block.walk([&](Operation *op) {
206 if (auto aliasInterface = dyn_cast<LLVM::AliasAnalysisOpInterface>(op)) {
207 aliasInterface.setAliasScopes(
208 convertScopeList(aliasInterface.getAliasScopesOrNull()));
209 aliasInterface.setNoAliasScopes(
210 convertScopeList(aliasInterface.getNoAliasScopesOrNull()));
211 }
212
213 if (auto noAliasScope = dyn_cast<LLVM::NoAliasScopeDeclOp>(op)) {
214 // Create the deep clones if necessary.
215 walker.walk(noAliasScope.getScopeAttr());
216
217 noAliasScope.setScopeAttr(cast<LLVM::AliasScopeAttr>(
218 mapping.lookup(noAliasScope.getScopeAttr())));
219 }
220 });
221 }
222}
223
224/// Creates a new ArrayAttr by concatenating `lhs` with `rhs`.
225/// Returns null if both parameters are null. If only one attribute is null,
226/// return the other.
228 if (!lhs)
229 return rhs;
230 if (!rhs)
231 return lhs;
232
234 llvm::append_range(result, lhs);
235 llvm::append_range(result, rhs);
236 return ArrayAttr::get(lhs.getContext(), result);
237}
238
239/// Attempts to return the set of all underlying pointer values that
240/// `pointerValue` is based on. This function traverses through select
241/// operations and block arguments.
242static FailureOr<SmallVector<Value>>
245 WalkContinuation walkResult = walkSlice(pointerValue, [&](Value val) {
246 // Attempt to advance to the source of the underlying view-like operation.
247 // Examples of view-like operations include GEPOp and AddrSpaceCastOp.
248 if (auto viewOp = val.getDefiningOp<ViewLikeOpInterface>()) {
249 if (val == viewOp.getViewDest())
250 return WalkContinuation::advanceTo(viewOp.getViewSource());
251 }
252
253 // Attempt to advance to control flow predecessors.
254 std::optional<SmallVector<Value>> controlFlowPredecessors =
256 if (controlFlowPredecessors)
257 return WalkContinuation::advanceTo(*controlFlowPredecessors);
258
259 // For all non-control flow results, consider `val` an underlying object.
260 if (isa<OpResult>(val)) {
261 result.push_back(val);
262 return WalkContinuation::skip();
263 }
264
265 // If this place is reached, `val` is a block argument that is not
266 // understood. Therefore, we conservatively interrupt.
267 // Note: Dealing with function arguments is not necessary, as the slice
268 // would have to go through an SSACopyOp first.
270 });
271
272 if (walkResult.wasInterrupted())
273 return failure();
274
275 return result;
276}
277
278/// Creates a new AliasScopeAttr for every noalias parameter and attaches it to
279/// the appropriate inlined memory operations in an attempt to preserve the
280/// original semantics of the parameter attribute.
282 Operation *call, iterator_range<Region::iterator> inlinedBlocks) {
283
284 // First, collect all ssa copy operations, which correspond to function
285 // parameters, and additionally store the noalias parameters. All parameters
286 // have been marked by the `handleArgument` implementation by using the
287 // `ssa.copy` intrinsic. Additionally, noalias parameters have an attached
288 // `noalias` attribute to the intrinsics. These intrinsics are only meant to
289 // be temporary and should therefore be deleted after we're done using them
290 // here.
292 SetVector<LLVM::SSACopyOp> noAliasParams;
293 for (Value argument : cast<LLVM::CallOp>(call).getArgOperands()) {
294 for (auto ssaCopy :
295 llvm::make_isa_range<LLVM::SSACopyOp>(argument.getUsers())) {
296 ssaCopies.insert(ssaCopy);
297
298 if (!ssaCopy->hasDiscardableAttr(LLVM::LLVMDialect::getNoAliasAttrName()))
299 continue;
300 noAliasParams.insert(ssaCopy);
301 }
302 }
303
304 // Scope exit block to make it impossible to forget to get rid of the
305 // intrinsics.
306 llvm::scope_exit exit([&] {
307 for (LLVM::SSACopyOp ssaCopyOp : ssaCopies) {
308 ssaCopyOp.replaceAllUsesWith(ssaCopyOp.getOperand());
309 ssaCopyOp->erase();
310 }
311 });
312
313 // If there were no noalias parameters, we have nothing to do here.
314 if (noAliasParams.empty())
315 return;
316
317 // Create a new domain for this specific inlining and a new scope for every
318 // noalias parameter.
319 auto functionDomain = LLVM::AliasScopeDomainAttr::get(
320 call->getContext(), cast<LLVM::CallOp>(call).getCalleeAttr().getAttr());
322 for (LLVM::SSACopyOp copyOp : noAliasParams) {
323 auto scope = LLVM::AliasScopeAttr::get(functionDomain);
324 pointerScopes[copyOp] = scope;
325
326 auto builder = OpBuilder(call);
327 LLVM::NoAliasScopeDeclOp::create(builder, call->getLoc(), scope);
328 }
329
330 // Go through every instruction and attempt to find which noalias parameters
331 // it is definitely based on and definitely not based on.
332 for (Block &inlinedBlock : inlinedBlocks) {
333 inlinedBlock.walk([&](LLVM::AliasAnalysisOpInterface aliasInterface) {
334 // Collect the pointer arguments affected by the alias scopes.
335 SmallVector<Value> pointerArgs = aliasInterface.getAccessedOperands();
336
337 // Find the set of underlying pointers that this pointer is based on.
338 SmallPtrSet<Value, 4> basedOnPointers;
339 for (Value pointer : pointerArgs) {
340 FailureOr<SmallVector<Value>> underlyingObjectSet =
341 getUnderlyingObjectSet(pointer);
342 if (failed(underlyingObjectSet))
343 return;
344 llvm::copy(*underlyingObjectSet,
345 std::inserter(basedOnPointers, basedOnPointers.begin()));
346 }
347
348 bool aliasesOtherKnownObject = false;
349 // Go through the based on pointers and check that they are either:
350 // * Constants that can be ignored (undef, poison, null pointer).
351 // * Based on a pointer parameter.
352 // * Other pointers that we know can't alias with our noalias parameter.
353 //
354 // Any other value might be a pointer based on any noalias parameter that
355 // hasn't been identified. In that case conservatively don't add any
356 // scopes to this operation indicating either aliasing or not aliasing
357 // with any parameter.
358 if (llvm::any_of(basedOnPointers, [&](Value object) {
359 if (matchPattern(object, m_Constant()))
360 return false;
361
362 if (auto ssaCopy = object.getDefiningOp<LLVM::SSACopyOp>()) {
363 // If that value is based on a noalias parameter, it is guaranteed
364 // to not alias with any other object.
365 aliasesOtherKnownObject |= !noAliasParams.contains(ssaCopy);
366 return false;
367 }
368
369 if (isa_and_nonnull<LLVM::AllocaOp, LLVM::AddressOfOp>(
370 object.getDefiningOp())) {
371 aliasesOtherKnownObject = true;
372 return false;
373 }
374 return true;
375 }))
376 return;
377
378 // Add all noalias parameter scopes to the noalias scope list that we are
379 // not based on.
380 SmallVector<Attribute> noAliasScopes;
381 for (LLVM::SSACopyOp noAlias : noAliasParams) {
382 if (basedOnPointers.contains(noAlias))
383 continue;
384
385 noAliasScopes.push_back(pointerScopes[noAlias]);
386 }
387
388 if (!noAliasScopes.empty())
389 aliasInterface.setNoAliasScopes(
390 concatArrayAttr(aliasInterface.getNoAliasScopesOrNull(),
391 ArrayAttr::get(call->getContext(), noAliasScopes)));
392
393 // Don't add alias scopes to call operations or operations that might
394 // operate on pointers not based on any noalias parameter.
395 // Since we add all scopes to an operation's noalias list that it
396 // definitely doesn't alias, we mustn't do the same for the alias.scope
397 // list if other objects are involved.
398 //
399 // Consider the following case:
400 // %0 = llvm.alloca
401 // %1 = select %magic, %0, %noalias_param
402 // store 5, %1 (1) noalias=[scope(...)]
403 // ...
404 // store 3, %0 (2) noalias=[scope(noalias_param), scope(...)]
405 //
406 // We can add the scopes of any noalias parameters that aren't
407 // noalias_param's scope to (1) and add all of them to (2). We mustn't add
408 // the scope of noalias_param to the alias.scope list of (1) since
409 // that would mean (2) cannot alias with (1) which is wrong since both may
410 // store to %0.
411 //
412 // In conclusion, only add scopes to the alias.scope list if all pointers
413 // have a corresponding scope.
414 // Call operations are included in this list since we do not know whether
415 // the callee accesses any memory besides the ones passed as its
416 // arguments.
417 if (aliasesOtherKnownObject ||
418 isa<LLVM::CallOp>(aliasInterface.getOperation()))
419 return;
420
421 SmallVector<Attribute> aliasScopes;
422 for (LLVM::SSACopyOp noAlias : noAliasParams)
423 if (basedOnPointers.contains(noAlias))
424 aliasScopes.push_back(pointerScopes[noAlias]);
425
426 if (!aliasScopes.empty())
427 aliasInterface.setAliasScopes(
428 concatArrayAttr(aliasInterface.getAliasScopesOrNull(),
429 ArrayAttr::get(call->getContext(), aliasScopes)));
430 });
431 }
432}
433
434/// Appends any alias scopes of the call operation to any inlined memory
435/// operation.
436static void
438 iterator_range<Region::iterator> inlinedBlocks) {
439 auto callAliasInterface = dyn_cast<LLVM::AliasAnalysisOpInterface>(call);
440 if (!callAliasInterface)
441 return;
442
443 ArrayAttr aliasScopes = callAliasInterface.getAliasScopesOrNull();
444 ArrayAttr noAliasScopes = callAliasInterface.getNoAliasScopesOrNull();
445 // If the call has neither alias scopes or noalias scopes we have nothing to
446 // do here.
447 if (!aliasScopes && !noAliasScopes)
448 return;
449
450 // Simply append the call op's alias and noalias scopes to any operation
451 // implementing AliasAnalysisOpInterface.
452 for (Block &block : inlinedBlocks) {
453 block.walk([&](LLVM::AliasAnalysisOpInterface aliasInterface) {
454 if (aliasScopes)
455 aliasInterface.setAliasScopes(concatArrayAttr(
456 aliasInterface.getAliasScopesOrNull(), aliasScopes));
457
458 if (noAliasScopes)
459 aliasInterface.setNoAliasScopes(concatArrayAttr(
460 aliasInterface.getNoAliasScopesOrNull(), noAliasScopes));
461 });
462 }
463}
464
465/// Handles all interactions with alias scopes during inlining.
466static void handleAliasScopes(Operation *call,
467 iterator_range<Region::iterator> inlinedBlocks) {
468 deepCloneAliasScopes(inlinedBlocks);
469 createNewAliasScopesFromNoAliasParameter(call, inlinedBlocks);
470 appendCallOpAliasScopes(call, inlinedBlocks);
471}
472
473/// Appends any access groups of the call operation to any inlined memory
474/// operation.
476 iterator_range<Region::iterator> inlinedBlocks) {
477 auto callAccessGroupInterface = dyn_cast<LLVM::AccessGroupOpInterface>(call);
478 if (!callAccessGroupInterface)
479 return;
480
481 auto accessGroups = callAccessGroupInterface.getAccessGroupsOrNull();
482 if (!accessGroups)
483 return;
484
485 // Simply append the call op's access groups to any operation implementing
486 // AccessGroupOpInterface.
487 for (Block &block : inlinedBlocks)
488 for (auto accessGroupOpInterface :
489 block.getOps<LLVM::AccessGroupOpInterface>())
490 accessGroupOpInterface.setAccessGroups(concatArrayAttr(
491 accessGroupOpInterface.getAccessGroupsOrNull(), accessGroups));
492}
493
494/// Whether the two call stacks agree up to the shorter length, matching
495/// LLVM's haveCommonPrefix: a MemProf context matches the new inlined
496/// callsite context when they share a prefix, even if the callsite stack
497/// is longer than the MemProf stack.
499 ArrayRef<int64_t> callsiteStack) {
500 size_t len = std::min(mibStack.size(), callsiteStack.size());
501 return mibStack.take_front(len) == callsiteStack.take_front(len);
502}
503
504/// Updates MemProf metadata on calls inlined into `call`, matching LLVM's
505/// propagateMemProfMetadata. Each cloned call's `llvm.callsite` stack is
506/// concatenated with the inlined callsite's stack, and its `llvm.memprof`
507/// MIBs are filtered to the ones whose call stack shares a prefix with the
508/// new callsite stack; the kept MIBs are unchanged. If the inlined call
509/// has no callsite metadata, or no MIB matches, both attributes are removed
510/// from the cloned call. A cloned call with `llvm.memprof` but no
511/// `llvm.callsite` cannot have its context extended, so its `llvm.memprof`
512/// attribute is removed.
513///
514/// Known gap: unlike LLVM, which rebuilds a filtered subset through a
515/// call-stack trie (trimming contexts, and replacing the metadata with a
516/// function attribute when a single allocation type is left), this keeps
517/// the raw subset. There is no MLIR way to carry that function attribute.
518static void
520 iterator_range<Region::iterator> inlinedBlocks) {
521 MLIRContext *context = call->getContext();
522 StringRef callsiteName = LLVM::LLVMDialect::getCallsiteAttrName();
523 StringRef memprofName = LLVM::LLVMDialect::getMemProfAttrName();
524 DenseI64ArrayAttr inlinedCallsite =
525 call->getDiscardableAttrOfType<DenseI64ArrayAttr>(callsiteName);
526 ArrayRef<int64_t> inlinedStack =
527 inlinedCallsite ? inlinedCallsite.asArrayRef() : ArrayRef<int64_t>{};
528
529 // Any op carrying these attributes lowers to a call, so act on every
530 // carrier, including calls nested in region ops and intrinsic calls that
531 // are not CallOpInterface, matching the set translation can produce.
532 for (Block &block : inlinedBlocks) {
533 block.walk([&](Operation *op) {
534 DenseI64ArrayAttr origCallsite =
536 ArrayAttr memprof = op->getDiscardableAttrOfType<ArrayAttr>(memprofName);
537 if (!origCallsite && !memprof)
538 return;
539 if (!origCallsite) {
540 // No callsite context to extend from: drop the memprof attribute
541 // when the clone carries one. LLVM asserts this case cannot happen;
542 // dropping is the conservative equivalent.
543 op->removeDiscardableAttr(memprofName);
544 return;
545 }
546 if (inlinedStack.empty()) {
547 // The inlined call carries no callsite context: the cloned call is
548 // not part of any profiled context.
549 op->removeDiscardableAttr(memprofName);
550 op->removeDiscardableAttr(callsiteName);
551 return;
552 }
553 SmallVector<int64_t> newStack(origCallsite.asArrayRef());
554 newStack.append(inlinedStack.begin(), inlinedStack.end());
555 op->setDiscardableAttr(callsiteName,
556 DenseI64ArrayAttr::get(context, newStack));
557 if (!memprof)
558 return;
559 SmallVector<Attribute> keptMIBs;
560 bool malformed = false;
561 for (Attribute mibAttr : memprof) {
562 auto mib = dyn_cast<LLVM::MemProfMIBAttr>(mibAttr);
563 if (!mib) {
564 malformed = true;
565 break;
566 }
567 if (haveCommonPrefix(mib.getCallStack().asArrayRef(), newStack))
568 keptMIBs.push_back(mibAttr);
569 }
570 if (malformed || keptMIBs.empty()) {
571 op->removeDiscardableAttr(memprofName);
572 op->removeDiscardableAttr(callsiteName);
573 } else if (keptMIBs.size() != memprof.size()) {
574 op->setDiscardableAttr(memprofName, ArrayAttr::get(context, keptMIBs));
575 }
576 });
577 }
578}
579
580static void
582 iterator_range<Region::iterator> inlinedBlocks) {
583 if (!isa<UnknownLoc>(call->getLoc()))
584 return;
585 auto func = call->getParentOfType<FunctionOpInterface>();
586 if (!func ||
587 !func->getLoc()->findInstanceOf<FusedLocWith<LLVM::DISubprogramAttr>>())
588 return;
589
590 // LLVM requires a callsite location in the caller's debug scope.
591 Location callSiteLoc =
592 FileLineColLoc::get(call->getContext(), "<unknown>", 0, 0);
593 for (Block &block : inlinedBlocks)
594 block.walk([&](Operation *op) {
595 op->setLoc(CallSiteLoc::get(op->getLoc(), callSiteLoc));
596 });
597}
598
599/// Updates locations inside loop annotations to reflect that they were inlined.
600static void
602 iterator_range<Region::iterator> inlinedBlocks) {
603 // Attempt to extract a DISubprogram from the callee.
604 auto func = call->getParentOfType<FunctionOpInterface>();
605 if (!func)
606 return;
607 LocationAttr funcLoc = func->getLoc();
608 auto fusedLoc = dyn_cast_if_present<FusedLoc>(funcLoc);
609 if (!fusedLoc)
610 return;
611 auto scope =
612 dyn_cast_if_present<LLVM::DISubprogramAttr>(fusedLoc.getMetadata());
613 if (!scope)
614 return;
615
616 // Helper to build a new fused location that reflects the inlining of the loop
617 // annotation.
618 auto updateLoc = [&](FusedLoc loc) -> FusedLoc {
619 if (!loc)
620 return {};
621 Location callSiteLoc = CallSiteLoc::get(loc, call->getLoc());
622 return FusedLoc::get(loc.getContext(), callSiteLoc, scope);
623 };
624
625 AttrTypeReplacer replacer;
626 replacer.addReplacement([&](LLVM::LoopAnnotationAttr loopAnnotation)
627 -> std::pair<Attribute, WalkResult> {
628 FusedLoc newStartLoc = updateLoc(loopAnnotation.getStartLoc());
629 FusedLoc newEndLoc = updateLoc(loopAnnotation.getEndLoc());
630 if (!newStartLoc && !newEndLoc)
631 return {loopAnnotation, WalkResult::advance()};
632 auto newLoopAnnotation = LLVM::LoopAnnotationAttr::get(
633 loopAnnotation.getContext(), loopAnnotation.getId(),
634 loopAnnotation.getDisableNonforced(), loopAnnotation.getVectorize(),
635 loopAnnotation.getInterleave(), loopAnnotation.getUnroll(),
636 loopAnnotation.getUnrollAndJam(), loopAnnotation.getLicm(),
637 loopAnnotation.getDistribute(), loopAnnotation.getPipeline(),
638 loopAnnotation.getPeeled(), loopAnnotation.getUnswitch(),
639 loopAnnotation.getMustProgress(), loopAnnotation.getIsVectorized(),
640 loopAnnotation.getAlign(), newStartLoc, newEndLoc,
641 loopAnnotation.getParallelAccesses());
642 // Needs to advance, as loop annotations can be nested.
643 return {newLoopAnnotation, WalkResult::advance()};
644 });
645
646 for (Block &block : inlinedBlocks)
647 for (Operation &op : block)
648 replacer.recursivelyReplaceElementsIn(&op);
649}
650
651/// If `requestedAlignment` is higher than the alignment specified on `alloca`,
652/// realigns `alloca` if this does not exceed the natural stack alignment.
653/// Returns the post-alignment of `alloca`, whether it was realigned or not.
654static uint64_t tryToEnforceAllocaAlignment(LLVM::AllocaOp alloca,
655 uint64_t requestedAlignment,
656 DataLayout const &dataLayout) {
657 uint64_t allocaAlignment = alloca.getAlignment().value_or(1);
658 if (requestedAlignment <= allocaAlignment)
659 // No realignment necessary.
660 return allocaAlignment;
661 uint64_t naturalStackAlignmentBits = dataLayout.getStackAlignment();
662 // If the natural stack alignment is not specified, the data layout returns
663 // zero. Optimistically allow realignment in this case.
664 if (naturalStackAlignmentBits == 0 ||
665 // If the requested alignment exceeds the natural stack alignment, this
666 // will trigger a dynamic stack realignment, so we prefer to copy...
667 8 * requestedAlignment <= naturalStackAlignmentBits ||
668 // ...unless the alloca already triggers dynamic stack realignment. Then
669 // we might as well further increase the alignment to avoid a copy.
670 8 * allocaAlignment > naturalStackAlignmentBits) {
671 alloca.setAlignment(requestedAlignment);
672 allocaAlignment = requestedAlignment;
673 }
674 return allocaAlignment;
675}
676
677/// Tries to find and return the alignment of the pointer `value` by looking for
678/// an alignment attribute on the defining allocation op or function argument.
679/// If the found alignment is lower than `requestedAlignment`, tries to realign
680/// the pointer, then returns the resulting post-alignment, regardless of
681/// whether it was realigned or not. If no existing alignment attribute is
682/// found, returns 1 (i.e., assume that no alignment is guaranteed).
683static uint64_t tryToEnforceAlignment(Value value, uint64_t requestedAlignment,
684 DataLayout const &dataLayout) {
685 if (Operation *definingOp = value.getDefiningOp()) {
686 if (auto alloca = dyn_cast<LLVM::AllocaOp>(definingOp))
687 return tryToEnforceAllocaAlignment(alloca, requestedAlignment,
688 dataLayout);
689 if (auto addressOf = dyn_cast<LLVM::AddressOfOp>(definingOp))
691 definingOp, addressOf.getGlobalNameAttr()))
692 return global.getAlignment().value_or(1);
693 // We don't currently handle this operation; assume no alignment.
694 return 1;
695 }
696 // Since there is no defining op, this is a block argument. Probably this
697 // comes directly from a function argument, so check that this is the case.
698 Operation *parentOp = value.getParentBlock()->getParentOp();
699 if (auto func = dyn_cast<LLVM::LLVMFuncOp>(parentOp)) {
700 // Use the alignment attribute set for this argument in the parent function
701 // if it has been set.
702 auto blockArg = llvm::cast<BlockArgument>(value);
703 if (Attribute alignAttr = func.getArgAttr(
704 blockArg.getArgNumber(), LLVM::LLVMDialect::getAlignAttrName()))
705 return cast<IntegerAttr>(alignAttr).getValue().getLimitedValue();
706 }
707 // We didn't find anything useful; assume no alignment.
708 return 1;
709}
710
711/// Introduces a new alloca and copies the memory pointed to by `argument` to
712/// the address of the new alloca, then returns the value of the new alloca.
714 Value argument, Type elementType,
715 uint64_t elementTypeSize,
716 uint64_t targetAlignment) {
717 // Allocate the new value on the stack.
718 Value allocaOp;
719 {
720 // Walk up from the call site to find the innermost AutomaticAllocationScope
721 // (e.g. an llvm.func or scf.forall). Placing the alloca at the entry block
722 // of that scope keeps it inside parallel regions rather than hoisting it
723 // out, while still landing at the function entry block for the common
724 // non-parallel case.
725 OpBuilder::InsertionGuard insertionGuard(builder);
726 Operation *scope = builder.getInsertionBlock()->getParentOp();
729 Block *entryBlock = &scope->getRegion(0).front();
730 builder.setInsertionPointToStart(entryBlock);
731 Value one = LLVM::ConstantOp::create(builder, loc, builder.getI64Type(),
732 builder.getI64IntegerAttr(1));
733 allocaOp = LLVM::AllocaOp::create(builder, loc, argument.getType(),
734 elementType, one, targetAlignment);
735 }
736 // Copy the pointee to the newly allocated value.
737 Value copySize =
738 LLVM::ConstantOp::create(builder, loc, builder.getI64Type(),
739 builder.getI64IntegerAttr(elementTypeSize));
740 // Preserve the alignment of the destination (alloca) in the memcpy's
741 // arg_attrs.
742 NamedAttribute dstAlignAttr =
743 builder.getNamedAttr(LLVM::LLVMDialect::getAlignAttrName(),
744 builder.getI64IntegerAttr(targetAlignment));
745 ArrayAttr argAttrs =
746 builder.getArrayAttr({builder.getDictionaryAttr({dstAlignAttr})});
747 LLVM::MemcpyOp::create(builder, loc, allocaOp, argument, copySize,
748 /*isVolatile=*/false,
749 /*tbaa_struct=*/nullptr,
750 /*access_groups=*/nullptr, /*alias_scopes=*/nullptr,
751 /*noalias_scopes=*/nullptr, /*tbaa=*/nullptr, argAttrs,
752 /*res_attrs=*/nullptr);
753 return allocaOp;
754}
755
756/// Handles a function argument marked with the byval attribute by introducing a
757/// memcpy or realigning the defining operation, if required either due to the
758/// pointee being writeable in the callee, and/or due to an alignment mismatch.
759/// `requestedAlignment` specifies the alignment set in the "align" argument
760/// attribute (or 1 if no align attribute was set).
761static Value handleByValArgument(OpBuilder &builder, Operation *callable,
762 Value argument, Type elementType,
763 uint64_t requestedAlignment) {
764 auto func = cast<LLVM::LLVMFuncOp>(callable);
765 LLVM::MemoryEffectsAttr memoryEffects = func.getMemoryEffectsAttr();
766 // If there is no memory effects attribute, assume that the function is
767 // not read-only.
768 bool isReadOnly = memoryEffects &&
769 memoryEffects.getArgMem() != LLVM::ModRefInfo::ModRef &&
770 memoryEffects.getArgMem() != LLVM::ModRefInfo::Mod;
771 // Check if there's an alignment mismatch requiring us to copy.
772 DataLayout dataLayout = DataLayout::closest(callable);
773 uint64_t minimumAlignment = dataLayout.getTypeABIAlignment(elementType);
774 if (isReadOnly) {
775 if (requestedAlignment <= minimumAlignment)
776 return argument;
777 uint64_t currentAlignment =
778 tryToEnforceAlignment(argument, requestedAlignment, dataLayout);
779 if (currentAlignment >= requestedAlignment)
780 return argument;
781 }
782 uint64_t targetAlignment = std::max(requestedAlignment, minimumAlignment);
784 builder, argument.getLoc(), argument, elementType,
785 dataLayout.getTypeSize(elementType), targetAlignment);
786}
787
788namespace {
789struct LLVMInlinerInterface : public DialectInlinerInterface {
790 using DialectInlinerInterface::DialectInlinerInterface;
791
792 LLVMInlinerInterface(Dialect *dialect)
793 : DialectInlinerInterface(dialect),
794 // Cache set of StringAttrs for fast lookup in `isLegalToInline`.
795 disallowedFunctionAttrs({
796 StringAttr::get(dialect->getContext(), "noduplicate"),
797 StringAttr::get(dialect->getContext(), "presplitcoroutine"),
798 StringAttr::get(dialect->getContext(), "returns_twice"),
799 }) {}
800
801 bool isLegalToInline(Operation *call, Operation *callable,
802 bool wouldBeCloned) const final {
803 auto callOp = dyn_cast<LLVM::CallOp>(call);
804 if (!callOp) {
805 LDBG() << "Cannot inline: call is not an '"
806 << LLVM::CallOp::getOperationName() << "' op";
807 return false;
808 }
809 if (callOp.getNoInline()) {
810 LDBG() << "Cannot inline: call is marked no_inline";
811 return false;
812 }
813 auto funcOp = dyn_cast<LLVM::LLVMFuncOp>(callable);
814 if (!funcOp) {
815 LDBG() << "Cannot inline: callable is not an '"
816 << LLVM::LLVMFuncOp::getOperationName() << "' op";
817 return false;
818 }
819 if (funcOp.isNoInline()) {
820 LDBG() << "Cannot inline: function is marked no_inline";
821 return false;
822 }
823 if (funcOp.getStrictfp()) {
824 LDBG() << "Cannot inline: function is marked strictfp";
825 return false;
826 }
827 if (funcOp.isVarArg()) {
828 LDBG() << "Cannot inline: callable is variadic";
829 return false;
830 }
831 // TODO: Generate aliasing metadata from noalias result attributes.
832 if (auto attrs = funcOp.getArgAttrs()) {
833 for (DictionaryAttr attrDict : attrs->getAsRange<DictionaryAttr>()) {
834 if (attrDict.contains(LLVM::LLVMDialect::getInAllocaAttrName())) {
835 LDBG() << "Cannot inline " << funcOp.getSymName()
836 << ": inalloca arguments not supported";
837 return false;
838 }
839 }
840 }
841 // TODO: Handle exceptions.
842 if (funcOp.getPersonality()) {
843 LDBG() << "Cannot inline " << funcOp.getSymName()
844 << ": unhandled function personality";
845 return false;
846 }
847 if (funcOp.getPassthrough()) {
848 // TODO: Used attributes should not be passthrough.
849 if (llvm::any_of(*funcOp.getPassthrough(), [&](Attribute attr) {
850 auto stringAttr = dyn_cast<StringAttr>(attr);
851 if (!stringAttr)
852 return false;
853 if (disallowedFunctionAttrs.contains(stringAttr)) {
854 LDBG() << "Cannot inline " << funcOp.getSymName()
855 << ": found disallowed function attribute " << stringAttr;
856 return true;
857 }
858 return false;
859 }))
860 return false;
861 }
862 // Refuse to inline if any block in the callee ends with an op that does
863 // not have the terminator trait. The MLIR verifier conservatively accepts
864 // unregistered ops as potential terminators (via mightHaveTrait), but
865 // handleTerminator uses cast<LLVM::ReturnOp> in the single-block path and
866 // would crash on such ops. Registered terminators from other dialects
867 // (e.g. cf.br) are safe: the multi-block path uses dyn_cast and skips
868 // non-llvm.return ops gracefully.
869 for (Block &block : funcOp.getBody()) {
870 if (!block.empty() && !block.back().hasTrait<OpTrait::IsTerminator>()) {
871 LDBG() << "Cannot inline " << funcOp.getSymName()
872 << ": block ends with non-terminator op";
873 return false;
874 }
875 }
876 return true;
877 }
878
879 bool isLegalToInline(Region *, Region *, bool, IRMapping &) const final {
880 return true;
881 }
882
883 bool isLegalToInline(Operation *op, Region *, bool, IRMapping &) const final {
884 // The inliner cannot handle variadic function arguments and blocktag
885 // operations prevent inlining since they the blockaddress operations
886 // reference them via the callee symbol.
887 return !(isa<LLVM::VaStartOp>(op) || isa<LLVM::BlockTagOp>(op));
888 }
889
890 /// Handle the given inlined return by replacing it with a branch. This
891 /// overload is called when the inlined region has more than one block.
892 void handleTerminator(Operation *op, Block *newDest) const final {
893 // Only return needs to be handled here.
894 auto returnOp = dyn_cast<LLVM::ReturnOp>(op);
895 if (!returnOp)
896 return;
897
898 // Replace the return with a branch to the dest.
899 OpBuilder builder(op);
900 LLVM::BrOp::create(builder, op->getLoc(), returnOp.getOperands(), newDest);
901 op->erase();
902 }
903
904 bool allowSingleBlockOptimization(Block *inlinedBlock) const final {
905 return !isa<LLVM::UnreachableOp>(inlinedBlock->getTerminator());
906 }
907
908 /// Handle the given inlined return by replacing the uses of the call with the
909 /// operands of the return. This overload is called when the inlined region
910 /// only contains one block.
911 void handleTerminator(Operation *op, ValueRange valuesToRepl) const final {
912 // Return will be the only terminator present.
913 auto returnOp = cast<LLVM::ReturnOp>(op);
914
915 // Replace the values directly with the return operands.
916 assert(returnOp.getNumOperands() == valuesToRepl.size());
917 for (auto [dst, src] : llvm::zip(valuesToRepl, returnOp.getOperands()))
918 dst.replaceAllUsesWith(src);
919 }
920
921 Value handleArgument(OpBuilder &builder, Operation *call, Operation *callable,
922 Value argument,
923 DictionaryAttr argumentAttrs) const final {
924 if (std::optional<NamedAttribute> attr =
925 argumentAttrs.getNamed(LLVM::LLVMDialect::getByValAttrName())) {
926 Type elementType = cast<TypeAttr>(attr->getValue()).getValue();
927 uint64_t requestedAlignment = 1;
928 if (std::optional<NamedAttribute> alignAttr =
929 argumentAttrs.getNamed(LLVM::LLVMDialect::getAlignAttrName())) {
930 requestedAlignment = cast<IntegerAttr>(alignAttr->getValue())
931 .getValue()
932 .getLimitedValue();
933 }
934 return handleByValArgument(builder, callable, argument, elementType,
935 requestedAlignment);
936 }
937
938 // This code is essentially a workaround for deficiencies in the inliner
939 // interface: We need to transform operations *after* inlined based on the
940 // argument attributes of the parameters *before* inlining. This method runs
941 // prior to actual inlining and thus cannot transform the post-inlining
942 // code, while `processInlinedCallBlocks` does not have access to
943 // pre-inlining function arguments. Additionally, it is required to
944 // distinguish which parameter an SSA value originally came from. As a
945 // workaround until this is changed: Create an ssa.copy intrinsic with the
946 // noalias attribute (when it was present before) that can easily be found,
947 // and is extremely unlikely to exist in the code prior to inlining, using
948 // this to communicate between this method and `processInlinedCallBlocks`.
949 // TODO: Fix this by refactoring the inliner interface.
950 auto copyOp = LLVM::SSACopyOp::create(builder, call->getLoc(), argument);
951 if (argumentAttrs.contains(LLVM::LLVMDialect::getNoAliasAttrName()))
952 copyOp->setDiscardableAttr(
953 builder.getStringAttr(LLVM::LLVMDialect::getNoAliasAttrName()),
954 builder.getUnitAttr());
955 return copyOp;
956 }
957
958 void processInlinedCallBlocks(
959 Operation *call,
960 iterator_range<Region::iterator> inlinedBlocks) const override {
961 handleInlinedAllocas(call, inlinedBlocks);
962 handleAliasScopes(call, inlinedBlocks);
963 handleAccessGroups(call, inlinedBlocks);
964 handleMemProfMetadata(call, inlinedBlocks);
965 handleInlinedLocations(call, inlinedBlocks);
966 handleLoopAnnotations(call, inlinedBlocks);
967 }
968
969 // Keeping this (immutable) state on the interface allows us to look up
970 // StringAttrs instead of looking up strings, since StringAttrs are bound to
971 // the current context and thus cannot be initialized as static fields.
972 const DenseSet<StringAttr> disallowedFunctionAttrs;
973};
974
975} // end anonymous namespace
976
978 registry.addExtension(+[](MLIRContext *ctx, LLVM::LLVMDialect *dialect) {
979 dialect->addInterfaces<LLVMInlinerInterface>();
980 });
981}
static bool hasLifetimeMarkers(LLVM::AllocaOp allocaOp)
Check whether the given alloca is an input to a lifetime intrinsic, optionally passing through one or...
static void handleMemProfMetadata(Operation *call, iterator_range< Region::iterator > inlinedBlocks)
Updates MemProf metadata on calls inlined into call, matching LLVM's propagateMemProfMetadata.
static void appendCallOpAliasScopes(Operation *call, iterator_range< Region::iterator > inlinedBlocks)
Appends any alias scopes of the call operation to any inlined memory operation.
static void handleLoopAnnotations(Operation *call, iterator_range< Region::iterator > inlinedBlocks)
Updates locations inside loop annotations to reflect that they were inlined.
static ArrayAttr concatArrayAttr(ArrayAttr lhs, ArrayAttr rhs)
Creates a new ArrayAttr by concatenating lhs with rhs.
static void createNewAliasScopesFromNoAliasParameter(Operation *call, iterator_range< Region::iterator > inlinedBlocks)
Creates a new AliasScopeAttr for every noalias parameter and attaches it to the appropriate inlined m...
static FailureOr< SmallVector< Value > > getUnderlyingObjectSet(Value pointerValue)
Attempts to return the set of all underlying pointer values that pointerValue is based on.
static void handleAccessGroups(Operation *call, iterator_range< Region::iterator > inlinedBlocks)
Appends any access groups of the call operation to any inlined memory operation.
static Value handleByValArgument(OpBuilder &builder, Operation *callable, Value argument, Type elementType, uint64_t requestedAlignment)
Handles a function argument marked with the byval attribute by introducing a memcpy or realigning the...
static void handleAliasScopes(Operation *call, iterator_range< Region::iterator > inlinedBlocks)
Handles all interactions with alias scopes during inlining.
static uint64_t tryToEnforceAllocaAlignment(LLVM::AllocaOp alloca, uint64_t requestedAlignment, DataLayout const &dataLayout)
If requestedAlignment is higher than the alignment specified on alloca, realigns alloca if this does ...
static bool haveCommonPrefix(ArrayRef< int64_t > mibStack, ArrayRef< int64_t > callsiteStack)
Whether the two call stacks agree up to the shorter length, matching LLVM's haveCommonPrefix: a MemPr...
static uint64_t tryToEnforceAlignment(Value value, uint64_t requestedAlignment, DataLayout const &dataLayout)
Tries to find and return the alignment of the pointer value by looking for an alignment attribute on ...
static void deepCloneAliasScopes(iterator_range< Region::iterator > inlinedBlocks)
Maps all alias scopes in the inlined operations to deep clones of the scopes and domain.
static Value handleByValArgumentInit(OpBuilder &builder, Location loc, Value argument, Type elementType, uint64_t elementTypeSize, uint64_t targetAlignment)
Introduces a new alloca and copies the memory pointed to by argument to the address of the new alloca...
static void handleInlinedLocations(Operation *call, iterator_range< Region::iterator > inlinedBlocks)
static void handleInlinedAllocas(Operation *call, iterator_range< Region::iterator > inlinedBlocks)
Handles alloca operations in the inlined blocks:
static bool isLegalToInline(InlinerInterface &interface, Region *src, Region *insertRegion, bool shouldCloneInlinedRegion, IRMapping &valueMapping)
Utility to check that all of the operations within 'src' can be inlined.
ArrayAttr()
This is an attribute/type replacer that is naively cached.
void addWalk(WalkFn< Attribute > &&fn)
Register a walk function for a given attribute or type.
WalkResult walk(T element)
Walk the given attribute/type, and recursively walk any sub elements.
Attributes are known-constant values of operations.
Definition Attributes.h:25
Block represents an ordered list of Operations.
Definition Block.h:34
iterator begin()
Definition Block.h:168
auto getOps()
Return an iterator range over the operations within this block that are of 'OpT'.
Definition Block.h:213
Operation * getParentOp()
Returns the closest surrounding operation that contains this block.
Definition Block.cpp:31
IntegerType getI64Type()
Definition Builders.cpp:73
IntegerAttr getI64IntegerAttr(int64_t value)
Definition Builders.cpp:120
Ty getType(Args &&...args)
Get or construct an instance of the type Ty with provided arguments.
Definition Builders.h:94
ArrayAttr getArrayAttr(ArrayRef< Attribute > value)
Definition Builders.cpp:275
DictionaryAttr getDictionaryAttr(ArrayRef< NamedAttribute > value)
Definition Builders.cpp:112
NamedAttribute getNamedAttr(StringRef name, Attribute val)
Definition Builders.cpp:102
The main mechanism for performing data layout queries.
static DataLayout closest(Operation *op)
Returns the layout of the closest parent operation carrying layout info.
llvm::TypeSize getTypeSize(Type t) const
Returns the size of the given type in the current scope.
uint64_t getStackAlignment() const
Returns the natural alignment of the stack in bits.
uint64_t getTypeABIAlignment(Type t) const
Returns the required alignment of the given type in the current scope.
The DialectRegistry maps a dialect namespace to a constructor for the matching dialect.
bool addExtension(TypeID extensionID, std::unique_ptr< DialectExtensionBase > extension)
Add the given extension to the registry.
MLIRContext * getContext() const
Definition Dialect.h:52
static FileLineColLoc get(StringAttr filename, unsigned line, unsigned column)
Definition Location.cpp:161
This class represents a fused location whose metadata is known to be an instance of the given type.
Definition Location.h:151
This is a utility class for mapping one set of IR entities to another.
Definition IRMapping.h:26
Location objects represent source locations information in MLIR.
Definition Location.h:32
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
NamedAttribute represents a combination of a name and an Attribute value.
Definition Attributes.h:166
RAII guard to reset the insertion point of the builder when destroyed.
Definition Builders.h:351
This class helps build Operations.
Definition Builders.h:210
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
Definition Builders.h:434
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition Builders.h:401
Block * getInsertionBlock() const
Return the block the current insertion point belongs to.
Definition Builders.h:445
A trait of region holding operations that define a new scope for automatic allocations,...
This class provides the API for ops that are known to be isolated from above.
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
void setLoc(Location loc)
Set the source location the operation was defined or derived from.
Definition Operation.h:243
Region & getRegion(unsigned index)
Returns the region held by this operation at position 'index'.
Definition Operation.h:740
bool mightHaveTrait()
Returns true if the operation might have the provided trait.
Definition Operation.h:811
void setDiscardableAttr(StringAttr name, Attribute value)
Set a discardable attribute by name.
Definition Operation.h:514
Operation * getParentWithTrait()
Returns the closest surrounding parent operation with trait Trait.
Definition Operation.h:273
Location getLoc()
The source location the operation was defined or derived from.
Definition Operation.h:240
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
Definition Operation.h:251
OpTy getParentOfType()
Return the closest surrounding parent operation that is of type 'OpTy'.
Definition Operation.h:255
Attribute removeDiscardableAttr(StringAttr name)
Remove the discardable attribute with the specified name if it exists.
Definition Operation.h:526
AttrClass getDiscardableAttrOfType(StringRef name)
Access a discardable attribute by name and cast it to AttrClass.
Definition Operation.h:495
user_range getUsers()
Returns a range of all users.
Definition Operation.h:927
Region * getParentRegion()
Returns the region to which the instruction belongs.
Definition Operation.h:247
MLIRContext * getContext()
Return the context this operation is associated with.
Definition Operation.h:233
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition Region.h:26
Block & front()
Definition Region.h:65
static Operation * lookupNearestSymbolFrom(Operation *from, StringAttr symbol)
Returns the operation registered with the given symbol name within the closest parent operation of,...
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
This class provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:392
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
Type getType() const
Return the type of this value.
Definition Value.h:105
Block * getParentBlock()
Return the Block in which this Value is defined.
Definition Value.cpp:46
Location getLoc() const
Return the location of this value.
Definition Value.cpp:24
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition Value.cpp:18
A class to signal how to proceed with the walk of the backward slice:
Definition SliceWalk.h:20
bool wasInterrupted() const
Returns true if the walk was interrupted.
Definition SliceWalk.h:60
static WalkContinuation skip()
Creates a continuation that advances the walk without adding any predecessor values to the work list.
Definition SliceWalk.h:55
static WalkContinuation advanceTo(mlir::ValueRange nextValues)
Creates a continuation that adds the user-specified nextValues to the work list and advances the walk...
Definition SliceWalk.h:49
static WalkContinuation interrupt()
Creates a continuation that interrupts the walk.
Definition SliceWalk.h:43
static WalkResult advance()
Definition WalkResult.h:47
void recursivelyReplaceElementsIn(Operation *op, bool replaceAttrs=true, bool replaceLocs=false, bool replaceTypes=false)
Replace the elements within the given operation, and all nested operations.
void addReplacement(ReplaceFn< Attribute > fn)
AttrTypeReplacerBase.
static DenseArrayAttrImpl get(MLIRContext *context, ArrayRef< int64_t > content)
void registerInlinerInterface(DialectRegistry &registry)
Register the LLVMInlinerInterface implementation of DialectInlinerInterface with the LLVM dialect.
Include the generated interface declarations.
bool matchPattern(Value value, const Pattern &pattern)
Entry point for matching a pattern over a Value.
Definition Matchers.h:490
detail::DenseArrayAttrImpl< int64_t > DenseI64ArrayAttr
std::optional< SmallVector< Value > > getControlFlowPredecessors(Value value)
Computes a vector of all control predecessors of value.
Definition SliceWalk.cpp:60
llvm::DenseSet< ValueT, ValueInfoT > DenseSet
Definition LLVM.h:125
llvm::SetVector< T, Vector, Set, N > SetVector
Definition LLVM.h:128
WalkContinuation walkSlice(mlir::ValueRange rootValues, WalkCallback walkCallback)
Walks the slice starting from the rootValues using a depth-first traversal.
Definition SliceWalk.cpp:6
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
Definition LLVM.h:123
detail::constant_op_matcher m_Constant()
Matches a constant foldable operation.
Definition Matchers.h:369
This trait indicates that a terminator operation is "return-like".